code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE OverloadedStrings, RecordWildCards, NamedFieldPuns #-} {-# LANGUAGE FlexibleInstances, ScopedTypeVariables, FlexibleContexts #-} {-# LANGUAGE BangPatterns #-} module Sajson.ToJson ( ToJson (..) , (.=) , (!.=) , encodeJson , encodeJsonStrict , encodeJsonBuilder , unsafeUtf8ByteString , unsafeBuilder , unsafeQuotedBuilder ) where import Prelude hiding (null) import Data.List (foldl') import Data.Monoid (Monoid (..), (<>), mempty) import Data.Char (ord) import Data.Text (Text) import Data.Word (Word8) import qualified Data.Text.Encoding as TE import qualified Data.ByteString as BS import Data.ByteString.Builder.Prim as BP import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Builder.Internal as B import Data.Vector (Vector) import Data.MonoTraversable (MonoFoldable, Element, onull, ofoldl') data ObjectBuilder = ObjectBuilder { obBuilder :: !B.Builder , obCount :: {-# UNPACK #-} !Int } instance Monoid ObjectBuilder where mempty = ObjectBuilder { obBuilder = mempty , obCount = 0 } -- TODO: We should never actually do a runtime test to decide whether to emit the comma. -- Add rewrite rules to provide this. mappend a b = ObjectBuilder { obBuilder = obBuilder a <> maybeComma <> obBuilder b , obCount = newCount } where newCount = obCount a + obCount b maybeComma | newCount >= 0 = comma | otherwise = mempty {-# RULES "objectbuilder/concat-to-mempty" forall (x :: ObjectBuilder). mappend mempty x = x ; "objectbuilder/concat-mempty" forall (x :: ObjectBuilder). mappend x mempty = x ; "objectbuilder/otherwise-assume-comma" forall (x :: ObjectBuilder) (y :: ObjectBuilder). mappend x y = mappendAlwaysComma x y #-} {-# INLINE mappendAlwaysComma #-} mappendAlwaysComma :: ObjectBuilder -> ObjectBuilder -> ObjectBuilder mappendAlwaysComma a b = ObjectBuilder { obBuilder = obBuilder a <> comma <> obBuilder b , obCount = 2 } newtype ValueBuilder = ValueBuilder B.Builder newArray :: [ValueBuilder] -> ValueBuilder newArray values = case values of [] -> ValueBuilder (openBracket <> closeBracket) (ValueBuilder first:rest) -> ValueBuilder $ openBracket <> first <> foldl' addElement mempty rest <> closeBracket where addElement :: B.Builder -> ValueBuilder -> B.Builder addElement b (ValueBuilder vb) = b <> comma <> vb {-# INLINE newArray #-} int :: Integral a => a -> ValueBuilder int i = ValueBuilder $ B.intDec $ fromIntegral i {-# INLINE int #-} bool :: Bool -> ValueBuilder bool b = ValueBuilder $ B.byteString bstr where bstr = if b then "true" else "false" {-# INLINE bool #-} null :: ValueBuilder null = ValueBuilder $ B.byteString "null" {-# INLINE null #-} float :: Float -> ValueBuilder float f = ValueBuilder $ B.floatDec f {-# INLINE float #-} double :: Double -> ValueBuilder double d = ValueBuilder $ B.doubleDec d {-# INLINE double #-} text :: Text -> ValueBuilder text t = ValueBuilder $ quoteText t {-# INLINE text #-} -- escapeText borrowed from Aeson. escapeText :: Text -> B.Builder escapeText t = B.char8 '"' <> TE.encodeUtf8BuilderEscaped escapeAscii t <> B.char8 '"' where escapeAscii :: BP.BoundedPrim Word8 escapeAscii = BP.condB (== c2w '\\' ) (ascii2 ('\\','\\')) $ BP.condB (== c2w '\"' ) (ascii2 ('\\','"' )) $ BP.condB (>= c2w '\x20') (BP.liftFixedToBounded BP.word8) $ BP.condB (== c2w '\n' ) (ascii2 ('\\','n' )) $ BP.condB (== c2w '\r' ) (ascii2 ('\\','r' )) $ BP.condB (== c2w '\t' ) (ascii2 ('\\','t' )) $ (BP.liftFixedToBounded hexEscape) -- fallback for chars < 0x20 c2w = fromIntegral . ord hexEscape :: BP.FixedPrim Word8 hexEscape = (\c -> ('\\', ('u', fromIntegral c))) BP.>$< BP.char8 BP.>*< BP.char8 BP.>*< BP.word16HexFixed ascii2 :: (Char, Char) -> BP.BoundedPrim a ascii2 cs = BP.liftFixedToBounded $ (const cs) BP.>$< BP.char7 BP.>*< BP.char7 {-# INLINE ascii2 #-} {-# INLINE escapeText #-} -- escapeText t = B.byteString $ TE.encodeUtf8 t -- | Unsafely insert a utf8 string into the JSON document. -- Do not use this for ByteStrings which are not legal utf8. unsafeUtf8ByteString :: BS.ByteString -> ValueBuilder -- unsafeUtf8ByteString bs = ValueBuilder $ quoteText $ TE.decodeUtf8 bs unsafeUtf8ByteString bs = ValueBuilder $ quote <> BP.primMapByteStringBounded escape bs <> quote where backslashW8 :: Word8 backslashW8 = fromIntegral $ fromEnum '\\' quoteW8 :: Word8 quoteW8 = fromIntegral $ fromEnum '"' escape :: BP.BoundedPrim Word8 escape = BP.condB (== backslashW8) (fixed2 (backslashW8, backslashW8)) $ BP.condB (== quoteW8) (fixed2 (backslashW8, quoteW8)) $ BP.liftFixedToBounded BP.word8 {-# INLINE fixed2 #-} fixed2 x = liftFixedToBounded $ const x BP.>$< BP.word8 BP.>*< BP.word8 -- | Unsafely insert a literal value into the JSON document. -- Using this makes it possible to formulate strings that are not legal JSON at all, so be careful. unsafeBuilder :: B.Builder -> ValueBuilder unsafeBuilder = ValueBuilder {-# INLINE unsafeBuilder #-} -- | Unsafely insert a quoted string into the JSON document. -- This DOES NOT escape anything. This function can thus be used to produce illegal JSON strings. -- Only use it when you know that the string you're emitting cannot contain anything that needs escaping. unsafeQuotedBuilder :: B.Builder -> ValueBuilder unsafeQuotedBuilder b = ValueBuilder $ B.char7 '"' <> b <> B.char7 '"' quoteText :: Text -> B.Builder quoteText t = quote <> escapeText t <> quote {-# INLINE quoteText #-} openCurly :: B.Builder openCurly = B.char7 '{' {-# INLINE openCurly #-} closeCurly :: B.Builder closeCurly = B.char7 '}' {-# INLINE closeCurly #-} comma :: B.Builder comma = B.char7 ',' {-# INLINE comma #-} colon :: B.Builder colon = B.char7 ':' {-# INLINE colon #-} quote :: B.Builder quote = B.char7 '"' {-# INLINE quote #-} openBracket :: B.Builder openBracket = B.char7 '[' {-# INLINE openBracket #-} closeBracket :: B.Builder closeBracket = B.char7 ']' {-# INLINE closeBracket #-} class ToJson a where toJson :: a -> ValueBuilder instance ToJson ValueBuilder where {-# INLINE toJson #-} toJson = id instance ToJson Bool where {-# INLINE toJson #-} toJson = bool instance ToJson Int where {-# INLINE toJson #-} toJson = int instance ToJson Float where {-# INLINE toJson #-} toJson = float instance ToJson Double where {-# INLINE toJson #-} toJson = double instance ToJson Text where {-# INLINE toJson #-} toJson = text instance ToJson a => ToJson (Maybe a) where toJson m = case m of Nothing -> null Just o -> toJson o instance ToJson ObjectBuilder where {-# INLINE toJson #-} toJson ObjectBuilder{..} = ValueBuilder $ openCurly <> obBuilder <> closeCurly arrayToJson :: (ToJson (Element collection), MonoFoldable collection) => collection -> ValueBuilder arrayToJson arr | onull arr = newArray [] | otherwise = let foldIt (!needComma, !accumulator) !el = let ValueBuilder eb = toJson el newBuilder = if needComma then accumulator <> comma <> eb else accumulator <> eb in (True, newBuilder) joined :: B.Builder joined = snd $ ofoldl' foldIt (False, mempty) arr in ValueBuilder $ openBracket <> joined <> closeBracket instance ToJson value => ToJson [value] where {-# INLINE toJson #-} toJson l = {-# SCC list_to_json #-} arrayToJson l instance ToJson value => ToJson (Vector value) where {-# INLINE toJson #-} toJson v = {-# SCC vector_to_json #-} arrayToJson v mkPair :: ToJson a => Text -> a -> ObjectBuilder mkPair k v = let ValueBuilder vb = toJson v in ObjectBuilder { obBuilder = quoteText k <> colon <> vb , obCount = 1 } {-# INLINE mkPair #-} {-| *Unsafely* build an object from a key and a value with the assumption that the key does not need escaping. - It turns out that escaping strings is time consuming. This function gives you a way to pick out strings that - you statically know not to require it. Good examples are string literals and URLs that you've previously properly encoded. - - This function is unsafe because misuse can yield syntactically illegal JSON. Beware! -} mkBSPair :: ToJson a => BS.ByteString -> a -> ObjectBuilder mkBSPair k v = let ValueBuilder kb = unsafeUtf8ByteString k ValueBuilder vb = toJson v in ObjectBuilder { obBuilder = kb <> colon <> vb , obCount = 1 } {-# INLINE mkBSPair #-} {-| Alias for 'mkPair' -} (.=) :: ToJson a => Text -> a -> ObjectBuilder (.=) = mkPair {-# INLINE (.=) #-} {-| Alias for 'mkBSPair' -} (!.=) :: ToJson a => BS.ByteString -> a -> ObjectBuilder (!.=) = mkBSPair {-# INLINE (!.=) #-} encodeJsonBuilder :: ToJson a => a -> B.Builder encodeJsonBuilder v = let ValueBuilder builder = toJson v in builder encodeJson :: ToJson a => a -> BSL.ByteString encodeJson v = let ValueBuilder builder = toJson v allocationStrategy = B.untrimmedStrategy (100 * kb) (100 * kb) kb = 1024 in B.toLazyByteStringWith allocationStrategy mempty builder encodeJsonStrict :: ToJson a => a -> BS.ByteString encodeJsonStrict = BSL.toStrict . encodeJson
andyfriesen/hs-sajson
src/Sajson/ToJson.hs
mit
9,678
0
16
2,272
2,280
1,227
1,053
-1
-1
module LexTypes where data InnerToken = OParen | CParen | ColonEq | Eq | DoubleEq | GEq | LEq | OAngleBracket | CAngleBracket | NEq | Plus | Slash | Asterisk | Dash | Percent | And | Or | Exclamation | IntLiteral Integer | LexRealLiteral Double | Module | ModuleName [String] | Import | Export | Dot | TypeName String | Return | While | Caret | For | In | Do | Enum | SemiColon | OBrace | CBrace | Variant | Comma | Backslash | LexStringLiteral String | LexCharacterLiteral Char | LexAtSymbol String | Symbol String | DoubleColon | If | Else | Case | Underscore | Pipe | RightArrow | LeftArrow | DoubleLeftArrow | OSqB | Colon | CSqb deriving (Show, Read, Eq) -- line number, column number, token type data Token = Token Int Int InnerToken deriving (Show, Read, Eq)
samphippen/pony
LexTypes.hs
mit
2,094
0
7
1,473
236
149
87
56
0
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings, ScopedTypeVariables #-} module Main where import qualified Data.Text as Text import qualified Data.Text.Lazy as LText import qualified Data.Binary as Bin import qualified Data.Acid as Acid import qualified Data.Map.Strict as Map import System.Console.ArgParser import Control.Applicative import Network.BitFunctor.Theory.Types import Network.BitFunctor.Theory.Coq.Types import Network.BitFunctor.Theory.Coq.TheoryAcid import Network.BitFunctor.Theory.RESTServer data TheoryDArguments = TheoryDArguments FilePath FilePath deriving (Show) theoryd_portnumber = 2718 theorydArgsParser :: ParserSpec TheoryDArguments theorydArgsParser = TheoryDArguments `parsedBy` reqPos "thdir" `Descr` "theory DB directory" `andBy` optFlag "" "rt" `Descr` "read from theory file" theorydArgsInterface :: IO (CmdLnInterface TheoryDArguments) theorydArgsInterface = (`setAppDescr` "Theory daemon program as a part of Bitfunctor environment") <$> (`setAppEpilog` "BitFunctor team") <$> mkApp theorydArgsParser readTheoryFile :: FilePath -> IO [CoqStatementT] readTheoryFile "" = return [] readTheoryFile thFile = do putStrLn "Reading the theory from the file..." th <- Bin.decodeFile thFile return th doTheoryDaemon (TheoryDArguments thDir thRFile) = do th' <- readTheoryFile thRFile acidTh <- Acid.openLocalStateFrom thDir (CoqTheoryAcid Map.empty) if (Prelude.null th') then return () else do putStrLn $ "Initializing theory from file..." res <- Acid.update acidTh (InitTheoryFromList th') return () (AcidResultSuccess sz) <- Acid.query acidTh (ThSize) putStrLn $ "Theory DB is open, total " ++ (show sz) ++ " elements." runTheoryRestServer theoryd_portnumber acidTh Acid.closeAcidState acidTh main = do interface <- theorydArgsInterface runApp interface doTheoryDaemon
BitFunctor/bitfunctor-theory
src/Network/BitFunctor/Theory/theoryd.hs
mit
2,149
0
13
541
445
241
204
46
2
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGAnimatedTransformList (js_getBaseVal, getBaseVal, js_getAnimVal, getAnimVal, SVGAnimatedTransformList, castToSVGAnimatedTransformList, gTypeSVGAnimatedTransformList) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"baseVal\"]" js_getBaseVal :: SVGAnimatedTransformList -> IO (Nullable SVGTransformList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedTransformList.baseVal Mozilla SVGAnimatedTransformList.baseVal documentation> getBaseVal :: (MonadIO m) => SVGAnimatedTransformList -> m (Maybe SVGTransformList) getBaseVal self = liftIO (nullableToMaybe <$> (js_getBaseVal (self))) foreign import javascript unsafe "$1[\"animVal\"]" js_getAnimVal :: SVGAnimatedTransformList -> IO (Nullable SVGTransformList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedTransformList.animVal Mozilla SVGAnimatedTransformList.animVal documentation> getAnimVal :: (MonadIO m) => SVGAnimatedTransformList -> m (Maybe SVGTransformList) getAnimVal self = liftIO (nullableToMaybe <$> (js_getAnimVal (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGAnimatedTransformList.hs
mit
1,985
12
10
261
460
283
177
33
1
{-# LANGUAGE OverloadedStrings #-} module Y2017.M12.D15.Exercise where import Data.Text import System.Directory {-- New topic! Today we're going to create an oembed service where we serve some simple resources, like, goats, ... because I like kids; they are SO CUTE! So, there are three things that make up a kids oembed service: 1. the resources themselves. They are here at this directory --} -- below import available via 1HaskellADay git repository goatsDir :: FilePath goatsDir = "Y2017/M12/D13/goats/" {-- ... but, actually, you can defer that to the resource, itself, if you have a repository of your assets, so, let's make that today's exercise, instead. Create a repository of the goats at that inode so that it returns your URL concatenated with the oembed request for the specific resource. ... so that also means you have to know how to extract files from an inode. --} goatsFiles :: FilePath -> IO [FilePath] goatsFiles dir = undefined -- return the path to the goats files prepended to only the goats files, -- themselves (so, no "." or "..", etc, if you please) {-- Now from those files, create a webpage that says something fetching, like, HERE ARE THE GOATS! And then list the links to the assets that, when selected, makes the oembed request to your web server. At your URL. That you (will) have. What does an oembed request look like. Let's look at a sample: http://www.flickr.com/services/oembed/?format=json&url=http%3A//www.flickr.com/photos/bees/2341623661/ A request is composed of several parts. --} -- 1. the uri of the (specific) oembed service oembedService :: FilePath oembedService = "http://127.0.0.1:8080/services/oembed/" -- 2. the query string which includes the url and which (may or may not) -- include the format data Format = JSON deriving Eq instance Show Format where show = const "json" query :: Maybe Format -> FilePath -> String query format relativeURI = undefined -- and with that, you can create your webpage with your goatsFiles links: goatsWebPage :: [FilePath] -> Text goatsWebPage goats = undefined {-- BONUS ----------------------------------------------------------------- Of course, who wants to look at raw oembed requests? You can hide those requests in the tiled images, right? Or something like that. Get fancy with your output that creates your web page. Now. Create an application that, given a directory of goat-assets, outputs a 'User Friendly' goats web page. --} main' :: [String] -> IO () main' dir = undefined -- We'll look at creating the oembed response tomorrow
geophf/1HaskellADay
exercises/HAD/Y2017/M12/D15/Exercise.hs
mit
2,576
0
7
446
171
100
71
20
1
{-# htermination addToFM_C :: (b -> b -> b) -> FiniteMap Float b -> Float -> b -> FiniteMap Float b #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_addToFM_C_6.hs
mit
121
0
3
24
5
3
2
1
0
module CSVUtils (parseCSV, showCSV, colFields, readCSV, writeCSV) where import Data.List type Separator = String type Document = String type CSV = [Entry] type Entry = [Field] type Field = String doc = "John;Doe;15\nTom;Sawyer;12\nAnnie;Blake;20" brokenDoc = "One;Two\nThree;Four;Five" csv = parseCSV ";" doc -- 8a) Define a function parseCSV that takes a separator and a string representing a CSV document and returns a CSV representation of the document. parseCSV :: Separator -> Document -> CSV parseCSV del doc | del !! 0 `notElem` doc = error $ "The character " ++ del ++ " does not occur in the text" | any (dim /=) [length x | x <- csv] = error "The CSV file is not well-formed" | otherwise = csv where csv = [words [if x == del !! 0 then ' ' else x | x <- xs] | xs <- lines doc] dim = length $ csv !! 00 -- 8b) Define a function showCSV that takes a separator and a CSV representation of a document and creates a CSV string from it. showCSV :: Separator -> CSV -> Document showCSV del csv | length csv == 0 || any (dim /=) [length x | x <- csv] = error "The CSV file is not well-formed" | otherwise = unlines [ intercalate del xs | xs <- csv] where dim = length $ csv !! 0 -- 8c) Define a function colFields that takes a CSV document and a field number and returns a list of fields in that column. colFields :: Int -> CSV -> [Field] colFields n csv | length csv == 0 || any (dim /=) [length x | x <- csv] = error "The CSV file is not well-formed" | n >= dim = error $ "There is no column " ++ show n ++ " in the CSV document" | otherwise = [xs !! n | xs <- csv] where dim = length $ csv !! 0 -- 8d) Define an IO function (an action) readCSV that takes a file path and a separator and returns the CSV representation of the file readCSV :: Separator -> FilePath -> IO CSV readCSV del path = do file <- readFile path return $ parseCSV del file -- 8e) Define a function writeCSV that takes a separator, a file path, and a CSV document and writes the document into a file. writeCSV :: Separator -> FilePath -> CSV -> IO () writeCSV del path csv = do writeFile path $ showCSV del csv
kbiscanic/PUH
hw03/CSVUtils.hs
mit
2,138
0
12
469
588
303
285
35
2
{-# LANGUAGE OverloadedStrings #-} -- | Types for choosing an option from a limited set. module Strive.Enums ( ActivityType (..) , ActivityZoneType (..) , AgeGroup (..) , ClubType (..) , FrameType (..) , Gender (..) , MeasurementPreference (..) , PhotoType (..) , Resolution (..) , ResourceState (..) , SegmentActivityType (..) , SeriesType (..) , SportType (..) , StreamType (..) , WeightClass (..) ) where import Control.Applicative (empty) import Data.Aeson (FromJSON, Value (Number, String), parseJSON) -- | An activity's type. data ActivityType = AlpineSki | BackcountrySki | Canoeing | CrossCountrySkiing | Crossfit | Elliptical | Hike | IceSkate | InlineSkate | Kayaking | KiteSurf | NordicSki | Ride | RockClimbing | RollerSki | Rowing | Run | Snowboard | Snowshoe | StairStepper | StandUpPaddling | Surfing | Swim | Walk | WeightTraining | Windsurf | Workout | Yoga deriving Show instance FromJSON ActivityType where parseJSON (String "AlpineSki") = return AlpineSki parseJSON (String "BackcountrySki") = return BackcountrySki parseJSON (String "Canoeing") = return Canoeing parseJSON (String "CrossCountrySkiing") = return CrossCountrySkiing parseJSON (String "Crossfit") = return Crossfit parseJSON (String "Elliptical") = return Elliptical parseJSON (String "Hike") = return Hike parseJSON (String "IceSkate") = return IceSkate parseJSON (String "InlineSkate") = return InlineSkate parseJSON (String "Kayaking") = return Kayaking parseJSON (String "KiteSurf") = return KiteSurf parseJSON (String "NordicSki") = return NordicSki parseJSON (String "Ride") = return Ride parseJSON (String "RockClimbing") = return RockClimbing parseJSON (String "RollerSki") = return RollerSki parseJSON (String "Rowing") = return Rowing parseJSON (String "Run") = return Run parseJSON (String "Snowboard") = return Snowboard parseJSON (String "Snowshoe") = return Snowshoe parseJSON (String "StairStepper") = return StairStepper parseJSON (String "StandUpPaddling") = return StandUpPaddling parseJSON (String "Surfing") = return Surfing parseJSON (String "Swim") = return Swim parseJSON (String "Walk") = return Walk parseJSON (String "WeightTraining") = return WeightTraining parseJSON (String "Windsurf") = return Windsurf parseJSON (String "Workout") = return Workout parseJSON (String "Yoga") = return Yoga parseJSON _ = empty -- | An activity zone's type. data ActivityZoneType = HeartrateZone | PowerZone deriving Show instance FromJSON ActivityZoneType where parseJSON (String "heartrate") = return HeartrateZone parseJSON (String "power") = return PowerZone parseJSON _ = empty -- | An athlete's age group. data AgeGroup = Ages0To24 | Ages25To34 | Ages35To44 | Ages45To54 | Ages55To64 | Ages65Plus instance Show AgeGroup where show Ages0To24 = "0_24" show Ages25To34 = "25_34" show Ages35To44 = "35_44" show Ages45To54 = "45_54" show Ages55To64 = "55_64" show Ages65Plus = "65_plus" -- | A club's type. data ClubType = CasualClub | Company | Other | RacingTeam | Shop deriving Show instance FromJSON ClubType where parseJSON (String "casual_club") = return CasualClub parseJSON (String "company") = return Company parseJSON (String "other") = return Other parseJSON (String "racing_team") = return RacingTeam parseJSON (String "shop") = return Shop parseJSON _ = empty -- | A bike's frame type. data FrameType = CrossFrame | MountainFrame | RoadFrame | TimeTrialFrame deriving Show instance FromJSON FrameType where parseJSON (Number 2) = return CrossFrame parseJSON (Number 1) = return MountainFrame parseJSON (Number 3) = return RoadFrame parseJSON (Number 4) = return TimeTrialFrame parseJSON _ = empty -- | An athlete's gender. data Gender = Female | Male instance Show Gender where show Female = "F" show Male = "M" instance FromJSON Gender where parseJSON (String "F") = return Female parseJSON (String "M") = return Male parseJSON _ = empty -- | An athlete's measurement preference. data MeasurementPreference = Feet | Meters deriving Show instance FromJSON MeasurementPreference where parseJSON (String "feet") = return Feet parseJSON (String "meters") = return Meters parseJSON _ = empty -- | A photo's type. data PhotoType = InstagramPhoto deriving Show instance FromJSON PhotoType where parseJSON (String "InstagramPhoto") = return InstagramPhoto parseJSON _ = empty -- | A stream's resolution. data Resolution = Low | Medium | High instance Show Resolution where show Low = "low" show Medium = "medium" show High = "high" instance FromJSON Resolution where parseJSON (String "low") = return Low parseJSON (String "medium") = return Medium parseJSON (String "high") = return High parseJSON _ = empty -- | A resource's state. data ResourceState = Meta | Summary | Detailed deriving Show instance FromJSON ResourceState where parseJSON (Number 1) = return Meta parseJSON (Number 2) = return Summary parseJSON (Number 3) = return Detailed parseJSON _ = empty -- | A segment's activity type. data SegmentActivityType = Riding | Running instance Show SegmentActivityType where show Riding = "riding" show Running = "running" -- | A series' type in a stream. data SeriesType = Distance | Time instance Show SeriesType where show Distance = "distance" show Time = "time" instance FromJSON SeriesType where parseJSON (String "distance") = return Distance parseJSON (String "time") = return Time parseJSON _ = empty -- | A club's sport type. data SportType = SportCycling | SportOther | SportRunning | SportTriathalon deriving Show instance FromJSON SportType where parseJSON (String "cycling") = return SportCycling parseJSON (String "other") = return SportOther parseJSON (String "running") = return SportRunning parseJSON (String "triathalon") = return SportTriathalon parseJSON _ = empty -- | A stream's type. data StreamType = AltitudeStream | CadenceStream | DistanceStream | GradeSmoothStream | HeartrateStream | LatlngStream | MovingStream | TempStream | TimeStream | VelocitySmoothStream | WattsStream instance Show StreamType where show AltitudeStream = "altitude" show CadenceStream = "cadence" show DistanceStream = "distance" show GradeSmoothStream = "grade_smooth" show HeartrateStream = "heartrate" show LatlngStream = "latlng" show MovingStream = "moving" show TempStream = "temp" show TimeStream = "time" show VelocitySmoothStream = "velocity_smooth" show WattsStream = "watts" -- | An athlete's weight class. data WeightClass = Kilograms0To54 | Kilograms55To64 | Kilograms65To74 | Kilograms75To84 | Kilograms85To94 | Kilograms95Plus | Pounds0To124 | Pounds125To149 | Pounds150To164 | Pounds165To179 | Pounds180To199 | Pounds200Plus instance Show WeightClass where show Kilograms0To54 = "0_54" show Kilograms55To64 = "55_64" show Kilograms65To74 = "65_74" show Kilograms75To84 = "75_84" show Kilograms85To94 = "85_94" show Kilograms95Plus = "95_plus" show Pounds0To124 = "0_124" show Pounds125To149 = "125_149" show Pounds150To164 = "150_164" show Pounds165To179 = "165_179" show Pounds180To199 = "180_199" show Pounds200Plus = "200_plus"
bitemyapp/strive
library/Strive/Enums.hs
mit
7,426
0
8
1,450
1,995
1,054
941
252
0
{- Part of possum4 Copyright (c) 2014 darkf Licensed under the terms of the MIT license See LICENSE.txt for details -} module Parser (parse, parseWith, parseString, parseStringWith, ArityMap) where import AST import Control.Monad.State import qualified Data.Map as M import qualified Tokenizer as T type ArityMap = M.Map String Int data ParserState = ParserState { arities :: ArityMap , tokens :: [T.Token] -- remaining tokens } type StateP = State ParserState -- Take n tokens from the stream, if non-empty takeTokens :: Int -> StateP (Maybe [T.Token]) takeTokens n = do p@ParserState {tokens=tokens} <- get if length tokens < n then return Nothing else do let tokens' = take n tokens put $ p {tokens=drop n tokens} return $ Just tokens' takeToken = takeTokens 1 >>= return . fmap head takeTokenUnsafe = do tok <- takeToken case tok of Just t -> return t Nothing -> error "takeTokenUnsafe: wanted one token, but got end of stream" -- Takes tokens until the token applied to the predicate is True. Also takes the matching token. takeTokensUntil :: (T.Token -> Bool) -> StateP [T.Token] takeTokensUntil predicate = do p@ParserState {tokens=tokens} <- get let (taken, _:tokens') = break predicate tokens put $ p {tokens=tokens'} return taken takeIdentifier = do tok <- takeToken case tok of Just (T.Ident s) -> return s Just t -> error $ "takeIdentifier: expected identifier, got " ++ show t Nothing -> error "takeIdentifier: expected identifier, got end of stream" peekToken = do ParserState {tokens=tokens} <- get if tokens == [] then return Nothing else return . Just $ head tokens lookupArity ident = do ParserState {arities=arities} <- get return $ M.lookup ident arities bindArity ident arity = do p@ParserState {arities=arities} <- get let arities' = M.insert ident arity arities put $ p {arities=arities'} expectToken token = do tok <- takeToken case tok of Just t | t == token -> return () Just t -> error $ "parser: expected " ++ show token ++ " but got " ++ show t Nothing -> error $ "parser: expected " ++ show token ++ " but got end of stream" -- Continually parse expressions until the predicate applied with current token is True. Consumes the matching token. parseUntil :: (Maybe T.Token -> Bool) -> StateP [AST] parseUntil predicate = do tok <- peekToken case tok of t | predicate t -> takeToken >> return [] _ -> do expr <- parseExpr next <- parseUntil predicate return $ expr : next -- Parses a defun -- defun f x y z is body end parseDefun :: StateP AST parseDefun = do name <- takeIdentifier args' <- takeTokensUntil (== T.Ident "is") let args = map (\(T.Ident i) -> Var i) args' let arity = length args bindArity name arity -- bind arity so that we can parse calls (and before the body so self-reference works) body <- parseUntil (== Just (T.Ident "end")) return $ Defun name args body -- Parse one expression parseExpr :: StateP AST parseExpr = do tok <- takeToken case tok of Just (T.Number n) -> return $ NumLit n Just (T.Str s) -> return $ StrLit s Just (T.Ident "defun") -> parseDefun Just (T.Ident "def") -> liftM2 Def takeIdentifier parseExpr Just (T.Ident "if") -> do cond <- parseExpr then_ <- parseExpr t <- peekToken case t of Just (T.Ident "else") -> do _ <- takeToken else_ <- parseExpr return $ If cond then_ (Just else_) _ -> return $ If cond then_ Nothing Just (T.Ident ident) -> do arity' <- lookupArity ident case arity' of Just arity -> do -- parse bare application args <- replicateM arity parseExpr return $ Apply (Var ident) args Nothing -> return $ Var ident -- variable Just T.LParen -> do -- parenthesized application fn <- parseExpr args <- parseUntil (== Just (T.RParen)) return $ Apply fn args Just t -> error $ "parseExpr: unhandled token " ++ show t Nothing -> error "parseExpr: empty stream" -- Parse the toplevel parseTop :: StateP [AST] parseTop = parseUntil (== Nothing) parse' :: ArityMap -> [T.Token] -> [AST] parse' arities tokens = evalState parseTop ParserState { arities=arities, tokens=tokens } parse :: [T.Token] -> [AST] parse = parse' M.empty parseWith :: ArityMap -> [T.Token] -> [AST] parseWith = parse' parseStringWith :: ArityMap -> String -> [AST] parseStringWith arities = parseWith arities . T.tokenize parseString :: String -> [AST] parseString = parse . T.tokenize
darkf/possum4
Parser.hs
mit
4,449
8
20
936
1,521
750
771
114
11
module Handler.Day where import Import import Data.Time.LocalTime import qualified Model.Event as E import Helpers import Calendar getDayR :: Day -> Handler Html getDayR date = do -- let date = fromGregorian year month day events <- runDB $ E.getEventsDay date tz <- liftIO getCurrentTimeZone widget <- calendarWidget defaultLayout $ do setTitle "Tampereen Frisbeeseura" $(widgetFile "banner") let sidebar = $(widgetFile "sidebar") $(widgetFile "calendar") $(widgetFile "day")
isankadn/yesod-testweb-full
Handler/Day.hs
mit
510
0
15
97
142
69
73
-1
-1
-- -- Copyright (c) 2013 Citrix Systems, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- {-# LANGUAGE ScopedTypeVariables #-} module NetworkManager where import Control.Applicative import Control.Concurrent import Data.Char import Data.String import Data.Maybe import Data.Int import Data.Word import qualified Data.Text.Lazy as T import qualified Data.ByteString as B import System.FilePath ((</>)) import Text.Printf (printf) import Tools.Log import Tools.Misc import Tools.XenStore import Rpc import Rpc.Core import Utils import Rpc.Autogen.NmManagerClient import Rpc.Autogen.NmDeviceClient import Rpc.Autogen.NmActiveConnectionClient import Rpc.Autogen.NmDeviceWifiClient import Rpc.Autogen.NmAccessPointClient type Ssid = [Word8] type Mac = String nmService = "org.freedesktop.NetworkManager" nmObj = "/org/freedesktop/NetworkManager" nmEtc = "/etc/NetworkManager" nmSysconDir = nmEtc </> "system-connections" nmVar = "/var/lib/NetworkManager" nmStateFile = nmVar </> "NetworkManager.state" nmConfFile = nmEtc </> "NetworkManager.conf" nmPidFile = "/var/run/NetworkManager.pid" nmOnDeviceStateChanged :: (String -> Rpc ()) -> Rpc () nmOnDeviceStateChanged action = let rule = matchSignal "org.freedesktop.NetworkManager.Device" "StateChanged" in rpcOnSignal rule process where process _ signal = let path = signalPath signal device = (show path) in action device nmOnWifiDevicePropertiesChanged :: (String -> Rpc ()) -> Rpc () nmOnWifiDevicePropertiesChanged action = let rule = matchSignal "org.freedesktop.NetworkManager.Device.Wireless" "PropertiesChanged" in rpcOnSignal rule process where process _ signal = let path = signalPath signal device = (show path) in action device objPathToStr :: ObjectPath -> String objPathToStr = T.unpack . strObjectPath nmObjPath :: String -> Rpc ObjectPath nmObjPath iface = do -- debug $ printf "nm device for %s " iface ifaceObj <- orgFreedesktopNetworkManagerGetDeviceByIpIface nmService nmObj iface -- debug $ printf "NM object path %s - %s" iface (show ifaceObj) return ifaceObj nmState :: Rpc (Word32) nmState = orgFreedesktopNetworkManagerGetState nmService nmObj nmListActiveConnections :: Rpc ([ObjectPath]) nmListActiveConnections = orgFreedesktopNetworkManagerGetActiveConnections nmService nmObj nmDeviceState nmDevObj = orgFreedesktopNetworkManagerDeviceGetState nmService nmDevObj nmDeviceInterface nmDevObj = orgFreedesktopNetworkManagerDeviceGetInterface nmService nmDevObj nmDeviceType nmDevObj = orgFreedesktopNetworkManagerDeviceGetDeviceType nmService nmDevObj nmDeviceManaged nmDevObj = orgFreedesktopNetworkManagerDeviceGetManaged nmService nmDevObj nmCarrier nmDevObj = (== eNM_DEVICE_STATE_ACTIVATED) <$> (nmDeviceState nmDevObj) nmActiveConnectionState nmConnection = orgFreedesktopNetworkManagerConnectionActiveGetState nmService nmConnection nmActiveAp nmDevObj = orgFreedesktopNetworkManagerDeviceWirelessGetActiveAccessPoint nmService nmDevObj nmApSsid nmApObj = orgFreedesktopNetworkManagerAccessPointGetSsid nmService nmApObj nmApStrength nmApObj = orgFreedesktopNetworkManagerAccessPointGetStrength nmService nmApObj nmApMode nmApObj = orgFreedesktopNetworkManagerAccessPointGetMode nmService nmApObj nmApFrequency nmApObj = orgFreedesktopNetworkManagerAccessPointGetFrequency nmService nmApObj nmApWpaFlags nmApObj = orgFreedesktopNetworkManagerAccessPointGetWpaFlags nmService nmApObj nmApRsnFlags nmApObj = orgFreedesktopNetworkManagerAccessPointGetRsnFlags nmService nmApObj nmApHwAddress nmApObj = orgFreedesktopNetworkManagerAccessPointGetHwAddress nmService nmApObj nmApMaxBitrate nmApObj = orgFreedesktopNetworkManagerAccessPointGetMaxBitrate nmService nmApObj
OpenXT/network
nws/NetworkManager.hs
gpl-2.0
4,506
0
12
661
720
386
334
73
1
-- germline_clone_mutation_count_source -- Mutation Module -- By G.W. Schwartz -- Collects all functions pertaining to mutations of codons, including -- Hamming distances and the like. module Mutation where -- Built in import Data.List import Data.Maybe import Control.Applicative -- Local import Types import Translation -- Checks if a Mutation is four fold redundant isFourFoldRedundantMutation :: Mutation -> Bool isFourFoldRedundantMutation x = elem x (mutList list1) || elem x (mutList list2) || elem x (mutList list3) || elem x (mutList list4) || elem x (mutList list5) || elem x (mutList list6) || elem x (mutList list7) || elem x (mutList list8) where list1 = ["CTT", "CTC", "CTA", "CTG"] list2 = ["GTT", "GTC", "GTA", "GTG"] list3 = ["TCT", "TCC", "TCA", "TCG"] list4 = ["CCT", "CCC", "CCA", "CCG"] list5 = ["ACT", "ACC", "ACA", "ACG"] list6 = ["GCT", "GCC", "GCA", "GCG"] list7 = ["CGT", "CGC", "CGA", "CGG"] list8 = ["GGT", "GGC", "GGA", "GGG"] mutList a = filter (\(i, j) -> i /= j) $ (,) <$> a <*> a -- Takes two strings, returns Hamming distance hamming :: String -> String -> Int hamming xs ys = length $ filter not $ zipWith (==) xs ys -- Checks if a pair is actually a mutation isMutation :: Mutation -> Bool isMutation (x, y) | codon2aa x == codon2aa y = False | otherwise = True -- Checks if a pair is actually a mutation isSilentMutation :: Mutation -> Bool isSilentMutation (x, y) | x /= y && codon2aa x == codon2aa y = True | otherwise = False -- Takes a list of mutations and returns the mutations that are -- actual mutations (the mutation is not just the same character with no gaps. filterMutStab :: (Mutation -> Bool) -> [Mutation] -> [Mutation] filterMutStab isWhat = filter filterRules where filterRules x = isWhat x && not (inTuple '-' x) && not (inTuple '.' x) && not (inTuple '~' x) inTuple c (x, y) = if c `elem` x || c `elem` y then True else False -- Return the mutation steps for a mutation mutation :: Mutation -> Maybe [[(Position, Nucleotide, Bool, Bool)]] mutation (x, y) | hamming x y == 0 = Nothing | hamming x y == 2 = Just [ mutSteps (mutPos x y 0 []) x y , mutSteps (reverse . mutPos x y 0 $ []) x y ] | hamming x y == 3 = Just [ mutSteps [0, 1, 2] x y , mutSteps [0, 2, 1] x y , mutSteps [1, 0, 2] x y , mutSteps [1, 2, 0] x y , mutSteps [2, 0, 1] x y , mutSteps [2, 1, 0] x y ] | otherwise = Just [mutSteps (mutPos x y 0 []) x y] -- | A spanning fold that collects the mutation steps from germline to -- clone codon -- mutSteps (order of positions mutated) (germline codon) (clone codon) mutSteps :: [Position] -> Codon -> Codon -> [(Position, Nucleotide, Bool, Bool)] mutSteps [] _ _ = [] mutSteps (n:ns) x y = ( n , y !! n , isSilentMutation intermediateMutation , isFourFoldRedundantMutation intermediateMutation ) : mutSteps ns (changeXToY n x y) y where intermediateMutation = (x, changeXToY n x y) -- | Change one nucleotide from xs to ys at position (n - 1) (index at 0) changeXToY :: Position -> String -> String -> String changeXToY 0 (_:xs) (y:_) = y:xs changeXToY n (x:xs) (_:ys) = x : changeXToY (n - 1) xs ys -- | Determine which positions are mutated in a codon mutPos :: String -> String -> Position -> [Position] -> [Position] mutPos _ _ 3 _ = [] mutPos [] _ _ _ = [] mutPos _ [] _ _ = [] mutPos (x:xs) (y:ys) n ns | x /= y = n : mutPos xs ys (n + 1) ns | otherwise = mutPos xs ys (n + 1) ns -- | Find the number of unique synonymous or non-synonymous mutations by -- nucleotide in each codon while taking into account theoretical -- intermediate steps from the germline. uniqueSynonymous :: MutationType -> Bias -> Bool -> CodonMut -> MutCount -> [[Mutation]] -> Int uniqueSynonymous mutType bias fourBool codonMut mutCount = sum . map ( length . getMutationCount ) where getMutationCount = nub -- Unique mutations . mutCountFrequent . filter (\(_, _, sil, four) -> biasValue mutType sil && isFourFold fourBool four) . concatMap (mutBias . fromJust) . filter isJust . map (mutatedCodon codonMut) -- Only codons with n muts . map mutation mutCountFrequent = concat . filter (\x -> length x >= mutCount) . group . sort mutBias [] = [] mutBias xs = xs !! (fromJust $ biasResult xs) biasResult xs = elemIndex (biasIndex mutType bias xs) (map sumMut xs) biasIndex Silent Silent = maximum . map sumMut biasIndex Silent Replacement = minimum . map sumMut biasIndex Replacement Silent = minimum . map sumMut biasIndex Replacement Replacement = maximum . map sumMut sumMut = sum . map ( \(_, _, sil, _) -> if ((biasValue mutType) sil) then 1 else 0 ) biasValue Silent = id biasValue Replacement = not isFourFold True x = x -- Check four fold redundancy isFourFold False _ = True -- Include it all if we don't care about it mutatedCodon 0 xs = xs mutatedCodon _ Nothing = Nothing mutatedCodon 1 (Just xs) | length xs == 1 = Just xs | otherwise = Nothing mutatedCodon 2 (Just xs) | length xs == 2 = Just xs | otherwise = Nothing mutatedCodon 3 (Just xs) | length xs == 6 = Just xs | otherwise = Nothing -- Return the mutations if they exist between the germline and a clone -- (unused in this algorithm, only here for completionist reasons). countMutations :: Germline -> Clone -> [(Position, Mutation)] countMutations germline clone = mut germline clone where mut x y = zip [1..] . zip x $ y
GregorySchwartz/count-mutations
src/Mutation.hs
gpl-2.0
6,727
0
16
2,461
1,964
1,034
930
125
12
-- OmegaGB Copyright 2007 Bit Connor -- This program is distributed under the terms of the GNU General Public License ----------------------------------------------------------------------------- -- | -- Module : AsciiTest01 -- Copyright : (c) Bit Connor 2007 <[email protected]> -- License : GPL -- Maintainer : [email protected] -- Stability : in-progress -- -- OmegaGB -- Game Boy Emulator -- -- This module executes a ROM and does some ascii art output -- ----------------------------------------------------------------------------- module AsciiTest01 where import Prerequisites import Data.Char import Data.Array.IArray --hiding ((!), (//)) import RomImage import Machine import Joypad romFile = "roms/Catrap (U) [!].gb" test01 :: IO () test01 = do romImage <- loadRomImage romFile let initialState = initialMachineState romImage let iter f x = let (r, x') = f x in r : iter f x' let l = iter (updateMachineDisplayFrame (initJoypadKeyStates False False False False False False False False)) initialState let clear = putStr ((chr 27) : "[H") let pixel c = case c of 0 -> " " 1 -> "~" 2 -> "=" 3 -> "@" let printRow d y = let s = concatMap (\x -> (pixel (d!(y, x)))) [0..159] in putStrLn s let printRows d = {- clear >> -} mapM_ (\y -> printRow d y) [0..138] mapM_ (\d -> printRows d) (take 200 l)
bitc/omegagb
src/AsciiTest01.hs
gpl-2.0
1,437
0
21
340
363
189
174
24
4
{- A lewd IRC bot that does useless things. Copyright (C) 2012 Shou This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} {-# LANGUAGE DoAndIfThenElse #-} {-# OPTIONS_HADDOCK prune #-} module KawaiiBot.IRC where import KawaiiBot.Bot import KawaiiBot.Types import KawaiiBot.Utils import Control.Applicative import Control.Concurrent import Control.Exception as E import Control.Monad hiding (join) import qualified Control.Monad as M import Control.Monad.Reader hiding (join) import Data.List import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Time.Clock import Data.Time.Clock.POSIX import Data.Time.Format import Data.Maybe import Data.String.Utils (split, join, strip) import Network import System.Directory import System.IO import System.Locale import System.Random (randomRIO) -- | Writes to the core which then passes it to an IRC server. ircwrite :: Handle -> String -> Memory () ircwrite h str = do debug <- asks (verbosityC . getConfig) meta <- asks getMeta let server = getServer meta message = concat ["serverwrite ", server, ":", str] e <- liftIO $ try (hPutStrLn h message) :: Memory (Either SomeException ()) case e of Right _ -> when (debug > 1) . liftIO . putStrLn $ "<- " ++ message Left e -> when (debug > 0) . liftIO $ print e -- | Writes to the core. corewrite :: Handle -> String -> Memory () corewrite h str = do debug <- asks (verbosityC . getConfig) let message = "<Core>" ++ ":" ++ str e <- liftIO $ try (hPutStrLn h str) :: Memory (Either SomeException ()) case e of Right _ -> when (debug > 1) . liftIO . putStrLn $ "<- " ++ message Left e -> when (debug > 0) . liftIO $ print e logWrite :: String -> Memory () logWrite msg = do meta <- asks getMeta logsPath <- asks (logsPathC . getConfig) verbosity <- asks (verbosityC . getConfig) time <- do utc <- liftIO $ getCurrentTime return $ formatTime defaultTimeLocale "%Y-%m-%d %H:%M:%S" utc let writeLog :: Memory (Either SomeException ()) writeLog = liftIO . try $ do let serverurl = getServer meta dest = getDestino meta path = logsPath ++ serverurl ++ " " ++ dest nick = getUsernick meta full = '\n' : intercalate "\t" [time,nick,msg] tmpfile = "/tmp/" ++ serverurl ++ " " ++ dest E.catch (copyFile path tmpfile) $ \e -> do evaluate (e :: SomeException) writeFile path "" copyFile path tmpfile appendFile tmpfile full copyFile tmpfile path e <- writeLog case e of Right _ -> return () Left e -> when (verbosity > 0) . liftIO $ print e -- | Reinitialize an event. eventInit :: Event -> Memory Event eventInit (Event f r ti c s te) = do time <- liftIO $ fmap realToFrac getPOSIXTime time' <- liftIO $ fmap (time +) r return $ Event f r time' c s te -- | Timed event function. event :: Handle -> Memory () event h = do events <- asks (eventsC . getConfig) currentTime <- liftIO $ fmap realToFrac getPOSIXTime events' <- forM events $ \event -> do let bool = currentTime >= eventTime event temp = eventTemp event cbool <- liftIO $ chance (eventChance event) case () of _ | bool && cbool -> do let servers :: [Server] servers = eventServers event metas :: [Meta] metas = concat . (`map` servers) $ \(Server _ server _ _ _ channels _ _) -> case channels of Blacklist chans -> [] Whitelist chans -> (`map` chans) $ \chan -> Meta chan "Anon" "" "" [] server temp forM_ metas $ \meta -> do text <- local (injectMeta meta) $ eventFunc event unless (null text) $ do local (injectMeta meta) $ do ircwrite h $ genPrivmsg meta text eventInit event | not bool -> return event | not cbool -> eventInit event liftIO . threadDelay $ 10^6 local (modConfig $ injectEvents events') $ event h where genPrivmsg (Meta dest _ _ _ _ _ _) t = "PRIVMSG " ++ dest ++ " :" ++ t chance :: Double -> IO Bool chance n = do let n' = if n > 1.0 then 1.0 else n i <- randomRIO (0.0, 1.0) return (n >= i) -- | Recursive function that gets a line from kawaiibot-core and parses it. listenLoop :: Handle -> Memory () listenLoop h = do s <- liftIO $ hGetLine h let arg = takeWhile (`notElem` " :") s if arg `elem` coreArgs then do liftIO . putStrLn $ "-> " ++ s mc <- parseCore h s local (\_ -> mc) $ listenLoop h else do parseIRC h s listenLoop h where coreArgs = [ "getservers" , "getnick" , "serverjoin" , "serverquit" , "getuserlist" ] -- | Parse a Core message parseCore :: Handle -- ^ Core server handle -> String -- ^ message received -> Memory MetaConfig parseCore h bs = do debug <- asks (verbosityC . getConfig) mc@(MetaConfig meta config) <- ask let (sCmd : xs) = concat (split " " <$> split ":" bs) sArgs = xs when (debug > 1) . liftIO . print $ sCmd : sArgs case sCmd of "getuserlist" -> do let margs :: Maybe (String, String, [String]) margs = do (server : channel : users) <- Just sArgs return (server, channel, users) case margs of Just (se, ch, us) -> do let servs = injectServerUserlist (serversC config) se ch us conf = mapConfigServers (const servs) config return $ MetaConfig meta conf -- Not enough arguments (this isn't supposed to ever happen) Nothing -> return mc -- Fallback _ -> return mc -- | Parse an IRC message. parseIRC :: Handle -- ^ Core server handle -> String -- ^ message received -> Memory () parseIRC h bs = do debug <- asks (verbosityC . getConfig) meta <- asks getMeta let nick = getUsernick meta sFull :: [String] sFull = ":" `split` bs sMsg = ":" `join` drop 2 sFull sArgs = map strip . splits "!@ " . concat . take 1 $ drop 1 sFull meta' = sFull !! 0 `injectServ` meta when (debug > 1) . liftIO . putStrLn $ show sArgs ++ ' ' : sMsg local (injectMeta meta') $ parseMsg h (sArgs, sMsg) where parseMsg :: Handle -> ([String], String) -> Memory () parseMsg h (args, msg) | isCmd args 3 "PRIVMSG" = do -- Interpret message and respond if meta <- asks getMeta -- anything is returned from `parser' config <- asks getConfig let nick = args !! 0 name = args !! 1 host = args !! 2 act = args !! 3 dest = args !! 4 channels = getChannels meta serverurl = getServer meta ulist = getUserlist $ getConfigMeta config serverurl dest meta' = Meta dest nick name host channels serverurl ulist local (injectMeta meta') $ do meta <- asks getMeta msgLogging <- asks (msgLoggingC . getConfig) allowThen allowTitle $ do -- URL fetching let urls = filter (isPrefixOf "http") $ words msg forkMe . forM_ urls $ \url -> do title' <- fmap fromMsg $ title url let titleMsg = unwords [ "PRIVMSG" , dest , ":\ETX5→\ETX" , title' ] unless (null title') $ ircwrite h titleMsg return EmptyMsg post <- parser msg let mAct = if isChannelMsg post then "PRIVMSG " ++ dest else "PRIVMSG " ++ nick msg' = fromMsg post when msgLogging $ do -- logging logWrite msg unless (null msg') $ do ircwrite h $ mAct ++ " :" ++ msg' kawaiinick <- getServerNick let kawaiimeta = emptyMeta { getUsernick = kawaiinick , getDestino = dest , getServer = serverurl } local (injectMeta kawaiimeta) $ do logWrite msg' return () | isCmd args 3 "INVITE" = do -- Join a channel on invite meta <- asks getMeta let nick = args !! 0 name = args !! 1 host = args !! 2 act = args !! 3 dest = args !! 4 channels = getChannels meta serverurl = getServer meta temp = getUserlist meta meta' = Meta dest nick name host channels serverurl temp allowedChans <- do let servers = serversC . getConfig mserver = (`findServer` serverurl) . servers asks (fmap allowedChannels . mserver) case allowedChans of Just (Blacklist xs) -> do if msg `elem` xs then do ircwrite h $ "JOIN " ++ msg else do let msg = "Your channel is blacklisted." ircwrite h $ "PRIVMSG " ++ dest ++ " :" ++ msg Just (Whitelist xs) -> do if msg `elem` xs then do ircwrite h $ "JOIN " ++ msg else do let msg = "Your channel is not whitelisted." ircwrite h $ "PRIVMSG " ++ dest ++ " :" ++ msg Nothing -> return () return () | isCmd args 3 "KICK" = do meta <- asks getMeta let dest = args !! 4 serverurl = getServer meta corewrite h $ concat ["getuserlist ", serverurl, ":", dest] | isCmd args 3 "PART" = do meta <- asks getMeta let nick = args !! 0 dest = args !! 4 serverurl = getServer meta corewrite h $ concat ["getuserlist ", serverurl, ":", dest] | isCmd args 3 "JOIN" = do meta <- asks getMeta let nick = args !! 0 dest = msg serverurl = getServer meta corewrite h $ concat ["getuserlist ", serverurl, ":", dest] varPath <- asks (variablePathC . getConfig) svars <- liftIO $ lines <$> readFile varPath let mvar :: [Variable] mvar = do v <- svars let mvars = maybeRead v guard $ isJust mvars let var = fromJust mvars guard $ readableReminder serverurl dest nick var return var case length mvar of 0 -> return () 1 -> ircwrite h $ unwords [ "PRIVMSG" , dest , ':' : nick ++ ":" , varContents $ head mvar ] _ -> ircwrite h $ unwords [ "PRIVMSG" , dest , ':' : nick ++ ":" , "You have " ++ show (length mvar) , "reminders:" , unwords $ map varName mvar ] | isCmd args 3 "QUIT" = do meta <- asks getMeta servers <- asks (serversC . getConfig) let nick = args !! 0 serverurl = getServer meta let mchans :: Maybe [String] mchans = listToMaybe $ do s <- servers guard $ serverURL s == serverurl return $ do m <- serverMetas s return $ getDestino m chans = fromJust $ mchans <|> Just [] forM_ chans $ \chan -> do corewrite h $ concat ["getuserlist ", serverurl, ":", chan] | isCmd args 3 "NICK" = do meta <- asks getMeta servers <- asks (serversC . getConfig) let nick = args !! 0 serverurl = getServer meta let mchans :: Maybe [String] mchans = listToMaybe $ do s <- servers guard $ serverURL s == serverurl return $ do m <- serverMetas s return $ getDestino m chans = fromJust $ mchans <|> Just [] forM_ chans $ \chan -> do corewrite h $ concat ["getuserlist ", serverurl, ":", chan] | isCmd args 3 "MODE" = do let nick = args !! 0 dest = args !! 4 mode = args !! 5 return () | isCmd args 1 "353" = do -- Receive nick list meta <- asks getMeta let dest = args !! 4 serverurl = getServer meta corewrite h $ concat ["getuserlist ", serverurl, ":", dest] | otherwise = do -- Fallback return () isCmd args n x | length args >= 3 = args !! 3 == x | otherwise = False -- | Connects to kawaiibot-core. serverConnect :: Memory () serverConnect = do h <- liftIO $ do h <- connectTo "localhost" (PortNumber $ fromIntegral 3737) hSetEncoding h utf8 hSetBuffering h LineBuffering hSetNewlineMode h (NewlineMode CRLF CRLF) forkIO . forever $ getLine >>= \s -> unless (null s) $ hPutStrLn h s return h events <- asks (eventsC . getConfig) events' <- mapM eventInit events local (modConfig $ injectEvents events') (forkMe $ event h) listenLoop h
Shou/KawaiiBot-hs
KawaiiBot/IRC.hs
gpl-2.0
15,954
0
29
7,105
4,297
2,089
2,208
332
8
------------------------------------------------------------------ -- | -- Module : Gom.Random -- Copyright : (c) Paul Brauner 2009 -- (c) Emilie Balland 2009 -- (c) INRIA 2009 -- Licence : GPL (see COPYING) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : non-portable (requires generalized newtype deriving) -- -- Instances of 'Test.QuickCheck.Arbitrary' for 'Gom.Sig' and other -- generators. -------------------------------------------------------------------- module Gom.Random () where import Gom.Sig import Test.QuickCheck genId :: Gen String genId = resize 10 . listOf1 $ oneof [choose ('a','z'), choose ('A','Z')] genUId :: Gen String genUId = resize 10 $ do c <- choose ('A','Z') ; cs <- genId ; return $ c:cs builtins :: [SortId] builtins = map makeSortId ["boolean","int","char","double","float","long","String"] instance Arbitrary SortId where arbitrary = makeSortId `fmap` genUId instance Arbitrary CtorId where arbitrary = makeCtorId `fmap` genId instance Arbitrary FieldId where arbitrary = makeFieldId `fmap` genId allDiff :: (Eq t) => [t] -> Bool allDiff [] = True allDiff (x:xs) = x `notElem` xs && allDiff xs instance Arbitrary Module where arbitrary = do modul <- genId sorts <- arbitrary `suchThat` allDiff -- we need at least one constructor per sort cidss <- resize 10 $ listOf (listOf1 arbitrary) `suchThat` (allDiff . concat) let mix = zip sorts cidss defs <- mapM (genSortDef (map fst mix)) mix return $ Module modul builtins defs shrink (Module m i d) = do d' <- shrink d return $ Module m i d' genTypedFields :: [SortId] -> Gen [(FieldId,SortId)] genTypedFields sorts = do flds <- listOf1 arbitrary `suchThat` allDiff doms <- listOf1 (elements $ sorts ++ builtins) return $ zip flds doms instance Arbitrary SortDef where arbitrary = error "not implemented" shrink (SortDef s c l) = do l' <- shrink l return $ SortDef s c l' genSortDef :: [SortId] -> (SortId, [CtorId]) -> Gen SortDef genSortDef sorts (sid,cids) = do flds <- genTypedFields sorts ctrs <- mapM (genCtor sorts flds) cids return $ SortDef sid (Just $ makeClassId "Object" "") ctrs instance Arbitrary Ctor where arbitrary = error "not implemented" shrink (Simple c l) = do l' <- shrink l ; return $ Simple c l' shrink x = return x genCtor :: [SortId] -> [(FieldId, SortId)] -> CtorId -> Gen Ctor genCtor sorts flds cname = oneof [genSCtor flds cname, genVCtor sorts cname] genSCtor :: [(FieldId, SortId)] -> CtorId -> Gen Ctor genSCtor flds cname = do fis <- listOf (elements flds) `suchThat` allDiff return $ Simple cname fis genVCtor :: [SortId] -> CtorId -> Gen Ctor genVCtor sorts cname = do sort <- elements sorts return $ Variadic cname sort
polux/hgom
test/Gom/Random.hs
gpl-3.0
2,848
0
13
597
950
491
459
58
1
{- hake: make tool. ruby : rake = haskell : hake Copyright (C) 2008-2008 Yoshikuni Jujo <[email protected]> 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/>. -} module Main where import System.Environment (getArgs) import System.Console.GetOpt (getOpt, ArgOrder(Permute), OptDescr(Option), ArgDescr(ReqArg, NoArg)) import System.Exit (exitWith, ExitCode(ExitFailure)) import Data.Version (showVersion) import Data.Maybe (mapMaybe) import Control.Applicative ((<$>)) import Paths_hake (version) import Development.Hake.RunHake (runHake) main :: IO () main = do (ver, hFile, args) <- processArgs if ver then putStrLn ("hake " ++ showVersion version) else runHake hFile hFile [] args >>= exitWith processArgs :: IO ( Bool, String, [ String ] ) processArgs = do (opts, args, errMsgs) <- getOpt Permute optionList <$> getArgs let ver = elem OptVersion opts hFile = head $ mapMaybe getHakefile $ opts ++ [ OptHakefile "Hakefile" ] case errMsgs of [] -> return () _ -> mapM_ putStr errMsgs >> exitWith (ExitFailure 1) return ( ver, hFile, args ) data Opt = OptVersion | OptHakefile FilePath deriving Eq getHakefile :: Opt -> Maybe FilePath getHakefile (OptHakefile hf) = Just hf getHakefile _ = Nothing optionList :: [ OptDescr Opt ] optionList = [ Option "f" [] (ReqArg OptHakefile "file as Hakefile") "set Hakefile", Option "" [ "version" ] (NoArg OptVersion) "show version" ]
YoshikuniJujo/hake_haskell
Main.hs
gpl-3.0
2,151
2
13
513
449
247
202
33
2
import qualified Data.Set as Set import Test.HUnit import Test.Framework import Test.Framework.Providers.HUnit import Pretzel main :: IO () main = defaultMainWithOpts tests mempty tests = [ testCase "show-1" $ showPretzel pretzel @?= diagram , testCase "read-success" $ readPretzel diagram @?= Just pretzel , testCase "read-failure" $ readPretzel "LOL" @?= Nothing ] pretzel = Set.fromList [ (0, 0, 0), (1, 0, 0), (2, 0, 0) , (0, 1, 0), (2, 1, 0) , (0, 2, 0), (1, 2, 0), (2, 2, 0) --------------------------------- , (0, 0, 1), (2, 0, 1) , (0, 1, 1), (2, 1, 1) , (0, 2, 1), (1, 2, 1), (2, 2, 1) --------------------------------- , (0, 0, 2), (1, 0, 2), (2, 0, 2) , (0, 1, 2) , (0, 2, 2), (1, 2, 2), (2, 2, 2) ] diagram = unlines [ "###" , "#.#" , "###" , "" , "#.#" , "#.#" , "###" , "" , "###" , "#.." , "###" , "" ]
mkovacs/pretzel
src/test/UnitReadShow.hs
gpl-3.0
935
0
8
276
428
268
160
38
1
{-# LANGUAGE TypeFamilies, TupleSections, DeriveGeneric #-} {-# Language FlexibleContexts, FlexibleInstances, ViewPatterns #-} -- | Imagine desiging a key-value store on top of the file system. -- The 'Simple' store is basically that, with a few added -- complications due to the versioning. -- -- The store runs out of a single directory on disk. The layout, as -- created by 'open', is: -- -- @ -- DB_DIR/ -- ├── format -- ├── version -- ├── clock -- ├── changelog -- ├── nodeName -- ├── clean-shutdown -- ├── tmp/ -- ├── keys/ -- ├── changesets/ -- └── values/ -- @ -- -- @DB_DIR/format@ contains a single string identifying the format of -- the key-value store. In our case, this is "simple". -- -- @DB_DIR/version@ contains the version of the key-value store. This -- is used to upgrade on-disk files. -- -- @DB_DIR/clock@ is the latest version clock seen by the store. This is probably also -- the version of the latest value written to disk, but this is not necessary. -- -- @DB_DIR/changelog@ is a list of all the versions and associated 'Changeset's of this -- store. -- -- @DB_DIR/clean-shutdown@ is only present if 1) the store is closed, and 2) the store was -- shutdown cleanly. -- -- @DB_DIR/tmp@ is a directory used as a staging ground for creating -- new files. On most file systems, /move/ is an atomic operation, -- but /create file and write to it/ is not. So, when writing to -- disk, we usually create a new file in this temporary directory, -- then move it to its real location. -- -- @DB_DIR/keys@ is a directory that contains a file for each key -- present in the key-value store. Each of these files is an -- S-Expression which contains meta information about the value of the -- key. -- -- @DB_DIR/changesets@ is a directory that contains a file for each change made to the -- key-value store. -- -- @DB_DIR/values@ is a directory that contains a file for each value -- present in the key-value store. The values in these files may be -- gzipped. These files are referenced by files in the @DB_DIR/keys@ -- directory. module Ltc.Store.Simple ( Simple, OpenParameters(..) ) where import Control.Applicative ( (<$>) ) import Control.Concurrent ( MVar, newMVar , modifyMVar_, readMVar, withMVar ) import Control.Concurrent.STM ( atomically, writeTChan ) import Control.Monad ( when, unless, forM ) import Data.ByteString.Lazy.Char8 ( ByteString ) import Data.Default ( Default(..) ) import Data.Digest.Pure.SHA ( sha1, showDigest, integerDigest ) import Data.Foldable ( foldlM ) import Data.List ( find ) import Data.Set ( Set ) import Data.Sequence ( Seq, ViewL(..), (|>) ) import Data.String ( fromString ) import Data.Typeable ( TypeRep, typeOf ) import GHC.Generics ( Generic ) import Language.Sexp ( Sexpable(..), parse, parseExn, printHum ) import Ltc.Changeset ( Changeset(..), changesetBaseVersion , changesFromList , wireDiffForKey, wireDiffFromTo, diffFromWireDiff ) import Ltc.Diff ( Diffable(..) ) import Ltc.Store.Class ( Store(..), SetCmd(..) , Key(..), KeyHash , NodeName , Storable, ValueHash , StoreClosed(..), CorruptValueFileError(..), NodeNameMismatchError(..) , TypeMismatchError(..), CorruptStoreError(..), CorruptKeyFileError(..) , Version, ChangesetHash , CorruptChangesetError(..), CorruptChangelogError(..) ) import Ltc.Store.Event ( EventChannel, Event(..), SetEvent(..) ) import qualified Codec.Compression.GZip as Z import qualified Control.Exception as CE import qualified Data.ByteString.Lazy.Char8 as BL import qualified Data.Set as S import qualified Data.Sequence as Seq import qualified Data.VectorClock as VC import qualified Text.Regex.TDFA.ByteString as T import System.Directory ( createDirectory, doesFileExist, doesDirectoryExist , renameFile, getDirectoryContents, removeFile ) import System.FilePath ( (</>) ) import System.IO ( hClose, openBinaryTempFile ) import System.Log.Logger ( debugM, warningM ) import Text.Printf ( printf ) import Text.Regex.TDFA ( defaultCompOpt, defaultExecOpt ) ---------------------- -- Debugging ---------------------- -- | Debugging tag for this module tag :: String tag = "Simple" ---------------------- -- Simple store identifiers ---------------------- formatString :: String formatString = "simple" storeVsn :: Int storeVsn = 7 ---------------------- -- Types ---------------------- data Simple = Simple { getBase :: FilePath , getUseCompression :: Bool , getNodeName :: NodeName , getEventChannels :: MVar [EventChannel] , getIsOpen :: MVar Bool , getClock :: MVar Version , getLock :: MVar () , getChangelog :: MVar Changelog } -- | There is one 'KeyVersion' record for each *value* stored for a -- key. So, a key whose value was set, and then changed twice, will -- have three of these records. data KeyVersion = KeyVersion { getVersion :: Version , getValueHash :: ValueHash } deriving ( Generic ) instance Sexpable KeyVersion -- | Represents a single 'Key' with at least one value ('getTip'), and -- possibly many older values ('getHistory'). History is ordered -- most-recent-first. The values of a key are of a particular type -- ('getValueType'); this is determined when the key is first created, -- and cannot be later changed. data KeyRecord = KR { getKeyName :: Key , getValueType :: TypeRep , getTip :: KeyVersion , getHistory :: [ChangesetHash] } deriving ( Generic ) instance Sexpable KeyRecord -- FIXME The changelog should be a map, not an alist. data Changelog = Changelog [(Version, ChangesetHash)] deriving ( Generic ) instance Sexpable Changelog ---------------------- -- Store interface ---------------------- instance Store Simple where -- | Store configuration. data OpenParameters Simple = SimpleParameters { -- | The store directory. location :: FilePath -- | Whether files should be gzip'd. , useCompression :: Bool -- | The name of the node opening the store. If the name stored on disk is -- different from this, a 'NodeNameMismatchError' will be thrown (unless -- 'forceOpen' is set). , nodeName :: ByteString -- | Create the store if it is missing. If this is not set and the store is -- missing, throw 'CorruptStoreError'. , createIfMissing :: Bool -- | Open the store even if there is a node name mismatch. , forceOpen :: Bool } open = doOpen close = doClose storeFormat _ = formatString storeVersion _ = storeVsn get = doGet getLatest = doGetLatest keyVersions = doKeyVersions changesetsNotBefore = doChangesetsNotBefore changesetsAfter = doChangesetsAfter keyType = doKeyType set = doSet mset = doMSet msetInternal = doMSetInternal addChangeset = doAddChangeset withWriteLock = lockStore keys = doKeys addEventChannel = doAddEventChannel tipVersion store = readMVar (getClock store) hasVersion = doHasVersion instance Default (OpenParameters Simple) where def = SimpleParameters { location = "ltc-store" , useCompression = False , nodeName = "my-node" , createIfMissing = True , forceOpen = False } doOpen :: OpenParameters Simple -> IO Simple doOpen params = do debugM tag (printf "open store '%s'" (location params)) -- Make sure that the store exists on disk. storeExists <- doesDirectoryExist (location params) when (not storeExists) $ do if createIfMissing params then initStore params else CE.throw (CorruptStoreError "missing") -- Check that the requested node name is the same as the one on disk. nn <- BL.readFile (locationNodeName (location params)) when (not (forceOpen params) && nn /= nodeName params) $ CE.throw (NodeNameMismatchError { requestedName = nodeName params , storeName = nn }) -- Check that the store's format version is the same as the one in this executable. vsn <- BL.readFile (locationVersion (location params)) when (vsn /= BL.pack (show storeVsn)) $ CE.throw (CorruptStoreError "different version") cleanShutdown <- doesFileExist (locationCleanShutdown (location params)) if cleanShutdown then removeFile (locationCleanShutdown (location params)) else doRecover clock <- newMVar =<< readClockExn (locationClock (location params)) changelog <- newMVar =<< readChangelogExn (location params) eventChannels <- newMVar [] isOpen <- newMVar True lock <- newMVar () return (Simple { getBase = location params , getUseCompression = useCompression params , getNodeName = nodeName params , getEventChannels = eventChannels , getIsOpen = isOpen , getClock = clock , getLock = lock , getChangelog = changelog }) where doRecover = do warningM tag "recovering store" doClose :: Simple -> IO () doClose store = do debugM tag (printf "close store '%s'" (getBase store)) modifyMVar_ (getIsOpen store) (const (return False)) writeFile (locationCleanShutdown (getBase store)) "" writeEventChannels store CloseEvent doGet :: forall a. (Storable a) => Simple -> Key -> Version -> IO (Maybe a) doGet store key version = do debugM tag (printf "get %s" (show key)) writeEventChannels store getEvent CE.handle (\(exn :: CE.IOException) -> do CE.throw (CorruptKeyFileError { keyFilePath = locationKey store key , ckfReason = show exn })) $ do withKeyRecord (locationKey store key) $ \kr -> do when (getValueType kr /= typeOf (undefined :: a)) $ CE.throw (TypeMismatchError { expectedType = typeOf (undefined :: a) , foundType = getValueType kr }) -- Read the tip value let valueFile = locationValueHash store (getValueHash (getTip kr)) s <- (if getUseCompression store then Z.decompress else id) <$> BL.readFile valueFile let val = case valueFromBinary s of Nothing -> CE.throw (CorruptValueFileError { valueFilePath = valueFile, cvfReason = "unparsable" }) Just v -> v -- Walk back through the history looking for the earliest version that was -- before or equal to the given version. chash <- changesetHashForVersion (getVersion (getTip kr)) Just <$> findVersion (Seq.singleton (val, chash)) where getEvent = let Key k = key in GetEvent { eventKey = key , keyDigest = fromInteger (integerDigest (sha1 k)) } valueFromBinary :: ByteString -> Maybe a valueFromBinary s = do case parse s of Left (err, _) -> fail err Right [sexp] -> fromSexp sexp Right _ -> fail "wrong number of sexps" changesetHashForVersion :: Version -> IO ChangesetHash changesetHashForVersion vsn = do Changelog changesets <- readMVar (getChangelog store) case lookup vsn changesets of Nothing -> error "no changeset for version" Just changeset -> return changeset findVersion :: Seq (a, ChangesetHash) -> IO a findVersion (Seq.viewl -> (val, chash) :< rest) = do changeset <- readChangesetExn (locationChangesetHash store chash) -- FIXME We are implicitly linearizing the history here. if not (getAfterVersion changeset `VC.causes` version) then do let val' = case wireDiffForKey (getChanges changeset) key of Nothing -> val Just wireDiff -> -- The only way for 'diffFromWireDiff' to fail is if the type -- is wrong, but it cannot be at this point in the execution. let Just diff = diffFromWireDiff wireDiff rdiff = reverseDiff diff in applyDiff val rdiff chash' <- changesetHashForVersion (changesetBaseVersion changeset) findVersion (rest |> (val', chash')) else do return val findVersion _ = do error "findVersion ran out of changes :(" doGetLatest :: (Storable a) => Simple -> Key -> IO (Maybe (a, Version)) doGetLatest store key = do debugM tag (printf "getLatest %s" (show key)) withKeyRecord (locationKey store key) $ \kr -> do let latestVersion = getVersion (getTip kr) -- Every key has at least one value. mvalue <- doGet store key latestVersion case mvalue of Just value -> return (Just (value, latestVersion)) Nothing -> CE.throw (CorruptStoreError (printf "%s's tip (%s) does not exist" (show (locationKey store key)) (show latestVersion))) doKeyVersions :: Simple -> Key -> IO (Maybe [Version]) doKeyVersions store key = do debugM tag (printf "keyVersions %s" (show key)) withKeyRecord (locationKey store key) $ \kr -> do Just <$> forM (getHistory kr) (\chash -> do changeset <- readChangesetExn (locationChangesetHash store chash) return (getAfterVersion changeset)) doChangesetsNotBefore :: Simple -> Version -> IO [Changeset] doChangesetsNotBefore store version = do Changelog changesets <- readMVar (getChangelog store) let changesetPaths = map (locationChangesetHash store) $ map snd $ filter (\(otherVersion, _) -> not (otherVersion `VC.causes` version)) changesets changesets' <- mapM readChangesetExn changesetPaths return (reverse changesets') doChangesetsAfter :: Simple -> Version -> IO [Changeset] doChangesetsAfter store version = do Changelog changesets <- readMVar (getChangelog store) let changesetPaths = map (locationChangesetHash store) $ map snd $ filter (\(otherVersion, _) -> version `VC.causes` otherVersion && version /= otherVersion) changesets changesets' <- mapM readChangesetExn changesetPaths return (reverse changesets') doKeyType :: Simple -> Key -> IO (Maybe TypeRep) doKeyType store key = do debugM tag (printf "keyType %s" (show key)) withKeyRecord (locationKey store key) $ \kr -> do return (Just (getValueType kr)) doSet :: (Storable a) => Simple -> Key -> a -> IO Version doSet store key value = doMSet store [SetCmd key value] doMSet :: Simple -> [SetCmd] -> IO Version doMSet store cmds = lockStore store $ do assertIsOpen store -- Log the set everywhere debugM tag (printf "mset %s" (show (map (\(SetCmd key _) -> key) cmds))) -- Increment the version clock. let nn = getNodeName store clock <- readMVar (getClock store) let clock' = case VC.inc nn clock of Nothing -> VC.insert nn (1 :: Int) clock Just newClock -> newClock -- Compute the 'Changeset' from the store state to the new one (the store is locked, -- so values can't be updated by something else while we're here). changes <- changesFromList <$> forM cmds (\(SetCmd key newVal) -> do mOldVal <- doGetLatest store key let oldVal = maybe def fst mOldVal return (key, wireDiffFromTo oldVal newVal)) let changeset = Update { getBeforeUpdateVersion = clock , getAfterVersion = clock' , getChanges = changes } doMSetInternal store changeset cmds True return clock' doMSetInternal :: Simple -> Changeset -> [SetCmd] -> Bool -> IO () doMSetInternal store changeset cmds shouldSendEvent = do -- Save the store clock. It's ok to increment the clock superfluously, so we can be -- interrupted here. modifyMVar_ (getClock store) (const (return (getAfterVersion changeset))) atomicWriteClock store (locationClock (getBase store)) (getAfterVersion changeset) -- Save the changeset to disk. Having superfluous changesets lying around is not a -- problem, so we can be interrupted here. doAddChangeset store changeset -- Update the values. event <- writeValuesAndUpdateKeyRecords when shouldSendEvent (writeEventChannels store event) where (_, chash) = serializedChangeset changeset writeValuesAndUpdateKeyRecords :: IO Event writeValuesAndUpdateKeyRecords = do -- Write the values. It's ok to write extra values, so we can be interrupted -- here. (vals, vhashes) <- unzip <$> forM cmds (\(SetCmd _ value) -> do let vhash = valueHash value val = valueToString value atomicWriteFile store (locationValueHash store vhash) ((if getUseCompression store then Z.compress else id) val) return (val, vhash)) -- Read the key records (the store is locked so there's no risk of them being -- updated by something else). mkrs <- forM (zip cmds vhashes) $ \(cmd@(SetCmd key _), vhash) -> do mkr <- readKeyRecordExn (locationKey store key) return (mkr, cmd, vhash) -- Update the key records in-memory, or create new ones if they are missing. krs' <- forM mkrs $ \(mkrOld, cmd@(SetCmd key value), vhash) -> do let tip = KeyVersion { getVersion = getAfterVersion changeset , getValueHash = vhash } case mkrOld of Nothing -> return $ (cmd, KR { getKeyName = key , getValueType = typeOf value , getTip = tip , getHistory = [chash] }) Just krOld -> do when (getValueType krOld /= typeOf value) $ do CE.throw (TypeMismatchError { expectedType = getValueType krOld , foundType = typeOf value }) return $ (cmd, krOld { getTip = tip , getHistory = chash : getHistory krOld }) -- Write the updated key records to disk. atomicWriteFiles store $ flip map krs' $ \(SetCmd key _, kr) -> (locationKey store key, printHum (toSexp kr)) -- Return the event that this change would cause. return (msetEvent vals) -- | The hash of a value. This hash is used as the filename under which the value is -- stored in the @values/@ folder. valueHash :: (Storable a) => a -> ValueHash valueHash = BL.pack . showDigest . sha1 . valueToString valueToString :: (Storable a) => a -> ByteString valueToString = printHum . toSexp msetEvent vals = MSetEvent (flip map (zip cmds vals) $ \(SetCmd key _, val) -> let Key k = key in SetEvent { setKey = key , setKeyDigest = fromInteger (integerDigest (sha1 k)) , valueDigest = fromInteger (integerDigest (sha1 val)) }) doAddChangeset :: Simple -> Changeset -> IO () doAddChangeset store changeset = do let (cbin, chash) = serializedChangeset changeset -- Write the new changeset. Having superfluous changesets is not a problem, so we can -- be interrupted here. atomicWriteFile store (locationChangesetHash store chash) cbin -- Update the changelog in-memory Changelog changesets <- readMVar (getChangelog store) let changelog' = Changelog ((getAfterVersion changeset, chash) : changesets) modifyMVar_ (getChangelog store) (const (return changelog')) -- Write the changelog to disk. Since we've already written the changeset, this -- leaves the store in a consistent state. atomicWriteFile store (locationChangelog (getBase store)) (printHum (toSexp changelog')) doKeys :: Simple -> String -> IO (Set Key) doKeys store regexp = do debugM tag (printf "keys %s" regexp) case T.compile defaultCompOpt defaultExecOpt (fromString regexp) of Left err -> do warningM tag (printf "keys bad pattern: %s" err) return S.empty Right reg -> do let keysDir = locationKeys (getBase store) kfs <- getDirectoryContents keysDir unfilteredKeys <- foldlM (\s kf -> do mk <- withKeyRecord (keysDir </> kf) (\kr -> return (Just (getKeyName kr))) return (maybe s (\k -> S.insert k s) mk)) S.empty kfs return (S.filter (\(Key key) -> isRightJust (T.execute reg (BL.toStrict key))) unfilteredKeys) where isRightJust :: Either a (Maybe b) -> Bool isRightJust (Right (Just _)) = True isRightJust _ = False doHasVersion :: Simple -> Version -> IO Bool doHasVersion store version = do Changelog versions <- readMVar (getChangelog store) case find (\(oldVersion, _) -> oldVersion == version) versions of Nothing -> return (version == VC.empty) Just _ -> return True doAddEventChannel :: Simple -> EventChannel -> IO () doAddEventChannel store eventChannel = do modifyMVar_ (getEventChannels store) $ \eventChannels -> return (eventChannel : eventChannels) ---------------------- -- Helpers ---------------------- -- | Wrapper around 'readKeyRecordExn'. withKeyRecord :: FilePath -> (KeyRecord -> IO (Maybe a)) -> IO (Maybe a) withKeyRecord path f = do mkr <- readKeyRecordExn path case mkr of Nothing -> return Nothing Just kr -> f kr -- FIXME parseOrError should be part of sexp. -- | Read a S-Expression-encoded value from a file, or invoke the given handler if an -- error occurs. parseWithHandler :: (Sexpable a) => FilePath -> (String -> IO a) -> IO a parseWithHandler path handleErr = do text <- BL.readFile path case parse text of Left err -> handleErr (show err) Right [s] -> case fromSexp s of Nothing -> handleErr "invalid sexp" Just kr -> return kr Right _ -> handleErr "multiple sexps" -- | Read a key record from disk. If the key doesn't exist, return -- 'Nothing'. If the key record is corrupt, fail. readKeyRecordExn :: FilePath -> IO (Maybe KeyRecord) readKeyRecordExn path = do keyExists <- doesFileExist path if keyExists then do Just <$> parseWithHandler path (\reason -> do CE.throw (CorruptKeyFileError { keyFilePath = path , ckfReason = reason })) else return Nothing -- | Read a 'Changeset' from disk. readChangesetExn :: FilePath -> IO Changeset readChangesetExn path = do parseWithHandler path $ \reason -> do CE.throw (CorruptChangesetError { changesetPath = path , ccsReason = reason }) -- | Read the store's 'Changelog'. readChangelogExn :: FilePath -> IO Changelog readChangelogExn base = do parseWithHandler (locationChangelog base) $ \reason -> do CE.throw (CorruptChangelogError reason) -- | Write the given 'ByteString' to the file atomically. Overwrite any previous content. -- The 'Simple' reference is needed in order to find the temporary directory (we can't use -- @/tmp@ because that may be on a different partition and 'renameFile' doesn't work in -- that case). atomicWriteFile :: Simple -> FilePath -> ByteString -> IO () atomicWriteFile store path content = do (tempFile, handle) <- openBinaryTempFile (locationTemporary (getBase store)) "ltc" BL.hPut handle content `CE.finally` hClose handle renameFile tempFile path -- | Write a version clock to disk atomically. atomicWriteClock :: Simple -> FilePath -> Version -> IO () atomicWriteClock store path clock = atomicWriteFile store path (printHum (toSexp clock)) -- | Write the given 'ByteString's to the given files atomically. See 'atomicWriteFile' -- for details. atomicWriteFiles :: Simple -> [(FilePath, ByteString)] -> IO () atomicWriteFiles store pcs = do -- FIXME Make 'atomicWriteFiles' atomic. mapM_ (uncurry (atomicWriteFile store)) pcs -- | Read a version clock from disk. Throw an exception if it is missing or if it is -- malformed. readClockExn :: FilePath -> IO Version readClockExn path = fromSexp . head . parseExn =<< BL.readFile path -- | Create the initial layout for the store at the given directory -- base. initStore :: OpenParameters Simple -> IO () initStore params = do debugM tag "initStore" let base = location params createDirectory base writeFile (locationFormat base) formatString writeFile (locationVersion base) (show storeVsn) BL.writeFile (locationClock base) (printHum (toSexp (VC.empty :: Version))) BL.writeFile (locationChangelog base) (printHum (toSexp (Changelog []))) BL.writeFile (locationNodeName base) (nodeName params) writeFile (locationCleanShutdown base) "" createDirectory (locationTemporary base) createDirectory (locationValues base) createDirectory (locationKeys base) createDirectory (locationChangesets base) -- | The hash of a key. This hash is used as the filename under which -- the key is stored in the @keys/@ folder. keyHash :: Key -> KeyHash keyHash (Key k) = BL.pack (showDigest (sha1 k)) -- | Write event to all event channels writeEventChannels :: Simple -> Event -> IO () writeEventChannels store event = do eventChannels <- readMVar (getEventChannels store) -- FIXME Is there any way to signal that a TChan is "closed"? mapM_ (atomically . flip writeTChan event) eventChannels -- | If the store is not open, throw 'StoreClosed'. assertIsOpen :: Simple -> IO () assertIsOpen store = do isOpen <- readMVar (getIsOpen store) unless isOpen $ CE.throw StoreClosed -- | Lock the store for the duration of the given action: only one such action can execute -- at any time. lockStore :: Simple -> IO a -> IO a lockStore store act = withMVar (getLock store) (const act) -- | Serialize a 'ChangeSet'. serializedChangeset :: Changeset -> (ByteString, ChangesetHash) serializedChangeset changeset = let cbin = printHum (toSexp changeset) in (cbin, BL.pack (showDigest (sha1 cbin))) ---------------------- -- Locations ---------------------- -- | The location of a key's value. locationValueHash :: Simple -> ValueHash -> FilePath locationValueHash store hash = locationValues (getBase store) </> BL.unpack hash -- | The location of a 'Changeset'. locationChangesetHash :: Simple -> ChangesetHash -> FilePath locationChangesetHash store hash = locationChangesets (getBase store) </> BL.unpack hash -- | The location of a key's record. locationKey :: Simple -> Key -> FilePath locationKey store key = locationKeys (getBase store) </> BL.unpack (keyHash key) locationFormat :: FilePath -> FilePath locationFormat base = base </> "format" locationVersion :: FilePath -> FilePath locationVersion base = base </> "version" locationClock :: FilePath -> FilePath locationClock base = base </> "clock" locationCleanShutdown :: FilePath -> FilePath locationCleanShutdown base = base </> "clean-shutdown" locationTemporary :: FilePath -> FilePath locationTemporary base = base </> "tmp" locationValues :: FilePath -> FilePath locationValues base = base </> "values" locationKeys :: FilePath -> FilePath locationKeys base = base </> "keys" locationChangesets :: FilePath -> FilePath locationChangesets base = base </> "changesets" locationChangelog :: FilePath -> FilePath locationChangelog base = base </> "changelog" locationNodeName :: FilePath -> FilePath locationNodeName base = base </> "nodeName"
scvalex/ltc
src/Ltc/Store/Simple.hs
gpl-3.0
29,049
0
26
8,248
6,570
3,420
3,150
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} module Haemu.Exception ( UnknownOpcode(..) , InvalidAddress(..) , InvalidRegister(..) , UnknownOptype(..) , (?->) ) where import Haemu.Types import Control.Monad.Exception -- | Raised when an opcode is not a valid instruction. -- The argument is the opcode that is unhandled. data UnknownOpcode = UnknownOpcode Opcode deriving (Typeable, Show) instance Exception UnknownOpcode -- | Raised when the type of an instruction doesn't have any meaning assigned to it. data UnknownOptype = UnknownOptype Optype deriving (Typeable, Show) instance Exception UnknownOptype -- | Raised when something is trying to access an invalid address. data InvalidAddress = InvalidAddress Address deriving (Typeable, Show) instance Exception InvalidAddress -- | Raised when something is trying to access an invalid register. data InvalidRegister = InvalidRegister Register deriving (Typeable, Show) instance Exception InvalidRegister -- | m ?-> e throws exception e when m is a Nothing, otherwise it returns the value in the Just. (?->) :: (Monad m, Exception e, Throws e l) => Maybe a -> e -> EMT l m a (?->) Nothing = throw (?->) (Just a) = const $ return a infixl 1 ?->
bennofs/haemu
src/Haemu/Exception.hs
gpl-3.0
1,200
0
8
194
253
145
108
21
1
-- | This module contains a data structure for RNAdistance output -- For more information on RNAdistance consult: <> module Bio.RNAdistanceData where -- | Data structure data RNAdistance = RNAdistance { secondaryStructureDistance :: Int } deriving (Show, Eq)
eggzilla/ViennaRNAParser
src/Bio/RNAdistanceData.hs
gpl-3.0
273
0
8
52
35
22
13
4
0
module HFlint.NF.Context where import HFlint.Utility.Prelude import Control.Exception.Safe ( MonadMask ) import Control.Monad.IO.Class ( MonadIO ) import HFlint.Internal.Context import HFlint.FMPQPoly import HFlint.NF.FFI type ReifiesNFContext ctxProxy = ReifiesFlintContext NFCtx ctxProxy withNFContext :: NFData b => FMPQPoly -> ( forall ctxProxy . ReifiesNFContext ctxProxy => Proxy ctxProxy -> b) -> b withNFContext = withFlintContextFromData NFCtxData withNFContextM :: ( MonadIO m, MonadMask m ) => FMPQPoly -> ( forall ctxProxy . ReifiesNFContext ctxProxy => Proxy ctxProxy -> m b) -> m b withNFContextM = withFlintContextFromDataM NFCtxData
martinra/hflint
src/HFlint/NF/Context.hs
gpl-3.0
700
0
12
133
179
99
80
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AccessContextManager.Organizations.GcpUserAccessBindings.Delete -- 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) -- -- Deletes a GcpUserAccessBinding. Completion of this long-running -- operation does not necessarily signify that the binding deletion is -- deployed onto all affected users, which may take more time. -- -- /See:/ <https://cloud.google.com/access-context-manager/docs/reference/rest/ Access Context Manager API Reference> for @accesscontextmanager.organizations.gcpUserAccessBindings.delete@. module Network.Google.Resource.AccessContextManager.Organizations.GcpUserAccessBindings.Delete ( -- * REST Resource OrganizationsGcpUserAccessBindingsDeleteResource -- * Creating a Request , organizationsGcpUserAccessBindingsDelete , OrganizationsGcpUserAccessBindingsDelete -- * Request Lenses , oguabdXgafv , oguabdUploadProtocol , oguabdAccessToken , oguabdUploadType , oguabdName , oguabdCallback ) where import Network.Google.AccessContextManager.Types import Network.Google.Prelude -- | A resource alias for @accesscontextmanager.organizations.gcpUserAccessBindings.delete@ method which the -- 'OrganizationsGcpUserAccessBindingsDelete' request conforms to. type OrganizationsGcpUserAccessBindingsDeleteResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Operation -- | Deletes a GcpUserAccessBinding. Completion of this long-running -- operation does not necessarily signify that the binding deletion is -- deployed onto all affected users, which may take more time. -- -- /See:/ 'organizationsGcpUserAccessBindingsDelete' smart constructor. data OrganizationsGcpUserAccessBindingsDelete = OrganizationsGcpUserAccessBindingsDelete' { _oguabdXgafv :: !(Maybe Xgafv) , _oguabdUploadProtocol :: !(Maybe Text) , _oguabdAccessToken :: !(Maybe Text) , _oguabdUploadType :: !(Maybe Text) , _oguabdName :: !Text , _oguabdCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OrganizationsGcpUserAccessBindingsDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oguabdXgafv' -- -- * 'oguabdUploadProtocol' -- -- * 'oguabdAccessToken' -- -- * 'oguabdUploadType' -- -- * 'oguabdName' -- -- * 'oguabdCallback' organizationsGcpUserAccessBindingsDelete :: Text -- ^ 'oguabdName' -> OrganizationsGcpUserAccessBindingsDelete organizationsGcpUserAccessBindingsDelete pOguabdName_ = OrganizationsGcpUserAccessBindingsDelete' { _oguabdXgafv = Nothing , _oguabdUploadProtocol = Nothing , _oguabdAccessToken = Nothing , _oguabdUploadType = Nothing , _oguabdName = pOguabdName_ , _oguabdCallback = Nothing } -- | V1 error format. oguabdXgafv :: Lens' OrganizationsGcpUserAccessBindingsDelete (Maybe Xgafv) oguabdXgafv = lens _oguabdXgafv (\ s a -> s{_oguabdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). oguabdUploadProtocol :: Lens' OrganizationsGcpUserAccessBindingsDelete (Maybe Text) oguabdUploadProtocol = lens _oguabdUploadProtocol (\ s a -> s{_oguabdUploadProtocol = a}) -- | OAuth access token. oguabdAccessToken :: Lens' OrganizationsGcpUserAccessBindingsDelete (Maybe Text) oguabdAccessToken = lens _oguabdAccessToken (\ s a -> s{_oguabdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). oguabdUploadType :: Lens' OrganizationsGcpUserAccessBindingsDelete (Maybe Text) oguabdUploadType = lens _oguabdUploadType (\ s a -> s{_oguabdUploadType = a}) -- | Required. Example: -- \"organizations\/256\/gcpUserAccessBindings\/b3-BhcX_Ud5N\" oguabdName :: Lens' OrganizationsGcpUserAccessBindingsDelete Text oguabdName = lens _oguabdName (\ s a -> s{_oguabdName = a}) -- | JSONP oguabdCallback :: Lens' OrganizationsGcpUserAccessBindingsDelete (Maybe Text) oguabdCallback = lens _oguabdCallback (\ s a -> s{_oguabdCallback = a}) instance GoogleRequest OrganizationsGcpUserAccessBindingsDelete where type Rs OrganizationsGcpUserAccessBindingsDelete = Operation type Scopes OrganizationsGcpUserAccessBindingsDelete = '["https://www.googleapis.com/auth/cloud-platform"] requestClient OrganizationsGcpUserAccessBindingsDelete'{..} = go _oguabdName _oguabdXgafv _oguabdUploadProtocol _oguabdAccessToken _oguabdUploadType _oguabdCallback (Just AltJSON) accessContextManagerService where go = buildClient (Proxy :: Proxy OrganizationsGcpUserAccessBindingsDeleteResource) mempty
brendanhay/gogol
gogol-accesscontextmanager/gen/Network/Google/Resource/AccessContextManager/Organizations/GcpUserAccessBindings/Delete.hs
mpl-2.0
5,818
0
15
1,179
700
411
289
108
1
-- | -- Module: SwiftNav.SBP.Tracking -- Copyright: Copyright (C) 2015 Swift Navigation, Inc. -- License: LGPL-3 -- Maintainer: Mark Fine <[email protected]> -- Stability: experimental -- Portability: portable -- -- Satellite code and carrier-phase tracking messages from the device. module SwiftNav.SBP.Tracking where import BasicPrelude import Control.Lens import Control.Monad.Loops import Data.Aeson.TH (deriveJSON, defaultOptions, fieldLabelModifier) import Data.Binary import Data.Binary.Get import Data.Binary.IEEE754 import Data.Binary.Put import Data.ByteString import Data.ByteString.Lazy hiding ( ByteString ) import Data.Int import Data.Word import SwiftNav.SBP.Encoding import SwiftNav.SBP.TH import SwiftNav.SBP.Types -- | TrackingChannelState. -- -- Tracking channel state for a specific satellite signal and measured signal -- power. data TrackingChannelState = TrackingChannelState { _trackingChannelState_state :: Word8 -- ^ Status of tracking channel , _trackingChannelState_sid :: SBPGnssSignal -- ^ GNSS signal being tracked , _trackingChannelState_cn0 :: Float -- ^ Carrier-to-noise density } deriving ( Show, Read, Eq ) instance Binary TrackingChannelState where get = do _trackingChannelState_state <- getWord8 _trackingChannelState_sid <- get _trackingChannelState_cn0 <- getFloat32le return TrackingChannelState {..} put TrackingChannelState {..} = do putWord8 _trackingChannelState_state put _trackingChannelState_sid putFloat32le _trackingChannelState_cn0 $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "_trackingChannelState_" . stripPrefix "_trackingChannelState_"} ''TrackingChannelState) $(makeLenses ''TrackingChannelState) msgTrackingState :: Word16 msgTrackingState = 0x0013 -- | SBP class for message MSG_TRACKING_STATE (0x0013). -- -- The tracking message returns a variable-length array of tracking channel -- states. It reports status and carrier-to-noise density measurements for all -- tracked satellites. data MsgTrackingState = MsgTrackingState { _msgTrackingState_states :: [TrackingChannelState] -- ^ Satellite tracking channel state } deriving ( Show, Read, Eq ) instance Binary MsgTrackingState where get = do _msgTrackingState_states <- whileM (liftM not isEmpty) get return MsgTrackingState {..} put MsgTrackingState {..} = do mapM_ put _msgTrackingState_states $(deriveSBP 'msgTrackingState ''MsgTrackingState) $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "_msgTrackingState_" . stripPrefix "_msgTrackingState_"} ''MsgTrackingState) $(makeLenses ''MsgTrackingState) -- | TrackingChannelCorrelation. -- -- Structure containing in-phase and quadrature correlation components. data TrackingChannelCorrelation = TrackingChannelCorrelation { _trackingChannelCorrelation_I :: Int32 -- ^ In-phase correlation , _trackingChannelCorrelation_Q :: Int32 -- ^ Quadrature correlation } deriving ( Show, Read, Eq ) instance Binary TrackingChannelCorrelation where get = do _trackingChannelCorrelation_I <- liftM fromIntegral getWord32le _trackingChannelCorrelation_Q <- liftM fromIntegral getWord32le return TrackingChannelCorrelation {..} put TrackingChannelCorrelation {..} = do putWord32le $ fromIntegral _trackingChannelCorrelation_I putWord32le $ fromIntegral _trackingChannelCorrelation_Q $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "_trackingChannelCorrelation_" . stripPrefix "_trackingChannelCorrelation_"} ''TrackingChannelCorrelation) $(makeLenses ''TrackingChannelCorrelation) msgTrackingIq :: Word16 msgTrackingIq = 0x001C -- | SBP class for message MSG_TRACKING_IQ (0x001C). -- -- When enabled, a tracking channel can output the correlations at each update -- interval. data MsgTrackingIq = MsgTrackingIq { _msgTrackingIq_channel :: Word8 -- ^ Tracking channel of origin , _msgTrackingIq_sid :: SBPGnssSignal -- ^ GNSS signal identifier , _msgTrackingIq_corrs :: [TrackingChannelCorrelation] -- ^ Early, Prompt and Late correlations } deriving ( Show, Read, Eq ) instance Binary MsgTrackingIq where get = do _msgTrackingIq_channel <- getWord8 _msgTrackingIq_sid <- get _msgTrackingIq_corrs <- replicateM 3 get return MsgTrackingIq {..} put MsgTrackingIq {..} = do putWord8 _msgTrackingIq_channel put _msgTrackingIq_sid mapM_ put _msgTrackingIq_corrs $(deriveSBP 'msgTrackingIq ''MsgTrackingIq) $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "_msgTrackingIq_" . stripPrefix "_msgTrackingIq_"} ''MsgTrackingIq) $(makeLenses ''MsgTrackingIq) -- | TrackingChannelStateDepA. -- -- Deprecated. data TrackingChannelStateDepA = TrackingChannelStateDepA { _trackingChannelStateDepA_state :: Word8 -- ^ Status of tracking channel , _trackingChannelStateDepA_prn :: Word8 -- ^ PRN-1 being tracked , _trackingChannelStateDepA_cn0 :: Float -- ^ Carrier-to-noise density } deriving ( Show, Read, Eq ) instance Binary TrackingChannelStateDepA where get = do _trackingChannelStateDepA_state <- getWord8 _trackingChannelStateDepA_prn <- getWord8 _trackingChannelStateDepA_cn0 <- getFloat32le return TrackingChannelStateDepA {..} put TrackingChannelStateDepA {..} = do putWord8 _trackingChannelStateDepA_state putWord8 _trackingChannelStateDepA_prn putFloat32le _trackingChannelStateDepA_cn0 $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "_trackingChannelStateDepA_" . stripPrefix "_trackingChannelStateDepA_"} ''TrackingChannelStateDepA) $(makeLenses ''TrackingChannelStateDepA) msgTrackingStateDepA :: Word16 msgTrackingStateDepA = 0x0016 -- | SBP class for message MSG_TRACKING_STATE_DEP_A (0x0016). -- -- Deprecated. data MsgTrackingStateDepA = MsgTrackingStateDepA { _msgTrackingStateDepA_states :: [TrackingChannelStateDepA] -- ^ Satellite tracking channel state } deriving ( Show, Read, Eq ) instance Binary MsgTrackingStateDepA where get = do _msgTrackingStateDepA_states <- whileM (liftM not isEmpty) get return MsgTrackingStateDepA {..} put MsgTrackingStateDepA {..} = do mapM_ put _msgTrackingStateDepA_states $(deriveSBP 'msgTrackingStateDepA ''MsgTrackingStateDepA) $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "_msgTrackingStateDepA_" . stripPrefix "_msgTrackingStateDepA_"} ''MsgTrackingStateDepA) $(makeLenses ''MsgTrackingStateDepA)
mookerji/libsbp
haskell/src/SwiftNav/SBP/Tracking.hs
lgpl-3.0
6,532
0
11
1,010
1,172
612
560
-1
-1
import Test.Hspec import Test.QuickCheck import Control.Exception (evaluate) import FizzBuzz main :: IO() main = hspec $ do describe "fizzBuzzer" $ do context "when is not divisible by 3 or 5" $ do it "returns the number" $ do fizzBuzzer 1 `shouldBe` "1" context "when is divisible by 3" $ do it "returns Fizz" $ do fizzBuzzer 3 `shouldBe` "Fizz" context "when is divisible by 5" $ do it "returns Buzz" $ do fizzBuzzer 5 `shouldBe` "Buzz" context "when is divisible by both" $ do it "returns FizzBuzz" $ do fizzBuzzer 15 `shouldBe`"FizzBuzz"
arthurms/tw-coding-dojo
test/FizzBuzzSpec.hs
apache-2.0
621
0
18
171
181
84
97
19
1
loop context n = do send context $ do clearRect (0,0,width context,height context) beginPath() save() translate (width context / 2,height context / 2) rotate (pi * n) beginPath() moveTo(-100,-100) lineTo(-100,100) lineTo(100,100) lineTo(100,-100) closePath() lineWidth 10 strokeStyle "green" stroke() restore() threadDelay (20 * 1000) loop context (n + 0.01)
ku-fpg/talks
blank-canvas/examples/RotatingTile.hs
bsd-2-clause
492
0
13
181
228
102
126
19
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.AmountOfMoney.EN.NZ.Rules ( rules ) where import Data.HashMap.Strict (HashMap) import Data.String import Data.Text (Text) import Prelude import Duckling.AmountOfMoney.Helpers import Duckling.AmountOfMoney.Types (Currency(..)) import Duckling.Numeral.Helpers (isPositive) import Duckling.Regex.Types import Duckling.Types import qualified Data.HashMap.Strict as HashMap import qualified Data.Text as Text import qualified Duckling.AmountOfMoney.Helpers as Helpers import qualified Duckling.Numeral.Types as TNumeral ruleAGrand :: Rule ruleAGrand = Rule { name = "a grand" , pattern = [ regex "a grand" ] , prod = \_ -> Just . Token AmountOfMoney . withValue 1000 $ currencyOnly NZD } ruleGrand :: Rule ruleGrand = Rule { name = "<amount> grand" , pattern = [ Predicate isPositive , regex "grand" ] , prod = \case (Token Numeral TNumeral.NumeralData{TNumeral.value = v}:_) -> Just . Token AmountOfMoney . withValue (1000 * v) $ currencyOnly NZD _ -> Nothing } ruleDollarCoin :: Rule ruleDollarCoin = Rule { name = "dollar coin" , pattern = [ regex "(nickel|dime|quarter)s?" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> do c <- HashMap.lookup (Text.toLower match) Helpers.dollarCoins Just . Token AmountOfMoney . withValue c $ currencyOnly NZD _ -> Nothing } rules :: [Rule] rules = [ ruleAGrand , ruleGrand , ruleDollarCoin ]
facebookincubator/duckling
Duckling/AmountOfMoney/EN/NZ/Rules.hs
bsd-3-clause
1,819
0
17
390
452
264
188
51
2
module Owl.Service.API.Internal.Res where import Control.Applicative ((<$>),(<*>)) import Control.Monad (mzero) import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as LB data OwlRes = OwlRes { cipher :: LB.ByteString } instance FromJSON OwlRes where parseJSON (Object o) = OwlRes <$> o .: "cipher" parseJSON _ = mzero instance ToJSON OwlRes where toJSON (OwlRes e) = object [ "cipher" .= e ]
cutsea110/owl-api
Owl/Service/API/Internal/Res.hs
bsd-3-clause
410
0
9
64
138
81
57
11
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TemplateHaskell #-} -- | Types shared by many modules in this application. module TauSigma.Types ( Domain(..) , TimeData , FreqData , Tagged(..) , TauSigma(..) , tau , sigma , Scale(..) , toScale , fromScale ) where import Control.Applicative import Control.Lens (makeLenses) import Data.Tagged import Data.Semigroup (Semigroup(..), Min(..), Max(..)) import qualified Data.Vector.Generic as G import Data.Csv import TauSigma.Statistics.Types (Tau, Sigma) data Domain = Phase | Frequency deriving Read -- | A tagged type to represent time domain data values, to avoid mixing -- them up with frequency domain data. type TimeData = Tagged 'Phase -- | A newtype to represent frequency domain data values, to avoid -- mixing them up with time domain data. type FreqData = Tagged 'Frequency -- | A tau/sigma pair. data TauSigma = TauSigma { _tau :: !(Tau Double), _sigma :: !(Sigma Double) } $(makeLenses ''TauSigma) instance FromRecord TauSigma where parseRecord v | G.length v == 2 = TauSigma <$> v.! 0 <*> v .! 1 | otherwise = empty; instance FromNamedRecord TauSigma where parseNamedRecord m = TauSigma <$> m .: "tau" <*> m .: "sigma" instance ToRecord TauSigma where toRecord (TauSigma tau sigma) = record [toField tau, toField sigma] instance ToNamedRecord TauSigma where toNamedRecord (TauSigma tau sigma) = namedRecord ["tau" .= tau, "sigma" .= sigma] -- | A 'Semigroup' for computing the scale of a non-empty set of -- values. By scale we mean the difference between the largest value -- and the smallest. data Scale a = Scale (Min a) (Max a) toScale :: a -> Scale a toScale a = Scale (Min a) (Max a) fromScale :: Num a => Scale a -> a fromScale (Scale (Min a) (Max b)) = b - a instance Ord a => Semigroup (Scale a) where Scale a b <> Scale c d = Scale (a <> c) (b <> d)
sacundim/tau-sigma
src/TauSigma/Types.hs
bsd-3-clause
2,052
0
11
476
567
312
255
50
1
{-# LANGUAGE RecordWildCards #-} -- | DSL for testing the modular solver module UnitTests.Distribution.Solver.Modular.DSL ( ExampleDependency(..) , Dependencies(..) , ExTest(..) , ExPreference(..) , ExampleDb , ExampleVersionRange , ExamplePkgVersion , ExamplePkgName , ExampleAvailable(..) , ExampleInstalled(..) , ExampleQualifier(..) , ExampleVar(..) , exAv , exInst , exFlag , exResolve , extractInstallPlan , withSetupDeps , withTest , withTests ) where -- base import Data.Either (partitionEithers) import Data.Maybe (catMaybes, isNothing) import Data.List (elemIndex, nub) import Data.Monoid import Data.Ord (comparing) import Data.Version import qualified Data.Map as Map -- Cabal import qualified Distribution.Compiler as C import qualified Distribution.InstalledPackageInfo as C import qualified Distribution.Package as C hiding (HasUnitId(..)) import qualified Distribution.PackageDescription as C import qualified Distribution.Simple.PackageIndex as C.PackageIndex import qualified Distribution.System as C import qualified Distribution.Version as C import Language.Haskell.Extension (Extension(..), Language) -- cabal-install import Distribution.Client.Dependency import Distribution.Client.Dependency.Types import Distribution.Client.Types import qualified Distribution.Client.InstallPlan as CI.InstallPlan import Distribution.Solver.Types.ComponentDeps (ComponentDeps) import qualified Distribution.Solver.Types.ComponentDeps as CD import Distribution.Solver.Types.ConstraintSource import Distribution.Solver.Types.LabeledPackageConstraint import Distribution.Solver.Types.OptionalStanza import qualified Distribution.Solver.Types.PackageIndex as CI.PackageIndex import qualified Distribution.Solver.Types.PackagePath as P import qualified Distribution.Solver.Types.PkgConfigDb as PC import Distribution.Solver.Types.Settings import Distribution.Solver.Types.SolverPackage import Distribution.Solver.Types.SourcePackage import Distribution.Solver.Types.Variable {------------------------------------------------------------------------------- Example package database DSL In order to be able to set simple examples up quickly, we define a very simple version of the package database here explicitly designed for use in tests. The design of `ExampleDb` takes the perspective of the solver, not the perspective of the package DB. This makes it easier to set up tests for various parts of the solver, but makes the mapping somewhat awkward, because it means we first map from "solver perspective" `ExampleDb` to the package database format, and then the modular solver internally in `IndexConversion` maps this back to the solver specific data structures. IMPLEMENTATION NOTES -------------------- TODO: Perhaps these should be made comments of the corresponding data type definitions. For now these are just my own conclusions and may be wrong. * The difference between `GenericPackageDescription` and `PackageDescription` is that `PackageDescription` describes a particular _configuration_ of a package (for instance, see documentation for `checkPackage`). A `GenericPackageDescription` can be turned into a `PackageDescription` in two ways: a. `finalizePackageDescription` does the proper translation, by taking into account the platform, available dependencies, etc. and picks a flag assignment (or gives an error if no flag assignment can be found) b. `flattenPackageDescription` ignores flag assignment and just joins all components together. The slightly odd thing is that a `GenericPackageDescription` contains a `PackageDescription` as a field; both of the above functions do the same thing: they take the embedded `PackageDescription` as a basis for the result value, but override `library`, `executables`, `testSuites`, `benchmarks` and `buildDepends`. * The `condTreeComponents` fields of a `CondTree` is a list of triples `(condition, then-branch, else-branch)`, where the `else-branch` is optional. -------------------------------------------------------------------------------} type ExamplePkgName = String type ExamplePkgVersion = Int type ExamplePkgHash = String -- for example "installed" packages type ExampleFlagName = String type ExampleTestName = String type ExampleVersionRange = C.VersionRange data Dependencies = NotBuildable | Buildable [ExampleDependency] deriving Show data ExampleDependency = -- | Simple dependency on any version ExAny ExamplePkgName -- | Simple dependency on a fixed version | ExFix ExamplePkgName ExamplePkgVersion -- | Dependencies indexed by a flag | ExFlag ExampleFlagName Dependencies Dependencies -- | Dependency on a language extension | ExExt Extension -- | Dependency on a language version | ExLang Language -- | Dependency on a pkg-config package | ExPkg (ExamplePkgName, ExamplePkgVersion) deriving Show data ExTest = ExTest ExampleTestName [ExampleDependency] exFlag :: ExampleFlagName -> [ExampleDependency] -> [ExampleDependency] -> ExampleDependency exFlag n t e = ExFlag n (Buildable t) (Buildable e) data ExPreference = ExPref String ExampleVersionRange data ExampleAvailable = ExAv { exAvName :: ExamplePkgName , exAvVersion :: ExamplePkgVersion , exAvDeps :: ComponentDeps [ExampleDependency] } deriving Show data ExampleVar = P ExampleQualifier ExamplePkgName | F ExampleQualifier ExamplePkgName ExampleFlagName | S ExampleQualifier ExamplePkgName OptionalStanza data ExampleQualifier = None | Indep Int | Setup ExamplePkgName | IndepSetup Int ExamplePkgName -- | Constructs an 'ExampleAvailable' package for the 'ExampleDb', -- given: -- -- 1. The name 'ExamplePkgName' of the available package, -- 2. The version 'ExamplePkgVersion' available -- 3. The list of dependency constraints 'ExampleDependency' -- that this package has. 'ExampleDependency' provides -- a number of pre-canned dependency types to look at. -- exAv :: ExamplePkgName -> ExamplePkgVersion -> [ExampleDependency] -> ExampleAvailable exAv n v ds = ExAv { exAvName = n, exAvVersion = v , exAvDeps = CD.fromLibraryDeps n ds } withSetupDeps :: ExampleAvailable -> [ExampleDependency] -> ExampleAvailable withSetupDeps ex setupDeps = ex { exAvDeps = exAvDeps ex <> CD.fromSetupDeps setupDeps } withTest :: ExampleAvailable -> ExTest -> ExampleAvailable withTest ex test = withTests ex [test] withTests :: ExampleAvailable -> [ExTest] -> ExampleAvailable withTests ex tests = let testCDs = CD.fromList [(CD.ComponentTest name, deps) | ExTest name deps <- tests] in ex { exAvDeps = exAvDeps ex <> testCDs } -- | An installed package in 'ExampleDb'; construct me with 'exInst'. data ExampleInstalled = ExInst { exInstName :: ExamplePkgName , exInstVersion :: ExamplePkgVersion , exInstHash :: ExamplePkgHash , exInstBuildAgainst :: [ExamplePkgHash] } deriving Show -- | Constructs an example installed package given: -- -- 1. The name of the package 'ExamplePkgName', i.e., 'String' -- 2. The version of the package 'ExamplePkgVersion', i.e., 'Int' -- 3. The IPID for the package 'ExamplePkgHash', i.e., 'String' -- (just some unique identifier for the package.) -- 4. The 'ExampleInstalled' packages which this package was -- compiled against.) -- exInst :: ExamplePkgName -> ExamplePkgVersion -> ExamplePkgHash -> [ExampleInstalled] -> ExampleInstalled exInst pn v hash deps = ExInst pn v hash (map exInstHash deps) -- | An example package database is a list of installed packages -- 'ExampleInstalled' and available packages 'ExampleAvailable'. -- Generally, you want to use 'exInst' and 'exAv' to construct -- these packages. type ExampleDb = [Either ExampleInstalled ExampleAvailable] type DependencyTree a = C.CondTree C.ConfVar [C.Dependency] a exDbPkgs :: ExampleDb -> [ExamplePkgName] exDbPkgs = map (either exInstName exAvName) exAvSrcPkg :: ExampleAvailable -> UnresolvedSourcePackage exAvSrcPkg ex = let (libraryDeps, exts, mlang, pcpkgs) = splitTopLevel (CD.libraryDeps (exAvDeps ex)) testSuites = [(name, deps) | (CD.ComponentTest name, deps) <- CD.toList (exAvDeps ex)] in SourcePackage { packageInfoId = exAvPkgId ex , packageSource = LocalTarballPackage "<<path>>" , packageDescrOverride = Nothing , packageDescription = C.GenericPackageDescription { C.packageDescription = C.emptyPackageDescription { C.package = exAvPkgId ex , C.libraries = error "not yet configured: library" , C.executables = error "not yet configured: executables" , C.testSuites = error "not yet configured: testSuites" , C.benchmarks = error "not yet configured: benchmarks" , C.buildDepends = error "not yet configured: buildDepends" , C.setupBuildInfo = Just C.SetupBuildInfo { C.setupDepends = mkSetupDeps (CD.setupDeps (exAvDeps ex)), C.defaultSetupDepends = False } } , C.genPackageFlags = nub $ concatMap extractFlags $ CD.libraryDeps (exAvDeps ex) ++ concatMap snd testSuites , C.condLibraries = [(exAvName ex, mkCondTree (extsLib exts <> langLib mlang <> pcpkgLib pcpkgs) disableLib (Buildable libraryDeps))] , C.condExecutables = [] , C.condTestSuites = let mkTree = mkCondTree mempty disableTest . Buildable in map (\(t, deps) -> (t, mkTree deps)) testSuites , C.condBenchmarks = [] } } where -- Split the set of dependencies into the set of dependencies of the library, -- the dependencies of the test suites and extensions. splitTopLevel :: [ExampleDependency] -> ( [ExampleDependency] , [Extension] , Maybe Language , [(ExamplePkgName, ExamplePkgVersion)] -- pkg-config ) splitTopLevel [] = ([], [], Nothing, []) splitTopLevel (ExExt ext:deps) = let (other, exts, lang, pcpkgs) = splitTopLevel deps in (other, ext:exts, lang, pcpkgs) splitTopLevel (ExLang lang:deps) = case splitTopLevel deps of (other, exts, Nothing, pcpkgs) -> (other, exts, Just lang, pcpkgs) _ -> error "Only 1 Language dependency is supported" splitTopLevel (ExPkg pkg:deps) = let (other, exts, lang, pcpkgs) = splitTopLevel deps in (other, exts, lang, pkg:pcpkgs) splitTopLevel (dep:deps) = let (other, exts, lang, pcpkgs) = splitTopLevel deps in (dep:other, exts, lang, pcpkgs) -- Extract the total set of flags used extractFlags :: ExampleDependency -> [C.Flag] extractFlags (ExAny _) = [] extractFlags (ExFix _ _) = [] extractFlags (ExFlag f a b) = C.MkFlag { C.flagName = C.FlagName f , C.flagDescription = "" , C.flagDefault = True , C.flagManual = False } : concatMap extractFlags (deps a ++ deps b) where deps :: Dependencies -> [ExampleDependency] deps NotBuildable = [] deps (Buildable ds) = ds extractFlags (ExExt _) = [] extractFlags (ExLang _) = [] extractFlags (ExPkg _) = [] mkCondTree :: Monoid a => a -> (a -> a) -> Dependencies -> DependencyTree a mkCondTree x dontBuild NotBuildable = C.CondNode { C.condTreeData = dontBuild x , C.condTreeConstraints = [] , C.condTreeComponents = [] } mkCondTree x dontBuild (Buildable deps) = let (directDeps, flaggedDeps) = splitDeps deps in C.CondNode { C.condTreeData = x -- Necessary for language extensions , C.condTreeConstraints = map mkDirect directDeps , C.condTreeComponents = map (mkFlagged dontBuild) flaggedDeps } mkDirect :: (ExamplePkgName, Maybe ExamplePkgVersion) -> C.Dependency mkDirect (dep, Nothing) = C.Dependency (C.PackageName dep) C.anyVersion mkDirect (dep, Just n) = C.Dependency (C.PackageName dep) (C.thisVersion v) where v = Version [n, 0, 0] [] mkFlagged :: Monoid a => (a -> a) -> (ExampleFlagName, Dependencies, Dependencies) -> (C.Condition C.ConfVar , DependencyTree a, Maybe (DependencyTree a)) mkFlagged dontBuild (f, a, b) = ( C.Var (C.Flag (C.FlagName f)) , mkCondTree mempty dontBuild a , Just (mkCondTree mempty dontBuild b) ) -- Split a set of dependencies into direct dependencies and flagged -- dependencies. A direct dependency is a tuple of the name of package and -- maybe its version (no version means any version) meant to be converted -- to a 'C.Dependency' with 'mkDirect' for example. A flagged dependency is -- the set of dependencies guarded by a flag. -- -- TODO: Take care of flagged language extensions and language flavours. splitDeps :: [ExampleDependency] -> ( [(ExamplePkgName, Maybe Int)] , [(ExampleFlagName, Dependencies, Dependencies)] ) splitDeps [] = ([], []) splitDeps (ExAny p:deps) = let (directDeps, flaggedDeps) = splitDeps deps in ((p, Nothing):directDeps, flaggedDeps) splitDeps (ExFix p v:deps) = let (directDeps, flaggedDeps) = splitDeps deps in ((p, Just v):directDeps, flaggedDeps) splitDeps (ExFlag f a b:deps) = let (directDeps, flaggedDeps) = splitDeps deps in (directDeps, (f, a, b):flaggedDeps) splitDeps (_:deps) = splitDeps deps -- Currently we only support simple setup dependencies mkSetupDeps :: [ExampleDependency] -> [C.Dependency] mkSetupDeps deps = let (directDeps, []) = splitDeps deps in map mkDirect directDeps -- A 'C.Library' with just the given extensions in its 'BuildInfo' extsLib :: [Extension] -> C.Library extsLib es = mempty { C.libBuildInfo = mempty { C.otherExtensions = es } } -- A 'C.Library' with just the given extensions in its 'BuildInfo' langLib :: Maybe Language -> C.Library langLib (Just lang) = mempty { C.libBuildInfo = mempty { C.defaultLanguage = Just lang } } langLib _ = mempty disableLib :: C.Library -> C.Library disableLib lib = lib { C.libBuildInfo = (C.libBuildInfo lib) { C.buildable = False }} disableTest :: C.TestSuite -> C.TestSuite disableTest test = test { C.testBuildInfo = (C.testBuildInfo test) { C.buildable = False }} -- A 'C.Library' with just the given pkgconfig-depends in its 'BuildInfo' pcpkgLib :: [(ExamplePkgName, ExamplePkgVersion)] -> C.Library pcpkgLib ds = mempty { C.libBuildInfo = mempty { C.pkgconfigDepends = [mkDirect (n, (Just v)) | (n,v) <- ds] } } exAvPkgId :: ExampleAvailable -> C.PackageIdentifier exAvPkgId ex = C.PackageIdentifier { pkgName = C.PackageName (exAvName ex) , pkgVersion = Version [exAvVersion ex, 0, 0] [] } exInstInfo :: ExampleInstalled -> C.InstalledPackageInfo exInstInfo ex = C.emptyInstalledPackageInfo { C.installedUnitId = C.mkUnitId (exInstHash ex) , C.sourcePackageId = exInstPkgId ex , C.depends = map C.mkUnitId (exInstBuildAgainst ex) } exInstPkgId :: ExampleInstalled -> C.PackageIdentifier exInstPkgId ex = C.PackageIdentifier { pkgName = C.PackageName (exInstName ex) , pkgVersion = Version [exInstVersion ex, 0, 0] [] } exAvIdx :: [ExampleAvailable] -> CI.PackageIndex.PackageIndex UnresolvedSourcePackage exAvIdx = CI.PackageIndex.fromList . map exAvSrcPkg exInstIdx :: [ExampleInstalled] -> C.PackageIndex.InstalledPackageIndex exInstIdx = C.PackageIndex.fromList . map exInstInfo exResolve :: ExampleDb -- List of extensions supported by the compiler, or Nothing if unknown. -> Maybe [Extension] -- List of languages supported by the compiler, or Nothing if unknown. -> Maybe [Language] -> PC.PkgConfigDb -> [ExamplePkgName] -> Solver -> Maybe Int -> IndependentGoals -> ReorderGoals -> EnableBackjumping -> Maybe [ExampleVar] -> [ExPreference] -> ([String], Either String CI.InstallPlan.SolverInstallPlan) exResolve db exts langs pkgConfigDb targets solver mbj indepGoals reorder enableBj vars prefs = runProgress $ resolveDependencies C.buildPlatform compiler pkgConfigDb solver params where defaultCompiler = C.unknownCompilerInfo C.buildCompilerId C.NoAbiTag compiler = defaultCompiler { C.compilerInfoExtensions = exts , C.compilerInfoLanguages = langs } (inst, avai) = partitionEithers db instIdx = exInstIdx inst avaiIdx = SourcePackageDb { packageIndex = exAvIdx avai , packagePreferences = Map.empty } enableTests = fmap (\p -> PackageConstraintStanzas (C.PackageName p) [TestStanzas]) (exDbPkgs db) targets' = fmap (\p -> NamedPackage (C.PackageName p) []) targets params = addPreferences (fmap toPref prefs) $ addConstraints (fmap toLpc enableTests) $ setIndependentGoals indepGoals $ setReorderGoals reorder $ setMaxBackjumps mbj $ setEnableBackjumping enableBj $ setGoalOrder goalOrder $ standardInstallPolicy instIdx avaiIdx targets' toLpc pc = LabeledPackageConstraint pc ConstraintSourceUnknown toPref (ExPref n v) = PackageVersionPreference (C.PackageName n) v goalOrder :: Maybe (Variable P.QPN -> Variable P.QPN -> Ordering) goalOrder = (orderFromList . map toVariable) `fmap` vars -- Sort elements in the list ahead of elements not in the list. Otherwise, -- follow the order in the list. orderFromList :: Eq a => [a] -> a -> a -> Ordering orderFromList xs = comparing $ \x -> let i = elemIndex x xs in (isNothing i, i) toVariable :: ExampleVar -> Variable P.QPN toVariable (P q pn) = PackageVar (toQPN q pn) toVariable (F q pn fn) = FlagVar (toQPN q pn) (C.FlagName fn) toVariable (S q pn stanza) = StanzaVar (toQPN q pn) stanza toQPN :: ExampleQualifier -> ExamplePkgName -> P.QPN toQPN q pn = P.Q pp (C.PackageName pn) where pp = case q of None -> P.PackagePath P.DefaultNamespace P.Unqualified Indep x -> P.PackagePath (P.Independent x) P.Unqualified Setup p -> P.PackagePath P.DefaultNamespace (P.Setup (C.PackageName p)) IndepSetup x p -> P.PackagePath (P.Independent x) (P.Setup (C.PackageName p)) extractInstallPlan :: CI.InstallPlan.SolverInstallPlan -> [(ExamplePkgName, ExamplePkgVersion)] extractInstallPlan = catMaybes . map confPkg . CI.InstallPlan.toList where confPkg :: CI.InstallPlan.SolverPlanPackage -> Maybe (String, Int) confPkg (CI.InstallPlan.Configured pkg) = Just $ srcPkg pkg confPkg _ = Nothing srcPkg :: SolverPackage UnresolvedPkgLoc -> (String, Int) srcPkg cpkg = let C.PackageIdentifier (C.PackageName p) (Version (n:_) _) = packageInfoId (solverPkgSource cpkg) in (p, n) {------------------------------------------------------------------------------- Auxiliary -------------------------------------------------------------------------------} -- | Run Progress computation -- -- Like `runLog`, but for the more general `Progress` type. runProgress :: Progress step e a -> ([step], Either e a) runProgress = go where go (Step s p) = let (ss, result) = go p in (s:ss, result) go (Fail e) = ([], Left e) go (Done a) = ([], Right a)
thomie/cabal
cabal-install/tests/UnitTests/Distribution/Solver/Modular/DSL.hs
bsd-3-clause
21,040
0
20
5,657
4,470
2,476
1,994
325
19
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-} module Oracles.WindowsRoot ( windowsRoot, fixAbsolutePathOnWindows, topDirectory, windowsRootOracle ) where import Data.Char (isSpace) import Base import Oracles.Config.Setting newtype WindowsRoot = WindowsRoot () deriving (Show, Typeable, Eq, Hashable, Binary, NFData) -- Looks up cygwin/msys root on Windows windowsRoot :: Action String windowsRoot = askOracle $ WindowsRoot () topDirectory :: Action FilePath topDirectory = do ghcSourcePath <- setting GhcSourcePath fixAbsolutePathOnWindows ghcSourcePath -- TODO: this is fragile, e.g. we currently only handle C: drive -- On Windows: -- * if the path starts with "/c/" change the prefix to "C:/" -- * otherwise, if the path starts with "/", prepend it with the correct path -- to the root, e.g: "/usr/local/bin/ghc.exe" => "C:/msys/usr/local/bin/ghc.exe" fixAbsolutePathOnWindows :: FilePath -> Action FilePath fixAbsolutePathOnWindows path = do windows <- windowsHost -- Note, below is different from FilePath.isAbsolute: if (windows && "/" `isPrefixOf` path) then do if ("/c/" `isPrefixOf` path) then return $ "C:" ++ drop 2 path else do root <- windowsRoot return . unifyPath $ root ++ drop 1 path else return path -- Oracle for windowsRoot. This operation requires caching as looking up -- the root is slow (at least the current implementation). windowsRootOracle :: Rules () windowsRootOracle = do root <- newCache $ \_ -> do Stdout out <- quietly $ cmd ["cygpath", "-m", "/"] let root = dropWhileEnd isSpace out putOracle $ "Detected root on Windows: " ++ root return root _ <- addOracle $ \WindowsRoot{} -> root () return ()
quchen/shaking-up-ghc
src/Oracles/WindowsRoot.hs
bsd-3-clause
1,796
0
15
388
372
194
178
34
3
{-# LANGUAGE ScopedTypeVariables, BangPatterns #-} {-# LANGUAGE ExistentialQuantification #-} module ECC.Types ( -- * Types ECC(..), Code(..), BEs, -- abstract Log(..), -- * Type Synonyms MessageLength, CodewordLength, Rate, EbN0, -- * 'ECC' function rateOf, -- * 'BEs' functions sumBEs, sizeBEs, eventBEs, extractBEs, -- * General Utils hard, soft, bitErrorRate ) where import Control.Monad import Data.List (unfoldr, transpose) import Data.Monoid import qualified Data.Vector.Unboxed as U import Data.Ratio import Control.Arrow ----------------------------------------------------------------------------- -- Regarding Common Synomyns type MessageLength = Int -- the size of the message type CodewordLength = Int -- the size of the message + parity bits type Rate = Ratio Int -- message size / codeword size type EbN0 = Double -- noise ----------------------------------------------------------------------------- -- Regarding ECC -- -- | Basic structure of an forward error-checking code. -- -- Law(s): -- -- > (encode >>= fmap hard >>= decode) == return -- -- * length of input to encode, and output of decode == message_length -- -- * length of output to encode, and input of decode == codeword_length -- data ECC m = ECC { name :: String -- ^ name for the output printer only. The name should have no spaces , encode :: U.Vector Bool -> m (U.Vector Bool) -- ^ encoded a 'MessageLength' list of bits into a 'CodewordLength' set of bits. , decode :: U.Vector Double -> m (U.Vector Bool,Bool) -- ^ decoding a codeword into a message, -- along with a parity flag (True = parity or unknown (assume good), False = bad parity) , message_length :: MessageLength -- ^ The length, in bits, of the message (the thing to be sent) , codeword_length :: CodewordLength -- length of w -- ^ The length, in bits, of the codeword (the thing that is sent over the air, inc. parity bits) } -- | compute the rate of an 'ECC'. rateOf :: ECC IO -> Ratio Int rateOf ecc = message_length ecc % codeword_length ecc ----------------------------------------------------------------------------- -- Regarding Code -- | Code is an encaptuation of an 'ECC' builder. -- It has a list/description of possible codes, -- and a mapping from expanded code-name (/ is the seperator), -- to possible 'EEC's. data Code = forall vars. Code [String] (IO vars) (vars -> IO ()) (vars -> [String] -> IO [ECC IO]) instance Show Code where show (Code codes _ _ _) = show codes instance Monoid Code where mempty = Code [] (return ()) (const (return ())) $ \ _ _ -> return [] mappend (Code !c1 !init1 !finalize1 !f1) (Code !c2 !init2 !finalize2 !f2) = Code (c1 ++ c2) (liftM2 (,) init1 init2) (\ !(vars1, vars2) -> finalize1 vars1 *> finalize2 vars2) $ \ !(vars1, vars2) xs -> liftM2 (++) (f1 vars1 xs) (f2 vars2 xs) ----------------------------------------------------------------------------- -- Regarding Bit Errors (BEs) -- | 'BEs' is a summary of bit errors in multiple runs. -- For example -- * bit errors: 0 | 1 | 2 | 3 -- * # packets: 97 | 0 | 1 | 2 -- means there were 97 runs that were perfect, one run that had 2 bit errors, -- and 2 runs that had 3 bit errors. In Haskell, BEs [97,0,1,2] data BEs = BEs ![Int] deriving (Read, Show) -- A space efficent version of instance Monoid BEs where mempty = BEs [] mappend (BEs xs) (BEs ys) = BEs $! f xs ys where f (x:xs) (y:ys) = (x + y) `cons` f xs ys f xs [] = xs f [] ys = ys cons !x !ys = x : ys -- | The total numbers of bit errors sumBEs :: BEs -> Int sumBEs (BEs xs) = sum [ n * i | (n,i) <- xs `zip` [0..]] -- | The number of samples that have been run. sizeBEs :: BEs -> Int sizeBEs (BEs xs) = sum xs -- | Extract all the packet bit errors. extractBEs :: BEs -> [Double] extractBEs b@(BEs bes) = expand 0 bes where expand i [] = [] expand i (x:xs) = take x (repeat i) ++ expand (i+1) xs -- | turn an event with a specific number of bit errors (possibly 0), -- and give a singleton 'BEs'. eventBEs :: Int -> BEs eventBEs n = BEs $ take n (repeat 0) ++ [1] {- -- for +ve ints prop_ECCBERS (xs :: [Int]) = sum xs == sumBEs (mconcat (map eventBEs xs)) -} ----------------------------------------------------------------------------- -- Regarding Bit. -- | turn a soft value into a hard value. hard :: (Num a, Ord a) => a -> Bool hard = (> 0) -- | turn a hard value into a soft value. soft :: (Num a) => Bool -> a soft False = -1 soft True = 1 -- | compute the bit error rate inside a 'BEs', for a specific 'ECC'. bitErrorRate :: ECC f -> BEs -> Double bitErrorRate ecc bes = fromIntegral (sumBEs bes) / (fromIntegral (sizeBEs bes * message_length ecc)) -------------------------------------------- -- A serializable log. data Log = Message (U.Vector Bool) -- the unencoded packet | TxCodeword (U.Vector Bool) -- the encoded packet | RxCodeword EbN0 (U.Vector Double) -- the encoded packet, after rx/tx (the soft value has lc multiplied in) | Decoded String (U.Vector Bool) -- the packet after decoding (should be the same as the Message) deriving (Read,Show)
ku-fpg/ecc-manifold
src/ECC/Types.hs
bsd-3-clause
5,630
2
13
1,535
1,182
661
521
83
2
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} module Day10 where import qualified Data.List as List import qualified Data.Map as Map import Data.Map (Map) import Data.Maybe import Text.Parsec hiding (State) type Parser = Parsec String () data Destination = Bot Int | Output Int deriving (Show) data Compare = Compare { low :: Destination , high :: Destination } deriving (Show) data Instruction = Value Int Int | Edges Int Compare deriving (Show) bot :: Parser Int bot = read <$ string "bot " <*> many1 digit value :: Parser Int value = read <$ string "value " <*> many1 digit destBot :: Parser Destination destBot = Bot <$> bot output :: Parser Destination output = (Output . read) <$ string "output " <*> many1 digit destination = try destBot <|> output edges :: Parser Instruction edges = mkCompare <$> bot <* string " gives low to " <*> destination <* string " and high to " <*> destination where mkCompare from lo hi = Edges from (Compare lo hi) fromDest :: Destination -> Int fromDest = \case Bot x -> x Output x -> x valueGoes :: Parser Instruction valueGoes = Value <$> value <* string " goes to " <*> bot instruction :: Parser Instruction instruction = try edges <|> valueGoes parse' s = either (error . show) id $ parse instruction "Inst" s input = readFile "day10" load = map parse' . lines type Graph = Map Int Compare type Values = Map Int [Int] type Outputs = Map Int Int data State = State { graph :: Graph , values :: Values , outputs :: Outputs } addValue :: Int -> Maybe [Int] -> Maybe [Int] addValue v Nothing = Just [v] addValue v (Just vs) = Just (v : vs) addInstruction :: (Graph, Values) -> Instruction -> (Graph, Values) addInstruction (g, vs) = \case Value v b -> (g, Map.alter (addValue v) b vs) Edges b c -> (Map.insert b c g, vs) mkGraphAndValues :: [Instruction] -> (Graph, Values) mkGraphAndValues = foldl addInstruction (Map.empty, Map.empty) addDest :: Int -> Destination -> State -> State addDest val dest state@State{..} = case dest of Bot b -> state{values = Map.alter (addValue val) b values} Output o -> state{outputs = Map.insert o val outputs} findActive :: Values -> [(Int, [Int])] findActive values = Map.toList $ Map.filter (\vs -> length vs > 1) values stepOne :: State -> (Int, [Int]) -> State stepOne state@State{..} (active, vals) = state''' where comp = fromJust $ Map.lookup active graph [lo, hi] = List.sort vals state' = state{values=Map.delete active values} state'' = addDest lo (low comp) state' state''' = addDest hi (high comp) state'' step :: State -> State step s = foldl stepOne s $ active where active = findActive (values s) run :: [Instruction] -> [State] run insts = iterate step (State g vs Map.empty) where (g, vs) = mkGraphAndValues insts solve :: [Instruction] -> Maybe State solve = List.find target . run where target State{..} = any (== [17, 61]) . map snd $ findActive values
mbernat/aoc16-haskell
src/Day10.hs
bsd-3-clause
3,039
0
12
684
1,184
629
555
87
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} module Main where import Options.Generic import System.Environment import Text.Parsec.String (parseFromFile) import qualified Language.Brainfuck.Internals.Interpreter as Interpreter import qualified Language.Brainfuck.Internals.CCodeGen as Compiler import qualified Language.Brainfuck.Internals.Optim.Contract as Contract import qualified Language.Brainfuck.Internals.Optim.Cancel as Cancel import qualified Language.Brainfuck.Internals.Optim.ClearLoop as ClearLoop import qualified Language.Brainfuck.Internals.Optim.CopyLoop as CopyLoop import qualified Language.Brainfuck.Brainfuck as BF import qualified Language.Brainfuck.OokOok as OO import qualified Language.Brainfuck.Hodor as H import qualified Language.Brainfuck.WoopWoop as W import qualified Language.Brainfuck.Buffalo as B -- Allows brainfuck dialects data Dialect = Brainfuck | OokOok | Hodor | WoopWoop | Buffalo deriving (Generic, Show, Read) -- Argument parser data Arguments = Arguments { compile :: Bool -- <?> "Compile programming using LLVM" , dialect :: Dialect -- <?> "One of: Brainfuck, OokOok, Hodor, WoopWoop, Buffalo." , file :: FilePath -- <?> "Source of program." } deriving (Generic, Show) instance ParseField Dialect instance ParseFields Dialect instance ParseRecord Dialect instance ParseRecord Arguments main :: IO () main = do args <- getRecord "Hodor: brainfuck interpreter and compiler" result <- parseFromFile (parser . dialect $ args) (file args) case result of Left err -> putStr "parse error at " >> print err Right x -> if compile args then Compiler.compile (opti x) "out.c" else Interpreter.interpret x where parser lang = case lang of Brainfuck -> BF.program OokOok -> OO.program Hodor -> H.program WoopWoop -> W.program Buffalo -> B.program opti = Contract.optim . Cancel.optim . ClearLoop.optim . CopyLoop.optim
remusao/Hodor
app/Main.hs
bsd-3-clause
2,159
0
13
468
440
262
178
51
7
module Sexy.Instances.Plus.Maybe () where import Sexy.Data (Maybe(..)) import Sexy.Classes (Plus(..)) instance (Plus a) => Plus (Maybe a) where Nothing + my = my mx + Nothing = mx (Just x) + (Just y) = Just (x + y)
DanBurton/sexy
src/Sexy/Instances/Plus/Maybe.hs
bsd-3-clause
237
0
8
60
117
64
53
7
0
{-# language CPP #-} -- No documentation found for Chapter "Promoted_From_VK_KHR_sampler_ycbcr_conversion" module Vulkan.Core11.Promoted_From_VK_KHR_sampler_ycbcr_conversion ( createSamplerYcbcrConversion , withSamplerYcbcrConversion , destroySamplerYcbcrConversion , SamplerYcbcrConversionInfo(..) , SamplerYcbcrConversionCreateInfo(..) , BindImagePlaneMemoryInfo(..) , ImagePlaneMemoryRequirementsInfo(..) , PhysicalDeviceSamplerYcbcrConversionFeatures(..) , SamplerYcbcrConversionImageFormatProperties(..) , SamplerYcbcrConversion(..) , Format(..) , StructureType(..) , ObjectType(..) , ImageCreateFlagBits(..) , ImageCreateFlags , FormatFeatureFlagBits(..) , FormatFeatureFlags , ImageAspectFlagBits(..) , ImageAspectFlags , SamplerYcbcrModelConversion(..) , SamplerYcbcrRange(..) , ChromaLocation(..) ) where import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Data.Typeable (eqT) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (castPtr) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.Type.Equality ((:~:)(Refl)) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.CStruct.Extends (forgetExtensions) import Vulkan.NamedType ((:::)) import Vulkan.Core10.AllocationCallbacks (AllocationCallbacks) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.CStruct.Extends (Chain) import Vulkan.Core11.Enums.ChromaLocation (ChromaLocation) import Vulkan.Core10.ImageView (ComponentMapping) import Vulkan.Core10.Handles (Device) import Vulkan.Core10.Handles (Device(..)) import Vulkan.Core10.Handles (Device(Device)) import Vulkan.Dynamic (DeviceCmds(pVkCreateSamplerYcbcrConversion)) import Vulkan.Dynamic (DeviceCmds(pVkDestroySamplerYcbcrConversion)) import Vulkan.Core10.Handles (Device_T) import Vulkan.CStruct.Extends (Extends) import Vulkan.CStruct.Extends (Extendss) import Vulkan.CStruct.Extends (Extensible(..)) import {-# SOURCE #-} Vulkan.Extensions.VK_ANDROID_external_memory_android_hardware_buffer (ExternalFormatANDROID) import Vulkan.Core10.Enums.Filter (Filter) import Vulkan.Core10.Enums.Format (Format) import Vulkan.Core10.Enums.ImageAspectFlagBits (ImageAspectFlagBits) import Vulkan.CStruct.Extends (PeekChain) import Vulkan.CStruct.Extends (PeekChain(..)) import Vulkan.CStruct.Extends (PokeChain) import Vulkan.CStruct.Extends (PokeChain(..)) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import Vulkan.Core11.Handles (SamplerYcbcrConversion) import Vulkan.Core11.Handles (SamplerYcbcrConversion(..)) import Vulkan.Core11.Enums.SamplerYcbcrModelConversion (SamplerYcbcrModelConversion) import Vulkan.Core11.Enums.SamplerYcbcrRange (SamplerYcbcrRange) import Vulkan.CStruct.Extends (SomeStruct) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Exception (VulkanException(..)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Core11.Enums.ChromaLocation (ChromaLocation(..)) import Vulkan.Core10.Enums.Format (Format(..)) import Vulkan.Core10.Enums.FormatFeatureFlagBits (FormatFeatureFlagBits(..)) import Vulkan.Core10.Enums.FormatFeatureFlagBits (FormatFeatureFlags) import Vulkan.Core10.Enums.ImageAspectFlagBits (ImageAspectFlagBits(..)) import Vulkan.Core10.Enums.ImageAspectFlagBits (ImageAspectFlags) import Vulkan.Core10.Enums.ImageCreateFlagBits (ImageCreateFlagBits(..)) import Vulkan.Core10.Enums.ImageCreateFlagBits (ImageCreateFlags) import Vulkan.Core10.Enums.ObjectType (ObjectType(..)) import Vulkan.Core11.Handles (SamplerYcbcrConversion(..)) import Vulkan.Core11.Enums.SamplerYcbcrModelConversion (SamplerYcbcrModelConversion(..)) import Vulkan.Core11.Enums.SamplerYcbcrRange (SamplerYcbcrRange(..)) import Vulkan.Core10.Enums.StructureType (StructureType(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCreateSamplerYcbcrConversion :: FunPtr (Ptr Device_T -> Ptr (SomeStruct SamplerYcbcrConversionCreateInfo) -> Ptr AllocationCallbacks -> Ptr SamplerYcbcrConversion -> IO Result) -> Ptr Device_T -> Ptr (SomeStruct SamplerYcbcrConversionCreateInfo) -> Ptr AllocationCallbacks -> Ptr SamplerYcbcrConversion -> IO Result -- | vkCreateSamplerYcbcrConversion - Create a new Y′CBCR conversion -- -- = Description -- -- The interpretation of the configured sampler Y′CBCR conversion is -- described in more detail in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-sampler-YCbCr-conversion the description of sampler Y′CBCR conversion> -- in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures Image Operations> -- chapter. -- -- == Valid Usage -- -- - #VUID-vkCreateSamplerYcbcrConversion-None-01648# The -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-samplerYcbcrConversion sampler Y′CBCR conversion feature> -- /must/ be enabled -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCreateSamplerYcbcrConversion-device-parameter# @device@ -- /must/ be a valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkCreateSamplerYcbcrConversion-pCreateInfo-parameter# -- @pCreateInfo@ /must/ be a valid pointer to a valid -- 'SamplerYcbcrConversionCreateInfo' structure -- -- - #VUID-vkCreateSamplerYcbcrConversion-pAllocator-parameter# If -- @pAllocator@ is not @NULL@, @pAllocator@ /must/ be a valid pointer -- to a valid 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' -- structure -- -- - #VUID-vkCreateSamplerYcbcrConversion-pYcbcrConversion-parameter# -- @pYcbcrConversion@ /must/ be a valid pointer to a -- 'Vulkan.Core11.Handles.SamplerYcbcrConversion' handle -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Core10.Handles.Device', -- 'Vulkan.Core11.Handles.SamplerYcbcrConversion', -- 'SamplerYcbcrConversionCreateInfo' createSamplerYcbcrConversion :: forall a io . (Extendss SamplerYcbcrConversionCreateInfo a, PokeChain a, MonadIO io) => -- | @device@ is the logical device that creates the sampler Y′CBCR -- conversion. Device -> -- | @pCreateInfo@ is a pointer to a 'SamplerYcbcrConversionCreateInfo' -- structure specifying the requested sampler Y′CBCR conversion. (SamplerYcbcrConversionCreateInfo a) -> -- | @pAllocator@ controls host memory allocation as described in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation> -- chapter. ("allocator" ::: Maybe AllocationCallbacks) -> io (SamplerYcbcrConversion) createSamplerYcbcrConversion device createInfo allocator = liftIO . evalContT $ do let vkCreateSamplerYcbcrConversionPtr = pVkCreateSamplerYcbcrConversion (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkCreateSamplerYcbcrConversionPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCreateSamplerYcbcrConversion is null" Nothing Nothing let vkCreateSamplerYcbcrConversion' = mkVkCreateSamplerYcbcrConversion vkCreateSamplerYcbcrConversionPtr pCreateInfo <- ContT $ withCStruct (createInfo) pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) pPYcbcrConversion <- ContT $ bracket (callocBytes @SamplerYcbcrConversion 8) free r <- lift $ traceAroundEvent "vkCreateSamplerYcbcrConversion" (vkCreateSamplerYcbcrConversion' (deviceHandle (device)) (forgetExtensions pCreateInfo) pAllocator (pPYcbcrConversion)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pYcbcrConversion <- lift $ peek @SamplerYcbcrConversion pPYcbcrConversion pure $ (pYcbcrConversion) -- | A convenience wrapper to make a compatible pair of calls to -- 'createSamplerYcbcrConversion' and 'destroySamplerYcbcrConversion' -- -- To ensure that 'destroySamplerYcbcrConversion' is always called: pass -- 'Control.Exception.bracket' (or the allocate function from your -- favourite resource management library) as the last argument. -- To just extract the pair pass '(,)' as the last argument. -- withSamplerYcbcrConversion :: forall a io r . (Extendss SamplerYcbcrConversionCreateInfo a, PokeChain a, MonadIO io) => Device -> SamplerYcbcrConversionCreateInfo a -> Maybe AllocationCallbacks -> (io SamplerYcbcrConversion -> (SamplerYcbcrConversion -> io ()) -> r) -> r withSamplerYcbcrConversion device pCreateInfo pAllocator b = b (createSamplerYcbcrConversion device pCreateInfo pAllocator) (\(o0) -> destroySamplerYcbcrConversion device o0 pAllocator) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkDestroySamplerYcbcrConversion :: FunPtr (Ptr Device_T -> SamplerYcbcrConversion -> Ptr AllocationCallbacks -> IO ()) -> Ptr Device_T -> SamplerYcbcrConversion -> Ptr AllocationCallbacks -> IO () -- | vkDestroySamplerYcbcrConversion - Destroy a created Y′CBCR conversion -- -- == Valid Usage (Implicit) -- -- - #VUID-vkDestroySamplerYcbcrConversion-device-parameter# @device@ -- /must/ be a valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkDestroySamplerYcbcrConversion-ycbcrConversion-parameter# If -- @ycbcrConversion@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- @ycbcrConversion@ /must/ be a valid -- 'Vulkan.Core11.Handles.SamplerYcbcrConversion' handle -- -- - #VUID-vkDestroySamplerYcbcrConversion-pAllocator-parameter# If -- @pAllocator@ is not @NULL@, @pAllocator@ /must/ be a valid pointer -- to a valid 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' -- structure -- -- - #VUID-vkDestroySamplerYcbcrConversion-ycbcrConversion-parent# If -- @ycbcrConversion@ is a valid handle, it /must/ have been created, -- allocated, or retrieved from @device@ -- -- == Host Synchronization -- -- - Host access to @ycbcrConversion@ /must/ be externally synchronized -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Core10.Handles.Device', -- 'Vulkan.Core11.Handles.SamplerYcbcrConversion' destroySamplerYcbcrConversion :: forall io . (MonadIO io) => -- | @device@ is the logical device that destroys the Y′CBCR conversion. Device -> -- | @ycbcrConversion@ is the conversion to destroy. SamplerYcbcrConversion -> -- | @pAllocator@ controls host memory allocation as described in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation> -- chapter. ("allocator" ::: Maybe AllocationCallbacks) -> io () destroySamplerYcbcrConversion device ycbcrConversion allocator = liftIO . evalContT $ do let vkDestroySamplerYcbcrConversionPtr = pVkDestroySamplerYcbcrConversion (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkDestroySamplerYcbcrConversionPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkDestroySamplerYcbcrConversion is null" Nothing Nothing let vkDestroySamplerYcbcrConversion' = mkVkDestroySamplerYcbcrConversion vkDestroySamplerYcbcrConversionPtr pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) lift $ traceAroundEvent "vkDestroySamplerYcbcrConversion" (vkDestroySamplerYcbcrConversion' (deviceHandle (device)) (ycbcrConversion) pAllocator) pure $ () -- | VkSamplerYcbcrConversionInfo - Structure specifying Y′CBCR conversion to -- a sampler or image view -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core11.Handles.SamplerYcbcrConversion', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data SamplerYcbcrConversionInfo = SamplerYcbcrConversionInfo { -- | @conversion@ is a 'Vulkan.Core11.Handles.SamplerYcbcrConversion' handle -- created with 'createSamplerYcbcrConversion'. -- -- #VUID-VkSamplerYcbcrConversionInfo-conversion-parameter# @conversion@ -- /must/ be a valid 'Vulkan.Core11.Handles.SamplerYcbcrConversion' handle conversion :: SamplerYcbcrConversion } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (SamplerYcbcrConversionInfo) #endif deriving instance Show SamplerYcbcrConversionInfo instance ToCStruct SamplerYcbcrConversionInfo where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p SamplerYcbcrConversionInfo{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SamplerYcbcrConversion)) (conversion) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SamplerYcbcrConversion)) (zero) f instance FromCStruct SamplerYcbcrConversionInfo where peekCStruct p = do conversion <- peek @SamplerYcbcrConversion ((p `plusPtr` 16 :: Ptr SamplerYcbcrConversion)) pure $ SamplerYcbcrConversionInfo conversion instance Storable SamplerYcbcrConversionInfo where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero SamplerYcbcrConversionInfo where zero = SamplerYcbcrConversionInfo zero -- | VkSamplerYcbcrConversionCreateInfo - Structure specifying the parameters -- of the newly created conversion -- -- = Description -- -- Note -- -- Setting @forceExplicitReconstruction@ to -- 'Vulkan.Core10.FundamentalTypes.TRUE' /may/ have a performance penalty -- on implementations where explicit reconstruction is not the default mode -- of operation. -- -- If @format@ supports -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT' -- the @forceExplicitReconstruction@ value behaves as if it was set to -- 'Vulkan.Core10.FundamentalTypes.TRUE'. -- -- If the @pNext@ chain includes a -- 'Vulkan.Extensions.VK_ANDROID_external_memory_android_hardware_buffer.ExternalFormatANDROID' -- structure with non-zero @externalFormat@ member, the sampler Y′CBCR -- conversion object represents an /external format conversion/, and -- @format@ /must/ be 'Vulkan.Core10.Enums.Format.FORMAT_UNDEFINED'. Such -- conversions /must/ only be used to sample image views with a matching -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-external-android-hardware-buffer-external-formats external format>. -- When creating an external format conversion, the value of @components@ -- is ignored. -- -- == Valid Usage -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-format-01904# If an -- external format conversion is being created, @format@ /must/ be -- 'Vulkan.Core10.Enums.Format.FORMAT_UNDEFINED' -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-format-04061# If an -- external format conversion is not being created, @format@ /must/ -- represent unsigned normalized values (i.e. the format must be a -- @UNORM@ format) -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-format-01650# The -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#potential-format-features potential format features> -- of the sampler Y′CBCR conversion /must/ support -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT' -- or -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT' -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-xChromaOffset-01651# If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#potential-format-features potential format features> -- of the sampler Y′CBCR conversion do not support -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT', -- @xChromaOffset@ and @yChromaOffset@ /must/ not be -- 'Vulkan.Core11.Enums.ChromaLocation.CHROMA_LOCATION_COSITED_EVEN' if -- the corresponding components are -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-chroma-reconstruction downsampled> -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-xChromaOffset-01652# If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#potential-format-features potential format features> -- of the sampler Y′CBCR conversion do not support -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT', -- @xChromaOffset@ and @yChromaOffset@ /must/ not be -- 'Vulkan.Core11.Enums.ChromaLocation.CHROMA_LOCATION_MIDPOINT' if the -- corresponding components are -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-chroma-reconstruction downsampled> -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-components-02581# If the -- format has a @_422@ or @_420@ suffix, then @components.g@ /must/ be -- the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-views-identity-mappings identity swizzle> -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-components-02582# If the -- format has a @_422@ or @_420@ suffix, then @components.a@ /must/ be -- the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-views-identity-mappings identity swizzle>, -- 'Vulkan.Core10.Enums.ComponentSwizzle.COMPONENT_SWIZZLE_ONE', or -- 'Vulkan.Core10.Enums.ComponentSwizzle.COMPONENT_SWIZZLE_ZERO' -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-components-02583# If the -- format has a @_422@ or @_420@ suffix, then @components.r@ /must/ be -- the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-views-identity-mappings identity swizzle> -- or 'Vulkan.Core10.Enums.ComponentSwizzle.COMPONENT_SWIZZLE_B' -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-components-02584# If the -- format has a @_422@ or @_420@ suffix, then @components.b@ /must/ be -- the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-views-identity-mappings identity swizzle> -- or 'Vulkan.Core10.Enums.ComponentSwizzle.COMPONENT_SWIZZLE_R' -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-components-02585# If the -- format has a @_422@ or @_420@ suffix, and if either @components.r@ -- or @components.b@ is the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-views-identity-mappings identity swizzle>, -- both values /must/ be the identity swizzle -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-ycbcrModel-01655# If -- @ycbcrModel@ is not -- 'Vulkan.Core11.Enums.SamplerYcbcrModelConversion.SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY', -- then @components.r@, @components.g@, and @components.b@ /must/ -- correspond to components of the @format@; that is, @components.r@, -- @components.g@, and @components.b@ /must/ not be -- 'Vulkan.Core10.Enums.ComponentSwizzle.COMPONENT_SWIZZLE_ZERO' or -- 'Vulkan.Core10.Enums.ComponentSwizzle.COMPONENT_SWIZZLE_ONE', and -- /must/ not correspond to a component containing zero or one as a -- consequence of -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-conversion-to-rgba conversion to RGBA> -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-ycbcrRange-02748# If -- @ycbcrRange@ is -- 'Vulkan.Core11.Enums.SamplerYcbcrRange.SAMPLER_YCBCR_RANGE_ITU_NARROW' -- then the R, G and B components obtained by applying the @component@ -- swizzle to @format@ /must/ each have a bit-depth greater than or -- equal to 8 -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-forceExplicitReconstruction-01656# -- If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#potential-format-features potential format features> -- of the sampler Y′CBCR conversion do not support -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT' -- @forceExplicitReconstruction@ /must/ be -- 'Vulkan.Core10.FundamentalTypes.FALSE' -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-chromaFilter-01657# If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#potential-format-features potential format features> -- of the sampler Y′CBCR conversion do not support -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT', -- @chromaFilter@ /must/ not be -- 'Vulkan.Core10.Enums.Filter.FILTER_LINEAR' -- -- == Valid Usage (Implicit) -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-sType-sType# @sType@ /must/ -- be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO' -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-pNext-pNext# @pNext@ /must/ -- be @NULL@ or a pointer to a valid instance of -- 'Vulkan.Extensions.VK_ANDROID_external_memory_android_hardware_buffer.ExternalFormatANDROID' -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-sType-unique# The @sType@ -- value of each struct in the @pNext@ chain /must/ be unique -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-format-parameter# @format@ -- /must/ be a valid 'Vulkan.Core10.Enums.Format.Format' value -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-ycbcrModel-parameter# -- @ycbcrModel@ /must/ be a valid -- 'Vulkan.Core11.Enums.SamplerYcbcrModelConversion.SamplerYcbcrModelConversion' -- value -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-ycbcrRange-parameter# -- @ycbcrRange@ /must/ be a valid -- 'Vulkan.Core11.Enums.SamplerYcbcrRange.SamplerYcbcrRange' value -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-components-parameter# -- @components@ /must/ be a valid -- 'Vulkan.Core10.ImageView.ComponentMapping' structure -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-xChromaOffset-parameter# -- @xChromaOffset@ /must/ be a valid -- 'Vulkan.Core11.Enums.ChromaLocation.ChromaLocation' value -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-yChromaOffset-parameter# -- @yChromaOffset@ /must/ be a valid -- 'Vulkan.Core11.Enums.ChromaLocation.ChromaLocation' value -- -- - #VUID-VkSamplerYcbcrConversionCreateInfo-chromaFilter-parameter# -- @chromaFilter@ /must/ be a valid 'Vulkan.Core10.Enums.Filter.Filter' -- value -- -- If @chromaFilter@ is 'Vulkan.Core10.Enums.Filter.FILTER_NEAREST', chroma -- samples are reconstructed to luma component resolution using -- nearest-neighbour sampling. Otherwise, chroma samples are reconstructed -- using interpolation. More details can be found in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-sampler-YCbCr-conversion the description of sampler Y′CBCR conversion> -- in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures Image Operations> -- chapter. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Core11.Enums.ChromaLocation.ChromaLocation', -- 'Vulkan.Core10.ImageView.ComponentMapping', -- 'Vulkan.Core10.Enums.Filter.Filter', -- 'Vulkan.Core10.Enums.Format.Format', -- 'Vulkan.Core11.Enums.SamplerYcbcrModelConversion.SamplerYcbcrModelConversion', -- 'Vulkan.Core11.Enums.SamplerYcbcrRange.SamplerYcbcrRange', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'createSamplerYcbcrConversion', -- 'Vulkan.Extensions.VK_KHR_sampler_ycbcr_conversion.createSamplerYcbcrConversionKHR' data SamplerYcbcrConversionCreateInfo (es :: [Type]) = SamplerYcbcrConversionCreateInfo { -- | @pNext@ is @NULL@ or a pointer to a structure extending this structure. next :: Chain es , -- | @format@ is the format of the image from which color information will be -- retrieved. format :: Format , -- | @ycbcrModel@ describes the color matrix for conversion between color -- models. ycbcrModel :: SamplerYcbcrModelConversion , -- | @ycbcrRange@ describes whether the encoded values have headroom and foot -- room, or whether the encoding uses the full numerical range. ycbcrRange :: SamplerYcbcrRange , -- | @components@ applies a /swizzle/ based on -- 'Vulkan.Core10.Enums.ComponentSwizzle.ComponentSwizzle' enums prior to -- range expansion and color model conversion. components :: ComponentMapping , -- | @xChromaOffset@ describes the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-chroma-reconstruction sample location> -- associated with downsampled chroma components in the x dimension. -- @xChromaOffset@ has no effect for formats in which chroma components are -- not downsampled horizontally. xChromaOffset :: ChromaLocation , -- | @yChromaOffset@ describes the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-chroma-reconstruction sample location> -- associated with downsampled chroma components in the y dimension. -- @yChromaOffset@ has no effect for formats in which the chroma components -- are not downsampled vertically. yChromaOffset :: ChromaLocation , -- | @chromaFilter@ is the filter for chroma reconstruction. chromaFilter :: Filter , -- | @forceExplicitReconstruction@ /can/ be used to ensure that -- reconstruction is done explicitly, if supported. forceExplicitReconstruction :: Bool } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (SamplerYcbcrConversionCreateInfo (es :: [Type])) #endif deriving instance Show (Chain es) => Show (SamplerYcbcrConversionCreateInfo es) instance Extensible SamplerYcbcrConversionCreateInfo where extensibleTypeName = "SamplerYcbcrConversionCreateInfo" setNext SamplerYcbcrConversionCreateInfo{..} next' = SamplerYcbcrConversionCreateInfo{next = next', ..} getNext SamplerYcbcrConversionCreateInfo{..} = next extends :: forall e b proxy. Typeable e => proxy e -> (Extends SamplerYcbcrConversionCreateInfo e => b) -> Maybe b extends _ f | Just Refl <- eqT @e @ExternalFormatANDROID = Just f | otherwise = Nothing instance (Extendss SamplerYcbcrConversionCreateInfo es, PokeChain es) => ToCStruct (SamplerYcbcrConversionCreateInfo es) where withCStruct x f = allocaBytes 64 $ \p -> pokeCStruct p x (f p) pokeCStruct p SamplerYcbcrConversionCreateInfo{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO) pNext'' <- fmap castPtr . ContT $ withChain (next) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext'' lift $ poke ((p `plusPtr` 16 :: Ptr Format)) (format) lift $ poke ((p `plusPtr` 20 :: Ptr SamplerYcbcrModelConversion)) (ycbcrModel) lift $ poke ((p `plusPtr` 24 :: Ptr SamplerYcbcrRange)) (ycbcrRange) lift $ poke ((p `plusPtr` 28 :: Ptr ComponentMapping)) (components) lift $ poke ((p `plusPtr` 44 :: Ptr ChromaLocation)) (xChromaOffset) lift $ poke ((p `plusPtr` 48 :: Ptr ChromaLocation)) (yChromaOffset) lift $ poke ((p `plusPtr` 52 :: Ptr Filter)) (chromaFilter) lift $ poke ((p `plusPtr` 56 :: Ptr Bool32)) (boolToBool32 (forceExplicitReconstruction)) lift $ f cStructSize = 64 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO) pNext' <- fmap castPtr . ContT $ withZeroChain @es lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext' lift $ poke ((p `plusPtr` 16 :: Ptr Format)) (zero) lift $ poke ((p `plusPtr` 20 :: Ptr SamplerYcbcrModelConversion)) (zero) lift $ poke ((p `plusPtr` 24 :: Ptr SamplerYcbcrRange)) (zero) lift $ poke ((p `plusPtr` 28 :: Ptr ComponentMapping)) (zero) lift $ poke ((p `plusPtr` 44 :: Ptr ChromaLocation)) (zero) lift $ poke ((p `plusPtr` 48 :: Ptr ChromaLocation)) (zero) lift $ poke ((p `plusPtr` 52 :: Ptr Filter)) (zero) lift $ poke ((p `plusPtr` 56 :: Ptr Bool32)) (boolToBool32 (zero)) lift $ f instance (Extendss SamplerYcbcrConversionCreateInfo es, PeekChain es) => FromCStruct (SamplerYcbcrConversionCreateInfo es) where peekCStruct p = do pNext <- peek @(Ptr ()) ((p `plusPtr` 8 :: Ptr (Ptr ()))) next <- peekChain (castPtr pNext) format <- peek @Format ((p `plusPtr` 16 :: Ptr Format)) ycbcrModel <- peek @SamplerYcbcrModelConversion ((p `plusPtr` 20 :: Ptr SamplerYcbcrModelConversion)) ycbcrRange <- peek @SamplerYcbcrRange ((p `plusPtr` 24 :: Ptr SamplerYcbcrRange)) components <- peekCStruct @ComponentMapping ((p `plusPtr` 28 :: Ptr ComponentMapping)) xChromaOffset <- peek @ChromaLocation ((p `plusPtr` 44 :: Ptr ChromaLocation)) yChromaOffset <- peek @ChromaLocation ((p `plusPtr` 48 :: Ptr ChromaLocation)) chromaFilter <- peek @Filter ((p `plusPtr` 52 :: Ptr Filter)) forceExplicitReconstruction <- peek @Bool32 ((p `plusPtr` 56 :: Ptr Bool32)) pure $ SamplerYcbcrConversionCreateInfo next format ycbcrModel ycbcrRange components xChromaOffset yChromaOffset chromaFilter (bool32ToBool forceExplicitReconstruction) instance es ~ '[] => Zero (SamplerYcbcrConversionCreateInfo es) where zero = SamplerYcbcrConversionCreateInfo () zero zero zero zero zero zero zero zero -- | VkBindImagePlaneMemoryInfo - Structure specifying how to bind an image -- plane to memory -- -- == Valid Usage -- -- - #VUID-VkBindImagePlaneMemoryInfo-planeAspect-02283# If the image’s -- @tiling@ is 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_LINEAR' or -- 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_OPTIMAL', then -- @planeAspect@ /must/ be a single valid /format plane/ for the image -- (that is, for a two-plane image @planeAspect@ /must/ be -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_0_BIT' -- or -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_1_BIT', -- and for a three-plane image @planeAspect@ /must/ be -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_0_BIT', -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_1_BIT' -- or -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_2_BIT') -- -- - #VUID-VkBindImagePlaneMemoryInfo-planeAspect-02284# If the image’s -- @tiling@ is -- 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT', -- then @planeAspect@ /must/ be a single valid /memory plane/ for the -- image (that is, @aspectMask@ /must/ specify a plane index that is -- less than the -- 'Vulkan.Extensions.VK_EXT_image_drm_format_modifier.DrmFormatModifierPropertiesEXT'::@drmFormatModifierPlaneCount@ -- associated with the image’s @format@ and -- 'Vulkan.Extensions.VK_EXT_image_drm_format_modifier.ImageDrmFormatModifierPropertiesEXT'::@drmFormatModifier@) -- -- == Valid Usage (Implicit) -- -- - #VUID-VkBindImagePlaneMemoryInfo-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO' -- -- - #VUID-VkBindImagePlaneMemoryInfo-planeAspect-parameter# -- @planeAspect@ /must/ be a valid -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.ImageAspectFlagBits' value -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.ImageAspectFlagBits', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data BindImagePlaneMemoryInfo = BindImagePlaneMemoryInfo { -- | @planeAspect@ is a -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.ImageAspectFlagBits' value -- specifying the aspect of the disjoint image plane to bind. planeAspect :: ImageAspectFlagBits } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (BindImagePlaneMemoryInfo) #endif deriving instance Show BindImagePlaneMemoryInfo instance ToCStruct BindImagePlaneMemoryInfo where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p BindImagePlaneMemoryInfo{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ImageAspectFlagBits)) (planeAspect) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ImageAspectFlagBits)) (zero) f instance FromCStruct BindImagePlaneMemoryInfo where peekCStruct p = do planeAspect <- peek @ImageAspectFlagBits ((p `plusPtr` 16 :: Ptr ImageAspectFlagBits)) pure $ BindImagePlaneMemoryInfo planeAspect instance Storable BindImagePlaneMemoryInfo where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero BindImagePlaneMemoryInfo where zero = BindImagePlaneMemoryInfo zero -- | VkImagePlaneMemoryRequirementsInfo - Structure specifying image plane -- for memory requirements -- -- == Valid Usage -- -- - #VUID-VkImagePlaneMemoryRequirementsInfo-planeAspect-02281# If the -- image’s @tiling@ is -- 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_LINEAR' or -- 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_OPTIMAL', then -- @planeAspect@ /must/ be a single valid /format plane/ for the image -- (that is, for a two-plane image @planeAspect@ /must/ be -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_0_BIT' -- or -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_1_BIT', -- and for a three-plane image @planeAspect@ /must/ be -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_0_BIT', -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_1_BIT' -- or -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_2_BIT') -- -- - #VUID-VkImagePlaneMemoryRequirementsInfo-planeAspect-02282# If the -- image’s @tiling@ is -- 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT', -- then @planeAspect@ /must/ be a single valid /memory plane/ for the -- image (that is, @aspectMask@ /must/ specify a plane index that is -- less than the -- 'Vulkan.Extensions.VK_EXT_image_drm_format_modifier.DrmFormatModifierPropertiesEXT'::@drmFormatModifierPlaneCount@ -- associated with the image’s @format@ and -- 'Vulkan.Extensions.VK_EXT_image_drm_format_modifier.ImageDrmFormatModifierPropertiesEXT'::@drmFormatModifier@) -- -- == Valid Usage (Implicit) -- -- - #VUID-VkImagePlaneMemoryRequirementsInfo-sType-sType# @sType@ /must/ -- be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO' -- -- - #VUID-VkImagePlaneMemoryRequirementsInfo-planeAspect-parameter# -- @planeAspect@ /must/ be a valid -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.ImageAspectFlagBits' value -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.ImageAspectFlagBits', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data ImagePlaneMemoryRequirementsInfo = ImagePlaneMemoryRequirementsInfo { -- | @planeAspect@ is a -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.ImageAspectFlagBits' value -- specifying the aspect corresponding to the image plane to query. planeAspect :: ImageAspectFlagBits } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (ImagePlaneMemoryRequirementsInfo) #endif deriving instance Show ImagePlaneMemoryRequirementsInfo instance ToCStruct ImagePlaneMemoryRequirementsInfo where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p ImagePlaneMemoryRequirementsInfo{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ImageAspectFlagBits)) (planeAspect) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ImageAspectFlagBits)) (zero) f instance FromCStruct ImagePlaneMemoryRequirementsInfo where peekCStruct p = do planeAspect <- peek @ImageAspectFlagBits ((p `plusPtr` 16 :: Ptr ImageAspectFlagBits)) pure $ ImagePlaneMemoryRequirementsInfo planeAspect instance Storable ImagePlaneMemoryRequirementsInfo where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero ImagePlaneMemoryRequirementsInfo where zero = ImagePlaneMemoryRequirementsInfo zero -- | VkPhysicalDeviceSamplerYcbcrConversionFeatures - Structure describing -- Y′CBCR conversion features that can be supported by an implementation -- -- = Members -- -- This structure describes the following feature: -- -- = Description -- -- If the 'PhysicalDeviceSamplerYcbcrConversionFeatures' structure is -- included in the @pNext@ chain of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2' -- structure passed to -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2', -- it is filled in to indicate whether each corresponding feature is -- supported. 'PhysicalDeviceSamplerYcbcrConversionFeatures' /can/ also be -- used in the @pNext@ chain of 'Vulkan.Core10.Device.DeviceCreateInfo' to -- selectively enable these features. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_sampler_ycbcr_conversion VK_KHR_sampler_ycbcr_conversion>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PhysicalDeviceSamplerYcbcrConversionFeatures = PhysicalDeviceSamplerYcbcrConversionFeatures { -- | #extension-features-samplerYcbcrConversion# @samplerYcbcrConversion@ -- specifies whether the implementation supports -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#samplers-YCbCr-conversion sampler Y′CBCR conversion>. -- If @samplerYcbcrConversion@ is 'Vulkan.Core10.FundamentalTypes.FALSE', -- sampler Y′CBCR conversion is not supported, and samplers using sampler -- Y′CBCR conversion /must/ not be used. samplerYcbcrConversion :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDeviceSamplerYcbcrConversionFeatures) #endif deriving instance Show PhysicalDeviceSamplerYcbcrConversionFeatures instance ToCStruct PhysicalDeviceSamplerYcbcrConversionFeatures where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDeviceSamplerYcbcrConversionFeatures{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (samplerYcbcrConversion)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct PhysicalDeviceSamplerYcbcrConversionFeatures where peekCStruct p = do samplerYcbcrConversion <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) pure $ PhysicalDeviceSamplerYcbcrConversionFeatures (bool32ToBool samplerYcbcrConversion) instance Storable PhysicalDeviceSamplerYcbcrConversionFeatures where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDeviceSamplerYcbcrConversionFeatures where zero = PhysicalDeviceSamplerYcbcrConversionFeatures zero -- | VkSamplerYcbcrConversionImageFormatProperties - Structure specifying -- combined image sampler descriptor count for multi-planar images -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Enums.StructureType.StructureType' data SamplerYcbcrConversionImageFormatProperties = SamplerYcbcrConversionImageFormatProperties { -- | @combinedImageSamplerDescriptorCount@ is the number of combined image -- sampler descriptors that the implementation uses to access the format. combinedImageSamplerDescriptorCount :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (SamplerYcbcrConversionImageFormatProperties) #endif deriving instance Show SamplerYcbcrConversionImageFormatProperties instance ToCStruct SamplerYcbcrConversionImageFormatProperties where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p SamplerYcbcrConversionImageFormatProperties{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (combinedImageSamplerDescriptorCount) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (zero) f instance FromCStruct SamplerYcbcrConversionImageFormatProperties where peekCStruct p = do combinedImageSamplerDescriptorCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pure $ SamplerYcbcrConversionImageFormatProperties combinedImageSamplerDescriptorCount instance Storable SamplerYcbcrConversionImageFormatProperties where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero SamplerYcbcrConversionImageFormatProperties where zero = SamplerYcbcrConversionImageFormatProperties zero
expipiplus1/vulkan
src/Vulkan/Core11/Promoted_From_VK_KHR_sampler_ycbcr_conversion.hs
bsd-3-clause
47,902
0
17
8,086
6,531
3,802
2,729
-1
-1
module Handler.Preview where import Control.Exception hiding (Handler) import qualified Data.ByteString.Lazy as LB import Data.Default import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Lazy as LT import qualified Data.Text.Lazy.Encoding as LT import Text.Blaze import Yesod import Yesod.Default.Util import Foundation getPreviewR :: Int -> Handler Html getPreviewR ident = do StoredFile filename contentType bytes <- getById ident defaultLayout $ do setTitle . toMarkup $ "File Processor - " `Text.append` filename previewBlock <- liftIO $ preview ident contentType bytes $(widgetFileNoReload def "preview") preview :: Int -> Text -> LB.ByteString -> IO Widget preview ident contentType bytes | "image/" `Text.isPrefixOf` contentType = return [whamlet|<img src=@{DownloadR ident}>|] | otherwise = do eText <- try . evaluate $ LT.decodeUtf8 bytes :: IO (Either SomeException LT.Text) return $ case eText of Left _ -> errorMessage Right text -> [whamlet|<pre>#{text}|] where errorMessage = [whamlet|<pre>Unable to display file contents.|]
Kwarrtz/flash
Handler/Preview.hs
bsd-3-clause
1,142
0
12
211
322
177
145
-1
-1
module Hydra ( module Hydra.Data , module Hydra.Stages.Simulate , module Hydra.Stages.Quote ) where import Hydra.Data import Hydra.Stages.Simulate import Hydra.Stages.Quote
giorgidze/Hydra
src/Hydra.hs
bsd-3-clause
175
0
5
21
43
29
14
7
0
-- The Timber compiler <timber-lang.org> -- -- Copyright 2008-2009 Johan Nordlander <[email protected]> -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the names of the copyright holder and any identified -- contributors, nor the names of their affiliations, may be used to -- endorse or promote products derived from this software without -- specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS -- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR -- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. module Syntax2Core where import Common import Syntax import Monad import qualified Core import PP syntax2core m = s2c m -- translate a module in the empty environment s2c :: Module -> M s Core.Module s2c (Module v is ds ps) = do (xs,es,ts,ws,bss) <- s2cDecls env0 ds [] [] [] [] [] [] return (Core.Module v is' xs es ts ws bss) where env0 = Env { sigs = [] } is' = [(b,n) | Import b n <- is] -- type signature environments data Env = Env { sigs :: Map Name Type } addSigs te env = env { sigs = te ++ sigs env } -- Syntax to Core translation of declarations ======================================================== -- Translate top-level declarations, accumulating signature environment env, kind environment ke, -- type declarations ts, instance names ws, bindings bs as well as default declarations xs s2cDecls env [] ke ts ws bss xs es = do bss <- s2cBindsList env (reverse bss) ke' <- mapM s2cKSig (impl_ke `zip` repeat KWild) xs' <- mapM s2cDefault xs es' <- mapM s2cExtern es let ds = Core.Types (reverse ke ++ ke') (reverse ts) return (xs', es', ds, ws, bss) where impl_ke = dom ts \\ dom ke s2cDecls env (DKSig c k : ds) ke ts ws bss xs es = do ck <- s2cKSig (c,k) s2cDecls env ds (ck:ke) ts ws bss xs es s2cDecls env (DData c vs bts cs : ds) ke ts ws bss xs es = do bts <- mapM s2cQualType bts cs <- mapM s2cConstr cs s2cDecls env' ds ke ((c,Core.DData vs bts cs):ts) ws bss xs es where env' = addSigs (teConstrs c vs cs) env s2cDecls env (DRec isC c vs bts ss : ds) ke ts ws bss xs es = do bts <- mapM s2cQualType bts sss <- mapM s2cSig ss s2cDecls env' ds ke ((c,Core.DRec isC vs bts (concat sss)):ts) ws bss xs es where env' = addSigs (teSigs c vs ss) env s2cDecls env (DType c vs t : ds) ke ts ws bss xs es = do t <- s2cType t s2cDecls env ds ke ((c,Core.DType vs t):ts) ws bss xs es s2cDecls env (DInstance vs : ds) ke ts ws bss xs es = s2cDecls env ds ke ts (ws++vs) bss xs es s2cDecls env (DDefault d : ds) ke ts ws bss xs es = s2cDecls env ds ke ts ws bss (d ++ xs) es s2cDecls env (DExtern es' : ds) ke ts ws bss xs es = s2cDecls env ds ke ts ws bss xs (es ++ es') s2cDecls env (DBind bs : ds) ke ts ws bss xs es = s2cDecls env ds ke ts ws (bs:bss) xs es s2cBindsList env [] = return [] s2cBindsList env (bs:bss) = do (te,bs) <- s2cBinds env bs bss <- s2cBindsList (addSigs te env) bss return (bs:bss) s2cDefault (Default t a b) = return (Default t a b) s2cDefault (Derive n t) = do t <- s2cQualType t return (Derive n t) s2cExtern (Extern n t) = do t <- s2cQualType t return (Extern n t) --translate a constructor declaration s2cConstr (Constr c ts ps) = do ts <- mapM s2cQualType ts (qs,ke) <- s2cQuals ps return (c, Core.Constr ts qs ke) -- translate a field declaration s2cSig (Sig vs qt) = s2cTSig vs qt -- add suppressed wildcard kind pVar v = PKind v KWild -- buld a signature environment for data constructors cs in type declaration tc vs teConstrs tc vs cs = map f cs where t0 = foldl TAp (TCon tc) (map TVar vs) f (Constr c ts ps) = (c,TQual (tFun ts t0) (ps ++ map pVar vs)) -- build a signature environment for record selectors ss in type declaration tc vs teSigs tc vs ss = concat (map f ss) where t0 = foldl TAp (TCon tc) (map TVar vs) f (Sig ws (TQual t ps)) = ws `zip` repeat (TQual (TFun [t0] t) (ps ++ map pVar vs)) f (Sig ws t) = ws `zip` repeat (TQual (TFun [t0] t) (map pVar vs)) -- Signatures ========================================================================= -- translate a type signature s2cTSig vs t = do ts <- mapM (s2cQualType . const t) vs return (vs `zip` ts) -- Types ============================================================================== -- translate a qualified type scheme s2cQualType (TQual t qs) = do (ps,ke) <- s2cQuals qs t <- s2cRhoType t return (Core.Scheme t ps ke) s2cQualType t = s2cQualType (TQual t []) -- translate a rank-N function type s2cRhoType (TFun ts t) = do ts <- mapM s2cQualType ts t <- s2cRhoType t return (Core.F ts t) s2cRhoType t = liftM Core.R (s2cType t) -- translate a monomorphic type s2cType (TSub t t') = s2cType (TFun [t] t') s2cType (TFun ts t) = do ts <- mapM s2cType ts t <- s2cType t return (Core.TFun ts t) s2cType (TAp t t') = liftM2 Core.TAp (s2cType t) (s2cType t') s2cType (TCon c) = return (Core.TId c) s2cType (TVar v) = return (Core.TId v) s2cType (TWild) = do k <- newKVar Core.newTvar k -- translate qualifiers, separating predicates from kind signatures along the way s2cQuals qs = s2c [] [] qs where s2c ps ke [] = return (reverse ps, reverse ke) s2c ps ke (PKind v k : qs) = do k <- s2cKind k s2c ps ((v,k) : ke) qs s2c ps ke (PType t : qs) = do p <- s2cQualType t s2c (p : ps) ke qs -- Kinds ============================================================================== -- translate a kind s2cKind Star = return Star s2cKind KWild = newKVar s2cKind (KFun k k') = liftM2 KFun (s2cKind k) (s2cKind k') s2cKSig (v,k) = do k <- s2cKind k return (v,k) -- Expressions and bindings ============================================================ -- the translated default case alternative dflt = [Core.Alt Core.PWild (Core.EVar (prim Fail))] -- translate a case alternative, inheriting type signature t top-down s2cAE env t alt = s2cA s2cEc env t alt s2cAS env alt = s2cA s2cSc env TWild alt s2cA s2cR env t (Alt p (RExp r)) = s2cA2 s2cR env t (p,r) s2cA2 s2cR env t (p,r) = s2cA' (pFlat p) r where s2cA' (PLit l,[]) e = do e' <- s2cR env t e return (Core.Alt (Core.PLit l) e') s2cA' (PCon c,ps) e = do e' <- s2cR (addSigs te env) t e te' <- s2cTE te --return (Alt (Core.PCon c []) (Core.eLam te' e')) -- old return (Core.Alt (Core.PCon c te') e') -- new where (te,t') = mergeT ps (lookupT c env) -- translate a record field s2cF env (Field s e) = do e <- s2cEc env (snd (splitT (lookupT s env))) e return (s,e) -- split bindings bs into type signatures and equations splitBinds bs = s2cB [] [] bs where s2cB sigs eqs [] = (reverse sigs, reverse eqs) s2cB sigs eqs (BSig vs t : bs) = s2cB (vs `zip` repeat t ++ sigs) eqs bs s2cB sigs eqs (BEqn (LFun v []) (RExp e) : bs) = s2cB sigs ((v,e):eqs) bs -- translate equation eqs in the scope of corresponding signatures sigs s2cBinds env bs = do (ts,es) <- fmap unzip (mapM s2cEqn eqs) let te = vs `zip` ts te' <- s2cTE te return (te, Core.Binds isRec te' (vs `zip` es)) where (sigs,eqs) = splitBinds bs vs = dom eqs isRec = not (null (filter (not . isPatTemp) vs `intersect` evars (rng eqs))) env' = addSigs sigs env s2cEqn (v,e) = case lookup v sigs of Nothing -> s2cEi env' e Just t -> do e <- s2cEc env' t' e return (t,e) where t' = if explicit (annot v) then expl t else peel t -- Expressions, inherit mode =============================================================== -- translate an expression, inheriting type signature t top-down s2cEc env t (ELam ps e) = do e' <- s2cEc (addSigs te env) t' e te' <- s2cTE te return (Core.ELam te' e') where (te,t') = mergeT ps t s2cEc env _ (EAp e1 e2) = do (t,e1) <- s2cEi env e1 let (t1,_) = splitT t e2 <- s2cEc env (peel t1) e2 return (Core.eAp2 e1 [e2]) s2cEc env t (ELet bs e) = do (te',bs') <- s2cBinds env bs e' <- s2cEc (addSigs te' env) t e return (Core.ELet bs' e') s2cEc env t (ECase e alts) = do e <- s2cEc env TWild e alts <- mapM (s2cAE env t) alts return (Core.ECase e (alts++dflt)) s2cEc env t (EMatch m) = do m <- s2cMc env t m return (eMatch m) s2cEc env t (ESelect e s) = do e <- s2cEc env (peel t1) e return (Core.ESel e s) where (t1,_) = splitT (lookupT s env) s2cEc env t (ECon c) = return (Core.ECon c) s2cEc env t (EVar v) = return (Core.EVar v) s2cEc env t (ELit l) = return (Core.ELit l) s2cEc env _ e = s2cE env e -- Expressions, agnostic mode ================================================================ -- translate an expression whose type cannot be rank-N polymorphic -- (i.e., no point inheriting nor synthesizing signatures) s2cE env (ERec (Just (c,_)) eqs) = do eqs <- mapM (s2cF env) eqs return (Core.ERec c eqs) s2cE env (EAct (Just x) (Stmts[SExp e]))= do (_,e) <- s2cEi env e return (Core.EAct (Core.EVar x) e) s2cE env (EReq (Just x) (Stmts[SExp e]))= do (_,e) <- s2cEi env e return (Core.EReq (Core.EVar x) e) s2cE env (EDo (Just x) Nothing ss) = do c <- s2cS env ss t <- s2cType TWild return (Core.EDo x t c) s2cE env (ETempl (Just x) Nothing ss) = do c <- s2cS (addSigs te env) ss t <- s2cType TWild te' <- s2cTE te return (Core.ETempl x t te' c) where vs = assignedVars ss te = sigs' ss sigs' (Stmts ss) = sigs ss sigs [] = [] sigs (SAss (PSig (PVar v) t) _ :ss) = (v,t) : sigs ss sigs (SAss (PVar v) _:ss) = (v,TWild) : sigs ss sigs (_ : ss) = sigs ss s2cE env e = internalError "s2cE: did not expect" e -- Pattern Matching ============================================================================ --eMatch = Core.EMatch -- new eMatch = Core.eMatch . desugarMatch -- compat desugarMatch = foldMatch Core.eCommit Core.eFail Core.eFatbar eCase Core.ELet where eCase e = Core.ECase e . map (uncurry Core.Alt) s2cMc env t m = case m of MCommit r -> MCommit `fmap` s2cEc env t r MFail -> return MFail MFatbar m1 m2 -> liftM2 MFatbar (s2cMc env t m1) (s2cMc env t m2) Case e alts -> do e <- s2cEc env TWild e alts <- mapM (s2cA2 s2cMc env t) alts return (Case e (uncurry zip (Core.unzipAlts alts)++dflt)) -- dflt?? where dflt = [(Core.PWild, MFail)] Let bs m -> do (te',bs') <- s2cBinds env bs e' <- s2cMc (addSigs te' env) t m return (Let bs' e') -- Statements ================================================================================== -- translate a statement list s2cSc env t ss = s2cS env ss s2cS env (Stmts ss) = s2cSs env ss s2cSs env [] = return (Core.CRet (Core.eUnit)) s2cSs env [SRet e] = do (t,e') <- s2cEi env e return (Core.CRet e') s2cSs env [SExp e] = do (t,e') <- s2cEi env e return (Core.CExp e') s2cSs env [SCase e alts] = do e <- s2cEc env TWild e alts <- mapM (s2cAS env) alts return (Core.CCase e alts) s2cSs env (SGen (PSig (PVar v) t) e :ss)= do t' <- s2cType t e' <- s2cEc env TWild e c <- s2cSs (addSigs [(v,t)] env) ss return (Core.CGen v t' e' c) s2cSs env (SGen (PVar v) e : ss) = do (_,e') <- s2cEi env e t <- s2cType TWild c <- s2cSs env ss return (Core.CGen v t e' c) s2cSs env (SAss (PSig v t) e : ss) = s2cSs env (SAss v e : ss) s2cSs env (SAss (PVar v) e : ss) = do e' <- s2cEc env (lookupT v env) e c <- s2cSs env ss return (Core.CAss v e' c) s2cSs env (SBind bs : ss) = do (te',bs') <- s2cBinds env bs c <- s2cSs (addSigs te' env) ss return (Core.CLet bs' c) s2cSs env ss = internalError "s2cSs: did not expect" (Stmts ss) -- Expressions, synthesize mode ================================================================ -- translate an expression, synthesize type signature bottom-up s2cEi env (ELam ps e) = do (t,e') <- s2cEi (addSigs te env) e te' <- s2cTE te return (TFun (rng te) t, Core.ELam te' e') where (te,_) = mergeT ps TWild s2cEi env (EAp e1 e2) = do (t,e1) <- s2cEi env e1 let (t1,t2) = splitT t e2 <- s2cEc env (peel t1) e2 return (t2, Core.eAp2 e1 [e2]) s2cEi env (ELet bs e) = do (te',bs') <- s2cBinds env bs (t,e') <- s2cEi (addSigs te' env) e return (t, Core.ELet bs' e') s2cEi env (ECase e alts) = do e <- s2cEc env TWild e alts <- mapM (s2cAE env TWild) alts return (TWild, Core.ECase e (alts++dflt)) s2cEi env (EMatch m) = do m <- s2cMc env TWild m return (TWild, eMatch m) s2cEi env (ESelect e s) = do e <- s2cEc env (peel t1) e return (t2, Core.ESel e s) where (t1,t2) = splitT (lookupT s env) s2cEi env (ECon c) = return (lookupT c env, Core.ECon c) s2cEi env (EVar v) = return (lookupT v env, Core.EVar v) s2cEi env (ELit l) = return (TWild, Core.ELit l) s2cEi env e = do e' <- s2cE env e return (TWild, e') -- Misc ==================================================================================== -- translate type enviroment te s2cTE te = mapM s2cVT te where s2cVT (v,t) = do t <- s2cQualType t return (v,t) -- split a function type into domain (one parameter only) and range -- if not a function type, fail gracefully (error will be caught later by real type-checker) splitT (TFun [t] t') = (t, t') splitT (TFun (t:ts) t') = (t, TFun ts t') splitT TWild = (TWild,TWild) splitT _ = (TWild,TWild) -- return the domain of a function type (all immediate parameters) splitArgs (TFun ts t) = ts splitArgs t = [] -- merge any signatures in patterns ps with domain of type t, pair with range of t mergeT ps t = (zipWith f ts ps, t') where (ts,t') = split (length ps) t f t (PVar v) = (v,t) f t (PSig (PVar v) t') = (v,t') f t e = internalError "mergeT: did not expect" e split 0 t = ([],t) split n t = (t1:ts,t') where (t1,t2) = splitT t (ts,t') = split (n-1) t2 -- find and instantate the type signature for x if present, otherwise return _ lookupT x env = case lookup x (sigs env) of Nothing -> TWild Just t -> peel t -- peel off the outermost qualifiers of a type, replacing all bound variables with _ peel (TQual t ps) = mkWild (bvars ps) t peel t = t -- turn class and subtype predicates into explicit function arguments, and peel off the quantifiers expl (TQual t ps) = mkWild (bvars ps) (TFun ts t) where ts = [ t | PType t <- ps ] -- replace all variables vs in a type by _ mkWild vs (TQual t ps) = TQual (mkWild vs' t) (map (mkWild' vs') ps) where vs' = vs \\ bvars ps mkWild vs (TAp t t') = TAp (mkWild vs t) (mkWild vs t') mkWild vs (TFun ts t) = TFun (map (mkWild vs) ts) (mkWild vs t) mkWild vs (TSub t t') = TSub (mkWild vs t) (mkWild vs t') mkWild vs (TList t) = TList (mkWild vs t) mkWild vs (TTup ts) = TTup (map (mkWild vs) ts) mkWild vs (TVar v) | v `elem` vs = TWild mkWild vs t = t -- replace all variables vs in a predicate by _ mkWild' vs (PType t) = PType (mkWild vs t) mkWild' vs p = p -- Checking whether bindings are recursive checkRecBinds (Core.Binds _ te es@[(x,e)]) = Core.Binds (x `elem` evars e) te es checkRecBinds (Core.Binds _ te es) = Core.Binds True te es
mattias-lundell/timber-llvm
src/Syntax2Core.hs
bsd-3-clause
21,951
0
18
9,503
6,702
3,316
3,386
278
5
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} module Text.Digestive.Heist.Extras.Value ( dfPathList , dfValueList ) where import Data.Map.Syntax ((##)) import Data.Monoid (mempty, (<>)) import qualified Data.Text as T import Heist import Heist.Interpreted import Text.Digestive.Types (Method, FormInput, Path, fromPath) import Text.Digestive.View import Text.Digestive.Form.Internal.Field import qualified Text.Digestive.Heist.Extras.Debug as D (dfPathList) import Text.Digestive.Heist.Extras.Internal.Field ---------------------------------------------------------------------- -- Provides a list of possible paths that are visible from the current view {-# DEPRECATED dfPathList "The dfPathList has been moved to Text.Digestive.Heist.Extras.Debug" #-} dfPathList :: Monad m => View T.Text -> Splice m dfPathList = D.dfPathList ---------------------------------------------------------------------- -- The purpose of this splice is to bind splices with static tag names so that -- the value of one field can be used as an attribute in another. dfValueList :: Monad m => View T.Text -> Splices (Splice m) dfValueList view@(View _ _ form input _ method) = let paths = debugViewPaths view splice :: Monad m => Path -> Splice m splice path = let givenInput = lookupInput path input in case queryField' path form (fieldSplice method givenInput) of Right s -> s Left e -> textSplice e in foldl (\xs x -> do xs; "dfValue:" <> fromPath x ## splice x) mempty paths fieldSplice :: Monad m => Method -> [FormInput] -> Field v a -> Splice m fieldSplice method givenInput field = case field of Text t -> textSplice $ evalField method givenInput (Text t) -- TODO: add splices for remaining Field types, as appropriate _ -> return []
cimmanon/digestive-functors-heist-extras
src/Text/Digestive/Heist/Extras/Value.hs
bsd-3-clause
1,866
12
14
321
454
248
206
36
2
even :: [a] -> [a] even [] = [] even [x] = [] even (x:y:z) = y : even z main :: Stream -> Stream main stdin = toStream $ unlines $ even $ lines $ fromStream stdin
tromp/hs2blc
examples/even_lines.hs
bsd-3-clause
164
0
8
39
103
53
50
6
1
module ABFA.Event where -- the event queue that handles all user input and many -- other things is defined import qualified Control.Concurrent.STM as STM import Control.Concurrent.STM.TChan import Control.Concurrent.STM.TMVar import qualified Control.Concurrent as CC import qualified GLUtil.ABFA as GLFW import ABFA.State -- type synonym type Queue = STM.TQueue -- all possible events data Event = EventError !GLFW.Error !String | EventWindowPos !GLFW.Window !Int !Int | EventWindowSize !GLFW.Window !Int !Int | EventWindowClose !GLFW.Window | EventWindowRefresh !GLFW.Window | EventFrameBufferSize !GLFW.Window !Int !Int | EventMouseButton !GLFW.Window !GLFW.MouseButton !GLFW.MouseButtonState !GLFW.ModifierKeys | EventCursorPos !GLFW.Window !Double !Double | EventCursorEnter !GLFW.Window !GLFW.CursorState | EventScroll !GLFW.Window !Double !Double | EventKey !GLFW.Window !GLFW.Key !Int !GLFW.KeyState !GLFW.ModifierKeys | EventChar !GLFW.Window !Char | EventWindowResize !GLFW.Window !Int !Int | EventLoaded !GameState | EventUpdateState !State | EventAnimState !State -- function synonym newQueue :: IO (STM.TQueue Event) newQueue = STM.newTQueueIO tryReadQueue :: STM.TQueue a -> STM.STM (Maybe a) tryReadQueue = STM.tryReadTQueue readQueue :: STM.TQueue a -> STM.STM a readQueue = STM.readTQueue writeQueue :: STM.TQueue a -> a -> STM.STM () writeQueue = STM.writeTQueue tryReadChan :: STM.TChan a -> STM.STM (Maybe a) tryReadChan = STM.tryReadTChan newChan :: IO (TChan a) newChan = atomically $ STM.newTChan readChan :: STM.TChan a -> STM.STM a readChan = STM.readTChan writeChan :: STM.TChan a -> a -> STM.STM () writeChan = STM.writeTChan atomically :: STM.STM a -> IO a atomically = STM.atomically threadDelay :: Int -> IO () threadDelay = CC.threadDelay -- empties a channel emptyChan :: STM.TChan a -> IO () emptyChan chan = do test <- atomically $ STM.isEmptyTChan chan if test then return () else do s <- atomically $ STM.readTChan chan emptyChan chan -- these event callbacks allow me to do things to GLFW or mine own program -- registers errors errorCallback :: Queue Event -> GLFW.Error -> String -> IO () errorCallback tc e s = atomically $ writeQueue tc $ EventError e s -- registers key states on input keyCallback :: Queue Event -> GLFW.Window -> GLFW.Key -> Int -> GLFW.KeyState -> GLFW.ModifierKeys -> IO () keyCallback tc win k sc ka mk = atomically $ writeQueue tc $ EventKey win k sc ka mk -- registers mouse buttons mouseButtonCallback :: Queue Event -> GLFW.Window -> GLFW.MouseButton -> GLFW.MouseButtonState -> GLFW.ModifierKeys -> IO () mouseButtonCallback tc win mb mbs mk = atomically $ writeQueue tc $ EventMouseButton win mb mbs mk -- registers mouse scrolling scrollCallback :: Queue Event -> GLFW.Window -> Double -> Double -> IO () scrollCallback tx win x y = atomically $ writeQueue tx $ EventScroll win x y -- called when the window is resized reshapeCallback :: Queue Event -> GLFW.Window -> Int -> Int -> IO () reshapeCallback tc win w h = atomically $ writeQueue tc $ EventWindowResize win w h -- call to change the state loadedCallback :: Queue Event -> GameState -> IO () loadedCallback tc state = atomically $ writeQueue tc $ EventLoaded state -- changes parts of the state with the world timer timerCallback :: Queue Event -> State -> IO () timerCallback tc state = atomically $ writeQueue tc $ EventUpdateState state -- changes parts of the state with the animation timer animCallback :: Queue Event -> State -> IO () animCallback tc state = atomically $ writeQueue tc $ EventAnimState state
coghex/abridgefaraway
src/ABFA/Event.hs
bsd-3-clause
3,746
0
13
739
1,111
550
561
144
2
{-# LANGUAGE TypeFamilies #-} module Test.AllStarTests where import Test.HUnit import ParserGenerator.AllStar import qualified Data.Set as DS --------------------------------TESTING----------------------------------------- instance Token Char where type Label Char = Char type Literal Char = Char getLabel c = c getLiteral c = c instance Token (a, b) where type Label (t1, t2) = t1 type Literal (t1, t2) = t2 getLabel (a, b) = a getLiteral (a, b) = b atnEnv = DS.fromList [ -- First path through the 'S' ATN (Init 'S', GS EPS, Middle 'S' 0 0), (Middle 'S' 0 0, GS (NT 'A'), Middle 'S' 0 1), (Middle 'S' 0 1, GS (T 'c'), Middle 'S' 0 2), (Middle 'S' 0 2, GS EPS, Final 'S'), -- Second path through the 'S' ATN (Init 'S', GS EPS, Middle 'S' 1 0), (Middle 'S' 1 0, GS (NT 'A'), Middle 'S' 1 1), (Middle 'S' 1 1, GS (T 'd'), Middle 'S' 1 2), (Middle 'S' 1 2, GS EPS, Final 'S'), -- First path through the 'A' ATN (Init 'A', GS EPS, Middle 'A' 0 0), (Middle 'A' 0 0, GS (T 'a'), Middle 'A' 0 1), (Middle 'A' 0 1, GS (NT 'A'), Middle 'A' 0 2), (Middle 'A' 0 2, GS EPS, Final 'A'), -- Second path through the 'A' ATN (Init 'A', GS EPS, Middle 'A' 1 0), (Middle 'A' 1 0, GS (T 'b'), Middle 'A' 1 1), (Middle 'A' 1 1, GS EPS, Final 'A')] -- For now, I'm only checking whether the input was accepted--not checking the derivation. -- Example from the manual trace of ALL(*)'s execution parseTest1 = TestCase (assertEqual "for parse [a, b, c]," (Right (Node 'S' [Node 'A' [Leaf 'a', Node 'A' [Leaf 'b']], Leaf 'c'])) (parse ['a', 'b', 'c'] (NT 'S') atnEnv True)) -- Example #1 from the ALL(*) paper parseTest2 = TestCase (assertEqual "for parse [b, c]," (Right (Node 'S' [Node 'A' [Leaf 'b'], Leaf 'c'])) (parse ['b', 'c'] (NT 'S') atnEnv True)) -- Example #2 from the ALL(*) paper parseTest3 = TestCase (assertEqual "for parse [b, d]," (Right (Node 'S' [Node 'A' [Leaf 'b'], Leaf 'd'])) (parse ['b', 'd'] (NT 'S') atnEnv True)) -- Input that requires more recursive traversals of the A ATN parseTest4 = TestCase (assertEqual "for parse [a a a b c]," (Right (Node 'S' [Node 'A' [Leaf 'a', Node 'A' [Leaf 'a', Node 'A' [Leaf 'a', Node 'A' [Leaf 'b']]]], Leaf 'c'])) (parse ['a', 'a', 'a', 'b', 'c'] (NT 'S') atnEnv True)) -- Make sure that the result of parsing an out-of-language string has a Left tag. parseTest5 = TestCase (assertEqual "for parse [a b a c]," True (let parseResult = parse ['a', 'b', 'a', 'c'] (NT 'S') atnEnv True isLeft pr = case pr of Left _ -> True _ -> False in isLeft parseResult)) -- To do: Update these tests so that they use the new ATN state representation. {- conflictsTest = TestCase (assertEqual "for getConflictSetsPerLoc()" ([[(MIDDLE 5, 1, []), (MIDDLE 5, 2, []),(MIDDLE 5, 3, [])], [(MIDDLE 5, 1, [MIDDLE 1]), (MIDDLE 5, 2, [MIDDLE 1])], [(MIDDLE 7, 2, [MIDDLE 6, MIDDLE 1])]] :: [[ATNConfig Char]]) (getConflictSetsPerLoc (D [(MIDDLE 5, 1, []), (MIDDLE 5, 2, []), (MIDDLE 5, 3, []), (MIDDLE 5, 1, [MIDDLE 1]), (MIDDLE 5, 2, [MIDDLE 1]), (MIDDLE 7, 2, [MIDDLE 6, MIDDLE 1])]))) prodsTest = TestCase (assertEqual "for getProdSetsPerState()" ([[(MIDDLE 5, 1, []), (MIDDLE 5, 2, []), (MIDDLE 5, 3, []), (MIDDLE 5, 1, [MIDDLE 1]), (MIDDLE 5, 2, [MIDDLE 1])], [(MIDDLE 7, 2, [MIDDLE 6, MIDDLE 1])]] :: [[ATNConfig Char]]) (getProdSetsPerState (D [(MIDDLE 5, 1, []), (MIDDLE 5, 2, []), (MIDDLE 5, 3, []), (MIDDLE 5, 1, [MIDDLE 1]), (MIDDLE 5, 2, [MIDDLE 1]), (MIDDLE 7, 2, [MIDDLE 6, MIDDLE 1])]))) -} ambigATNEnv = DS.fromList [(Init 'S', GS EPS, Middle 'S' 0 0), (Middle 'S' 0 0, GS (T 'a'), Middle 'S' 0 1), (Middle 'S' 0 1, GS EPS, Final 'S'), (Init 'S', GS EPS, Middle 'S' 1 0), (Middle 'S' 1 0, GS (T 'a'), Middle 'S' 1 1), (Middle 'S' 1 1, GS EPS, Final 'S'), (Init 'S', GS EPS, Middle 'S' 2 0), (Middle 'S' 2 0, GS (T 'a'), Middle 'S' 2 1), (Middle 'S' 2 1, GS (T 'b'), Middle 'S' 2 2), (Middle 'S' 2 2, GS EPS, Final 'S')] ambigParseTest1 = TestCase (assertEqual "for parse [a]," True (let parseResult = parse ['a'] (NT 'S') ambigATNEnv True isLeft pr = case pr of Left _ -> True _ -> False in isLeft parseResult)) ambigParseTest2 = TestCase (assertEqual "for parse [a b]," (Right (Node 'S' [Leaf 'a', Leaf 'b'])) (parse ['a', 'b'] (NT 'S') ambigATNEnv True)) -- ATN for a grammar that accepts either one or two 8s atomATN = DS.fromList [(Init "start",GS EPS,Middle "start" 0 0), (Init "s_expr",GS EPS,Middle "s_expr" 1 0), (Init "s_expr",GS EPS,Middle "s_expr" 2 0), (Init "atom",GS EPS,Middle "atom" 3 0), (Middle "start" 0 0,GS (NT "s_expr"),Middle "start" 0 1), (Middle "start" 0 1,GS EPS,Final "start"), (Middle "s_expr" 1 0,GS (NT "atom"),Middle "s_expr" 1 1), (Middle "s_expr" 1 1,GS EPS,Final "s_expr"), (Middle "s_expr" 2 0,GS (NT "atom"),Middle "s_expr" 2 1), (Middle "s_expr" 2 1,GS (NT "atom"),Middle "s_expr" 2 2), (Middle "s_expr" 2 2,GS EPS,Final "s_expr"), (Middle "atom" 3 0,GS (T '8'),Middle "atom" 3 1), (Middle "atom" 3 1,GS EPS,Final "atom")] parenItemSeqATN = DS.fromList [(Init "start",GS EPS,Middle "start" 0 0), (Init "list",GS EPS,Middle "list" 1 0), (Init "items",GS EPS,Middle "items" 2 0), (Init "items",GS EPS,Middle "items" 3 0), (Init "atom",GS EPS,Middle "atom" 4 0), (Middle "start" 0 0,GS (NT "list"),Middle "start" 0 1), (Middle "start" 0 1,GS EPS,Final "start"), (Middle "list" 1 0,GS (T '('),Middle "list" 1 1), (Middle "list" 1 1,GS (NT "items"),Middle "list" 1 2), (Middle "list" 1 2,GS (T ')'),Middle "list" 1 3), (Middle "list" 1 3,GS EPS,Final "list"), (Middle "items" 2 0,GS (NT "atom"),Middle "items" 2 1), (Middle "items" 2 1,GS EPS,Final "items"), (Middle "items" 3 0,GS (NT "atom"),Middle "items" 3 1), (Middle "items" 3 1,GS (NT "items"),Middle "items" 3 2), (Middle "items" 3 2,GS EPS,Final "items"), (Middle "atom" 4 0,GS (T '8'),Middle "atom" 4 1), (Middle "atom" 4 1,GS EPS,Final "atom")] tests = [TestLabel "parseTest1" parseTest1, TestLabel "parseTest2" parseTest2, TestLabel "parseTest3" parseTest3, TestLabel "parseTest4" parseTest4, TestLabel "parseTest5" parseTest5, --TestLabel "conflictsTest" conflictsTest, --TestLabel "prodsTest" prodsTest, TestLabel "ambigParseTest1" ambigParseTest1, TestLabel "ambigParseTest2" ambigParseTest2] main = runTestTT (TestList tests)
slasser/AllStar
Test/AllStarTests.hs
bsd-3-clause
11,072
0
21
5,960
2,519
1,314
1,205
131
2
module League.Types.Version ( Version(..) , VersionString(..) , version ) where import Control.Applicative import Control.Lens import Data.Aeson import Data.Monoid (mempty) import Data.Text (Text, splitOn, unpack) import Text.Read (readMaybe) import qualified Data.Version as Version data VersionString = VersionString Text deriving (Show, Read, Eq) instance FromJSON VersionString where parseJSON j = VersionString <$> parseJSON j data Version = Version [Int] deriving (Show, Read, Eq) version :: Iso' Version Version.Version version = iso (\(Version v) -> Version.Version v []) (\(Version.Version v _) -> Version v) instance FromJSON Version where parseJSON (String s) = maybe mempty (return . Version) $ mapM (readMaybe . unpack) (splitOn "." s) parseJSON _ = mempty
intolerable/league-of-legends
src/League/Types/Version.hs
bsd-3-clause
802
0
10
138
291
161
130
24
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_HADDOCK show-extensions #-} {-| Module : $Header$ Copyright : (c) 2016 Deakin Software & Technology Innovation Lab License : BSD3 Maintainer : Rhys Adams <[email protected]> Stability : unstable Portability : portable Entry point for the Eclogues CLI. -} module Main where import Prelude hiding (readFile) import qualified Eclogues.Client as C import qualified Eclogues.Job as Job import Control.Applicative (optional) import Control.Concurrent (threadDelay) import Control.Monad ((<=<)) import Control.Monad.IO.Class (liftIO) import Control.Monad.Loops (firstM, iterateUntil) import Control.Monad.Trans.Except (ExceptT, runExceptT) import Data.Aeson (ToJSON, encode, eitherDecode) import Data.Aeson.TH (deriveJSON, defaultOptions) import Data.Bifoldable (biList) import Data.Bifunctor (first) import Data.ByteString.Lazy (readFile) import qualified Data.ByteString.Lazy.Char8 as BSLC import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.List (foldl', intercalate) import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import qualified Data.Text as T import Data.Word (Word16) import Lens.Micro ((^.)) import Network.HTTP.Client (newManager, defaultManagerSettings) import Options.Applicative ( Parser, argument, strOption, strArgument, switch, option, auto , long, metavar, help, info, helper, fullDesc , subparser, command, progDesc, header, execParser ) import Options.Applicative.Types (readerAsk) import Servant.Client (BaseUrl (..), Scheme (Http)) import System.Directory (doesFileExist) import System.Environment.XDG.BaseDir (getAllConfigFiles) import System.Exit (die) -- | CLI options. data Opts = Opts { optHost :: Maybe String , optPort :: Maybe Word16 , optCommand :: Command } -- | CLI subcommand. data Command = ListJobs | JobStage Job.Name | CreateJob FilePath | KillJob Job.Name | DeleteJob Job.Name | WaitFor Job.Name | JobStats Bool -- | JSON configuration type. data ClientConfig = ClientConfig { host :: String, port :: Word16 } $(deriveJSON defaultOptions ''ClientConfig) -- | Find and read the config file. readConfigFile :: IO (Either String ClientConfig) readConfigFile = do paths <- getAllConfigFiles "eclogues" "client.json" path <- note "Cannot find config file" <$> firstM doesFileExist paths first ("Error in config file: " <>) . (eitherDecode =<<) <$> traverse readFile path where note n = maybe (Left n) Right go :: Opts -> IO () go Opts{..} = do http <- newManager defaultManagerSettings (hst, prt) <- readConfigFile >>= \case Right (ClientConfig ch cp) -> pure (fromMaybe ch optHost, fromMaybe cp optPort) Left _ -> pure (fromMaybe "localhost" optHost, fromMaybe 8000 optPort) let client = C.mkClient http (BaseUrl Http hst (fromIntegral prt) "") case optCommand of ListJobs -> runClient putJSON $ C.getJobs client JobStats as -> runClient (printStats as) $ C.getJobs client JobStage name -> runClient (print . (^. Job.stage)) $ C.getJobStatus client name DeleteJob name -> runClient pure $ C.deleteJob client name KillJob name -> runClient pure $ C.killJob client name CreateJob sf -> do cts <- readFile sf case eitherDecode cts of Right spec -> either (die . show) (const $ pure ()) <=< runExceptT $ C.createJob client spec Left err -> die $ "Invalid spec file: " ++ err WaitFor name -> runClient print . iterateUntil (Job.isTerminationStage . (^. Job.stage)) $ liftIO (threadDelay waitTime) *> C.getJobStatus client name where runClient :: forall a e. (Show e) => (a -> IO ()) -> ExceptT e IO a -> IO () runClient f = f <=< either (die . show) pure <=< runExceptT printStats :: Bool -> [Job.Status] -> IO () printStats as = mapM_ (putStrLn . intercalate "\t" . biList . fmap show) . HashMap.toList . getStats (statStart as) statStart :: Bool -> HashMap String Integer statStart False = HashMap.empty statStart True = foldl' (flip (`HashMap.insert` 0)) HashMap.empty Job.majorStages getStats :: HashMap String Integer -> [Job.Status] -> HashMap String Integer getStats = foldl' (\m j -> HashMap.insertWith (+) (Job.majorStage $ j ^. Job.stage) 1 m) waitTime = 2000000 -- 2 seconds in microseconds putJSON :: (ToJSON a) => a -> IO () putJSON = BSLC.putStrLn . encode main :: IO () main = go =<< execParser opts where opts = info (helper <*> optsP) ( fullDesc <> header "eclogues-client - Direct an Eclogues task scheduler" ) optsP :: Parser Opts optsP = Opts <$> hostOpt <*> portOpt <*> cmdOpt hostOpt = optional $ strOption (long "host" <> metavar "HOST" <> help "Eclogues host") portOpt = optional $ option auto (long "port" <> metavar "PORT" <> help "Eclogues port") cmdOpt :: Parser Command cmdOpt = subparser ( command "list" (info (pure ListJobs) (progDesc "List all jobs")) <> command "stage" (info (JobStage <$> nameArg) (progDesc "Get the stage of a job")) <> command "create" (info (CreateJob <$> specArg) (progDesc "Schedule a job")) <> command "kill" (info (KillJob <$> nameArg) (progDesc "Kill a job")) <> command "delete" (info (DeleteJob <$> nameArg) (progDesc "Delete a job")) <> command "wait" (info (WaitFor <$> nameArg) (progDesc "Wait for a job to terminate")) <> command "stats" (info (JobStats <$> allArg) (progDesc "Get running job stats"))) nameArg = argument (Job.mkName . T.pack =<< readerAsk) (metavar "JOB_NAME") specArg = strArgument (metavar "SPEC_FILE") allArg = switch (long "all-stages" <> help "List stages with no associated jobs")
rimmington/eclogues
eclogues-impl/app/client/Main.hs
bsd-3-clause
6,108
0
21
1,403
1,820
972
848
111
10
-- #hide -------------------------------------------------------------------------------- -- | -- Module : Sound.OpenAL.AL.SourceState -- Copyright : (c) Sven Panne 2003-2005 -- License : BSD-style (see the file libraries/OpenAL/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -------------------------------------------------------------------------------- module Sound.OpenAL.AL.SourceState ( SourceState(..), unmarshalSourceState ) where import Sound.OpenAL.AL.BasicTypes ( ALint ) import Sound.OpenAL.Constants ( al_INITIAL, al_PLAYING, al_PAUSED, al_STOPPED ) -------------------------------------------------------------------------------- -- | Each source can be in one of four possible execution states: 'Initial', -- 'Playing', 'Paused', 'Stopped'. Sources that are either 'Playing' or 'Paused' -- are considered active. Sources that are 'Stopped' or 'Initial' are considered -- inactive. Only 'Playing' sources are included in the processing. The -- implementation is free to skip those processing stages for sources that have -- no effect on the output (e.g. mixing for a source muted by zero gain, but not -- sample offset increments). Depending on the current state of a source certain -- (e.g. repeated) state transition commands are legal NOPs: they will be -- ignored, no error is generated. data SourceState = Initial | Playing | Paused | Stopped deriving ( Eq, Ord, Show ) unmarshalSourceState :: ALint -> SourceState unmarshalSourceState x | x == al_INITIAL = Initial | x == al_PLAYING = Playing | x == al_PAUSED = Paused | x == al_STOPPED = Stopped | otherwise = error ("unmarshalSourceState: illegal value " ++ show x)
FranklinChen/hugs98-plus-Sep2006
packages/OpenAL/Sound/OpenAL/AL/SourceState.hs
bsd-3-clause
1,759
0
9
289
193
116
77
17
1
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, PatternGuards #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.Gaps -- Description : Create manually-sized gaps along edges of the screen. -- Copyright : (c) 2008 Brent Yorgey -- License : BSD3 -- -- Maintainer : <[email protected]> -- Stability : unstable -- Portability : unportable -- -- Create manually-sized gaps along edges of the screen which will not -- be used for tiling, along with support for toggling gaps on and -- off. -- -- Note 1: For gaps\/space around /windows/ see "XMonad.Layout.Spacing". -- -- Note 2: "XMonad.Hooks.ManageDocks" is the preferred solution for -- leaving space for your dock-type applications (status bars, -- toolbars, docks, etc.), since it automatically sets up appropriate -- gaps, allows them to be toggled, etc. However, this module may -- still be useful in some situations where the automated approach of -- ManageDocks does not work; for example, to work with a dock-type -- application that does not properly set the STRUTS property, or to -- leave part of the screen blank which is truncated by a projector, -- and so on. ----------------------------------------------------------------------------- module XMonad.Layout.Gaps ( -- * Usage -- $usage Direction2D(..), Gaps, GapSpec, gaps, gaps', GapMessage(..), weakModifyGaps, modifyGap, setGaps, setGap ) where import XMonad.Prelude (delete, fi) import XMonad.Core import Graphics.X11 (Rectangle(..)) import XMonad.Layout.LayoutModifier import XMonad.Util.Types (Direction2D(..)) -- $usage -- You can use this module by importing it into your @~\/.xmonad\/xmonad.hs@ file: -- -- > import XMonad.Layout.Gaps -- -- and applying the 'gaps' modifier to your layouts as follows (for -- example): -- -- > layoutHook = gaps [(U,18), (R,23)] $ Tall 1 (3/100) (1/2) ||| Full -- leave gaps at the top and right -- -- You can additionally add some keybindings to toggle or modify the gaps, -- for example: -- -- > , ((modm .|. controlMask, xK_g), sendMessage $ ToggleGaps) -- toggle all gaps -- > , ((modm .|. controlMask, xK_t), sendMessage $ ToggleGap U) -- toggle the top gap -- > , ((modm .|. controlMask, xK_w), sendMessage $ IncGap 5 R) -- increment the right-hand gap -- > , ((modm .|. controlMask, xK_q), sendMessage $ DecGap 5 R) -- decrement the right-hand gap -- > , ((modm .|. controlMask, xK_r), sendMessage $ ModifyGaps rotateGaps) -- rotate gaps 90 degrees clockwise -- > , ((modm .|. controlMask, xK_h), sendMessage $ weakModifyGaps halveHor) -- halve the left and right-hand gaps -- > , ((modm .|. controlMask, xK_d), sendMessage $ modifyGap (*2) L) -- double the left-hand gap -- > , ((modm .|. controlMask, xK_s), sendMessage $ setGaps [(U,18), (R,23)]) -- reset the GapSpec -- > , ((modm .|. controlMask, xK_b), sendMessage $ setGap 30 D) -- set the bottom gap to 30 -- > ] -- > where rotateGaps gs = zip (map (rotate . fst) gs) (map snd gs) -- > rotate U = R -- > rotate R = D -- > rotate D = L -- > rotate L = U -- > halveHor d i | d `elem` [L, R] = i `div` 2 -- > | otherwise = i -- -- If you want complete control over all gaps, you could include -- something like this in your keybindings, assuming in this case you -- are using 'XMonad.Util.EZConfig.mkKeymap' or -- 'XMonad.Util.EZConfig.additionalKeysP' from "XMonad.Util.EZConfig" -- for string keybinding specifications: -- -- > ++ -- > [ ("M-g " ++ f ++ " " ++ k, sendMessage $ m d) -- > | (k, d) <- [("a",L), ("s",D), ("w",U), ("d",R)] -- > , (f, m) <- [("v", ToggleGap), ("h", IncGap 10), ("f", DecGap 10)] -- > ] -- -- Given the above keybinding definition, for example, you could type -- @M-g, v, a@ to toggle the top gap. -- -- To configure gaps differently per-screen, use -- "XMonad.Layout.PerScreen" (coming soon). -- -- __Warning__: If you also use the 'avoidStruts' layout modifier, it -- must come /before/ any of these modifiers. See the documentation of -- 'avoidStruts' for details. -- | A manual gap configuration. Each side of the screen on which a -- gap is enabled is paired with a size in pixels. type GapSpec = [(Direction2D,Int)] -- | The gap state. The first component is the configuration (which -- gaps are allowed, and their current size), the second is the gaps -- which are currently active. data Gaps a = Gaps GapSpec [Direction2D] deriving (Show, Read) -- | Messages which can be sent to a gap modifier. data GapMessage = ToggleGaps -- ^ Toggle all gaps. | ToggleGap !Direction2D -- ^ Toggle a single gap. | IncGap !Int !Direction2D -- ^ Increase a gap by a certain number of pixels. | DecGap !Int !Direction2D -- ^ Decrease a gap. | ModifyGaps (GapSpec -> GapSpec) -- ^ Modify arbitrarily. instance Message GapMessage instance LayoutModifier Gaps a where modifyLayout g w r = runLayout w (applyGaps g r) pureMess (Gaps conf cur) m | Just ToggleGaps <- fromMessage m = Just $ Gaps conf (toggleGaps conf cur) | Just (ToggleGap d) <- fromMessage m = Just $ Gaps conf (toggleGap conf cur d) | Just (IncGap i d) <- fromMessage m = Just $ Gaps (limit . continuation (+ i ) d $ conf) cur | Just (DecGap i d) <- fromMessage m = Just $ Gaps (limit . continuation (+(-i)) d $ conf) cur | Just (ModifyGaps f) <- fromMessage m = Just $ Gaps (limit . f $ conf) cur | otherwise = Nothing -- | Modifies gaps weakly, for convenience. weakModifyGaps :: (Direction2D -> Int -> Int) -> GapMessage weakModifyGaps = ModifyGaps . weakToStrong -- | Arbitrarily modify a single gap with the given function. modifyGap :: (Int -> Int) -> Direction2D -> GapMessage modifyGap f d = ModifyGaps $ continuation f d -- | Set the GapSpec. setGaps :: GapSpec -> GapMessage setGaps = ModifyGaps . const -- | Set a gap to the given value. setGap :: Int -> Direction2D -> GapMessage setGap = modifyGap . const -- | Imposes limits upon a GapSpec, ensuring gaps are at least 0. Not exposed. limit :: GapSpec -> GapSpec limit = weakToStrong $ \_ -> max 0 -- | Takes a weak gaps-modifying function f and returns a GapSpec modifying -- function. Not exposed. weakToStrong :: (Direction2D -> Int -> Int) -> GapSpec -> GapSpec weakToStrong f gs = zip (map fst gs) (map (uncurry f) gs) -- | Given f as a definition for the behaviour of a gaps modifying function in -- one direction d, produces a continuation of the function to the other -- directions using the identity. Not exposed. continuation :: (Int -> Int) -> Direction2D -> GapSpec -> GapSpec continuation f d1 = weakToStrong h where h d2 | d2 == d1 = f | otherwise = id applyGaps :: Gaps a -> Rectangle -> Rectangle applyGaps gs r = foldr applyGap r (activeGaps gs) where applyGap (U,z) (Rectangle x y w h) = Rectangle x (y + fi z) w (h - fi z) applyGap (D,z) (Rectangle x y w h) = Rectangle x y w (h - fi z) applyGap (L,z) (Rectangle x y w h) = Rectangle (x + fi z) y (w - fi z) h applyGap (R,z) (Rectangle x y w h) = Rectangle x y (w - fi z) h activeGaps :: Gaps a -> GapSpec activeGaps (Gaps conf cur) = filter ((`elem` cur) . fst) conf toggleGaps :: GapSpec -> [Direction2D] -> [Direction2D] toggleGaps conf [] = map fst conf toggleGaps _ _ = [] toggleGap :: GapSpec -> [Direction2D] -> Direction2D -> [Direction2D] toggleGap conf cur d | d `elem` cur = delete d cur | d `elem` map fst conf = d:cur | otherwise = cur -- | Add togglable manual gaps to a layout. gaps :: GapSpec -- ^ The gaps to allow, paired with their initial sizes. -> l a -- ^ The layout to modify. -> ModifiedLayout Gaps l a gaps g = ModifiedLayout (Gaps g (map fst g)) -- | Add togglable manual gaps to a layout, explicitly specifying the initial states. gaps' :: [((Direction2D,Int),Bool)] -- ^ The gaps to allow and their initial states. -> l a -- ^ The layout to modify. -> ModifiedLayout Gaps l a gaps' g = ModifiedLayout (Gaps (map fst g) [d | ((d,_),v) <- g, v])
xmonad/xmonad-contrib
XMonad/Layout/Gaps.hs
bsd-3-clause
8,489
0
15
2,091
1,432
795
637
82
4
{-# LANGUAGE FlexibleContexts #-} module Ifrit.Framework where import Control.Failure data Message = TitledMessage { title :: String , message :: String } deriving (Eq, Show) class Sendable a where send :: a -> Message -> IO Bool class Receivable a where receive :: a -> IO Message
frio/ifrit
src/hs/Ifrit/Framework.hs
bsd-3-clause
349
0
9
114
90
49
41
10
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TupleSections #-} module Main ( main ) where import Jerimum.Storage.LMDB.Device as D import Jerimum.Storage.LMDB.Segment as S import qualified Jerimum.Tests.Unit.PostgreSQL.CodecTest as PostgreSQLCodec import qualified Jerimum.Tests.Unit.PostgreSQL.Types.AnyTest as AnyTest import qualified Jerimum.Tests.Unit.PostgreSQL.Types.BinaryTest as BinaryTest import qualified Jerimum.Tests.Unit.PostgreSQL.Types.BooleanTest as BooleanTest import qualified Jerimum.Tests.Unit.PostgreSQL.Types.DateRangeTest as DateRangeTest import qualified Jerimum.Tests.Unit.PostgreSQL.Types.DateTimeTest as DateTimeTest import qualified Jerimum.Tests.Unit.PostgreSQL.Types.Int32ArrayTest as Int32ArrayTest import qualified Jerimum.Tests.Unit.PostgreSQL.Types.LsnTest as LsnTest import qualified Jerimum.Tests.Unit.PostgreSQL.Types.NumericTest as NumericTest import qualified Jerimum.Tests.Unit.PostgreSQL.Types.TextTest as TextTest import qualified Jerimum.Tests.Unit.PostgreSQL.Types.TypeTest as TypeTest import qualified Jerimum.Tests.Unit.PostgreSQL.Types.UUIDTest as UUIDTest import qualified Jerimum.Tests.Unit.Storage.LMDB.DeviceTest as StorageDevice import qualified Jerimum.Tests.Unit.Storage.LMDB.SegmentTest as StorageSegment import System.Directory import System.IO.Temp import Test.Tasty allTests :: TestTree allTests = testGroup "unit-tests" [ PostgreSQLCodec.tests , BinaryTest.tests , BooleanTest.tests , TypeTest.tests , NumericTest.tests , TextTest.tests , UUIDTest.tests , DateTimeTest.tests , LsnTest.tests , DateRangeTest.tests , AnyTest.tests , Int32ArrayTest.tests , withResource acquireDevice releaseDevice (StorageDevice.tests . useDevice) , withResource acquireHandle releaseHandle (StorageSegment.tests . useSegment) ] main :: IO () main = defaultMain allTests acquireDevice :: IO (FilePath, Device) acquireDevice = do systempdir <- getCanonicalTemporaryDirectory jTempDir <- createTempDirectory systempdir "jerimum" (jTempDir, ) <$> D.open jTempDir (256 * 1024 * 1024) releaseDevice :: (FilePath, Device) -> IO () releaseDevice (path, device) = do D.close device removeDirectoryRecursive path acquireHandle :: IO (FilePath, Handle 'RW) acquireHandle = do systempdir <- getCanonicalTemporaryDirectory jTempDir <- createTempDirectory systempdir "jerimum" (jTempDir, ) <$> S.open jTempDir (256 * 1024 * 1024) S.rwMode releaseHandle :: (FilePath, Handle 'RW) -> IO () releaseHandle (path, handle) = do S.close handle removeDirectoryRecursive path useSegment :: IO (a, S.Handle 'S.RW) -> IO (S.Handle 'S.RW) useSegment getSegment = do segment <- snd <$> getSegment S.truncate segment pure segment useDevice :: IO (a, Device) -> IO Device useDevice getDevice = do device <- snd <$> getDevice D.truncate device pure device
dgvncsz0f/nws
test/unit-tests.hs
bsd-3-clause
3,067
0
11
589
716
426
290
74
1
------------------------------------------------------------------------------- -- | -- Module : Network.MacAddress -- Copyright : (c) 2009, Tom Lokhorst -- License : BSD3 -- -- Maintainer : Tom Lokhorst <[email protected]> -- Stability : Experimental -- -- A 'sort of' reusable module for mac addresses. -- ------------------------------------------------------------------------------- module Network.MacAddress ( MacAddress (..) , parse , bytes ) where import Data.List.Split import Data.Word import Numeric data MacAddress = MacAddress Word8 Word8 Word8 Word8 Word8 Word8 instance Show MacAddress where show (MacAddress b0 b1 b2 b3 b4 b5) = ( showHex b0 . colon . showHex b1 . colon . showHex b2 . colon . showHex b3 . colon . showHex b4 . colon . showHex b5) "" where colon = showString ":" -- | Partial function to "parse" a `String` to a `MacAddress` parse :: String -> MacAddress parse s = let parts = splitOn ":" s words = map (fst . head . readHex) parts in if length words /= 6 then error $ "Network.MacAddress.parse: malformed MacAddress '" ++ s ++ "'" else MacAddress (words !! 0) (words !! 1) (words !! 2) (words !! 3) (words !! 4) (words !! 5) -- | Get all bytes in a mac address bytes :: MacAddress -> [Word8] bytes (MacAddress b0 b1 b2 b3 b4 b5) = [b0, b1, b2, b3, b4, b5]
tomlokhorst/wol
src/Network/MacAddress.hs
bsd-3-clause
1,390
0
18
317
364
199
165
23
2
-- | -- Module : Data.OI.Force -- Copyright : (c) Nobuo Yamashita 2012-2016 -- License : BSD3 -- Author : Nobuo Yamashita -- Maintainer : [email protected] -- Stability : experimental -- module Data.OI.Force ( -- * Forcing utility functions force ,force' ,forceSeq ) where import Control.Parallel -- | forces sequence forceSeq :: [a] -> () forceSeq = force . dropWhile (()==) . map force -- | forces force :: a -> () force x = x `pseq` () -- | returns forcing invoker force' :: a -> (a,()) force' x = x `pseq` (x,())
nobsun/oi
src/Data/OI/Force.hs
bsd-3-clause
551
0
9
128
140
86
54
11
1
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-} {-# LANGUAGE OverloadedStrings #-} module NLP.Verba.Parser ( readInflections, readDictEntries, readInflectionsFile, readDictEntriesFile ) where import Control.Applicative ((<|>)) import Control.Monad (void) import Data.Char (digitToInt, isDigit) import Data.Attoparsec.Text (Parser, parseOnly, string, char, letter, digit, satisfy, inClass, choice, takeTill, takeWhile1, sepBy1, endOfLine, isEndOfLine, isHorizontalSpace, skipMany) import qualified Data.Attoparsec.Text as Attoparsec import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T.IO import NLP.Verba.Types import Paths_verba (getDataFileName) readCase :: Text -> Case readCase "NOM" = Nominative readCase "GEN" = Genitive readCase "ACC" = Accusative readCase "ABL" = Ablative readCase "VOC" = Vocative readCase "LOC" = Locative readCase _ = OtherCase caseP :: Parser Case caseP = readCase <$> choice (map string ["X", "NOM", "GEN", "ACC", "DAT", "ABL", "VOC", "LOC"]) readGender :: Char -> Gender readGender 'M' = Masculine readGender 'F' = Feminine readGender 'N' = Neuter readGender 'C' = Common readGender _ = OtherGender genderP :: Parser Gender genderP = readGender <$> satisfy (inClass "MFNCX") readNumber :: Char -> Number readNumber 'S' = Singular readNumber 'P' = Plural readNumber _ = OtherNumber numberP :: Parser Number numberP = readNumber <$> satisfy (inClass "SPX") readTense :: Text -> Tense readTense "PRES" = Present readTense "IMPF" = Imperfect readTense "FUT" = Future readTense "PERF" = Perfect readTense "PLUP" = Pluperfect readTense "FUTP" = FuturePerfect readTense _ = OtherTense tenseP :: Parser Tense tenseP = readTense <$> choice (map string ["X", "PRES", "IMPF", "FUTP", "FUT", "PERF", "PLUP"]) readVoice :: Text -> Voice readVoice "ACTIVE" = Active readVoice "PASSIVE" = Passive readVoice _ = OtherVoice voiceP :: Parser Voice voiceP = readVoice <$> choice (map string ["X", "ACTIVE", "PASSIVE"]) readMood :: Text -> Mood readMood "IND" = Indicative readMood "SUB" = Subjunctive readMood "IMP" = Imperative readMood "INF" = Infinitive readMood "PPL" = Participle readMood _ = OtherMood moodP :: Parser Mood moodP = readMood <$> choice (map string ["X", "IND", "SUB", "IMP", "INF", "PPL"]) digitP :: Parser Int digitP = digitToInt <$> digit readPerson :: Char -> Person readPerson '1' = First readPerson '2' = Second readPerson '3' = Third readPerson _ = OtherPerson personP :: Parser Person personP = readPerson <$> digit readComparison :: Text -> Comparison readComparison "POS" = Positive readComparison "COMP" = Comparative readComparison "SUP" = Superlative readComparison _ = OtherComparison comparisonP :: Parser Comparison comparisonP = readComparison <$> choice (map string ["X", "POS", "COMP", "SUPER"]) readNumeralType :: Text -> NumeralType readNumeralType "CARD" = Cardinal readNumeralType "ORD" = Ordinal readNumeralType "DIST" = Distributive readNumeralType "ADVERB" = Adverbial readNumeralType _ = OtherNumeralType numeralTypeP :: Parser NumeralType numeralTypeP = readNumeralType <$> choice (map string ["X", "CARD", "ORD", "DIST", "ADVERB"]) sepP :: Parser () sepP = takeWhile1 isHorizontalSpace >> pure () declensionP :: Parser Declension declensionP = do major <- digitP <* sepP minor <- digitP pure (major, minor) endingP :: Parser (Int, Text, Age, Freq) endingP = do stemIndex <- digitP <* sepP endingLen <- digitP <* sepP ending <- if endingLen > 0 then takeTill isHorizontalSpace <* sepP else pure "" age <- letter <* sepP freq <- letter pure (stemIndex, ending, age, freq) nounInfP :: Parser Inflection nounInfP = do char 'N' <* sepP declension <- declensionP <* sepP kase <- caseP <* sepP number <- numberP <* sepP gender <- genderP <* sepP (stemIndex, ending, age, freq) <- endingP pure Inflection { _ending = ending, _declension = declension, _stemIndex = stemIndex, _info = NounInfo kase gender number, _age = age, _freq = freq} verbInfP :: Parser Inflection verbInfP = do char 'V' <* sepP declension <- declensionP <* sepP tense <- tenseP <* sepP voice <- voiceP <* sepP mood <- moodP <* sepP person <- personP <* sepP number <- numberP <* sepP (stemIndex, ending, age, freq) <- endingP pure Inflection { _ending = ending , _declension = declension , _stemIndex = stemIndex , _info = VerbInfo tense voice mood person number , _age = age , _freq = freq } adjectiveInfP :: Parser Inflection adjectiveInfP = do string "ADJ" <* sepP declension <- declensionP <* sepP kase <- caseP <* sepP number <- numberP <* sepP gender <- genderP <* sepP comparison <- comparisonP <* sepP (stemIndex, ending, age, freq) <- endingP pure Inflection { _ending = ending , _declension = declension , _stemIndex = stemIndex , _info = AdjectiveInfo kase gender number comparison , _age = age , _freq = freq } pronounInfP :: Parser Inflection pronounInfP = do string "PRON" <* sepP declension <- declensionP <* sepP kase <- caseP <* sepP number <- numberP <* sepP gender <- genderP <* sepP (stemIndex, ending, age, freq) <- endingP pure Inflection { _ending = ending , _declension = declension , _stemIndex = stemIndex , _info = PronounInfo kase gender number , _age = age , _freq = freq } adverbInfP :: Parser Inflection adverbInfP = do string "ADV" <* sepP comparison <- comparisonP <* sepP (stemIndex, ending, age, freq) <- endingP pure Inflection { _ending = ending , _declension = (0, 0) , _stemIndex = stemIndex , _info = AdverbInfo comparison , _age = age , _freq = freq } prepositionInfP :: Parser Inflection prepositionInfP = do string "PREP" <* sepP kase <- caseP <* sepP (stemIndex, ending, age, freq) <- endingP pure Inflection { _ending = ending , _declension = (0, 0) , _stemIndex = stemIndex , _info = PrepositionInfo kase , _age = age , _freq = freq } conjunctionInfP :: Parser Inflection conjunctionInfP = do string "CONJ" <* sepP (stemIndex, ending, age, freq) <- endingP pure Inflection { _ending = ending , _declension = (0, 0) , _stemIndex = stemIndex , _info = ConjunctionInfo , _age = age , _freq = freq } interjectionInfP :: Parser Inflection interjectionInfP = do string "INTERJ" <* sepP (stemIndex, ending, age, freq) <- endingP pure Inflection { _ending = ending , _declension = (0, 0) , _stemIndex = stemIndex , _info = InterjectionInfo , _age = age , _freq = freq } verbParticipleInfP :: Parser Inflection verbParticipleInfP = do string "VPAR" <* sepP declension <- declensionP <* sepP kase <- caseP <* sepP number <- numberP <* sepP gender <- genderP <* sepP tense <- tenseP <* sepP voice <- voiceP <* sepP mood <- moodP <* sepP (stemIndex, ending, age, freq) <- endingP pure Inflection { _ending = ending , _declension = declension , _stemIndex = stemIndex , _info = VerbParticipleInfo kase gender number tense voice mood , _age = age , _freq = freq } supineInfP :: Parser Inflection supineInfP = do string "SUPINE" <* sepP declension <- declensionP <* sepP kase <- caseP <* sepP number <- numberP <* sepP gender <- genderP <* sepP (stemIndex, ending, age, freq) <- endingP pure Inflection { _ending = ending , _declension = declension , _stemIndex = stemIndex , _info = SupineInfo kase gender number , _age = age , _freq = freq } numeralInfP :: Parser Inflection numeralInfP = do string "NUM" <* sepP declension <- declensionP <* sepP kase <- caseP <* sepP number <- numberP <* sepP gender <- genderP <* sepP form <- numeralTypeP <* sepP (stemIndex, ending, age, freq) <- endingP pure Inflection { _ending = ending , _declension = declension , _stemIndex = stemIndex , _info = NumeralInfo kase gender number form , _age = age , _freq = freq } inflectionP :: Parser Inflection inflectionP = choice [nounInfP, verbInfP, adjectiveInfP, pronounInfP, adverbInfP, prepositionInfP, conjunctionInfP, interjectionInfP, verbParticipleInfP, supineInfP, numeralInfP] inflectionLineP :: Parser Inflection inflectionLineP = do Attoparsec.takeWhile isHorizontalSpace inf <- inflectionP takeTill isEndOfLine pure inf commentP :: Parser Text commentP = do Attoparsec.takeWhile isHorizontalSpace string "--" Attoparsec.takeWhile isHorizontalSpace takeTill isEndOfLine blankLineP :: Parser () blankLineP = Attoparsec.takeWhile isHorizontalSpace *> endOfLine skipLinesP :: Parser () skipLinesP = skipMany (void commentP <|> blankLineP) inflectionsP :: Parser [Inflection] inflectionsP = skipLinesP *> sepBy1 inflectionLineP skipLinesP nounTypeP :: Parser NounType nounTypeP = satisfy (inClass "XSMAGNPTLW") readVerbType :: Text -> VerbType readVerbType "TO_BE" = ToBe readVerbType "TO_BEING" = ToBeing readVerbType "GEN" = TakesGenitive readVerbType "DAT" = TakesDative readVerbType "ABL" = TakesAblative readVerbType "TRANS" = Transitive readVerbType "INTRANS" = Intransitive readVerbType "IMPERS" = Impersonal readVerbType "DEP" = Deponent readVerbType "SEMIDEP" = SemiDeponent readVerbType "PERFDEF" = PerfectDefinite readVerbType _ = OtherVerbType verbTypeP :: Parser VerbType verbTypeP = readVerbType <$> choice (map string ["X", "TO_BEING", "TO_BE", "GEN", "DAT", "ABL", "TRANS", "INTRANS", "IMPERS", "DEP", "SEMIDEP", "PERFDEF"]) readPronounType :: Text -> PronounType readPronounType "PERS" = Personal readPronounType "REL" = Relative readPronounType "REFLEX" = Reflexive readPronounType "DEMONS" = Demonstrative readPronounType "INTERR" = Interrogative readPronounType "INDEF" = Indefinite readPronounType "ADJECT" = Adjectival readPronounType _ = OtherPronounType pronounTypeP :: Parser PronounType pronounTypeP = readPronounType <$> choice (map string ["X", "PERS", "REL", "REFLEX", "DEMONS", "INTERR", "INDEF", "ADJECT"]) tagsP :: Parser [Char] tagsP = do t0 <- letter <* sepP t1 <- letter <* sepP t2 <- letter <* sepP t3 <- letter <* sepP t4 <- letter pure [t0, t1, t2, t3, t4] stemsP :: Parser [Text] stemsP = do s0 <- Attoparsec.take 19 s1 <- Attoparsec.take 19 s2 <- Attoparsec.take 19 s3 <- Attoparsec.take 19 pure (map T.strip [s0, s1, s2, s3]) definitionP :: Parser Text definitionP = takeTill isEndOfLine nounSubP :: Parser (Declension, SubEntry) nounSubP = do char 'N' <* sepP declension <- declensionP <* sepP gender <- genderP <* sepP nt <- nounTypeP pure (declension, NounEntry gender nt) verbSubP :: Parser (Declension, SubEntry) verbSubP = do char 'V' <* sepP declension <- declensionP <* sepP vt <- verbTypeP pure (declension, VerbEntry vt) adjectiveSubP :: Parser (Declension, SubEntry) adjectiveSubP = do string "ADJ" <* sepP declension <- declensionP <* sepP comparison <- comparisonP pure (declension, AdjectiveEntry comparison) pronounSubP :: Parser (Declension, SubEntry) pronounSubP = do string "PRON" <* sepP declension <- declensionP <* sepP pt <- pronounTypeP pure (declension, PronounEntry pt) adverbSubP :: Parser (Declension, SubEntry) adverbSubP = do string "ADV" <* sepP comparison <- comparisonP pure ((0, 0), AdverbEntry comparison) prepositionSubP :: Parser (Declension, SubEntry) prepositionSubP = do string "PREP" <* sepP kase <- caseP pure ((0, 0), PrepositionEntry kase) conjunctionSubP :: Parser (Declension, SubEntry) conjunctionSubP = string "CONJ" >> pure ((0, 0), ConjunctionEntry) interjectionSubP :: Parser (Declension, SubEntry) interjectionSubP = string "INTERJ" >> pure ((0, 0), InterjectionEntry) numeralSubP :: Parser (Declension, SubEntry) numeralSubP = do string "NUM" <* sepP declension <- declensionP <* sepP nf <- numeralTypeP <* sepP _num <- Attoparsec.takeWhile isDigit pure (declension, NumeralEntry nf) packSubP :: Parser (Declension, SubEntry) packSubP = do string "PACK" <* sepP declension <- declensionP <* sepP pt <- pronounTypeP pure (declension, PackEntry pt) subEntryP :: Parser (Declension, SubEntry) subEntryP = choice [nounSubP, verbSubP, adjectiveSubP, pronounSubP, adverbSubP, prepositionSubP, conjunctionSubP, interjectionSubP, numeralSubP, packSubP] dictEntryP :: Parser DictEntry dictEntryP = do stems <- stemsP (declension, sub) <- subEntryP <* sepP tags <- tagsP <* sepP definition <- definitionP pure DictEntry { _stems = stems , _entryDeclension = declension , _tags = tags , _definition = definition , _sub = sub } dictEntriesP :: Parser [DictEntry] dictEntriesP = sepBy1 dictEntryP endOfLine -- | Parse a list of inflections from the format used by -- Whitaker's Words program. readInflections :: Text -> Either String [Inflection] readInflections = parseOnly inflectionsP -- | Parse a list of dictionary entries from the format used by -- Whitaker's Words program. readDictEntries :: Text -> Either String [DictEntry] readDictEntries = parseOnly dictEntriesP -- | Parse the standard inflections file shipped with Verba. readInflectionsFile :: IO (Either String [Inflection]) readInflectionsFile = do path <- getDataFileName "data/inflects.lat" text <- T.IO.readFile path return (readInflections text) -- | Parse the standard dictionary file shipped with Verba. readDictEntriesFile :: IO (Either String [DictEntry]) readDictEntriesFile = do path <- getDataFileName "data/dictline.gen" text <- T.IO.readFile path return (readDictEntries text)
micxjo/verba
src/NLP/Verba/Parser.hs
bsd-3-clause
14,175
0
10
3,168
4,236
2,233
2,003
432
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleInstances #-} -- | Transition map with a hash. module Data.DAWG.Trans.Hashed ( Hashed (..) ) where import Prelude hiding (lookup) import Control.Applicative ((<$>), (<*>)) import Data.DAWG.Util (combine) import Data.Binary (Binary, put, get) import Data.DAWG.Trans import qualified Data.DAWG.Trans.Map as M import qualified Data.DAWG.Trans.Vector as V -- | Hash of a transition map is a sum of element-wise hashes. -- Hash for a given element @(Sym, ID)@ is equal to @combine Sym ID@. data Hashed t = Hashed { hash :: {-# UNPACK #-} !Int , trans :: !t } deriving (Show) instance Binary t => Binary (Hashed t) where put Hashed{..} = put hash >> put trans get = Hashed <$> get <*> get instance Trans t => Trans (Hashed t) where empty = Hashed 0 empty {-# INLINE empty #-} lookup x = lookup x . trans {-# INLINE lookup #-} index x = index x . trans {-# INLINE index #-} byIndex i = byIndex i . trans {-# INLINE byIndex #-} insert x y (Hashed h t) = Hashed (h - h' + combine x y) (insert x y t) where h' = case lookup x t of Just y' -> combine x y' Nothing -> 0 {-# INLINE insert #-} fromList xs = Hashed (sum $ map (uncurry combine) xs) (fromList xs) {-# INLINE fromList #-} toList = toList . trans {-# INLINE toList #-} deriving instance Eq (Hashed M.Trans) deriving instance Ord (Hashed M.Trans) deriving instance Eq (Hashed V.Trans) deriving instance Ord (Hashed V.Trans)
kawu/dawg
src/Data/DAWG/Trans/Hashed.hs
bsd-2-clause
1,645
0
11
441
472
260
212
47
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} module Numeric.Units.Dimensional.Parsing.Units2 ( Parser , ParsedUnitName , topLevel , lexeme , symbol , quantity , unitName , atomicUnitName , decimal , superscriptInteger , superscriptDecimal ) where import Data.Text (Text, pack) import Data.Void (Void) import Text.Megaparsec import Text.Megaparsec.Char (char, space1, letterChar) import qualified Text.Megaparsec.Char.Lexer as L import Numeric.Units.Dimensional.UnitNames (Metricality(..)) import Numeric.Units.Dimensional.UnitNames.Internal (UnitName'(..)) import qualified Numeric.Units.Dimensional.UnitNames as N import qualified Data.Foldable as F import Prelude hiding (exponent) type Parser = Parsec Void Text type ParsedUnitName = UnitName' 'NonMetric Text sc :: Parser () sc = L.space space1 empty empty topLevel :: Parser a -> Parser a topLevel = between sc eof lexeme :: Parser a -> Parser a lexeme = L.lexeme sc decimal :: (Integral a) => Parser a decimal = lexeme L.decimal symbol :: Text -> Parser Text symbol = L.symbol sc -- Parsing Numbers optionalSign :: (Num a) => Parser (a -> a) optionalSign = sign <|> pure id sign :: (Num a) => Parser (a -> a) sign = negate <$ char '-' <|> id <$ char '+' -- Parsing Quantities quantity :: Parser a -> Parser (a, Maybe ParsedUnitName) quantity n = do n' <- n u <- optional unitName return (n', u) <?> "quantity" -- Parsing Unit Names unitName :: Parser ParsedUnitName unitName = try (Quotient <$> numeratorUnitName <*> (symbol "/" *> simpleUnitName)) <|> try numeratorUnitName <|> withPowers simpleUnitName where optionalQuotient n (Just d) = Quotient n d optionalQuotient n Nothing = n numeratorUnitName :: Parser ParsedUnitName numeratorUnitName = One <$ symbol "1" <|> productUnitName simpleUnitName :: Parser ParsedUnitName simpleUnitName = grouped unitName <|> withSuperscriptPower atomicUnitName grouped :: Parser ParsedUnitName -> Parser ParsedUnitName grouped u = N.grouped <$> between (symbol "(") (symbol ")") u productUnitName :: Parser ParsedUnitName productUnitName = N.product <$> some simpleUnitName withPowers :: Parser ParsedUnitName -> Parser ParsedUnitName withPowers p = applyPowers <$> withSuperscriptPower p <*> many exponent where exponent :: Parser Int exponent = symbol "^" *> optionalSign <*> decimal <?> "exponent" applyPowers :: ParsedUnitName -> [Int] -> ParsedUnitName applyPowers u (n:ns) = applyPowers (u N.^ n) ns applyPowers u _ = u withSuperscriptPower :: Parser ParsedUnitName -> Parser ParsedUnitName withSuperscriptPower p = lexeme $ optionalPower <$> p <*> optional superscriptInteger where optionalPower :: ParsedUnitName -> Maybe Int -> ParsedUnitName optionalPower u (Just n) = u N.^ n optionalPower u _ = u atomicUnitName :: Parser ParsedUnitName atomicUnitName = lexeme atomicUnitName' atomicUnitName' :: Parser ParsedUnitName atomicUnitName' = Atomic <$> unitNameAtom <?> "atomic unit name" unitNameAtom :: Parser Text unitNameAtom = pack <$> try (some (letterChar <|> char '°' <|> char '\'') >>= check) <?> "unit name atom" where reservedWords = ["and"] check x = if x `elem` reservedWords then fail $ "keyword " ++ show x ++ " cannot be a unit name" else return x -- Parsing Superscript Numbers superscriptInteger :: (Integral a) => Parser a superscriptInteger = optionalSuperscriptSign <*> superscriptDecimal <?> "superscript integer" optionalSuperscriptSign :: (Num a) => Parser (a -> a) optionalSuperscriptSign = superscriptSign <|> pure id superscriptSign :: (Num a) => Parser (a -> a) superscriptSign = negate <$ char '\x207b' <|> id <$ char '\x207a' <?> "superscript sign" superscriptDecimal :: (Num a) => Parser a superscriptDecimal = F.foldl' (\x d -> (10 * x) + d) 0 <$> some superscriptDigit <?> "superscript decimal" superscriptDigit :: (Num a) => Parser a superscriptDigit = 1 <$ char '¹' <|> 2 <$ char '²' <|> 3 <$ char '³' <|> 4 <$ char '⁴' <|> 5 <$ char '⁵' <|> 6 <$ char '\x2076' <|> 7 <$ char '\x2077' <|> 8 <$ char '\x2078' <|> 9 <$ char '\x2079' <|> 0 <$ char '\x2070' <?> "superscript digit"
dmcclean/dimensional-parsing
src/Numeric/Units/Dimensional/Parsing/Units2.hs
bsd-3-clause
4,494
0
25
1,060
1,321
692
629
113
2
{-# LANGUAGE FlexibleContexts #-} module Distribution.Parsec.Class ( Parsec(..), -- * Warnings parsecWarning, -- * Utilities parsecTestedWith, parsecToken, parsecToken', parsecFilePath, parsecQuoted, parsecMaybeQuoted, parsecCommaList, parsecOptCommaList, ) where import Prelude () import Distribution.Compat.Prelude import Data.Functor.Identity (Identity) import qualified Distribution.Compat.Parsec as P import Distribution.Parsec.Types.Common (PWarnType (..), PWarning (..), Position (..)) import qualified Text.Parsec as Parsec import qualified Text.Parsec.Language as Parsec import qualified Text.Parsec.Token as Parsec -- Instances import Distribution.Compiler (CompilerFlavor (..), classifyCompilerFlavor) import Distribution.License (License (..)) import Distribution.ModuleName (ModuleName) import qualified Distribution.ModuleName as ModuleName import Distribution.System (Arch (..), ClassificationStrictness (..), OS (..), classifyArch, classifyOS) import Distribution.Text (display) import Distribution.Types.BenchmarkType (BenchmarkType (..)) import Distribution.Types.BuildType (BuildType (..)) import Distribution.Types.Dependency (Dependency (..)) import Distribution.Types.ExeDependency (ExeDependency (..)) import Distribution.Types.LegacyExeDependency (LegacyExeDependency (..)) import Distribution.Types.PkgconfigDependency (PkgconfigDependency (..)) import Distribution.Types.PkgconfigName (PkgconfigName, mkPkgconfigName) import Distribution.Types.GenericPackageDescription (FlagName, mkFlagName) import Distribution.Types.ModuleReexport (ModuleReexport (..)) import Distribution.Types.SourceRepo (RepoKind, RepoType, classifyRepoKind, classifyRepoType) import Distribution.Types.TestType (TestType (..)) import Distribution.Types.ForeignLib (LibVersionInfo, mkLibVersionInfo) import Distribution.Types.ForeignLibType (ForeignLibType (..)) import Distribution.Types.ForeignLibOption (ForeignLibOption (..)) import Distribution.Types.ModuleRenaming import Distribution.Types.IncludeRenaming import Distribution.Types.Mixin import Distribution.Types.PackageName (PackageName, mkPackageName) import Distribution.Types.UnqualComponentName (UnqualComponentName, mkUnqualComponentName) import Distribution.Types.ExecutableScope import Distribution.Version (Version, VersionRange (..), anyVersion, earlierVersion, intersectVersionRanges, laterVersion, majorBoundVersion, mkVersion, noVersion, orEarlierVersion, orLaterVersion, thisVersion, unionVersionRanges, withinVersion) import Language.Haskell.Extension (Extension, Language, classifyExtension, classifyLanguage) ------------------------------------------------------------------------------- -- Class ------------------------------------------------------------------------------- -- | -- -- TODO: implementation details: should be careful about consuming trailing whitespace? -- Should we always consume it? class Parsec a where parsec :: P.Stream s Identity Char => P.Parsec s [PWarning] a -- | 'parsec' /could/ consume trailing spaces, this function /must/ consume. lexemeParsec :: P.Stream s Identity Char => P.Parsec s [PWarning] a lexemeParsec = parsec <* P.spaces parsecWarning :: PWarnType -> String -> P.Parsec s [PWarning] () parsecWarning t w = Parsec.modifyState (PWarning t (Position 0 0) w :) ------------------------------------------------------------------------------- -- Instances ------------------------------------------------------------------------------- -- TODO: use lexemeParsec -- TODO avoid String parsecUnqualComponentName :: P.Stream s Identity Char => P.Parsec s [PWarning] String parsecUnqualComponentName = intercalate "-" <$> P.sepBy1 component (P.char '-') where component :: P.Stream s Identity Char => P.Parsec s [PWarning] String component = do cs <- P.munch1 isAlphaNum if all isDigit cs then fail "all digits in portion of unqualified component name" else return cs instance Parsec UnqualComponentName where parsec = mkUnqualComponentName <$> parsecUnqualComponentName instance Parsec PackageName where parsec = mkPackageName <$> parsecUnqualComponentName instance Parsec PkgconfigName where parsec = mkPkgconfigName <$> P.munch1 (\c -> isAlphaNum c || c `elem` "+-._") instance Parsec ModuleName where parsec = ModuleName.fromComponents <$> P.sepBy1 component (P.char '.') where component = do c <- P.satisfy isUpper cs <- P.munch validModuleChar return (c:cs) validModuleChar :: Char -> Bool validModuleChar c = isAlphaNum c || c == '_' || c == '\'' instance Parsec FlagName where parsec = mkFlagName . map toLower . intercalate "-" <$> P.sepBy1 component (P.char '-') where -- http://hackage.haskell.org/package/cabal-debian-4.24.8/cabal-debian.cabal -- has flag with all digit component: pretty-112 component :: P.Stream s Identity Char => P.Parsec s [PWarning] String component = P.munch1 (\c -> isAlphaNum c || c `elem` "_") instance Parsec Dependency where parsec = do name <- lexemeParsec ver <- parsec <|> pure anyVersion return (Dependency name ver) instance Parsec ExeDependency where parsec = do name <- lexemeParsec _ <- P.char ':' exe <- lexemeParsec ver <- parsec <|> pure anyVersion return (ExeDependency name exe ver) instance Parsec LegacyExeDependency where parsec = do name <- parsecMaybeQuoted nameP P.spaces verRange <- parsecMaybeQuoted parsec <|> pure anyVersion pure $ LegacyExeDependency name verRange where nameP = intercalate "-" <$> P.sepBy1 component (P.char '-') component = do cs <- P.munch1 (\c -> isAlphaNum c || c == '+' || c == '_') if all isDigit cs then fail "invalid component" else return cs instance Parsec PkgconfigDependency where parsec = do name <- parsec P.spaces verRange <- parsec <|> pure anyVersion pure $ PkgconfigDependency name verRange instance Parsec Version where parsec = mkVersion <$> P.sepBy1 P.integral (P.char '.') <* tags where tags = do ts <- P.optionMaybe $ some $ P.char '-' *> some (P.satisfy isAlphaNum) case ts of Nothing -> pure () -- TODO: make this warning severe Just _ -> parsecWarning PWTVersionTag "version with tags" -- TODO: this is not good parsec code -- use lexer, also see D.P.ConfVar instance Parsec VersionRange where parsec = expr where expr = do P.spaces t <- term P.spaces (do _ <- P.string "||" P.spaces e <- expr return (unionVersionRanges t e) <|> return t) term = do f <- factor P.spaces (do _ <- P.string "&&" P.spaces t <- term return (intersectVersionRanges f t) <|> return f) factor = P.choice $ parens expr : parseAnyVersion : parseNoVersion : parseWildcardRange : map parseRangeOp rangeOps parseAnyVersion = P.string "-any" >> return anyVersion parseNoVersion = P.string "-none" >> return noVersion parseWildcardRange = P.try $ do _ <- P.string "==" P.spaces branch <- some (P.integral <* P.char '.') _ <- P.char '*' return (withinVersion (mkVersion branch)) parens p = P.between (P.char '(' >> P.spaces) (P.char ')' >> P.spaces) (do a <- p P.spaces return (VersionRangeParens a)) -- TODO: make those non back-tracking parseRangeOp (s,f) = P.try (P.string s *> P.spaces *> fmap f parsec) rangeOps = [ ("<", earlierVersion), ("<=", orEarlierVersion), (">", laterVersion), (">=", orLaterVersion), ("^>=", majorBoundVersion), ("==", thisVersion) ] instance Parsec LibVersionInfo where parsec = do c <- P.integral (r, a) <- P.option (0,0) $ do _ <- P.char ':' r <- P.integral a <- P.option 0 $ do _ <- P.char ':' P.integral return (r,a) return $ mkLibVersionInfo (c,r,a) instance Parsec Language where parsec = classifyLanguage <$> P.munch1 isAlphaNum instance Parsec Extension where parsec = classifyExtension <$> P.munch1 isAlphaNum instance Parsec RepoType where parsec = classifyRepoType <$> P.munch1 isIdent instance Parsec RepoKind where parsec = classifyRepoKind <$> P.munch1 isIdent instance Parsec License where parsec = do name <- P.munch1 isAlphaNum version <- P.optionMaybe (P.char '-' *> parsec) return $! case (name, version :: Maybe Version) of ("GPL", _ ) -> GPL version ("LGPL", _ ) -> LGPL version ("AGPL", _ ) -> AGPL version ("BSD2", Nothing) -> BSD2 ("BSD3", Nothing) -> BSD3 ("BSD4", Nothing) -> BSD4 ("ISC", Nothing) -> ISC ("MIT", Nothing) -> MIT ("MPL", Just version') -> MPL version' ("Apache", _ ) -> Apache version ("PublicDomain", Nothing) -> PublicDomain ("AllRightsReserved", Nothing) -> AllRightsReserved ("OtherLicense", Nothing) -> OtherLicense _ -> UnknownLicense $ name ++ maybe "" (('-':) . display) version instance Parsec BuildType where parsec = do name <- P.munch1 isAlphaNum return $ case name of "Simple" -> Simple "Configure" -> Configure "Custom" -> Custom "Make" -> Make _ -> UnknownBuildType name instance Parsec TestType where parsec = stdParse $ \ver name -> case name of "exitcode-stdio" -> TestTypeExe ver "detailed" -> TestTypeLib ver _ -> TestTypeUnknown name ver instance Parsec BenchmarkType where parsec = stdParse $ \ver name -> case name of "exitcode-stdio" -> BenchmarkTypeExe ver _ -> BenchmarkTypeUnknown name ver instance Parsec ForeignLibType where parsec = do name <- P.munch1 (\c -> isAlphaNum c || c == '-') return $ case name of "native-shared" -> ForeignLibNativeShared "native-static" -> ForeignLibNativeStatic _ -> ForeignLibTypeUnknown instance Parsec ForeignLibOption where parsec = do name <- P.munch1 (\c -> isAlphaNum c || c == '-') case name of "standalone" -> return ForeignLibStandalone _ -> fail "unrecognized foreign-library option" instance Parsec OS where parsec = classifyOS Compat <$> parsecIdent instance Parsec Arch where parsec = classifyArch Strict <$> parsecIdent instance Parsec CompilerFlavor where parsec = classifyCompilerFlavor <$> component where component :: P.Stream s Identity Char => P.Parsec s [PWarning] String component = do cs <- P.munch1 isAlphaNum if all isDigit cs then fail "all digits compiler name" else return cs instance Parsec ModuleReexport where parsec = do mpkgname <- P.optionMaybe (P.try $ parsec <* P.char ':') origname <- parsec newname <- P.option origname $ P.try $ do P.spaces _ <- P.string "as" P.spaces parsec return (ModuleReexport mpkgname origname newname) instance Parsec ModuleRenaming where -- NB: try not necessary as the first token is obvious parsec = P.choice [ parseRename, parseHiding, return DefaultRenaming ] where parseRename = do rns <- P.between (P.char '(') (P.char ')') parseList P.spaces return (ModuleRenaming rns) parseHiding = do _ <- P.string "hiding" P.spaces hides <- P.between (P.char '(') (P.char ')') (P.sepBy parsec (P.char ',' >> P.spaces)) return (HidingRenaming hides) parseList = P.sepBy parseEntry (P.char ',' >> P.spaces) parseEntry = do orig <- parsec P.spaces P.option (orig, orig) $ do _ <- P.string "as" P.spaces new <- parsec P.spaces return (orig, new) instance Parsec IncludeRenaming where parsec = do prov_rn <- parsec req_rn <- P.option defaultRenaming $ P.try $ do P.spaces _ <- P.string "requires" P.spaces parsec return (IncludeRenaming prov_rn req_rn) instance Parsec Mixin where parsec = do mod_name <- parsec P.spaces incl <- parsec return (Mixin mod_name incl) instance Parsec ExecutableScope where parsec = do name <- P.munch1 (\c -> isAlphaNum c || c == '-') return $ case name of "public" -> ExecutablePublic "private" -> ExecutablePrivate _ -> ExecutableScopeUnknown ------------------------------------------------------------------------------- -- Utilities ------------------------------------------------------------------------------- isIdent :: Char -> Bool isIdent c = isAlphaNum c || c == '_' || c == '-' parsecTestedWith :: P.Stream s Identity Char => P.Parsec s [PWarning] (CompilerFlavor, VersionRange) parsecTestedWith = do name <- lexemeParsec ver <- parsec <|> pure anyVersion return (name, ver) parsecToken :: P.Stream s Identity Char => P.Parsec s [PWarning] String parsecToken = parsecHaskellString <|> (P.munch1 (\x -> not (isSpace x) && x /= ',') P.<?> "identifier" ) parsecToken' :: P.Stream s Identity Char => P.Parsec s [PWarning] String parsecToken' = parsecHaskellString <|> (P.munch1 (not . isSpace) P.<?> "token") parsecFilePath :: P.Stream s Identity Char => P.Parsec s [PWarning] String parsecFilePath = parsecToken -- | Parse a benchmark/test-suite types. stdParse :: P.Stream s Identity Char => (Version -> String -> a) -> P.Parsec s [PWarning] a stdParse f = do -- TODO: this backtracks cs <- some $ P.try (component <* P.char '-') ver <- parsec let name = map toLower (intercalate "-" cs) return $! f ver name where component = do cs <- P.munch1 isAlphaNum if all isDigit cs then fail "all digit component" else return cs -- each component must contain an alphabetic character, to avoid -- ambiguity in identifiers like foo-1 (the 1 is the version number). parsecCommaList :: P.Stream s Identity Char => P.Parsec s [PWarning] a -> P.Parsec s [PWarning] [a] parsecCommaList p = P.sepBy (p <* P.spaces) (P.char ',' *> P.spaces) parsecOptCommaList :: P.Stream s Identity Char => P.Parsec s [PWarning] a -> P.Parsec s [PWarning] [a] parsecOptCommaList p = P.sepBy (p <* P.spaces) (P.optional comma) where comma = P.char ',' *> P.spaces -- | Content isn't unquoted parsecQuoted :: P.Stream s Identity Char => P.Parsec s [PWarning] a -> P.Parsec s [PWarning] a parsecQuoted = P.between (P.char '"') (P.char '"') -- | @parsecMaybeQuoted p = 'parsecQuoted' p <|> p@. parsecMaybeQuoted :: P.Stream s Identity Char => P.Parsec s [PWarning] a -> P.Parsec s [PWarning] a parsecMaybeQuoted p = parsecQuoted p <|> p parsecHaskellString :: P.Stream s Identity Char => P.Parsec s [PWarning] String parsecHaskellString = Parsec.stringLiteral $ Parsec.makeTokenParser Parsec.emptyDef { Parsec.commentStart = "{-" , Parsec.commentEnd = "-}" , Parsec.commentLine = "--" , Parsec.nestedComments = True , Parsec.identStart = P.satisfy isAlphaNum , Parsec.identLetter = P.satisfy isAlphaNum <|> P.oneOf "_'" , Parsec.opStart = opl , Parsec.opLetter = opl , Parsec.reservedOpNames= [] , Parsec.reservedNames = [] , Parsec.caseSensitive = True } where opl = P.oneOf ":!#$%&*+./<=>?@\\^|-~" parsecIdent :: P.Stream s Identity Char => P.Parsec s [PWarning] String parsecIdent = (:) <$> firstChar <*> rest where firstChar = P.satisfy isAlpha rest = P.munch (\c -> isAlphaNum c || c == '_' || c == '-')
themoritz/cabal
Cabal/Distribution/Parsec/Class.hs
bsd-3-clause
17,757
0
18
5,545
4,648
2,406
2,242
378
2
{-# LANGUAGE CPP #-} -- | Groups black-box tests of cabal-install and configures them to test -- the correct binary. -- -- This file should do nothing but import tests from other modules and run -- them with the path to the correct cabal-install binary. module Main where -- Modules from Cabal. import Distribution.Compat.CreatePipe (createPipe) import Distribution.Compat.Environment (setEnv, getEnvironment) import Distribution.Compat.Internal.TempFile (createTempDirectory) import Distribution.Simple.Configure (findDistPrefOrDefault) import Distribution.Simple.Program.Builtin (ghcPkgProgram) import Distribution.Simple.Program.Db (defaultProgramDb, requireProgram, setProgramSearchPath) import Distribution.Simple.Program.Find (ProgramSearchPathEntry(ProgramSearchPathDir), defaultProgramSearchPath) import Distribution.Simple.Program.Types ( Program(..), simpleProgram, programPath) import Distribution.Simple.Setup ( Flag(..) ) import Distribution.Simple.Utils ( findProgramVersion, copyDirectoryRecursive, installOrdinaryFile ) import Distribution.Verbosity (normal) -- Third party modules. import Control.Concurrent.Async (withAsync, wait) import Control.Exception (bracket) import Data.Maybe (fromMaybe) import System.Directory ( canonicalizePath , findExecutable , getDirectoryContents , getTemporaryDirectory , doesDirectoryExist , removeDirectoryRecursive , doesFileExist ) import System.FilePath import Test.Tasty (TestTree, defaultMain, testGroup) import Test.Tasty.HUnit (testCase, Assertion, assertFailure) import Control.Monad ( filterM, forM, unless, when ) import Data.List (isPrefixOf, isSuffixOf, sort) import Data.IORef (newIORef, writeIORef, readIORef) import System.Exit (ExitCode(..)) import System.IO (withBinaryFile, IOMode(ReadMode)) import System.Process (runProcess, waitForProcess) import Text.Regex.Posix ((=~)) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C8 import Data.ByteString (ByteString) #if MIN_VERSION_base(4,6,0) import System.Environment ( getExecutablePath ) #endif -- | Test case. data TestCase = TestCase { tcName :: String -- ^ Name of the shell script , tcBaseDirectory :: FilePath -- ^ The base directory where tests are found -- e.g., cabal-install/tests/IntegrationTests , tcCategory :: String -- ^ Category of test; e.g., custom, exec, freeze, ... , tcStdOutPath :: Maybe FilePath -- ^ File path of expected standard output , tcStdErrPath :: Maybe FilePath -- ^ File path of expected standard error } -- | Test result. data TestResult = TestResult { trExitCode :: ExitCode -- ^ Exit code of test script , trStdOut :: ByteString -- ^ Actual standard output , trStdErr :: ByteString -- ^ Actual standard error , trWorkingDirectory :: FilePath -- ^ Temporary working directory test was -- executed in. } -- | Cabal executable cabalProgram :: Program cabalProgram = (simpleProgram "cabal") { programFindVersion = findProgramVersion "--numeric-version" id } -- | Convert test result to user-friendly string message. testResultToString :: TestResult -> String testResultToString testResult = exitStatus ++ "\n" ++ workingDirectory ++ "\n\n" ++ stdOut ++ "\n\n" ++ stdErr where exitStatus = "Exit status: " ++ show (trExitCode testResult) workingDirectory = "Working directory: " ++ (trWorkingDirectory testResult) stdOut = "<stdout> was:\n" ++ C8.unpack (trStdOut testResult) stdErr = "<stderr> was:\n" ++ C8.unpack (trStdErr testResult) -- | Returns the command that was issued, the return code, and the output text run :: FilePath -> String -> [String] -> IO TestResult run cwd path args = do -- path is relative to the current directory; canonicalizePath makes it -- absolute, so that runProcess will find it even when changing directory. path' <- canonicalizePath path (pid, hReadStdOut, hReadStdErr) <- do -- Create pipes for StdOut and StdErr (hReadStdOut, hWriteStdOut) <- createPipe (hReadStdErr, hWriteStdErr) <- createPipe -- Run the process env0 <- getEnvironment -- CABAL_BUILDDIR can interfere with test running, so -- be sure to clear it out. let env = filter ((/= "CABAL_BUILDDIR") . fst) env0 pid <- runProcess path' args (Just cwd) (Just env) Nothing (Just hWriteStdOut) (Just hWriteStdErr) -- Return the pid and read ends of the pipes return (pid, hReadStdOut, hReadStdErr) -- Read subprocess output using asynchronous threads; we need to -- do this aynchronously to avoid deadlocks due to buffers filling -- up. withAsync (B.hGetContents hReadStdOut) $ \stdOutAsync -> do withAsync (B.hGetContents hReadStdErr) $ \stdErrAsync -> do -- Wait for the subprocess to terminate exitcode <- waitForProcess pid -- We can now be sure that no further output is going to arrive, -- so we wait for the results of the asynchronous reads. stdOut <- wait stdOutAsync stdErr <- wait stdErrAsync -- Done return $ TestResult exitcode stdOut stdErr cwd -- | Get a list of all names in a directory, excluding all hidden or -- system files/directories such as '.', '..' or any files/directories -- starting with a '.'. listDirectory :: FilePath -> IO [String] listDirectory directory = do fmap (filter notHidden) $ getDirectoryContents directory where notHidden = not . isHidden isHidden name = "." `isPrefixOf` name -- | List a directory as per 'listDirectory', but return an empty list -- in case the directory does not exist. listDirectoryLax :: FilePath -> IO [String] listDirectoryLax directory = do d <- doesDirectoryExist directory if d then listDirectory directory else return [ ] -- | @pathIfExists p == return (Just p)@ if @p@ exists, and -- @return Nothing@ otherwise. pathIfExists :: FilePath -> IO (Maybe FilePath) pathIfExists p = do e <- doesFileExist p if e then return $ Just p else return Nothing -- | Checks if file @p@ matches a 'ByteString' @s@, subject -- to line-break normalization. Lines in the file which are -- prefixed with @RE:@ are treated specially as a regular expression. fileMatchesString :: FilePath -> ByteString -> IO Bool fileMatchesString p s = do withBinaryFile p ReadMode $ \h -> do expected <- (C8.lines . normalizeLinebreaks) `fmap` B.hGetContents h -- Strict let actual = C8.lines $ normalizeLinebreaks s return $ length expected == length actual && and (zipWith matches expected actual) where matches :: ByteString -> ByteString -> Bool matches pattern line | C8.pack "RE:" `B.isPrefixOf` pattern = line =~ C8.drop 3 pattern | otherwise = line == pattern -- This is a bit of a hack, but since we're comparing -- *text* output, we should be OK. normalizeLinebreaks = B.filter (not . ((==) 13)) -- carriage return -- | Check if the @actual@ 'ByteString' matches the contents of -- @expected@ (always succeeds if the expectation is 'Nothing'). -- Also takes the 'TestResult' and a label @handleName@ describing -- what text the string values correspond to. mustMatch :: TestResult -> String -> ByteString -> Maybe FilePath -> Assertion mustMatch _ _ _ Nothing = return () mustMatch testResult handleName actual (Just expected) = do m <- fileMatchesString expected actual unless m $ assertFailure $ "<" ++ handleName ++ "> did not match file '" ++ expected ++ "'.\n" ++ testResultToString testResult -- | Given a @directory@, return its subdirectories. This is -- run on @cabal-install/tests/IntegrationTests@ to get the -- list of test categories which can be run. discoverTestCategories :: FilePath -> IO [String] discoverTestCategories directory = do names <- listDirectory directory fmap sort $ filterM (\name -> doesDirectoryExist $ directory </> name) names -- | Find all shell scripts in @baseDirectory </> category@. discoverTestCases :: FilePath -> String -> IO [TestCase] discoverTestCases baseDirectory category = do -- Find the names of the shell scripts names <- fmap (filter isTestCase) $ listDirectoryLax directory -- Fill in TestCase for each script forM (sort names) $ \name -> do stdOutPath <- pathIfExists $ directory </> name `replaceExtension` ".out" stdErrPath <- pathIfExists $ directory </> name `replaceExtension` ".err" return $ TestCase { tcName = name , tcBaseDirectory = baseDirectory , tcCategory = category , tcStdOutPath = stdOutPath , tcStdErrPath = stdErrPath } where directory = baseDirectory </> category isTestCase name = ".sh" `isSuffixOf` name -- | Given a list of 'TestCase's (describing a shell script for a -- single test case), run @mk@ on each of them to form a runnable -- 'TestTree'. createTestCases :: [TestCase] -> (TestCase -> Assertion) -> IO [TestTree] createTestCases testCases mk = return $ (flip map) testCases $ \tc -> testCase (tcName tc ++ suffix tc) $ mk tc where suffix tc = case (tcStdOutPath tc, tcStdErrPath tc) of (Nothing, Nothing) -> " (ignoring stdout+stderr)" (Just _ , Nothing) -> " (ignoring stderr)" (Nothing, Just _ ) -> " (ignoring stdout)" (Just _ , Just _ ) -> "" -- | Given a 'TestCase', run it. -- -- A test case of the form @category/testname.sh@ is -- run in the following way -- -- 1. We make a full copy all of @category@ into a temporary -- directory. -- 2. In the temporary directory, run @testname.sh@. -- 3. Test that the exit code is zero, and that stdout/stderr -- match the expected results. -- runTestCase :: TestCase -> IO () runTestCase tc = do doRemove <- newIORef False bracket createWorkDirectory (removeWorkDirectory doRemove) $ \workDirectory -> do -- Run let scriptDirectory = workDirectory sh <- fmap (fromMaybe $ error "Cannot find 'sh' executable") $ findExecutable "sh" testResult <- run scriptDirectory sh [ "-e", tcName tc] -- Assert that we got what we expected case trExitCode testResult of ExitSuccess -> return () -- We're good ExitFailure _ -> assertFailure $ "Unexpected exit status.\n\n" ++ testResultToString testResult mustMatch testResult "stdout" (trStdOut testResult) (tcStdOutPath tc) mustMatch testResult "stderr" (trStdErr testResult) (tcStdErrPath tc) -- Only remove working directory if test succeeded writeIORef doRemove True where createWorkDirectory = do -- Create the temporary directory tempDirectory <- getTemporaryDirectory workDirectory <- createTempDirectory tempDirectory "cabal-install-test" -- Copy all the files from the category into the working directory. copyDirectoryRecursive normal (tcBaseDirectory tc </> tcCategory tc) workDirectory -- Copy in the common.sh stub let commonDest = workDirectory </> "common.sh" e <- doesFileExist commonDest unless e $ installOrdinaryFile normal (tcBaseDirectory tc </> "common.sh") commonDest -- Done return workDirectory removeWorkDirectory doRemove workDirectory = do remove <- readIORef doRemove when remove $ removeDirectoryRecursive workDirectory discoverCategoryTests :: FilePath -> String -> IO [TestTree] discoverCategoryTests baseDirectory category = do testCases <- discoverTestCases baseDirectory category createTestCases testCases runTestCase main :: IO () main = do -- Find executables and build directories, etc. distPref <- guessDistDir buildDir <- canonicalizePath (distPref </> "build/cabal") let programSearchPath = ProgramSearchPathDir buildDir : defaultProgramSearchPath (cabal, _) <- requireProgram normal cabalProgram (setProgramSearchPath programSearchPath defaultProgramDb) (ghcPkg, _) <- requireProgram normal ghcPkgProgram defaultProgramDb baseDirectory <- canonicalizePath $ "tests" </> "IntegrationTests" -- Set up environment variables for test scripts setEnv "GHC_PKG" $ programPath ghcPkg setEnv "CABAL" $ programPath cabal -- Define default arguments setEnv "CABAL_ARGS" $ "--config-file=config-file" setEnv "CABAL_ARGS_NO_CONFIG_FILE" " " -- Don't get Unicode output from GHC setEnv "LC_ALL" "C" -- Discover all the test categories categories <- discoverTestCategories baseDirectory -- Discover tests in each category tests <- forM categories $ \category -> do categoryTests <- discoverCategoryTests baseDirectory category return (category, categoryTests) -- Map into a test tree let testTree = map (\(category, categoryTests) -> testGroup category categoryTests) tests -- Run the tests defaultMain $ testGroup "Integration Tests" $ testTree -- See this function in Cabal's PackageTests. If you update this, -- update its copy in cabal-install. (Why a copy here? I wanted -- to try moving this into the Cabal library, but to do this properly -- I'd have to BC'ify getExecutablePath, and then it got hairy, so -- I aborted and did something simple.) guessDistDir :: IO FilePath guessDistDir = do #if MIN_VERSION_base(4,6,0) exe_path <- canonicalizePath =<< getExecutablePath let dist0 = dropFileName exe_path </> ".." </> ".." b <- doesFileExist (dist0 </> "setup-config") #else let dist0 = error "no path" b = False #endif -- Method (2) if b then canonicalizePath dist0 else findDistPrefOrDefault NoFlag >>= canonicalizePath
sopvop/cabal
cabal-install/tests/IntegrationTests.hs
bsd-3-clause
13,713
0
16
2,859
2,674
1,423
1,251
196
4
-- (c) The University of Glasgow 2006 {-# LANGUAGE CPP, DeriveDataTypeable #-} -- | Module for (a) type kinds and (b) type coercions, -- as used in System FC. See 'CoreSyn.Expr' for -- more on System FC and how coercions fit into it. -- module Coercion ( -- * Main data type Coercion(..), Var, CoVar, LeftOrRight(..), pickLR, Role(..), ltRole, -- ** Functions over coercions coVarKind, coVarRole, coercionType, coercionKind, coercionKinds, isReflCo, isReflCo_maybe, coercionRole, coercionKindRole, mkCoercionType, -- ** Constructing coercions mkReflCo, mkCoVarCo, mkAxInstCo, mkUnbranchedAxInstCo, mkAxInstLHS, mkAxInstRHS, mkUnbranchedAxInstRHS, mkPiCo, mkPiCos, mkCoCast, mkSymCo, mkTransCo, mkNthCo, mkNthCoRole, mkLRCo, mkInstCo, mkAppCo, mkAppCoFlexible, mkTyConAppCo, mkFunCo, mkForAllCo, mkUnsafeCo, mkUnivCo, mkSubCo, mkPhantomCo, mkNewTypeCo, downgradeRole, mkAxiomRuleCo, -- ** Decomposition instNewTyCon_maybe, NormaliseStepper, NormaliseStepResult(..), composeSteppers, modifyStepResultCo, unwrapNewTypeStepper, topNormaliseNewType_maybe, topNormaliseTypeX_maybe, decomposeCo, getCoVar_maybe, splitAppCo_maybe, splitForAllCo_maybe, nthRole, tyConRolesX, setNominalRole_maybe, -- ** Coercion variables mkCoVar, isCoVar, isCoVarType, coVarName, setCoVarName, setCoVarUnique, -- ** Free variables tyCoVarsOfCo, tyCoVarsOfCos, coVarsOfCo, coercionSize, -- ** Substitution CvSubstEnv, emptyCvSubstEnv, CvSubst(..), emptyCvSubst, Coercion.lookupTyVar, lookupCoVar, isEmptyCvSubst, zapCvSubstEnv, getCvInScope, substCo, substCos, substCoVar, substCoVars, substCoWithTy, substCoWithTys, cvTvSubst, tvCvSubst, mkCvSubst, zipOpenCvSubst, substTy, extendTvSubst, extendCvSubstAndInScope, extendTvSubstAndInScope, substTyVarBndr, substCoVarBndr, -- ** Lifting liftCoMatch, liftCoSubstTyVar, liftCoSubstWith, -- ** Comparison coreEqCoercion, coreEqCoercion2, -- ** Forcing evaluation of coercions seqCo, -- * Pretty-printing pprCo, pprParendCo, pprCoAxiom, pprCoAxBranch, pprCoAxBranchHdr, -- * Tidying tidyCo, tidyCos, -- * Other applyCo, ) where #include "HsVersions.h" import Unify ( MatchEnv(..), matchList ) import TypeRep import qualified Type import Type hiding( substTy, substTyVarBndr, extendTvSubst ) import TyCon import CoAxiom import Var import VarEnv import VarSet import Binary import Maybes ( orElse ) import Name ( Name, NamedThing(..), nameUnique, nameModule, getSrcSpan ) import OccName ( parenSymOcc ) import Util import BasicTypes import Outputable import Unique import Pair import SrcLoc import PrelNames ( funTyConKey, eqPrimTyConKey, eqReprPrimTyConKey ) #if __GLASGOW_HASKELL__ < 709 import Control.Applicative hiding ( empty ) import Data.Traversable (traverse, sequenceA) #endif import FastString import ListSetOps import qualified Data.Data as Data hiding ( TyCon ) import Control.Arrow ( first ) {- ************************************************************************ * * Coercions * * ************************************************************************ -} -- | A 'Coercion' is concrete evidence of the equality/convertibility -- of two types. -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data Coercion -- Each constructor has a "role signature", indicating the way roles are -- propagated through coercions. P, N, and R stand for coercions of the -- given role. e stands for a coercion of a specific unknown role (think -- "role polymorphism"). "e" stands for an explicit role parameter -- indicating role e. _ stands for a parameter that is not a Role or -- Coercion. -- These ones mirror the shape of types = -- Refl :: "e" -> _ -> e Refl Role Type -- See Note [Refl invariant] -- Invariant: applications of (Refl T) to a bunch of identity coercions -- always show up as Refl. -- For example (Refl T) (Refl a) (Refl b) shows up as (Refl (T a b)). -- Applications of (Refl T) to some coercions, at least one of -- which is NOT the identity, show up as TyConAppCo. -- (They may not be fully saturated however.) -- ConAppCo coercions (like all coercions other than Refl) -- are NEVER the identity. -- Use (Refl Representational _), not (SubCo (Refl Nominal _)) -- These ones simply lift the correspondingly-named -- Type constructors into Coercions -- TyConAppCo :: "e" -> _ -> ?? -> e -- See Note [TyConAppCo roles] | TyConAppCo Role TyCon [Coercion] -- lift TyConApp -- The TyCon is never a synonym; -- we expand synonyms eagerly -- But it can be a type function | AppCo Coercion Coercion -- lift AppTy -- AppCo :: e -> N -> e -- See Note [Forall coercions] | ForAllCo TyVar Coercion -- forall a. g -- :: _ -> e -> e -- These are special | CoVarCo CoVar -- :: _ -> (N or R) -- result role depends on the tycon of the variable's type -- AxiomInstCo :: e -> _ -> [N] -> e | AxiomInstCo (CoAxiom Branched) BranchIndex [Coercion] -- See also [CoAxiom index] -- The coercion arguments always *precisely* saturate -- arity of (that branch of) the CoAxiom. If there are -- any left over, we use AppCo. See -- See [Coercion axioms applied to coercions] -- see Note [UnivCo] | UnivCo FastString Role Type Type -- :: "e" -> _ -> _ -> e -- the FastString is just a note for provenance | SymCo Coercion -- :: e -> e | TransCo Coercion Coercion -- :: e -> e -> e -- The number of types and coercions should match exactly the expectations -- of the CoAxiomRule (i.e., the rule is fully saturated). | AxiomRuleCo CoAxiomRule [Type] [Coercion] -- These are destructors | NthCo Int Coercion -- Zero-indexed; decomposes (T t0 ... tn) -- :: _ -> e -> ?? (inverse of TyConAppCo, see Note [TyConAppCo roles]) -- See Note [NthCo and newtypes] | LRCo LeftOrRight Coercion -- Decomposes (t_left t_right) -- :: _ -> N -> N | InstCo Coercion Type -- :: e -> _ -> e | SubCo Coercion -- Turns a ~N into a ~R -- :: N -> R deriving (Data.Data, Data.Typeable) -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data LeftOrRight = CLeft | CRight deriving( Eq, Data.Data, Data.Typeable ) instance Binary LeftOrRight where put_ bh CLeft = putByte bh 0 put_ bh CRight = putByte bh 1 get bh = do { h <- getByte bh ; case h of 0 -> return CLeft _ -> return CRight } pickLR :: LeftOrRight -> (a,a) -> a pickLR CLeft (l,_) = l pickLR CRight (_,r) = r {- Note [Refl invariant] ~~~~~~~~~~~~~~~~~~~~~ Coercions have the following invariant Refl is always lifted as far as possible. You might think that a consequencs is: Every identity coercions has Refl at the root But that's not quite true because of coercion variables. Consider g where g :: Int~Int Left h where h :: Maybe Int ~ Maybe Int etc. So the consequence is only true of coercions that have no coercion variables. Note [Coercion axioms applied to coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The reason coercion axioms can be applied to coercions and not just types is to allow for better optimization. There are some cases where we need to be able to "push transitivity inside" an axiom in order to expose further opportunities for optimization. For example, suppose we have C a : t[a] ~ F a g : b ~ c and we want to optimize sym (C b) ; t[g] ; C c which has the kind F b ~ F c (stopping through t[b] and t[c] along the way). We'd like to optimize this to just F g -- but how? The key is that we need to allow axioms to be instantiated by *coercions*, not just by types. Then we can (in certain cases) push transitivity inside the axiom instantiations, and then react opposite-polarity instantiations of the same axiom. In this case, e.g., we match t[g] against the LHS of (C c)'s kind, to obtain the substitution a |-> g (note this operation is sort of the dual of lifting!) and hence end up with C g : t[b] ~ F c which indeed has the same kind as t[g] ; C c. Now we have sym (C b) ; C g which can be optimized to F g. Note [CoAxiom index] ~~~~~~~~~~~~~~~~~~~~ A CoAxiom has 1 or more branches. Each branch has contains a list of the free type variables in that branch, the LHS type patterns, and the RHS type for that branch. When we apply an axiom to a list of coercions, we must choose which branch of the axiom we wish to use, as the different branches may have different numbers of free type variables. (The number of type patterns is always the same among branches, but that doesn't quite concern us here.) The Int in the AxiomInstCo constructor is the 0-indexed number of the chosen branch. Note [Forall coercions] ~~~~~~~~~~~~~~~~~~~~~~~ Constructing coercions between forall-types can be a bit tricky. Currently, the situation is as follows: ForAllCo TyVar Coercion represents a coercion between polymorphic types, with the rule v : k g : t1 ~ t2 ---------------------------------------------- ForAllCo v g : (all v:k . t1) ~ (all v:k . t2) Note that it's only necessary to coerce between polymorphic types where the type variables have identical kinds, because equality on kinds is trivial. Note [Predicate coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have g :: a~b How can we coerce between types ([c]~a) => [a] -> c and ([c]~b) => [b] -> c where the equality predicate *itself* differs? Answer: we simply treat (~) as an ordinary type constructor, so these types really look like ((~) [c] a) -> [a] -> c ((~) [c] b) -> [b] -> c So the coercion between the two is obviously ((~) [c] g) -> [g] -> c Another way to see this to say that we simply collapse predicates to their representation type (see Type.coreView and Type.predTypeRep). This collapse is done by mkPredCo; there is no PredCo constructor in Coercion. This is important because we need Nth to work on predicates too: Nth 1 ((~) [c] g) = g See Simplify.simplCoercionF, which generates such selections. Note [Kind coercions] ~~~~~~~~~~~~~~~~~~~~~ Suppose T :: * -> *, and g :: A ~ B Then the coercion TyConAppCo T [g] T g : T A ~ T B Now suppose S :: forall k. k -> *, and g :: A ~ B Then the coercion TyConAppCo S [Refl *, g] T <*> g : T * A ~ T * B Notice that the arguments to TyConAppCo are coercions, but the first represents a *kind* coercion. Now, we don't allow any non-trivial kind coercions, so it's an invariant that any such kind coercions are Refl. Lint checks this. However it's inconvenient to insist that these kind coercions are always *structurally* (Refl k), because the key function exprIsConApp_maybe pushes coercions into constructor arguments, so C k ty e |> g may turn into C (Nth 0 g) .... Now (Nth 0 g) will optimise to Refl, but perhaps not instantly. Note [Roles] ~~~~~~~~~~~~ Roles are a solution to the GeneralizedNewtypeDeriving problem, articulated in Trac #1496. The full story is in docs/core-spec/core-spec.pdf. Also, see http://ghc.haskell.org/trac/ghc/wiki/RolesImplementation Here is one way to phrase the problem: Given: newtype Age = MkAge Int type family F x type instance F Age = Bool type instance F Int = Char This compiles down to: axAge :: Age ~ Int axF1 :: F Age ~ Bool axF2 :: F Int ~ Char Then, we can make: (sym (axF1) ; F axAge ; axF2) :: Bool ~ Char Yikes! The solution is _roles_, as articulated in "Generative Type Abstraction and Type-level Computation" (POPL 2010), available at http://www.seas.upenn.edu/~sweirich/papers/popl163af-weirich.pdf The specification for roles has evolved somewhat since that paper. For the current full details, see the documentation in docs/core-spec. Here are some highlights. We label every equality with a notion of type equivalence, of which there are three options: Nominal, Representational, and Phantom. A ground type is nominally equivalent only with itself. A newtype (which is considered a ground type in Haskell) is representationally equivalent to its representation. Anything is "phantomly" equivalent to anything else. We use "N", "R", and "P" to denote the equivalences. The axioms above would be: axAge :: Age ~R Int axF1 :: F Age ~N Bool axF2 :: F Age ~N Char Then, because transitivity applies only to coercions proving the same notion of equivalence, the above construction is impossible. However, there is still an escape hatch: we know that any two types that are nominally equivalent are representationally equivalent as well. This is what the form SubCo proves -- it "demotes" a nominal equivalence into a representational equivalence. So, it would seem the following is possible: sub (sym axF1) ; F axAge ; sub axF2 :: Bool ~R Char -- WRONG What saves us here is that the arguments to a type function F, lifted into a coercion, *must* prove nominal equivalence. So, (F axAge) is ill-formed, and we are safe. Roles are attached to parameters to TyCons. When lifting a TyCon into a coercion (through TyConAppCo), we need to ensure that the arguments to the TyCon respect their roles. For example: data T a b = MkT a (F b) If we know that a1 ~R a2, then we know (T a1 b) ~R (T a2 b). But, if we know that b1 ~R b2, we know nothing about (T a b1) and (T a b2)! This is because the type function F branches on b's *name*, not representation. So, we say that 'a' has role Representational and 'b' has role Nominal. The third role, Phantom, is for parameters not used in the type's definition. Given the following definition data Q a = MkQ Int the Phantom role allows us to say that (Q Bool) ~R (Q Char), because we can construct the coercion Bool ~P Char (using UnivCo). See the paper cited above for more examples and information. Note [UnivCo] ~~~~~~~~~~~~~ The UnivCo ("universal coercion") serves two rather separate functions: - the implementation for unsafeCoerce# - placeholder for phantom parameters in a TyConAppCo At Representational, it asserts that two (possibly unrelated) types have the same representation and can be casted to one another. This form is necessary for unsafeCoerce#. For optimisation purposes, it is convenient to allow UnivCo to appear at Nominal role. If we have data Foo a = MkFoo (F a) -- F is a type family and we want an unsafe coercion from Foo Int to Foo Bool, then it would be nice to have (TyConAppCo Foo (UnivCo Nominal Int Bool)). So, we allow Nominal UnivCo's. At Phantom role, it is used as an argument to TyConAppCo in the place of a phantom parameter (a type parameter unused in the type definition). For example: data Q a = MkQ Int We want a coercion for (Q Bool) ~R (Q Char). (TyConAppCo Representational Q [UnivCo Phantom Bool Char]) does the trick. Note [TyConAppCo roles] ~~~~~~~~~~~~~~~~~~~~~~~ The TyConAppCo constructor has a role parameter, indicating the role at which the coercion proves equality. The choice of this parameter affects the required roles of the arguments of the TyConAppCo. To help explain it, assume the following definition: type instance F Int = Bool -- Axiom axF : F Int ~N Bool newtype Age = MkAge Int -- Axiom axAge : Age ~R Int data Foo a = MkFoo a -- Role on Foo's parameter is Representational TyConAppCo Nominal Foo axF : Foo (F Int) ~N Foo Bool For (TyConAppCo Nominal) all arguments must have role Nominal. Why? So that Foo Age ~N Foo Int does *not* hold. TyConAppCo Representational Foo (SubCo axF) : Foo (F Int) ~R Foo Bool TyConAppCo Representational Foo axAge : Foo Age ~R Foo Int For (TyConAppCo Representational), all arguments must have the roles corresponding to the result of tyConRoles on the TyCon. This is the whole point of having roles on the TyCon to begin with. So, we can have Foo Age ~R Foo Int, if Foo's parameter has role R. If a Representational TyConAppCo is over-saturated (which is otherwise fine), the spill-over arguments must all be at Nominal. This corresponds to the behavior for AppCo. TyConAppCo Phantom Foo (UnivCo Phantom Int Bool) : Foo Int ~P Foo Bool All arguments must have role Phantom. This one isn't strictly necessary for soundness, but this choice removes ambiguity. The rules here dictate the roles of the parameters to mkTyConAppCo (should be checked by Lint). Note [NthCo and newtypes] ~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have newtype N a = MkN Int type role N representational This yields axiom NTCo:N :: forall a. N a ~R Int We can then build co :: forall a b. N a ~R N b co = NTCo:N a ; sym (NTCo:N b) for any `a` and `b`. Because of the role annotation on N, if we use NthCo, we'll get out a representational coercion. That is: NthCo 0 co :: forall a b. a ~R b Yikes! Clearly, this is terrible. The solution is simple: forbid NthCo to be used on newtypes if the internal coercion is representational. This is not just some corner case discovered by a segfault somewhere; it was discovered in the proof of soundness of roles and described in the "Safe Coercions" paper (ICFP '14). ************************************************************************ * * \subsection{Coercion variables} * * ************************************************************************ -} coVarName :: CoVar -> Name coVarName = varName setCoVarUnique :: CoVar -> Unique -> CoVar setCoVarUnique = setVarUnique setCoVarName :: CoVar -> Name -> CoVar setCoVarName = setVarName isCoVar :: Var -> Bool isCoVar v = isCoVarType (varType v) isCoVarType :: Type -> Bool isCoVarType ty -- Tests for t1 ~# t2, the unboxed equality = case splitTyConApp_maybe ty of Just (tc,tys) -> (tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey) && tys `lengthAtLeast` 2 Nothing -> False tyCoVarsOfCo :: Coercion -> VarSet -- Extracts type and coercion variables from a coercion tyCoVarsOfCo (Refl _ ty) = tyVarsOfType ty tyCoVarsOfCo (TyConAppCo _ _ cos) = tyCoVarsOfCos cos tyCoVarsOfCo (AppCo co1 co2) = tyCoVarsOfCo co1 `unionVarSet` tyCoVarsOfCo co2 tyCoVarsOfCo (ForAllCo tv co) = tyCoVarsOfCo co `delVarSet` tv tyCoVarsOfCo (CoVarCo v) = unitVarSet v tyCoVarsOfCo (AxiomInstCo _ _ cos) = tyCoVarsOfCos cos tyCoVarsOfCo (UnivCo _ _ ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2 tyCoVarsOfCo (SymCo co) = tyCoVarsOfCo co tyCoVarsOfCo (TransCo co1 co2) = tyCoVarsOfCo co1 `unionVarSet` tyCoVarsOfCo co2 tyCoVarsOfCo (NthCo _ co) = tyCoVarsOfCo co tyCoVarsOfCo (LRCo _ co) = tyCoVarsOfCo co tyCoVarsOfCo (InstCo co ty) = tyCoVarsOfCo co `unionVarSet` tyVarsOfType ty tyCoVarsOfCo (SubCo co) = tyCoVarsOfCo co tyCoVarsOfCo (AxiomRuleCo _ ts cs) = tyVarsOfTypes ts `unionVarSet` tyCoVarsOfCos cs tyCoVarsOfCos :: [Coercion] -> VarSet tyCoVarsOfCos = mapUnionVarSet tyCoVarsOfCo coVarsOfCo :: Coercion -> VarSet -- Extract *coerction* variables only. Tiresome to repeat the code, but easy. coVarsOfCo (Refl _ _) = emptyVarSet coVarsOfCo (TyConAppCo _ _ cos) = coVarsOfCos cos coVarsOfCo (AppCo co1 co2) = coVarsOfCo co1 `unionVarSet` coVarsOfCo co2 coVarsOfCo (ForAllCo _ co) = coVarsOfCo co coVarsOfCo (CoVarCo v) = unitVarSet v coVarsOfCo (AxiomInstCo _ _ cos) = coVarsOfCos cos coVarsOfCo (UnivCo _ _ _ _) = emptyVarSet coVarsOfCo (SymCo co) = coVarsOfCo co coVarsOfCo (TransCo co1 co2) = coVarsOfCo co1 `unionVarSet` coVarsOfCo co2 coVarsOfCo (NthCo _ co) = coVarsOfCo co coVarsOfCo (LRCo _ co) = coVarsOfCo co coVarsOfCo (InstCo co _) = coVarsOfCo co coVarsOfCo (SubCo co) = coVarsOfCo co coVarsOfCo (AxiomRuleCo _ _ cos) = coVarsOfCos cos coVarsOfCos :: [Coercion] -> VarSet coVarsOfCos = mapUnionVarSet coVarsOfCo coercionSize :: Coercion -> Int coercionSize (Refl _ ty) = typeSize ty coercionSize (TyConAppCo _ _ cos) = 1 + sum (map coercionSize cos) coercionSize (AppCo co1 co2) = coercionSize co1 + coercionSize co2 coercionSize (ForAllCo _ co) = 1 + coercionSize co coercionSize (CoVarCo _) = 1 coercionSize (AxiomInstCo _ _ cos) = 1 + sum (map coercionSize cos) coercionSize (UnivCo _ _ ty1 ty2) = typeSize ty1 + typeSize ty2 coercionSize (SymCo co) = 1 + coercionSize co coercionSize (TransCo co1 co2) = 1 + coercionSize co1 + coercionSize co2 coercionSize (NthCo _ co) = 1 + coercionSize co coercionSize (LRCo _ co) = 1 + coercionSize co coercionSize (InstCo co ty) = 1 + coercionSize co + typeSize ty coercionSize (SubCo co) = 1 + coercionSize co coercionSize (AxiomRuleCo _ tys cos) = 1 + sum (map typeSize tys) + sum (map coercionSize cos) {- ************************************************************************ * * Tidying coercions * * ************************************************************************ -} tidyCo :: TidyEnv -> Coercion -> Coercion tidyCo env@(_, subst) co = go co where go (Refl r ty) = Refl r (tidyType env ty) go (TyConAppCo r tc cos) = let args = map go cos in args `seqList` TyConAppCo r tc args go (AppCo co1 co2) = (AppCo $! go co1) $! go co2 go (ForAllCo tv co) = ForAllCo tvp $! (tidyCo envp co) where (envp, tvp) = tidyTyVarBndr env tv go (CoVarCo cv) = case lookupVarEnv subst cv of Nothing -> CoVarCo cv Just cv' -> CoVarCo cv' go (AxiomInstCo con ind cos) = let args = tidyCos env cos in args `seqList` AxiomInstCo con ind args go (UnivCo s r ty1 ty2) = (UnivCo s r $! tidyType env ty1) $! tidyType env ty2 go (SymCo co) = SymCo $! go co go (TransCo co1 co2) = (TransCo $! go co1) $! go co2 go (NthCo d co) = NthCo d $! go co go (LRCo lr co) = LRCo lr $! go co go (InstCo co ty) = (InstCo $! go co) $! tidyType env ty go (SubCo co) = SubCo $! go co go (AxiomRuleCo ax tys cos) = let tys1 = map (tidyType env) tys cos1 = tidyCos env cos in tys1 `seqList` cos1 `seqList` AxiomRuleCo ax tys1 cos1 tidyCos :: TidyEnv -> [Coercion] -> [Coercion] tidyCos env = map (tidyCo env) {- ************************************************************************ * * Pretty-printing coercions * * ************************************************************************ @pprCo@ is the standard @Coercion@ printer; the overloaded @ppr@ function is defined to use this. @pprParendCo@ is the same, except it puts parens around the type, except for the atomic cases. @pprParendCo@ works just by setting the initial context precedence very high. -} instance Outputable Coercion where ppr = pprCo pprCo, pprParendCo :: Coercion -> SDoc pprCo co = ppr_co TopPrec co pprParendCo co = ppr_co TyConPrec co ppr_co :: TyPrec -> Coercion -> SDoc ppr_co _ (Refl r ty) = angleBrackets (ppr ty) <> ppr_role r ppr_co p co@(TyConAppCo _ tc [_,_]) | tc `hasKey` funTyConKey = ppr_fun_co p co ppr_co _ (TyConAppCo r tc cos) = pprTcApp TyConPrec ppr_co tc cos <> ppr_role r ppr_co p (AppCo co1 co2) = maybeParen p TyConPrec $ pprCo co1 <+> ppr_co TyConPrec co2 ppr_co p co@(ForAllCo {}) = ppr_forall_co p co ppr_co _ (CoVarCo cv) = parenSymOcc (getOccName cv) (ppr cv) ppr_co p (AxiomInstCo con index cos) = pprPrefixApp p (ppr (getName con) <> brackets (ppr index)) (map (ppr_co TyConPrec) cos) ppr_co p co@(TransCo {}) = maybeParen p FunPrec $ case trans_co_list co [] of [] -> panic "ppr_co" (co:cos) -> sep ( ppr_co FunPrec co : [ char ';' <+> ppr_co FunPrec co | co <- cos]) ppr_co p (InstCo co ty) = maybeParen p TyConPrec $ pprParendCo co <> ptext (sLit "@") <> pprType ty ppr_co p (UnivCo s r ty1 ty2) = pprPrefixApp p (ptext (sLit "UnivCo") <+> ftext s <+> ppr r) [pprParendType ty1, pprParendType ty2] ppr_co p (SymCo co) = pprPrefixApp p (ptext (sLit "Sym")) [pprParendCo co] ppr_co p (NthCo n co) = pprPrefixApp p (ptext (sLit "Nth:") <> int n) [pprParendCo co] ppr_co p (LRCo sel co) = pprPrefixApp p (ppr sel) [pprParendCo co] ppr_co p (SubCo co) = pprPrefixApp p (ptext (sLit "Sub")) [pprParendCo co] ppr_co p (AxiomRuleCo co ts cs) = maybeParen p TopPrec $ ppr_axiom_rule_co co ts cs ppr_axiom_rule_co :: CoAxiomRule -> [Type] -> [Coercion] -> SDoc ppr_axiom_rule_co co ts ps = ppr (coaxrName co) <> ppTs ts $$ nest 2 (ppPs ps) where ppTs [] = Outputable.empty ppTs [t] = ptext (sLit "@") <> ppr_type TopPrec t ppTs ts = ptext (sLit "@") <> parens (hsep $ punctuate comma $ map pprType ts) ppPs [] = Outputable.empty ppPs [p] = pprParendCo p ppPs (p : ps) = ptext (sLit "(") <+> pprCo p $$ vcat [ ptext (sLit ",") <+> pprCo q | q <- ps ] $$ ptext (sLit ")") ppr_role :: Role -> SDoc ppr_role r = underscore <> pp_role where pp_role = case r of Nominal -> char 'N' Representational -> char 'R' Phantom -> char 'P' trans_co_list :: Coercion -> [Coercion] -> [Coercion] trans_co_list (TransCo co1 co2) cos = trans_co_list co1 (trans_co_list co2 cos) trans_co_list co cos = co : cos instance Outputable LeftOrRight where ppr CLeft = ptext (sLit "Left") ppr CRight = ptext (sLit "Right") ppr_fun_co :: TyPrec -> Coercion -> SDoc ppr_fun_co p co = pprArrowChain p (split co) where split :: Coercion -> [SDoc] split (TyConAppCo _ f [arg,res]) | f `hasKey` funTyConKey = ppr_co FunPrec arg : split res split co = [ppr_co TopPrec co] ppr_forall_co :: TyPrec -> Coercion -> SDoc ppr_forall_co p ty = maybeParen p FunPrec $ sep [pprForAll tvs, ppr_co TopPrec rho] where (tvs, rho) = split1 [] ty split1 tvs (ForAllCo tv ty) = split1 (tv:tvs) ty split1 tvs ty = (reverse tvs, ty) pprCoAxiom :: CoAxiom br -> SDoc pprCoAxiom ax@(CoAxiom { co_ax_tc = tc, co_ax_branches = branches }) = hang (ptext (sLit "axiom") <+> ppr ax <+> dcolon) 2 (vcat (map (pprCoAxBranch tc) $ fromBranchList branches)) pprCoAxBranch :: TyCon -> CoAxBranch -> SDoc pprCoAxBranch fam_tc (CoAxBranch { cab_tvs = tvs , cab_lhs = lhs , cab_rhs = rhs }) = hang (pprUserForAll tvs) 2 (hang (pprTypeApp fam_tc lhs) 2 (equals <+> (ppr rhs))) pprCoAxBranchHdr :: CoAxiom br -> BranchIndex -> SDoc pprCoAxBranchHdr ax@(CoAxiom { co_ax_tc = fam_tc, co_ax_name = name }) index | CoAxBranch { cab_lhs = tys, cab_loc = loc } <- coAxiomNthBranch ax index = hang (pprTypeApp fam_tc tys) 2 (ptext (sLit "-- Defined") <+> ppr_loc loc) where ppr_loc loc | isGoodSrcSpan loc = ptext (sLit "at") <+> ppr (srcSpanStart loc) | otherwise = ptext (sLit "in") <+> quotes (ppr (nameModule name)) {- ************************************************************************ * * Functions over Kinds * * ************************************************************************ -} -- | This breaks a 'Coercion' with type @T A B C ~ T D E F@ into -- a list of 'Coercion's of kinds @A ~ D@, @B ~ E@ and @E ~ F@. Hence: -- -- > decomposeCo 3 c = [nth 0 c, nth 1 c, nth 2 c] decomposeCo :: Arity -> Coercion -> [Coercion] decomposeCo arity co = [mkNthCo n co | n <- [0..(arity-1)] ] -- Remember, Nth is zero-indexed -- | Attempts to obtain the type variable underlying a 'Coercion' getCoVar_maybe :: Coercion -> Maybe CoVar getCoVar_maybe (CoVarCo cv) = Just cv getCoVar_maybe _ = Nothing -- first result has role equal to input; second result is Nominal splitAppCo_maybe :: Coercion -> Maybe (Coercion, Coercion) -- ^ Attempt to take a coercion application apart. splitAppCo_maybe (AppCo co1 co2) = Just (co1, co2) splitAppCo_maybe (TyConAppCo r tc cos) | isDecomposableTyCon tc || cos `lengthExceeds` tyConArity tc , Just (cos', co') <- snocView cos , Just co'' <- setNominalRole_maybe co' = Just (mkTyConAppCo r tc cos', co'') -- Never create unsaturated type family apps! -- Use mkTyConAppCo to preserve the invariant -- that identity coercions are always represented by Refl splitAppCo_maybe (Refl r ty) | Just (ty1, ty2) <- splitAppTy_maybe ty = Just (Refl r ty1, Refl Nominal ty2) splitAppCo_maybe _ = Nothing splitForAllCo_maybe :: Coercion -> Maybe (TyVar, Coercion) splitForAllCo_maybe (ForAllCo tv co) = Just (tv, co) splitForAllCo_maybe _ = Nothing ------------------------------------------------------- -- and some coercion kind stuff coVarKind :: CoVar -> (Type,Type) coVarKind cv | Just (tc, [_kind,ty1,ty2]) <- splitTyConApp_maybe (varType cv) = ASSERT(tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey) (ty1,ty2) | otherwise = panic "coVarKind, non coercion variable" coVarRole :: CoVar -> Role coVarRole cv | tc `hasKey` eqPrimTyConKey = Nominal | tc `hasKey` eqReprPrimTyConKey = Representational | otherwise = pprPanic "coVarRole: unknown tycon" (ppr cv) where tc = case tyConAppTyCon_maybe (varType cv) of Just tc0 -> tc0 Nothing -> pprPanic "coVarRole: not tyconapp" (ppr cv) -- | Makes a coercion type from two types: the types whose equality -- is proven by the relevant 'Coercion' mkCoercionType :: Role -> Type -> Type -> Type mkCoercionType Nominal = mkPrimEqPred mkCoercionType Representational = mkReprPrimEqPred mkCoercionType Phantom = panic "mkCoercionType" isReflCo :: Coercion -> Bool isReflCo (Refl {}) = True isReflCo _ = False isReflCo_maybe :: Coercion -> Maybe Type isReflCo_maybe (Refl _ ty) = Just ty isReflCo_maybe _ = Nothing {- ************************************************************************ * * Building coercions * * ************************************************************************ Note [Role twiddling functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are a plethora of functions for twiddling roles: mkSubCo: Requires a nominal input coercion and always produces a representational output. This is used when you (the programmer) are sure you know exactly that role you have and what you want. downgradeRole_maybe: This function takes both the input role and the output role as parameters. (The *output* role comes first!) It can only *downgrade* a role -- that is, change it from N to R or P, or from R to P. This one-way behavior is why there is the "_maybe". If an upgrade is requested, this function produces Nothing. This is used when you need to change the role of a coercion, but you're not sure (as you're writing the code) of which roles are involved. This function could have been written using coercionRole to ascertain the role of the input. But, that function is recursive, and the caller of downgradeRole_maybe often knows the input role. So, this is more efficient. downgradeRole: This is just like downgradeRole_maybe, but it panics if the conversion isn't a downgrade. setNominalRole_maybe: This is the only function that can *upgrade* a coercion. The result (if it exists) is always Nominal. The input can be at any role. It works on a "best effort" basis, as it should never be strictly necessary to upgrade a coercion during compilation. It is currently only used within GHC in splitAppCo_maybe. In order to be a proper inverse of mkAppCo, the second coercion that splitAppCo_maybe returns must be nominal. But, it's conceivable that splitAppCo_maybe is operating over a TyConAppCo that uses a representational coercion. Hence the need for setNominalRole_maybe. splitAppCo_maybe, in turn, is used only within coercion optimization -- thus, it is not absolutely critical that setNominalRole_maybe be complete. Note that setNominalRole_maybe will never upgrade a phantom UnivCo. Phantom UnivCos are perfectly type-safe, whereas representational and nominal ones are not. Indeed, `unsafeCoerce` is implemented via a representational UnivCo. (Nominal ones are no worse than representational ones, so this function *will* change a UnivCo Representational to a UnivCo Nominal.) Conal Elliott also came across a need for this function while working with the GHC API, as he was decomposing Core casts. The Core casts use representational coercions, as they must, but his use case required nominal coercions (he was building a GADT). So, that's why this function is exported from this module. One might ask: shouldn't downgradeRole_maybe just use setNominalRole_maybe as appropriate? I (Richard E.) have decided not to do this, because upgrading a role is bizarre and a caller should have to ask for this behavior explicitly. -} mkCoVarCo :: CoVar -> Coercion -- cv :: s ~# t mkCoVarCo cv | ty1 `eqType` ty2 = Refl (coVarRole cv) ty1 | otherwise = CoVarCo cv where (ty1, ty2) = ASSERT( isCoVar cv ) coVarKind cv mkReflCo :: Role -> Type -> Coercion mkReflCo = Refl mkAxInstCo :: Role -> CoAxiom br -> BranchIndex -> [Type] -> Coercion -- mkAxInstCo can legitimately be called over-staturated; -- i.e. with more type arguments than the coercion requires mkAxInstCo role ax index tys | arity == n_tys = downgradeRole role ax_role $ AxiomInstCo ax_br index rtys | otherwise = ASSERT( arity < n_tys ) downgradeRole role ax_role $ foldl AppCo (AxiomInstCo ax_br index (take arity rtys)) (drop arity rtys) where n_tys = length tys ax_br = toBranchedAxiom ax branch = coAxiomNthBranch ax_br index arity = length $ coAxBranchTyVars branch arg_roles = coAxBranchRoles branch rtys = zipWith mkReflCo (arg_roles ++ repeat Nominal) tys ax_role = coAxiomRole ax -- to be used only with unbranched axioms mkUnbranchedAxInstCo :: Role -> CoAxiom Unbranched -> [Type] -> Coercion mkUnbranchedAxInstCo role ax tys = mkAxInstCo role ax 0 tys mkAxInstLHS, mkAxInstRHS :: CoAxiom br -> BranchIndex -> [Type] -> Type -- Instantiate the axiom with specified types, -- returning the instantiated RHS -- A companion to mkAxInstCo: -- mkAxInstRhs ax index tys = snd (coercionKind (mkAxInstCo ax index tys)) mkAxInstLHS ax index tys | CoAxBranch { cab_tvs = tvs, cab_lhs = lhs } <- coAxiomNthBranch ax index , (tys1, tys2) <- splitAtList tvs tys = ASSERT( tvs `equalLength` tys1 ) mkTyConApp (coAxiomTyCon ax) (substTysWith tvs tys1 lhs ++ tys2) mkAxInstRHS ax index tys | CoAxBranch { cab_tvs = tvs, cab_rhs = rhs } <- coAxiomNthBranch ax index , (tys1, tys2) <- splitAtList tvs tys = ASSERT( tvs `equalLength` tys1 ) mkAppTys (substTyWith tvs tys1 rhs) tys2 mkUnbranchedAxInstRHS :: CoAxiom Unbranched -> [Type] -> Type mkUnbranchedAxInstRHS ax = mkAxInstRHS ax 0 -- | Apply a 'Coercion' to another 'Coercion'. -- The second coercion must be Nominal, unless the first is Phantom. -- If the first is Phantom, then the second can be either Phantom or Nominal. mkAppCo :: Coercion -> Coercion -> Coercion mkAppCo co1 co2 = mkAppCoFlexible co1 Nominal co2 -- Note, mkAppCo is careful to maintain invariants regarding -- where Refl constructors appear; see the comments in the definition -- of Coercion and the Note [Refl invariant] in types/TypeRep.hs. -- | Apply a 'Coercion' to another 'Coercion'. -- The second 'Coercion's role is given, making this more flexible than -- 'mkAppCo'. mkAppCoFlexible :: Coercion -> Role -> Coercion -> Coercion mkAppCoFlexible (Refl r ty1) _ (Refl _ ty2) = Refl r (mkAppTy ty1 ty2) mkAppCoFlexible (Refl r ty1) r2 co2 | Just (tc, tys) <- splitTyConApp_maybe ty1 -- Expand type synonyms; a TyConAppCo can't have a type synonym (Trac #9102) = TyConAppCo r tc (zip_roles (tyConRolesX r tc) tys) where zip_roles (r1:_) [] = [downgradeRole r1 r2 co2] zip_roles (r1:rs) (ty1:tys) = mkReflCo r1 ty1 : zip_roles rs tys zip_roles _ _ = panic "zip_roles" -- but the roles are infinite... mkAppCoFlexible (TyConAppCo r tc cos) r2 co = case r of Nominal -> ASSERT( r2 == Nominal ) TyConAppCo Nominal tc (cos ++ [co]) Representational -> TyConAppCo Representational tc (cos ++ [co']) where new_role = (tyConRolesX Representational tc) !! (length cos) co' = downgradeRole new_role r2 co Phantom -> TyConAppCo Phantom tc (cos ++ [mkPhantomCo co]) mkAppCoFlexible co1 _r2 co2 = ASSERT( _r2 == Nominal ) AppCo co1 co2 -- | Applies multiple 'Coercion's to another 'Coercion', from left to right. -- See also 'mkAppCo'. mkAppCos :: Coercion -> [Coercion] -> Coercion mkAppCos co1 cos = foldl mkAppCo co1 cos -- | Apply a type constructor to a list of coercions. It is the -- caller's responsibility to get the roles correct on argument coercions. mkTyConAppCo :: Role -> TyCon -> [Coercion] -> Coercion mkTyConAppCo r tc cos -- Expand type synonyms | Just (tv_co_prs, rhs_ty, leftover_cos) <- expandSynTyCon_maybe tc cos = mkAppCos (liftCoSubst r tv_co_prs rhs_ty) leftover_cos | Just tys <- traverse isReflCo_maybe cos = Refl r (mkTyConApp tc tys) -- See Note [Refl invariant] | otherwise = TyConAppCo r tc cos -- | Make a function 'Coercion' between two other 'Coercion's mkFunCo :: Role -> Coercion -> Coercion -> Coercion mkFunCo r co1 co2 = mkTyConAppCo r funTyCon [co1, co2] -- | Make a 'Coercion' which binds a variable within an inner 'Coercion' mkForAllCo :: Var -> Coercion -> Coercion -- note that a TyVar should be used here, not a CoVar (nor a TcTyVar) mkForAllCo tv (Refl r ty) = ASSERT( isTyVar tv ) Refl r (mkForAllTy tv ty) mkForAllCo tv co = ASSERT( isTyVar tv ) ForAllCo tv co ------------------------------- -- | Create a symmetric version of the given 'Coercion' that asserts -- equality between the same types but in the other "direction", so -- a kind of @t1 ~ t2@ becomes the kind @t2 ~ t1@. mkSymCo :: Coercion -> Coercion -- Do a few simple optimizations, but don't bother pushing occurrences -- of symmetry to the leaves; the optimizer will take care of that. mkSymCo co@(Refl {}) = co mkSymCo (UnivCo s r ty1 ty2) = UnivCo s r ty2 ty1 mkSymCo (SymCo co) = co mkSymCo co = SymCo co -- | Create a new 'Coercion' by composing the two given 'Coercion's transitively. mkTransCo :: Coercion -> Coercion -> Coercion mkTransCo (Refl {}) co = co mkTransCo co (Refl {}) = co mkTransCo co1 co2 = TransCo co1 co2 -- the Role is the desired one. It is the caller's responsibility to make -- sure this request is reasonable mkNthCoRole :: Role -> Int -> Coercion -> Coercion mkNthCoRole role n co = downgradeRole role nth_role $ nth_co where nth_co = mkNthCo n co nth_role = coercionRole nth_co mkNthCo :: Int -> Coercion -> Coercion mkNthCo n (Refl r ty) = ASSERT( ok_tc_app ty n ) Refl r' (tyConAppArgN n ty) where tc = tyConAppTyCon ty r' = nthRole r tc n mkNthCo n co = ASSERT( ok_tc_app _ty1 n && ok_tc_app _ty2 n ) NthCo n co where Pair _ty1 _ty2 = coercionKind co mkLRCo :: LeftOrRight -> Coercion -> Coercion mkLRCo lr (Refl eq ty) = Refl eq (pickLR lr (splitAppTy ty)) mkLRCo lr co = LRCo lr co ok_tc_app :: Type -> Int -> Bool ok_tc_app ty n = case splitTyConApp_maybe ty of Just (_, tys) -> tys `lengthExceeds` n Nothing -> False -- | Instantiates a 'Coercion' with a 'Type' argument. mkInstCo :: Coercion -> Type -> Coercion mkInstCo co ty = InstCo co ty -- | Manufacture an unsafe coercion from thin air. -- Currently (May 14) this is used only to implement the -- @unsafeCoerce#@ primitive. Optimise by pushing -- down through type constructors. mkUnsafeCo :: Type -> Type -> Coercion mkUnsafeCo = mkUnivCo (fsLit "mkUnsafeCo") Representational mkUnivCo :: FastString -> Role -> Type -> Type -> Coercion mkUnivCo prov role ty1 ty2 | ty1 `eqType` ty2 = Refl role ty1 | otherwise = UnivCo prov role ty1 ty2 mkAxiomRuleCo :: CoAxiomRule -> [Type] -> [Coercion] -> Coercion mkAxiomRuleCo = AxiomRuleCo -- input coercion is Nominal; see also Note [Role twiddling functions] mkSubCo :: Coercion -> Coercion mkSubCo (Refl Nominal ty) = Refl Representational ty mkSubCo (TyConAppCo Nominal tc cos) = TyConAppCo Representational tc (applyRoles tc cos) mkSubCo (UnivCo s Nominal ty1 ty2) = UnivCo s Representational ty1 ty2 mkSubCo co = ASSERT2( coercionRole co == Nominal, ppr co <+> ppr (coercionRole co) ) SubCo co -- only *downgrades* a role. See Note [Role twiddling functions] downgradeRole_maybe :: Role -- desired role -> Role -- current role -> Coercion -> Maybe Coercion -- In (downgradeRole_maybe dr cr co) it's a precondition that -- cr = coercionRole co downgradeRole_maybe Representational Nominal co = Just (mkSubCo co) downgradeRole_maybe Nominal Representational _ = Nothing downgradeRole_maybe Phantom Phantom co = Just co downgradeRole_maybe Phantom _ co = Just (mkPhantomCo co) downgradeRole_maybe _ Phantom _ = Nothing downgradeRole_maybe _ _ co = Just co -- panics if the requested conversion is not a downgrade. -- See also Note [Role twiddling functions] downgradeRole :: Role -- desired role -> Role -- current role -> Coercion -> Coercion downgradeRole r1 r2 co = case downgradeRole_maybe r1 r2 co of Just co' -> co' Nothing -> pprPanic "downgradeRole" (ppr co) -- Converts a coercion to be nominal, if possible. -- See also Note [Role twiddling functions] setNominalRole_maybe :: Coercion -> Maybe Coercion setNominalRole_maybe co | Nominal <- coercionRole co = Just co setNominalRole_maybe (SubCo co) = Just co setNominalRole_maybe (Refl _ ty) = Just $ Refl Nominal ty setNominalRole_maybe (TyConAppCo Representational tc coes) = do { cos' <- mapM setNominalRole_maybe coes ; return $ TyConAppCo Nominal tc cos' } setNominalRole_maybe (UnivCo s Representational ty1 ty2) = Just $ UnivCo s Nominal ty1 ty2 -- We do *not* promote UnivCo Phantom, as that's unsafe. -- UnivCo Nominal is no more unsafe than UnivCo Representational setNominalRole_maybe (TransCo co1 co2) = TransCo <$> setNominalRole_maybe co1 <*> setNominalRole_maybe co2 setNominalRole_maybe (AppCo co1 co2) = AppCo <$> setNominalRole_maybe co1 <*> pure co2 setNominalRole_maybe (ForAllCo tv co) = ForAllCo tv <$> setNominalRole_maybe co setNominalRole_maybe (NthCo n co) = NthCo n <$> setNominalRole_maybe co setNominalRole_maybe (InstCo co ty) = InstCo <$> setNominalRole_maybe co <*> pure ty setNominalRole_maybe _ = Nothing -- takes any coercion and turns it into a Phantom coercion mkPhantomCo :: Coercion -> Coercion mkPhantomCo co | Just ty <- isReflCo_maybe co = Refl Phantom ty | Pair ty1 ty2 <- coercionKind co = UnivCo (fsLit "mkPhantomCo") Phantom ty1 ty2 -- don't optimise here... wait for OptCoercion -- All input coercions are assumed to be Nominal, -- or, if Role is Phantom, the Coercion can be Phantom, too. applyRole :: Role -> Coercion -> Coercion applyRole Nominal = id applyRole Representational = mkSubCo applyRole Phantom = mkPhantomCo -- Convert args to a TyConAppCo Nominal to the same TyConAppCo Representational applyRoles :: TyCon -> [Coercion] -> [Coercion] applyRoles tc cos = zipWith applyRole (tyConRolesX Representational tc) cos -- the Role parameter is the Role of the TyConAppCo -- defined here because this is intimiately concerned with the implementation -- of TyConAppCo tyConRolesX :: Role -> TyCon -> [Role] tyConRolesX Representational tc = tyConRoles tc ++ repeat Nominal tyConRolesX role _ = repeat role nthRole :: Role -> TyCon -> Int -> Role nthRole Nominal _ _ = Nominal nthRole Phantom _ _ = Phantom nthRole Representational tc n = (tyConRolesX Representational tc) !! n ltRole :: Role -> Role -> Bool -- Is one role "less" than another? -- Nominal < Representational < Phantom ltRole Phantom _ = False ltRole Representational Phantom = True ltRole Representational _ = False ltRole Nominal Nominal = False ltRole Nominal _ = True -- See note [Newtype coercions] in TyCon -- | Create a coercion constructor (axiom) suitable for the given -- newtype 'TyCon'. The 'Name' should be that of a new coercion -- 'CoAxiom', the 'TyVar's the arguments expected by the @newtype@ and -- the type the appropriate right hand side of the @newtype@, with -- the free variables a subset of those 'TyVar's. mkNewTypeCo :: Name -> TyCon -> [TyVar] -> [Role] -> Type -> CoAxiom Unbranched mkNewTypeCo name tycon tvs roles rhs_ty = CoAxiom { co_ax_unique = nameUnique name , co_ax_name = name , co_ax_implicit = True -- See Note [Implicit axioms] in TyCon , co_ax_role = Representational , co_ax_tc = tycon , co_ax_branches = FirstBranch branch } where branch = CoAxBranch { cab_loc = getSrcSpan name , cab_tvs = tvs , cab_lhs = mkTyVarTys tvs , cab_roles = roles , cab_rhs = rhs_ty , cab_incomps = [] } mkPiCos :: Role -> [Var] -> Coercion -> Coercion mkPiCos r vs co = foldr (mkPiCo r) co vs mkPiCo :: Role -> Var -> Coercion -> Coercion mkPiCo r v co | isTyVar v = mkForAllCo v co | otherwise = mkFunCo r (mkReflCo r (varType v)) co -- The first coercion *must* be Nominal. mkCoCast :: Coercion -> Coercion -> Coercion -- (mkCoCast (c :: s1 ~# t1) (g :: (s1 ~# t1) ~# (s2 ~# t2) mkCoCast c g = mkSymCo g1 `mkTransCo` c `mkTransCo` g2 where -- g :: (s1 ~# s2) ~# (t1 ~# t2) -- g1 :: s1 ~# t1 -- g2 :: s2 ~# t2 [_reflk, g1, g2] = decomposeCo 3 g -- Remember, (~#) :: forall k. k -> k -> * -- so it takes *three* arguments, not two {- ************************************************************************ * * Newtypes * * ************************************************************************ -} -- | If @co :: T ts ~ rep_ty@ then: -- -- > instNewTyCon_maybe T ts = Just (rep_ty, co) -- -- Checks for a newtype, and for being saturated instNewTyCon_maybe :: TyCon -> [Type] -> Maybe (Type, Coercion) instNewTyCon_maybe tc tys | Just (tvs, ty, co_tc) <- unwrapNewTyConEtad_maybe tc -- Check for newtype , tvs `leLength` tys -- Check saturated enough = Just ( applyTysX tvs ty tys , mkUnbranchedAxInstCo Representational co_tc tys) | otherwise = Nothing {- ************************************************************************ * * Type normalisation * * ************************************************************************ -} -- | A function to check if we can reduce a type by one step. Used -- with 'topNormaliseTypeX_maybe'. type NormaliseStepper = RecTcChecker -> TyCon -- tc -> [Type] -- tys -> NormaliseStepResult -- | The result of stepping in a normalisation function. -- See 'topNormaliseTypeX_maybe'. data NormaliseStepResult = NS_Done -- ^ nothing more to do | NS_Abort -- ^ utter failure. The outer function should fail too. | NS_Step RecTcChecker Type Coercion -- ^ we stepped, yielding new bits; -- ^ co :: old type ~ new type modifyStepResultCo :: (Coercion -> Coercion) -> NormaliseStepResult -> NormaliseStepResult modifyStepResultCo f (NS_Step rec_nts ty co) = NS_Step rec_nts ty (f co) modifyStepResultCo _ result = result -- | Try one stepper and then try the next, if the first doesn't make -- progress. composeSteppers :: NormaliseStepper -> NormaliseStepper -> NormaliseStepper composeSteppers step1 step2 rec_nts tc tys = case step1 rec_nts tc tys of success@(NS_Step {}) -> success NS_Done -> step2 rec_nts tc tys NS_Abort -> NS_Abort -- | A 'NormaliseStepper' that unwraps newtypes, careful not to fall into -- a loop. If it would fall into a loop, it produces 'NS_Abort'. unwrapNewTypeStepper :: NormaliseStepper unwrapNewTypeStepper rec_nts tc tys | Just (ty', co) <- instNewTyCon_maybe tc tys = case checkRecTc rec_nts tc of Just rec_nts' -> NS_Step rec_nts' ty' co Nothing -> NS_Abort | otherwise = NS_Done -- | A general function for normalising the top-level of a type. It continues -- to use the provided 'NormaliseStepper' until that function fails, and then -- this function returns. The roles of the coercions produced by the -- 'NormaliseStepper' must all be the same, which is the role returned from -- the call to 'topNormaliseTypeX_maybe'. topNormaliseTypeX_maybe :: NormaliseStepper -> Type -> Maybe (Coercion, Type) topNormaliseTypeX_maybe stepper = go initRecTc Nothing where go rec_nts mb_co1 ty | Just (tc, tys) <- splitTyConApp_maybe ty = case stepper rec_nts tc tys of NS_Step rec_nts' ty' co2 -> go rec_nts' (mb_co1 `trans` co2) ty' NS_Done -> all_done NS_Abort -> Nothing | otherwise = all_done where all_done | Just co <- mb_co1 = Just (co, ty) | otherwise = Nothing Nothing `trans` co2 = Just co2 (Just co1) `trans` co2 = Just (co1 `mkTransCo` co2) topNormaliseNewType_maybe :: Type -> Maybe (Coercion, Type) -- ^ Sometimes we want to look through a @newtype@ and get its associated coercion. -- This function strips off @newtype@ layers enough to reveal something that isn't -- a @newtype@, or responds False to ok_tc. Specifically, here's the invariant: -- -- > topNormaliseNewType_maybe ty = Just (co, ty') -- -- then (a) @co : ty0 ~ ty'@. -- (b) ty' is not a newtype. -- -- The function returns @Nothing@ for non-@newtypes@, -- or unsaturated applications -- -- This function does *not* look through type families, because it has no access to -- the type family environment. If you do have that at hand, consider to use -- topNormaliseType_maybe, which should be a drop-in replacement for -- topNormaliseNewType_maybe -- topNormaliseNewType_maybe ty = topNormaliseTypeX_maybe unwrapNewTypeStepper ty {- ************************************************************************ * * Equality of coercions * * ************************************************************************ -} -- | Determines syntactic equality of coercions coreEqCoercion :: Coercion -> Coercion -> Bool coreEqCoercion co1 co2 = coreEqCoercion2 rn_env co1 co2 where rn_env = mkRnEnv2 (mkInScopeSet (tyCoVarsOfCo co1 `unionVarSet` tyCoVarsOfCo co2)) coreEqCoercion2 :: RnEnv2 -> Coercion -> Coercion -> Bool coreEqCoercion2 env (Refl eq1 ty1) (Refl eq2 ty2) = eq1 == eq2 && eqTypeX env ty1 ty2 coreEqCoercion2 env (TyConAppCo eq1 tc1 cos1) (TyConAppCo eq2 tc2 cos2) = eq1 == eq2 && tc1 == tc2 && all2 (coreEqCoercion2 env) cos1 cos2 coreEqCoercion2 env (AppCo co11 co12) (AppCo co21 co22) = coreEqCoercion2 env co11 co21 && coreEqCoercion2 env co12 co22 coreEqCoercion2 env (ForAllCo v1 co1) (ForAllCo v2 co2) = coreEqCoercion2 (rnBndr2 env v1 v2) co1 co2 coreEqCoercion2 env (CoVarCo cv1) (CoVarCo cv2) = rnOccL env cv1 == rnOccR env cv2 coreEqCoercion2 env (AxiomInstCo con1 ind1 cos1) (AxiomInstCo con2 ind2 cos2) = con1 == con2 && ind1 == ind2 && all2 (coreEqCoercion2 env) cos1 cos2 -- the provenance string is just a note, so don't use in comparisons coreEqCoercion2 env (UnivCo _ r1 ty11 ty12) (UnivCo _ r2 ty21 ty22) = r1 == r2 && eqTypeX env ty11 ty21 && eqTypeX env ty12 ty22 coreEqCoercion2 env (SymCo co1) (SymCo co2) = coreEqCoercion2 env co1 co2 coreEqCoercion2 env (TransCo co11 co12) (TransCo co21 co22) = coreEqCoercion2 env co11 co21 && coreEqCoercion2 env co12 co22 coreEqCoercion2 env (NthCo d1 co1) (NthCo d2 co2) = d1 == d2 && coreEqCoercion2 env co1 co2 coreEqCoercion2 env (LRCo d1 co1) (LRCo d2 co2) = d1 == d2 && coreEqCoercion2 env co1 co2 coreEqCoercion2 env (InstCo co1 ty1) (InstCo co2 ty2) = coreEqCoercion2 env co1 co2 && eqTypeX env ty1 ty2 coreEqCoercion2 env (SubCo co1) (SubCo co2) = coreEqCoercion2 env co1 co2 coreEqCoercion2 env (AxiomRuleCo a1 ts1 cs1) (AxiomRuleCo a2 ts2 cs2) = a1 == a2 && all2 (eqTypeX env) ts1 ts2 && all2 (coreEqCoercion2 env) cs1 cs2 coreEqCoercion2 _ _ _ = False {- ************************************************************************ * * Substitution of coercions * * ************************************************************************ -} -- | A substitution of 'Coercion's for 'CoVar's (OR 'TyVar's, when -- doing a \"lifting\" substitution) type CvSubstEnv = VarEnv Coercion emptyCvSubstEnv :: CvSubstEnv emptyCvSubstEnv = emptyVarEnv data CvSubst = CvSubst InScopeSet -- The in-scope type variables TvSubstEnv -- Substitution of types CvSubstEnv -- Substitution of coercions instance Outputable CvSubst where ppr (CvSubst ins tenv cenv) = brackets $ sep[ ptext (sLit "CvSubst"), nest 2 (ptext (sLit "In scope:") <+> ppr ins), nest 2 (ptext (sLit "Type env:") <+> ppr tenv), nest 2 (ptext (sLit "Coercion env:") <+> ppr cenv) ] emptyCvSubst :: CvSubst emptyCvSubst = CvSubst emptyInScopeSet emptyVarEnv emptyVarEnv isEmptyCvSubst :: CvSubst -> Bool isEmptyCvSubst (CvSubst _ tenv cenv) = isEmptyVarEnv tenv && isEmptyVarEnv cenv getCvInScope :: CvSubst -> InScopeSet getCvInScope (CvSubst in_scope _ _) = in_scope zapCvSubstEnv :: CvSubst -> CvSubst zapCvSubstEnv (CvSubst in_scope _ _) = CvSubst in_scope emptyVarEnv emptyVarEnv cvTvSubst :: CvSubst -> TvSubst cvTvSubst (CvSubst in_scope tvs _) = TvSubst in_scope tvs tvCvSubst :: TvSubst -> CvSubst tvCvSubst (TvSubst in_scope tenv) = CvSubst in_scope tenv emptyCvSubstEnv extendTvSubst :: CvSubst -> TyVar -> Type -> CvSubst extendTvSubst (CvSubst in_scope tenv cenv) tv ty = CvSubst in_scope (extendVarEnv tenv tv ty) cenv extendTvSubstAndInScope :: CvSubst -> TyVar -> Type -> CvSubst extendTvSubstAndInScope (CvSubst in_scope tenv cenv) tv ty = CvSubst (in_scope `extendInScopeSetSet` tyVarsOfType ty) (extendVarEnv tenv tv ty) cenv extendCvSubstAndInScope :: CvSubst -> CoVar -> Coercion -> CvSubst -- Also extends the in-scope set extendCvSubstAndInScope (CvSubst in_scope tenv cenv) cv co = CvSubst (in_scope `extendInScopeSetSet` tyCoVarsOfCo co) tenv (extendVarEnv cenv cv co) substCoVarBndr :: CvSubst -> CoVar -> (CvSubst, CoVar) substCoVarBndr subst@(CvSubst in_scope tenv cenv) old_var = ASSERT( isCoVar old_var ) (CvSubst (in_scope `extendInScopeSet` new_var) tenv new_cenv, new_var) where -- When we substitute (co :: t1 ~ t2) we may get the identity (co :: t ~ t) -- In that case, mkCoVarCo will return a ReflCoercion, and -- we want to substitute that (not new_var) for old_var new_co = mkCoVarCo new_var no_change = new_var == old_var && not (isReflCo new_co) new_cenv | no_change = delVarEnv cenv old_var | otherwise = extendVarEnv cenv old_var new_co new_var = uniqAway in_scope subst_old_var subst_old_var = mkCoVar (varName old_var) (substTy subst (varType old_var)) -- It's important to do the substitution for coercions, -- because they can have free type variables substTyVarBndr :: CvSubst -> TyVar -> (CvSubst, TyVar) substTyVarBndr (CvSubst in_scope tenv cenv) old_var = case Type.substTyVarBndr (TvSubst in_scope tenv) old_var of (TvSubst in_scope' tenv', new_var) -> (CvSubst in_scope' tenv' cenv, new_var) mkCvSubst :: InScopeSet -> [(Var,Coercion)] -> CvSubst mkCvSubst in_scope prs = CvSubst in_scope Type.emptyTvSubstEnv (mkVarEnv prs) zipOpenCvSubst :: [Var] -> [Coercion] -> CvSubst zipOpenCvSubst vs cos | debugIsOn && (length vs /= length cos) = pprTrace "zipOpenCvSubst" (ppr vs $$ ppr cos) emptyCvSubst | otherwise = CvSubst (mkInScopeSet (tyCoVarsOfCos cos)) emptyTvSubstEnv (zipVarEnv vs cos) substCoWithTy :: InScopeSet -> TyVar -> Type -> Coercion -> Coercion substCoWithTy in_scope tv ty = substCoWithTys in_scope [tv] [ty] substCoWithTys :: InScopeSet -> [TyVar] -> [Type] -> Coercion -> Coercion substCoWithTys in_scope tvs tys co | debugIsOn && (length tvs /= length tys) = pprTrace "substCoWithTys" (ppr tvs $$ ppr tys) co | otherwise = ASSERT( length tvs == length tys ) substCo (CvSubst in_scope (zipVarEnv tvs tys) emptyVarEnv) co -- | Substitute within a 'Coercion' substCo :: CvSubst -> Coercion -> Coercion substCo subst co | isEmptyCvSubst subst = co | otherwise = subst_co subst co -- | Substitute within several 'Coercion's substCos :: CvSubst -> [Coercion] -> [Coercion] substCos subst cos | isEmptyCvSubst subst = cos | otherwise = map (substCo subst) cos substTy :: CvSubst -> Type -> Type substTy subst = Type.substTy (cvTvSubst subst) subst_co :: CvSubst -> Coercion -> Coercion subst_co subst co = go co where go_ty :: Type -> Type go_ty = Coercion.substTy subst go :: Coercion -> Coercion go (Refl eq ty) = Refl eq $! go_ty ty go (TyConAppCo eq tc cos) = let args = map go cos in args `seqList` TyConAppCo eq tc args go (AppCo co1 co2) = mkAppCo (go co1) $! go co2 go (ForAllCo tv co) = case substTyVarBndr subst tv of (subst', tv') -> ForAllCo tv' $! subst_co subst' co go (CoVarCo cv) = substCoVar subst cv go (AxiomInstCo con ind cos) = AxiomInstCo con ind $! map go cos go (UnivCo s r ty1 ty2) = (UnivCo s r $! go_ty ty1) $! go_ty ty2 go (SymCo co) = mkSymCo (go co) go (TransCo co1 co2) = mkTransCo (go co1) (go co2) go (NthCo d co) = mkNthCo d (go co) go (LRCo lr co) = mkLRCo lr (go co) go (InstCo co ty) = mkInstCo (go co) $! go_ty ty go (SubCo co) = mkSubCo (go co) go (AxiomRuleCo co ts cs) = let ts1 = map go_ty ts cs1 = map go cs in ts1 `seqList` cs1 `seqList` AxiomRuleCo co ts1 cs1 substCoVar :: CvSubst -> CoVar -> Coercion substCoVar (CvSubst in_scope _ cenv) cv | Just co <- lookupVarEnv cenv cv = co | Just cv1 <- lookupInScope in_scope cv = ASSERT( isCoVar cv1 ) CoVarCo cv1 | otherwise = WARN( True, ptext (sLit "substCoVar not in scope") <+> ppr cv $$ ppr in_scope) ASSERT( isCoVar cv ) CoVarCo cv substCoVars :: CvSubst -> [CoVar] -> [Coercion] substCoVars subst cvs = map (substCoVar subst) cvs lookupTyVar :: CvSubst -> TyVar -> Maybe Type lookupTyVar (CvSubst _ tenv _) tv = lookupVarEnv tenv tv lookupCoVar :: CvSubst -> Var -> Maybe Coercion lookupCoVar (CvSubst _ _ cenv) v = lookupVarEnv cenv v {- ************************************************************************ * * "Lifting" substitution [(TyVar,Coercion)] -> Type -> Coercion * * ************************************************************************ Note [Lifting coercions over types: liftCoSubst] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The KPUSH rule deals with this situation data T a = MkK (a -> Maybe a) g :: T t1 ~ K t2 x :: t1 -> Maybe t1 case (K @t1 x) |> g of K (y:t2 -> Maybe t2) -> rhs We want to push the coercion inside the constructor application. So we do this g' :: t1~t2 = Nth 0 g case K @t2 (x |> g' -> Maybe g') of K (y:t2 -> Maybe t2) -> rhs The crucial operation is that we * take the type of K's argument: a -> Maybe a * and substitute g' for a thus giving *coercion*. This is what liftCoSubst does. Note [Substituting kinds in liftCoSubst] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We need to take care with kind polymorphism. Suppose K :: forall k (a:k). (forall b:k. a -> b) -> T k a Now given (K @kk1 @ty1 v) |> g) where g :: T kk1 ty1 ~ T kk2 ty2 we want to compute (forall b:k a->b) [ Nth 0 g/k, Nth 1 g/a ] Notice that we MUST substitute for 'k'; this happens in liftCoSubstTyVarBndr. But what should we substitute? We need to take b's kind 'k' and return a Kind, not a Coercion! Happily we can do this because we know that all kind coercions ((Nth 0 g) in this case) are Refl. So we need a special purpose subst_kind: LiftCoSubst -> Kind -> Kind that expects a Refl coercion (or something equivalent to Refl) when it looks up a kind variable. -} -- ---------------------------------------------------- -- See Note [Lifting coercions over types: liftCoSubst] -- ---------------------------------------------------- data LiftCoSubst = LCS InScopeSet LiftCoEnv type LiftCoEnv = VarEnv Coercion -- Maps *type variables* to *coercions* -- That's the whole point of this function! liftCoSubstWith :: Role -> [TyVar] -> [Coercion] -> Type -> Coercion liftCoSubstWith r tvs cos ty = liftCoSubst r (zipEqual "liftCoSubstWith" tvs cos) ty liftCoSubst :: Role -> [(TyVar,Coercion)] -> Type -> Coercion liftCoSubst r prs ty | null prs = Refl r ty | otherwise = ty_co_subst (LCS (mkInScopeSet (tyCoVarsOfCos (map snd prs))) (mkVarEnv prs)) r ty -- | The \"lifting\" operation which substitutes coercions for type -- variables in a type to produce a coercion. -- -- For the inverse operation, see 'liftCoMatch' -- The Role parameter is the _desired_ role ty_co_subst :: LiftCoSubst -> Role -> Type -> Coercion ty_co_subst subst role ty = go role ty where go Phantom ty = lift_phantom ty go role (TyVarTy tv) = liftCoSubstTyVar subst role tv `orElse` Refl role (TyVarTy tv) -- A type variable from a non-cloned forall -- won't be in the substitution go role (AppTy ty1 ty2) = mkAppCo (go role ty1) (go Nominal ty2) go role (TyConApp tc tys) = mkTyConAppCo role tc (zipWith go (tyConRolesX role tc) tys) -- IA0_NOTE: Do we need to do anything -- about kind instantiations? I don't think -- so. see Note [Kind coercions] go role (FunTy ty1 ty2) = mkFunCo role (go role ty1) (go role ty2) go role (ForAllTy v ty) = mkForAllCo v' $! (ty_co_subst subst' role ty) where (subst', v') = liftCoSubstTyVarBndr subst v go role ty@(LitTy {}) = ASSERT( role == Nominal ) mkReflCo role ty lift_phantom ty = mkUnivCo (fsLit "lift_phantom") Phantom (liftCoSubstLeft subst ty) (liftCoSubstRight subst ty) {- Note [liftCoSubstTyVar] ~~~~~~~~~~~~~~~~~~~~~~~ This function can fail (i.e., return Nothing) for two separate reasons: 1) The variable is not in the substutition 2) The coercion found is of too low a role liftCoSubstTyVar is called from two places: in liftCoSubst (naturally), and also in matchAxiom in OptCoercion. From liftCoSubst, the so-called lifting lemma guarantees that the roles work out. If we fail for reason 2) in this case, we really should panic -- something is deeply wrong. But, in matchAxiom, failing for reason 2) is fine. matchAxiom is trying to find a set of coercions that match, but it may fail, and this is healthy behavior. Bottom line: if you find that liftCoSubst is doing weird things (like leaving out-of-scope variables lying around), disable coercion optimization (bypassing matchAxiom) and use downgradeRole instead of downgradeRole_maybe. The panic will then happen, and you may learn something useful. -} liftCoSubstTyVar :: LiftCoSubst -> Role -> TyVar -> Maybe Coercion liftCoSubstTyVar (LCS _ cenv) r tv = do { co <- lookupVarEnv cenv tv ; let co_role = coercionRole co -- could theoretically take this as -- a parameter, but painful ; downgradeRole_maybe r co_role co } -- see Note [liftCoSubstTyVar] liftCoSubstTyVarBndr :: LiftCoSubst -> TyVar -> (LiftCoSubst, TyVar) liftCoSubstTyVarBndr subst@(LCS in_scope cenv) old_var = (LCS (in_scope `extendInScopeSet` new_var) new_cenv, new_var) where new_cenv | no_change = delVarEnv cenv old_var | otherwise = extendVarEnv cenv old_var (Refl Nominal (TyVarTy new_var)) no_change = no_kind_change && (new_var == old_var) new_var1 = uniqAway in_scope old_var old_ki = tyVarKind old_var no_kind_change = isEmptyVarSet (tyVarsOfType old_ki) new_var | no_kind_change = new_var1 | otherwise = setTyVarKind new_var1 (subst_kind subst old_ki) -- map every variable to the type on the *left* of its mapped coercion liftCoSubstLeft :: LiftCoSubst -> Type -> Type liftCoSubstLeft (LCS in_scope cenv) ty = Type.substTy (mkTvSubst in_scope (mapVarEnv (pFst . coercionKind) cenv)) ty -- same, but to the type on the right liftCoSubstRight :: LiftCoSubst -> Type -> Type liftCoSubstRight (LCS in_scope cenv) ty = Type.substTy (mkTvSubst in_scope (mapVarEnv (pSnd . coercionKind) cenv)) ty subst_kind :: LiftCoSubst -> Kind -> Kind -- See Note [Substituting kinds in liftCoSubst] subst_kind subst@(LCS _ cenv) kind = go kind where go (LitTy n) = n `seq` LitTy n go (TyVarTy kv) = subst_kv kv go (TyConApp tc tys) = let args = map go tys in args `seqList` TyConApp tc args go (FunTy arg res) = (FunTy $! (go arg)) $! (go res) go (AppTy fun arg) = mkAppTy (go fun) $! (go arg) go (ForAllTy tv ty) = case liftCoSubstTyVarBndr subst tv of (subst', tv') -> ForAllTy tv' $! (subst_kind subst' ty) subst_kv kv | Just co <- lookupVarEnv cenv kv , let co_kind = coercionKind co = ASSERT2( pFst co_kind `eqKind` pSnd co_kind, ppr kv $$ ppr co ) pFst co_kind | otherwise = TyVarTy kv -- | 'liftCoMatch' is sort of inverse to 'liftCoSubst'. In particular, if -- @liftCoMatch vars ty co == Just s@, then @tyCoSubst s ty == co@. -- That is, it matches a type against a coercion of the same -- "shape", and returns a lifting substitution which could have been -- used to produce the given coercion from the given type. liftCoMatch :: TyVarSet -> Type -> Coercion -> Maybe LiftCoSubst liftCoMatch tmpls ty co = case ty_co_match menv emptyVarEnv ty co of Just cenv -> Just (LCS in_scope cenv) Nothing -> Nothing where menv = ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope } in_scope = mkInScopeSet (tmpls `unionVarSet` tyCoVarsOfCo co) -- Like tcMatchTy, assume all the interesting variables -- in ty are in tmpls -- | 'ty_co_match' does all the actual work for 'liftCoMatch'. ty_co_match :: MatchEnv -> LiftCoEnv -> Type -> Coercion -> Maybe LiftCoEnv ty_co_match menv subst ty co | Just ty' <- coreView ty = ty_co_match menv subst ty' co -- Match a type variable against a non-refl coercion ty_co_match menv cenv (TyVarTy tv1) co | Just co1' <- lookupVarEnv cenv tv1' -- tv1' is already bound to co1 = if coreEqCoercion2 (nukeRnEnvL rn_env) co1' co then Just cenv else Nothing -- no match since tv1 matches two different coercions | tv1' `elemVarSet` me_tmpls menv -- tv1' is a template var = if any (inRnEnvR rn_env) (varSetElems (tyCoVarsOfCo co)) then Nothing -- occurs check failed else return (extendVarEnv cenv tv1' co) -- BAY: I don't think we need to do any kind matching here yet -- (compare 'match'), but we probably will when moving to SHE. | otherwise -- tv1 is not a template ty var, so the only thing it -- can match is a reflexivity coercion for itself. -- But that case is dealt with already = Nothing where rn_env = me_env menv tv1' = rnOccL rn_env tv1 ty_co_match menv subst (AppTy ty1 ty2) co | Just (co1, co2) <- splitAppCo_maybe co -- c.f. Unify.match on AppTy = do { subst' <- ty_co_match menv subst ty1 co1 ; ty_co_match menv subst' ty2 co2 } ty_co_match menv subst (TyConApp tc1 tys) (TyConAppCo _ tc2 cos) | tc1 == tc2 = ty_co_matches menv subst tys cos ty_co_match menv subst (FunTy ty1 ty2) (TyConAppCo _ tc cos) | tc == funTyCon = ty_co_matches menv subst [ty1,ty2] cos ty_co_match menv subst (ForAllTy tv1 ty) (ForAllCo tv2 co) = ty_co_match menv' subst ty co where menv' = menv { me_env = rnBndr2 (me_env menv) tv1 tv2 } ty_co_match menv subst ty co | Just co' <- pushRefl co = ty_co_match menv subst ty co' | otherwise = Nothing ty_co_matches :: MatchEnv -> LiftCoEnv -> [Type] -> [Coercion] -> Maybe LiftCoEnv ty_co_matches menv = matchList (ty_co_match menv) pushRefl :: Coercion -> Maybe Coercion pushRefl (Refl Nominal (AppTy ty1 ty2)) = Just (AppCo (Refl Nominal ty1) (Refl Nominal ty2)) pushRefl (Refl r (FunTy ty1 ty2)) = Just (TyConAppCo r funTyCon [Refl r ty1, Refl r ty2]) pushRefl (Refl r (TyConApp tc tys)) = Just (TyConAppCo r tc (zipWith mkReflCo (tyConRolesX r tc) tys)) pushRefl (Refl r (ForAllTy tv ty)) = Just (ForAllCo tv (Refl r ty)) pushRefl _ = Nothing {- ************************************************************************ * * Sequencing on coercions * * ************************************************************************ -} seqCo :: Coercion -> () seqCo (Refl eq ty) = eq `seq` seqType ty seqCo (TyConAppCo eq tc cos) = eq `seq` tc `seq` seqCos cos seqCo (AppCo co1 co2) = seqCo co1 `seq` seqCo co2 seqCo (ForAllCo tv co) = tv `seq` seqCo co seqCo (CoVarCo cv) = cv `seq` () seqCo (AxiomInstCo con ind cos) = con `seq` ind `seq` seqCos cos seqCo (UnivCo s r ty1 ty2) = s `seq` r `seq` seqType ty1 `seq` seqType ty2 seqCo (SymCo co) = seqCo co seqCo (TransCo co1 co2) = seqCo co1 `seq` seqCo co2 seqCo (NthCo _ co) = seqCo co seqCo (LRCo _ co) = seqCo co seqCo (InstCo co ty) = seqCo co `seq` seqType ty seqCo (SubCo co) = seqCo co seqCo (AxiomRuleCo _ ts cs) = seqTypes ts `seq` seqCos cs seqCos :: [Coercion] -> () seqCos [] = () seqCos (co:cos) = seqCo co `seq` seqCos cos {- ************************************************************************ * * The kind of a type, and of a coercion * * ************************************************************************ Note [Computing a coercion kind and role] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To compute a coercion's kind is straightforward: see coercionKind. But to compute a coercion's role, in the case for NthCo we need its kind as well. So if we have two separate functions (one for kinds and one for roles) we can get exponentially bad behaviour, since each NthCo node makes a separate call to coercionKind, which traverses the sub-tree again. This was part of the problem in Trac #9233. Solution: compute both together; hence coercionKindRole. We keep a separate coercionKind function because it's a bit more efficient if the kind is all you want. -} coercionType :: Coercion -> Type coercionType co = case coercionKindRole co of (Pair ty1 ty2, r) -> mkCoercionType r ty1 ty2 ------------------ -- | If it is the case that -- -- > c :: (t1 ~ t2) -- -- i.e. the kind of @c@ relates @t1@ and @t2@, then @coercionKind c = Pair t1 t2@. coercionKind :: Coercion -> Pair Type coercionKind co = go co where go (Refl _ ty) = Pair ty ty go (TyConAppCo _ tc cos) = mkTyConApp tc <$> (sequenceA $ map go cos) go (AppCo co1 co2) = mkAppTy <$> go co1 <*> go co2 go (ForAllCo tv co) = mkForAllTy tv <$> go co go (CoVarCo cv) = toPair $ coVarKind cv go (AxiomInstCo ax ind cos) | CoAxBranch { cab_tvs = tvs, cab_lhs = lhs, cab_rhs = rhs } <- coAxiomNthBranch ax ind , Pair tys1 tys2 <- sequenceA (map go cos) = ASSERT( cos `equalLength` tvs ) -- Invariant of AxiomInstCo: cos should -- exactly saturate the axiom branch Pair (substTyWith tvs tys1 (mkTyConApp (coAxiomTyCon ax) lhs)) (substTyWith tvs tys2 rhs) go (UnivCo _ _ ty1 ty2) = Pair ty1 ty2 go (SymCo co) = swap $ go co go (TransCo co1 co2) = Pair (pFst $ go co1) (pSnd $ go co2) go (NthCo d co) = tyConAppArgN d <$> go co go (LRCo lr co) = (pickLR lr . splitAppTy) <$> go co go (InstCo aco ty) = go_app aco [ty] go (SubCo co) = go co go (AxiomRuleCo ax tys cos) = case coaxrProves ax tys (map go cos) of Just res -> res Nothing -> panic "coercionKind: Malformed coercion" go_app :: Coercion -> [Type] -> Pair Type -- Collect up all the arguments and apply all at once -- See Note [Nested InstCos] go_app (InstCo co ty) tys = go_app co (ty:tys) go_app co tys = (`applyTys` tys) <$> go co -- | Apply 'coercionKind' to multiple 'Coercion's coercionKinds :: [Coercion] -> Pair [Type] coercionKinds tys = sequenceA $ map coercionKind tys -- | Get a coercion's kind and role. -- Why both at once? See Note [Computing a coercion kind and role] coercionKindRole :: Coercion -> (Pair Type, Role) coercionKindRole = go where go (Refl r ty) = (Pair ty ty, r) go (TyConAppCo r tc cos) = (mkTyConApp tc <$> (sequenceA $ map coercionKind cos), r) go (AppCo co1 co2) = let (tys1, r1) = go co1 in (mkAppTy <$> tys1 <*> coercionKind co2, r1) go (ForAllCo tv co) = let (tys, r) = go co in (mkForAllTy tv <$> tys, r) go (CoVarCo cv) = (toPair $ coVarKind cv, coVarRole cv) go co@(AxiomInstCo ax _ _) = (coercionKind co, coAxiomRole ax) go (UnivCo _ r ty1 ty2) = (Pair ty1 ty2, r) go (SymCo co) = first swap $ go co go (TransCo co1 co2) = let (tys1, r) = go co1 in (Pair (pFst tys1) (pSnd $ coercionKind co2), r) go (NthCo d co) = let (Pair t1 t2, r) = go co (tc1, args1) = splitTyConApp t1 (_tc2, args2) = splitTyConApp t2 in ASSERT( tc1 == _tc2 ) ((`getNth` d) <$> Pair args1 args2, nthRole r tc1 d) go co@(LRCo {}) = (coercionKind co, Nominal) go (InstCo co ty) = go_app co [ty] go (SubCo co) = (coercionKind co, Representational) go co@(AxiomRuleCo ax _ _) = (coercionKind co, coaxrRole ax) go_app :: Coercion -> [Type] -> (Pair Type, Role) -- Collect up all the arguments and apply all at once -- See Note [Nested InstCos] go_app (InstCo co ty) tys = go_app co (ty:tys) go_app co tys = let (pair, r) = go co in ((`applyTys` tys) <$> pair, r) -- | Retrieve the role from a coercion. coercionRole :: Coercion -> Role coercionRole = snd . coercionKindRole -- There's not a better way to do this, because NthCo needs the *kind* -- and role of its argument. Luckily, laziness should generally avoid -- the need for computing kinds in other cases. {- Note [Nested InstCos] ~~~~~~~~~~~~~~~~~~~~~ In Trac #5631 we found that 70% of the entire compilation time was being spent in coercionKind! The reason was that we had (g @ ty1 @ ty2 .. @ ty100) -- The "@s" are InstCos where g :: forall a1 a2 .. a100. phi If we deal with the InstCos one at a time, we'll do this: 1. Find the kind of (g @ ty1 .. @ ty99) : forall a100. phi' 2. Substitute phi'[ ty100/a100 ], a single tyvar->type subst But this is a *quadratic* algorithm, and the blew up Trac #5631. So it's very important to do the substitution simultaneously. cf Type.applyTys (which in fact we call here) -} applyCo :: Type -> Coercion -> Type -- Gives the type of (e co) where e :: (a~b) => ty applyCo ty co | Just ty' <- coreView ty = applyCo ty' co applyCo (FunTy _ ty) _ = ty applyCo _ _ = panic "applyCo" {- Note [Kind coercions] ~~~~~~~~~~~~~~~~~~~~~ Kind coercions are only of the form: Refl kind. They are only used to instantiate kind polymorphic type constructors in TyConAppCo. Remember that kind instantiation only happens with TyConApp, not AppTy. -}
christiaanb/ghc
compiler/types/Coercion.hs
bsd-3-clause
80,254
1,008
12
21,193
11,664
7,222
4,442
938
16
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section{SetLevels} *************************** Overview *************************** 1. We attach binding levels to Core bindings, in preparation for floating outwards (@FloatOut@). 2. We also let-ify many expressions (notably case scrutinees), so they will have a fighting chance of being floated sensible. 3. Note [Need for cloning during float-out] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We clone the binders of any floatable let-binding, so that when it is floated out it will be unique. Example (let x=2 in x) + (let x=3 in x) we must clone before floating so we get let x1=2 in let x2=3 in x1+x2 NOTE: this can't be done using the uniqAway idea, because the variable must be unique in the whole program, not just its current scope, because two variables in different scopes may float out to the same top level place NOTE: Very tiresomely, we must apply this substitution to the rules stored inside a variable too. We do *not* clone top-level bindings, because some of them must not change, but we *do* clone bindings that are heading for the top level 4. Note [Binder-swap during float-out] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the expression case x of wild { p -> ...wild... } we substitute x for wild in the RHS of the case alternatives: case x of wild { p -> ...x... } This means that a sub-expression involving x is not "trapped" inside the RHS. And it's not inconvenient because we already have a substitution. Note that this is EXACTLY BACKWARDS from the what the simplifier does. The simplifier tries to get rid of occurrences of x, in favour of wild, in the hope that there will only be one remaining occurrence of x, namely the scrutinee of the case, and we can inline it. -} {-# LANGUAGE CPP #-} module SetLevels ( setLevels, Level(..), tOP_LEVEL, LevelledBind, LevelledExpr, LevelledBndr, FloatSpec(..), floatSpecLevel, incMinorLvl, ltMajLvl, ltLvl, isTopLvl ) where #include "HsVersions.h" import CoreSyn import CoreMonad ( FloatOutSwitches(..) ) import CoreUtils ( exprType , exprOkForSpeculation , exprIsBottom , collectStaticPtrSatArgs ) import CoreArity ( exprBotStrictness_maybe ) import CoreFVs -- all of it import CoreSubst import MkCore ( sortQuantVars ) import Id import IdInfo import Var import VarSet import VarEnv import Literal ( litIsTrivial ) import Demand ( StrictSig ) import Name ( getOccName, mkSystemVarName ) import OccName ( occNameString ) import Type ( isUnliftedType, Type, mkLamTypes ) import BasicTypes ( Arity, RecFlag(..) ) import UniqSupply import Util import Outputable import FastString import UniqDFM import FV import Data.Maybe {- ************************************************************************ * * \subsection{Level numbers} * * ************************************************************************ -} type LevelledExpr = TaggedExpr FloatSpec type LevelledBind = TaggedBind FloatSpec type LevelledBndr = TaggedBndr FloatSpec data Level = Level Int -- Major level: number of enclosing value lambdas Int -- Minor level: number of big-lambda and/or case -- expressions between here and the nearest -- enclosing value lambda data FloatSpec = FloatMe Level -- Float to just inside the binding -- tagged with this level | StayPut Level -- Stay where it is; binding is -- tagged with tihs level floatSpecLevel :: FloatSpec -> Level floatSpecLevel (FloatMe l) = l floatSpecLevel (StayPut l) = l {- The {\em level number} on a (type-)lambda-bound variable is the nesting depth of the (type-)lambda which binds it. The outermost lambda has level 1, so (Level 0 0) means that the variable is bound outside any lambda. On an expression, it's the maximum level number of its free (type-)variables. On a let(rec)-bound variable, it's the level of its RHS. On a case-bound variable, it's the number of enclosing lambdas. Top-level variables: level~0. Those bound on the RHS of a top-level definition but ``before'' a lambda; e.g., the \tr{x} in (levels shown as ``subscripts'')... \begin{verbatim} a_0 = let b_? = ... in x_1 = ... b ... in ... \end{verbatim} The main function @lvlExpr@ carries a ``context level'' (@ctxt_lvl@). That's meant to be the level number of the enclosing binder in the final (floated) program. If the level number of a sub-expression is less than that of the context, then it might be worth let-binding the sub-expression so that it will indeed float. If you can float to level @Level 0 0@ worth doing so because then your allocation becomes static instead of dynamic. We always start with context @Level 0 0@. Note [FloatOut inside INLINE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @InlineCtxt@ very similar to @Level 0 0@, but is used for one purpose: to say "don't float anything out of here". That's exactly what we want for the body of an INLINE, where we don't want to float anything out at all. See notes with lvlMFE below. But, check this out: -- At one time I tried the effect of not float anything out of an InlineMe, -- but it sometimes works badly. For example, consider PrelArr.done. It -- has the form __inline (\d. e) -- where e doesn't mention d. If we float this to -- __inline (let x = e in \d. x) -- things are bad. The inliner doesn't even inline it because it doesn't look -- like a head-normal form. So it seems a lesser evil to let things float. -- In SetLevels we do set the context to (Level 0 0) when we get to an InlineMe -- which discourages floating out. So the conclusion is: don't do any floating at all inside an InlineMe. (In the above example, don't float the {x=e} out of the \d.) One particular case is that of workers: we don't want to float the call to the worker outside the wrapper, otherwise the worker might get inlined into the floated expression, and an importing module won't see the worker at all. -} instance Outputable FloatSpec where ppr (FloatMe l) = char 'F' <> ppr l ppr (StayPut l) = ppr l tOP_LEVEL :: Level tOP_LEVEL = Level 0 0 incMajorLvl :: Level -> Level incMajorLvl (Level major _) = Level (major + 1) 0 incMinorLvl :: Level -> Level incMinorLvl (Level major minor) = Level major (minor+1) maxLvl :: Level -> Level -> Level maxLvl l1@(Level maj1 min1) l2@(Level maj2 min2) | (maj1 > maj2) || (maj1 == maj2 && min1 > min2) = l1 | otherwise = l2 ltLvl :: Level -> Level -> Bool ltLvl (Level maj1 min1) (Level maj2 min2) = (maj1 < maj2) || (maj1 == maj2 && min1 < min2) ltMajLvl :: Level -> Level -> Bool -- Tells if one level belongs to a difft *lambda* level to another ltMajLvl (Level maj1 _) (Level maj2 _) = maj1 < maj2 isTopLvl :: Level -> Bool isTopLvl (Level 0 0) = True isTopLvl _ = False instance Outputable Level where ppr (Level maj min) = hcat [ char '<', int maj, char ',', int min, char '>' ] instance Eq Level where (Level maj1 min1) == (Level maj2 min2) = maj1 == maj2 && min1 == min2 {- ************************************************************************ * * \subsection{Main level-setting code} * * ************************************************************************ -} setLevels :: FloatOutSwitches -> CoreProgram -> UniqSupply -> [LevelledBind] setLevels float_lams binds us = initLvl us (do_them init_env binds) where init_env = initialEnv float_lams do_them :: LevelEnv -> [CoreBind] -> LvlM [LevelledBind] do_them _ [] = return [] do_them env (b:bs) = do { (lvld_bind, env') <- lvlTopBind env b ; lvld_binds <- do_them env' bs ; return (lvld_bind : lvld_binds) } lvlTopBind :: LevelEnv -> Bind Id -> LvlM (LevelledBind, LevelEnv) lvlTopBind env (NonRec bndr rhs) = do { rhs' <- lvlExpr env (freeVars rhs) ; let (env', [bndr']) = substAndLvlBndrs NonRecursive env tOP_LEVEL [bndr] ; return (NonRec bndr' rhs', env') } lvlTopBind env (Rec pairs) = do let (bndrs,rhss) = unzip pairs (env', bndrs') = substAndLvlBndrs Recursive env tOP_LEVEL bndrs rhss' <- mapM (lvlExpr env' . freeVars) rhss return (Rec (bndrs' `zip` rhss'), env') {- ************************************************************************ * * \subsection{Setting expression levels} * * ************************************************************************ Note [Floating over-saturated applications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we see (f x y), and (f x) is a redex (ie f's arity is 1), we call (f x) an "over-saturated application" Should we float out an over-sat app, if can escape a value lambda? It is sometimes very beneficial (-7% runtime -4% alloc over nofib -O2). But we don't want to do it for class selectors, because the work saved is minimal, and the extra local thunks allocated cost money. Arguably we could float even class-op applications if they were going to top level -- but then they must be applied to a constant dictionary and will almost certainly be optimised away anyway. -} lvlExpr :: LevelEnv -- Context -> CoreExprWithFVs -- Input expression -> LvlM LevelledExpr -- Result expression {- The @ctxt_lvl@ is, roughly, the level of the innermost enclosing binder. Here's an example v = \x -> ...\y -> let r = case (..x..) of ..x.. in .. When looking at the rhs of @r@, @ctxt_lvl@ will be 1 because that's the level of @r@, even though it's inside a level-2 @\y@. It's important that @ctxt_lvl@ is 1 and not 2 in @r@'s rhs, because we don't want @lvlExpr@ to turn the scrutinee of the @case@ into an MFE --- because it isn't a *maximal* free expression. If there were another lambda in @r@'s rhs, it would get level-2 as well. -} lvlExpr env (_, AnnType ty) = return (Type (substTy (le_subst env) ty)) lvlExpr env (_, AnnCoercion co) = return (Coercion (substCo (le_subst env) co)) lvlExpr env (_, AnnVar v) = return (lookupVar env v) lvlExpr _ (_, AnnLit lit) = return (Lit lit) lvlExpr env (_, AnnCast expr (_, co)) = do expr' <- lvlExpr env expr return (Cast expr' (substCo (le_subst env) co)) lvlExpr env (_, AnnTick tickish expr) = do expr' <- lvlExpr env expr return (Tick tickish expr') lvlExpr env expr@(_, AnnApp _ _) = do let (fun, args) = collectAnnArgs expr -- case fun of (_, AnnVar f) | floatOverSat env -- See Note [Floating over-saturated applications] , arity > 0 , arity < n_val_args , Nothing <- isClassOpId_maybe f -> do let (lapp, rargs) = left (n_val_args - arity) expr [] rargs' <- mapM (lvlMFE False env) rargs lapp' <- lvlMFE False env lapp return (foldl App lapp' rargs') where n_val_args = count (isValArg . deAnnotate) args arity = idArity f -- separate out the PAP that we are floating from the extra -- arguments, by traversing the spine until we have collected -- (n_val_args - arity) value arguments. left 0 e rargs = (e, rargs) left n (_, AnnApp f a) rargs | isValArg (deAnnotate a) = left (n-1) f (a:rargs) | otherwise = left n f (a:rargs) left _ _ _ = panic "SetLevels.lvlExpr.left" -- No PAPs that we can float: just carry on with the -- arguments and the function. _otherwise -> do args' <- mapM (lvlMFE False env) args fun' <- lvlExpr env fun return (foldl App fun' args') -- We don't split adjacent lambdas. That is, given -- \x y -> (x+1,y) -- we don't float to give -- \x -> let v = x+1 in \y -> (v,y) -- Why not? Because partial applications are fairly rare, and splitting -- lambdas makes them more expensive. lvlExpr env expr@(_, AnnLam {}) = do { new_body <- lvlMFE True new_env body ; return (mkLams new_bndrs new_body) } where (bndrs, body) = collectAnnBndrs expr (env1, bndrs1) = substBndrsSL NonRecursive env bndrs (new_env, new_bndrs) = lvlLamBndrs env1 (le_ctxt_lvl env) bndrs1 -- At one time we called a special verion of collectBinders, -- which ignored coercions, because we don't want to split -- a lambda like this (\x -> coerce t (\s -> ...)) -- This used to happen quite a bit in state-transformer programs, -- but not nearly so much now non-recursive newtypes are transparent. -- [See SetLevels rev 1.50 for a version with this approach.] lvlExpr env (_, AnnLet bind body) = do { (bind', new_env) <- lvlBind env bind ; body' <- lvlExpr new_env body -- No point in going via lvlMFE here. If the binding is alive -- (mentioned in body), and the whole let-expression doesn't -- float, then neither will the body ; return (Let bind' body') } lvlExpr env (_, AnnCase scrut case_bndr ty alts) = do { scrut' <- lvlMFE True env scrut ; lvlCase env (freeVarsOf scrut) scrut' case_bndr ty alts } ------------------------------------------- lvlCase :: LevelEnv -- Level of in-scope names/tyvars -> DVarSet -- Free vars of input scrutinee -> LevelledExpr -- Processed scrutinee -> Id -> Type -- Case binder and result type -> [CoreAltWithFVs] -- Input alternatives -> LvlM LevelledExpr -- Result expression lvlCase env scrut_fvs scrut' case_bndr ty alts | [(con@(DataAlt {}), bs, body)] <- alts , exprOkForSpeculation scrut' -- See Note [Check the output scrutinee for okForSpec] , not (isTopLvl dest_lvl) -- Can't have top-level cases , not (floatTopLvlOnly env) -- Can float anywhere = -- See Note [Floating cases] -- Always float the case if possible -- Unlike lets we don't insist that it escapes a value lambda do { (env1, (case_bndr' : bs')) <- cloneCaseBndrs env dest_lvl (case_bndr : bs) ; let rhs_env = extendCaseBndrEnv env1 case_bndr scrut' ; body' <- lvlMFE True rhs_env body ; let alt' = (con, [TB b (StayPut dest_lvl) | b <- bs'], body') ; return (Case scrut' (TB case_bndr' (FloatMe dest_lvl)) ty [alt']) } | otherwise -- Stays put = do { let (alts_env1, [case_bndr']) = substAndLvlBndrs NonRecursive env incd_lvl [case_bndr] alts_env = extendCaseBndrEnv alts_env1 case_bndr scrut' ; alts' <- mapM (lvl_alt alts_env) alts ; return (Case scrut' case_bndr' ty alts') } where incd_lvl = incMinorLvl (le_ctxt_lvl env) dest_lvl = maxFvLevel (const True) env scrut_fvs -- Don't abstact over type variables, hence const True lvl_alt alts_env (con, bs, rhs) = do { rhs' <- lvlMFE True new_env rhs ; return (con, bs', rhs') } where (new_env, bs') = substAndLvlBndrs NonRecursive alts_env incd_lvl bs {- Note [Floating cases] ~~~~~~~~~~~~~~~~~~~~~ Consider this: data T a = MkT !a f :: T Int -> blah f x vs = case x of { MkT y -> let f vs = ...(case y of I# w -> e)...f.. in f vs Here we can float the (case y ...) out , because y is sure to be evaluated, to give f x vs = case x of { MkT y -> caes y of I# w -> let f vs = ...(e)...f.. in f vs That saves unboxing it every time round the loop. It's important in some DPH stuff where we really want to avoid that repeated unboxing in the inner loop. Things to note * We can't float a case to top level * It's worth doing this float even if we don't float the case outside a value lambda. Example case x of { MkT y -> (case y of I# w2 -> ..., case y of I# w2 -> ...) If we floated the cases out we could eliminate one of them. * We only do this with a single-alternative case Note [Check the output scrutinee for okForSpec] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: case x of y { A -> ....(case y of alts).... } Because of the binder-swap, the inner case will get substituted to (case x of ..). So when testing whether the scrutinee is okForSpecuation we must be careful to test the *result* scrutinee ('x' in this case), not the *input* one 'y'. The latter *is* ok for speculation here, but the former is not -- and indeed we can't float the inner case out, at least not unless x is also evaluated at its binding site. That's why we apply exprOkForSpeculation to scrut' and not to scrut. -} lvlMFE :: Bool -- True <=> strict context [body of case or let] -> LevelEnv -- Level of in-scope names/tyvars -> CoreExprWithFVs -- input expression -> LvlM LevelledExpr -- Result expression -- lvlMFE is just like lvlExpr, except that it might let-bind -- the expression, so that it can itself be floated. lvlMFE _ env (_, AnnType ty) = return (Type (substTy (le_subst env) ty)) -- No point in floating out an expression wrapped in a coercion or note -- If we do we'll transform lvl = e |> co -- to lvl' = e; lvl = lvl' |> co -- and then inline lvl. Better just to float out the payload. lvlMFE strict_ctxt env (_, AnnTick t e) = do { e' <- lvlMFE strict_ctxt env e ; return (Tick t e') } lvlMFE strict_ctxt env (_, AnnCast e (_, co)) = do { e' <- lvlMFE strict_ctxt env e ; return (Cast e' (substCo (le_subst env) co)) } -- Note [Case MFEs] lvlMFE True env e@(_, AnnCase {}) = lvlExpr env e -- Don't share cases lvlMFE strict_ctxt env ann_expr | floatTopLvlOnly env && not (isTopLvl dest_lvl) -- Only floating to the top level is allowed. || isUnliftedType (exprType expr) -- Can't let-bind it; see Note [Unlifted MFEs] -- This includes coercions, which we don't want to float anyway -- NB: no need to substitute cos isUnliftedType doesn't change || notWorthFloating ann_expr abs_vars || not float_me = -- Don't float it out lvlExpr env ann_expr | otherwise -- Float it out! = do { expr' <- lvlFloatRhs abs_vars dest_lvl env ann_expr ; var <- newLvlVar expr' is_bot ; return (Let (NonRec (TB var (FloatMe dest_lvl)) expr') (mkVarApps (Var var) abs_vars)) } where expr = deAnnotate ann_expr fvs = freeVarsOf ann_expr is_bot = exprIsBottom expr -- Note [Bottoming floats] dest_lvl = destLevel env fvs (isFunction ann_expr) is_bot abs_vars = abstractVars dest_lvl env fvs -- A decision to float entails let-binding this thing, and we only do -- that if we'll escape a value lambda, or will go to the top level. float_me = dest_lvl `ltMajLvl` (le_ctxt_lvl env) -- Escapes a value lambda -- OLD CODE: not (exprIsCheap expr) || isTopLvl dest_lvl -- see Note [Escaping a value lambda] || (isTopLvl dest_lvl -- Only float if we are going to the top level && floatConsts env -- and the floatConsts flag is on && not strict_ctxt) -- Don't float from a strict context -- We are keen to float something to the top level, even if it does not -- escape a lambda, because then it needs no allocation. But it's controlled -- by a flag, because doing this too early loses opportunities for RULES -- which (needless to say) are important in some nofib programs -- (gcd is an example). -- -- Beware: -- concat = /\ a -> foldr ..a.. (++) [] -- was getting turned into -- lvl = /\ a -> foldr ..a.. (++) [] -- concat = /\ a -> lvl a -- which is pretty stupid. Hence the strict_ctxt test -- -- Also a strict contxt includes uboxed values, and they -- can't be bound at top level {- Note [Unlifted MFEs] ~~~~~~~~~~~~~~~~~~~~ We don't float unlifted MFEs, which potentially loses big opportunites. For example: \x -> f (h y) where h :: Int -> Int# is expensive. We'd like to float the (h y) outside the \x, but we don't because it's unboxed. Possible solution: box it. Note [Bottoming floats] ~~~~~~~~~~~~~~~~~~~~~~~ If we see f = \x. g (error "urk") we'd like to float the call to error, to get lvl = error "urk" f = \x. g lvl Furthermore, we want to float a bottoming expression even if it has free variables: f = \x. g (let v = h x in error ("urk" ++ v)) Then we'd like to abstact over 'x' can float the whole arg of g: lvl = \x. let v = h x in error ("urk" ++ v) f = \x. g (lvl x) See Maessen's paper 1999 "Bottom extraction: factoring error handling out of functional programs" (unpublished I think). When we do this, we set the strictness and arity of the new bottoming Id, *immediately*, for three reasons: * To prevent the abstracted thing being immediately inlined back in again via preInlineUnconditionally. The latter has a test for bottoming Ids to stop inlining them, so we'd better make sure it *is* a bottoming Id! * So that it's properly exposed as such in the interface file, even if this is all happening after strictness analysis. * In case we do CSE with the same expression that *is* marked bottom lvl = error "urk" x{str=bot) = error "urk" Here we don't want to replace 'x' with 'lvl', else we may get Lint errors, e.g. via a case with empty alternatives: (case x of {}) Lint complains unless the scrutinee of such a case is clearly bottom. This was reported in Trac #11290. But since the whole bottoming-float thing is based on the cheap-and-cheerful exprIsBottom, I'm not sure that it'll nail all such cases. Note [Bottoming floats: eta expansion] c.f Note [Bottoming floats] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tiresomely, though, the simplifier has an invariant that the manifest arity of the RHS should be the same as the arity; but we can't call etaExpand during SetLevels because it works over a decorated form of CoreExpr. So we do the eta expansion later, in FloatOut. Note [Case MFEs] ~~~~~~~~~~~~~~~~ We don't float a case expression as an MFE from a strict context. Why not? Because in doing so we share a tiny bit of computation (the switch) but in exchange we build a thunk, which is bad. This case reduces allocation by 7% in spectral/puzzle (a rather strange benchmark) and 1.2% in real/fem. Doesn't change any other allocation at all. -} annotateBotStr :: Id -> Maybe (Arity, StrictSig) -> Id -- See Note [Bottoming floats] for why we want to add -- bottoming information right now annotateBotStr id Nothing = id annotateBotStr id (Just (arity, sig)) = id `setIdArity` arity `setIdStrictness` sig notWorthFloating :: CoreExprWithFVs -> [Var] -> Bool -- Returns True if the expression would be replaced by -- something bigger than it is now. For example: -- abs_vars = tvars only: return True if e is trivial, -- but False for anything bigger -- abs_vars = [x] (an Id): return True for trivial, or an application (f x) -- but False for (f x x) -- -- One big goal is that floating should be idempotent. Eg if -- we replace e with (lvl79 x y) and then run FloatOut again, don't want -- to replace (lvl79 x y) with (lvl83 x y)! notWorthFloating e abs_vars = go e (count isId abs_vars) where go (_, AnnVar {}) n = n >= 0 go (_, AnnLit lit) n = ASSERT( n==0 ) litIsTrivial lit -- Note [Floating literals] go (_, AnnTick t e) n = not (tickishIsCode t) && go e n go (_, AnnCast e _) n = go e n go (_, AnnApp e arg) n | (_, AnnType {}) <- arg = go e n | (_, AnnCoercion {}) <- arg = go e n | n==0 = False | is_triv arg = go e (n-1) | otherwise = False go _ _ = False is_triv (_, AnnLit {}) = True -- Treat all literals as trivial is_triv (_, AnnVar {}) = True -- (ie not worth floating) is_triv (_, AnnCast e _) = is_triv e is_triv (_, AnnApp e (_, AnnType {})) = is_triv e is_triv (_, AnnApp e (_, AnnCoercion {})) = is_triv e is_triv (_, AnnTick t e) = not (tickishIsCode t) && is_triv e is_triv _ = False {- Note [Floating literals] ~~~~~~~~~~~~~~~~~~~~~~~~ It's important to float Integer literals, so that they get shared, rather than being allocated every time round the loop. Hence the litIsTrivial. We'd *like* to share MachStr literal strings too, mainly so we could CSE them, but alas can't do so directly because they are unlifted. Note [Escaping a value lambda] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We want to float even cheap expressions out of value lambdas, because that saves allocation. Consider f = \x. .. (\y.e) ... Then we'd like to avoid allocating the (\y.e) every time we call f, (assuming e does not mention x). An example where this really makes a difference is simplrun009. Another reason it's good is because it makes SpecContr fire on functions. Consider f = \x. ....(f (\y.e)).... After floating we get lvl = \y.e f = \x. ....(f lvl)... and that is much easier for SpecConstr to generate a robust specialisation for. The OLD CODE (given where this Note is referred to) prevents floating of the example above, so I just don't understand the old code. I don't understand the old comment either (which appears below). I measured the effect on nofib of changing OLD CODE to 'True', and got zeros everywhere, but a 4% win for 'puzzle'. Very small 0.5% loss for 'cse'; turns out to be because our arity analysis isn't good enough yet (mentioned in Simon-nofib-notes). OLD comment was: Even if it escapes a value lambda, we only float if it's not cheap (unless it'll get all the way to the top). I've seen cases where we float dozens of tiny free expressions, which cost more to allocate than to evaluate. NB: exprIsCheap is also true of bottom expressions, which is good; we don't want to share them It's only Really Bad to float a cheap expression out of a strict context, because that builds a thunk that otherwise would never be built. So another alternative would be to add || (strict_ctxt && not (exprIsBottom expr)) to the condition above. We should really try this out. ************************************************************************ * * \subsection{Bindings} * * ************************************************************************ The binding stuff works for top level too. -} lvlBind :: LevelEnv -> CoreBindWithFVs -> LvlM (LevelledBind, LevelEnv) lvlBind env (AnnNonRec bndr rhs) | isTyVar bndr -- Don't do anything for TyVar binders -- (simplifier gets rid of them pronto) || isCoVar bndr -- Difficult to fix up CoVar occurrences (see extendPolyLvlEnv) -- so we will ignore this case for now || not (profitableFloat env dest_lvl) || (isTopLvl dest_lvl && isUnliftedType (idType bndr)) -- We can't float an unlifted binding to top level, so we don't -- float it at all. It's a bit brutal, but unlifted bindings -- aren't expensive either = -- No float do { rhs' <- lvlExpr env rhs ; let bind_lvl = incMinorLvl (le_ctxt_lvl env) (env', [bndr']) = substAndLvlBndrs NonRecursive env bind_lvl [bndr] ; return (NonRec bndr' rhs', env') } -- Otherwise we are going to float | null abs_vars = do { -- No type abstraction; clone existing binder rhs' <- lvlExpr (setCtxtLvl env dest_lvl) rhs ; (env', [bndr']) <- cloneLetVars NonRecursive env dest_lvl [bndr] ; return (NonRec (TB bndr' (FloatMe dest_lvl)) rhs', env') } | otherwise = do { -- Yes, type abstraction; create a new binder, extend substitution, etc rhs' <- lvlFloatRhs abs_vars dest_lvl env rhs ; (env', [bndr']) <- newPolyBndrs dest_lvl env abs_vars [bndr] ; return (NonRec (TB bndr' (FloatMe dest_lvl)) rhs', env') } where rhs_fvs = freeVarsOf rhs bind_fvs = rhs_fvs `unionDVarSet` dIdFreeVars bndr abs_vars = abstractVars dest_lvl env bind_fvs dest_lvl = destLevel env bind_fvs (isFunction rhs) is_bot is_bot = exprIsBottom (deAnnotate rhs) lvlBind env (AnnRec pairs) | floatTopLvlOnly env && not (isTopLvl dest_lvl) -- Only floating to the top level is allowed. || not (profitableFloat env dest_lvl) = do { let bind_lvl = incMinorLvl (le_ctxt_lvl env) (env', bndrs') = substAndLvlBndrs Recursive env bind_lvl bndrs ; rhss' <- mapM (lvlExpr env') rhss ; return (Rec (bndrs' `zip` rhss'), env') } | null abs_vars = do { (new_env, new_bndrs) <- cloneLetVars Recursive env dest_lvl bndrs ; new_rhss <- mapM (lvlExpr (setCtxtLvl new_env dest_lvl)) rhss ; return ( Rec ([TB b (FloatMe dest_lvl) | b <- new_bndrs] `zip` new_rhss) , new_env) } -- ToDo: when enabling the floatLambda stuff, -- I think we want to stop doing this | [(bndr,rhs)] <- pairs , count isId abs_vars > 1 = do -- Special case for self recursion where there are -- several variables carried around: build a local loop: -- poly_f = \abs_vars. \lam_vars . letrec f = \lam_vars. rhs in f lam_vars -- This just makes the closures a bit smaller. If we don't do -- this, allocation rises significantly on some programs -- -- We could elaborate it for the case where there are several -- mutually functions, but it's quite a bit more complicated -- -- This all seems a bit ad hoc -- sigh let (rhs_env, abs_vars_w_lvls) = lvlLamBndrs env dest_lvl abs_vars rhs_lvl = le_ctxt_lvl rhs_env (rhs_env', [new_bndr]) <- cloneLetVars Recursive rhs_env rhs_lvl [bndr] let (lam_bndrs, rhs_body) = collectAnnBndrs rhs (body_env1, lam_bndrs1) = substBndrsSL NonRecursive rhs_env' lam_bndrs (body_env2, lam_bndrs2) = lvlLamBndrs body_env1 rhs_lvl lam_bndrs1 new_rhs_body <- lvlExpr body_env2 rhs_body (poly_env, [poly_bndr]) <- newPolyBndrs dest_lvl env abs_vars [bndr] return (Rec [(TB poly_bndr (FloatMe dest_lvl) , mkLams abs_vars_w_lvls $ mkLams lam_bndrs2 $ Let (Rec [( TB new_bndr (StayPut rhs_lvl) , mkLams lam_bndrs2 new_rhs_body)]) (mkVarApps (Var new_bndr) lam_bndrs1))] , poly_env) | otherwise -- Non-null abs_vars = do { (new_env, new_bndrs) <- newPolyBndrs dest_lvl env abs_vars bndrs ; new_rhss <- mapM (lvlFloatRhs abs_vars dest_lvl new_env) rhss ; return ( Rec ([TB b (FloatMe dest_lvl) | b <- new_bndrs] `zip` new_rhss) , new_env) } where (bndrs,rhss) = unzip pairs -- Finding the free vars of the binding group is annoying bind_fvs = ((unionDVarSets [ freeVarsOf rhs | (_, rhs) <- pairs]) `unionDVarSet` (fvDVarSet $ unionsFV [ idFVs bndr | (bndr, (_,_)) <- pairs])) `delDVarSetList` bndrs dest_lvl = destLevel env bind_fvs (all isFunction rhss) False abs_vars = abstractVars dest_lvl env bind_fvs profitableFloat :: LevelEnv -> Level -> Bool profitableFloat env dest_lvl = (dest_lvl `ltMajLvl` le_ctxt_lvl env) -- Escapes a value lambda || isTopLvl dest_lvl -- Going all the way to top level ---------------------------------------------------- -- Three help functions for the type-abstraction case lvlFloatRhs :: [OutVar] -> Level -> LevelEnv -> CoreExprWithFVs -> UniqSM (Expr LevelledBndr) lvlFloatRhs abs_vars dest_lvl env rhs = do { rhs' <- lvlExpr rhs_env rhs ; return (mkLams abs_vars_w_lvls rhs') } where (rhs_env, abs_vars_w_lvls) = lvlLamBndrs env dest_lvl abs_vars {- ************************************************************************ * * \subsection{Deciding floatability} * * ************************************************************************ -} substAndLvlBndrs :: RecFlag -> LevelEnv -> Level -> [InVar] -> (LevelEnv, [LevelledBndr]) substAndLvlBndrs is_rec env lvl bndrs = lvlBndrs subst_env lvl subst_bndrs where (subst_env, subst_bndrs) = substBndrsSL is_rec env bndrs substBndrsSL :: RecFlag -> LevelEnv -> [InVar] -> (LevelEnv, [OutVar]) -- So named only to avoid the name clash with CoreSubst.substBndrs substBndrsSL is_rec env@(LE { le_subst = subst, le_env = id_env }) bndrs = ( env { le_subst = subst' , le_env = foldl add_id id_env (bndrs `zip` bndrs') } , bndrs') where (subst', bndrs') = case is_rec of NonRecursive -> substBndrs subst bndrs Recursive -> substRecBndrs subst bndrs lvlLamBndrs :: LevelEnv -> Level -> [OutVar] -> (LevelEnv, [LevelledBndr]) -- Compute the levels for the binders of a lambda group lvlLamBndrs env lvl bndrs = lvlBndrs env new_lvl bndrs where new_lvl | any is_major bndrs = incMajorLvl lvl | otherwise = incMinorLvl lvl is_major bndr = isId bndr && not (isProbablyOneShotLambda bndr) -- The "probably" part says "don't float things out of a -- probable one-shot lambda" -- See Note [Computing one-shot info] in Demand.hs lvlBndrs :: LevelEnv -> Level -> [CoreBndr] -> (LevelEnv, [LevelledBndr]) -- The binders returned are exactly the same as the ones passed, -- apart from applying the substitution, but they are now paired -- with a (StayPut level) -- -- The returned envt has ctxt_lvl updated to the new_lvl -- -- All the new binders get the same level, because -- any floating binding is either going to float past -- all or none. We never separate binders. lvlBndrs env@(LE { le_lvl_env = lvl_env }) new_lvl bndrs = ( env { le_ctxt_lvl = new_lvl , le_lvl_env = addLvls new_lvl lvl_env bndrs } , lvld_bndrs) where lvld_bndrs = [TB bndr (StayPut new_lvl) | bndr <- bndrs] -- Destination level is the max Id level of the expression -- (We'll abstract the type variables, if any.) destLevel :: LevelEnv -> DVarSet -> Bool -- True <=> is function -> Bool -- True <=> is bottom -> Level destLevel env fvs is_function is_bot | is_bot = tOP_LEVEL -- Send bottoming bindings to the top -- regardless; see Note [Bottoming floats] | Just n_args <- floatLams env , n_args > 0 -- n=0 case handled uniformly by the 'otherwise' case , is_function , countFreeIds fvs <= n_args = tOP_LEVEL -- Send functions to top level; see -- the comments with isFunction | otherwise = maxFvLevel isId env fvs -- Max over Ids only; the tyvars -- will be abstracted isFunction :: CoreExprWithFVs -> Bool -- The idea here is that we want to float *functions* to -- the top level. This saves no work, but -- (a) it can make the host function body a lot smaller, -- and hence inlinable. -- (b) it can also save allocation when the function is recursive: -- h = \x -> letrec f = \y -> ...f...y...x... -- in f x -- becomes -- f = \x y -> ...(f x)...y...x... -- h = \x -> f x x -- No allocation for f now. -- We may only want to do this if there are sufficiently few free -- variables. We certainly only want to do it for values, and not for -- constructors. So the simple thing is just to look for lambdas isFunction (_, AnnLam b e) | isId b = True | otherwise = isFunction e -- isFunction (_, AnnTick _ e) = isFunction e -- dubious isFunction _ = False countFreeIds :: DVarSet -> Int countFreeIds = nonDetFoldUDFM add 0 -- It's OK to use nonDetFoldUDFM here because we're just counting things. where add :: Var -> Int -> Int add v n | isId v = n+1 | otherwise = n {- ************************************************************************ * * \subsection{Free-To-Level Monad} * * ************************************************************************ -} type InVar = Var -- Pre cloning type InId = Id -- Pre cloning type OutVar = Var -- Post cloning type OutId = Id -- Post cloning data LevelEnv = LE { le_switches :: FloatOutSwitches , le_ctxt_lvl :: Level -- The current level , le_lvl_env :: VarEnv Level -- Domain is *post-cloned* TyVars and Ids , le_subst :: Subst -- Domain is pre-cloned TyVars and Ids -- The Id -> CoreExpr in the Subst is ignored -- (since we want to substitute a LevelledExpr for -- an Id via le_env) but we do use the Co/TyVar substs , le_env :: IdEnv ([OutVar], LevelledExpr) -- Domain is pre-cloned Ids } -- We clone let- and case-bound variables so that they are still -- distinct when floated out; hence the le_subst/le_env. -- (see point 3 of the module overview comment). -- We also use these envs when making a variable polymorphic -- because we want to float it out past a big lambda. -- -- The le_subst and le_env always implement the same mapping, but the -- le_subst maps to CoreExpr and the le_env to LevelledExpr -- Since the range is always a variable or type application, -- there is never any difference between the two, but sadly -- the types differ. The le_subst is used when substituting in -- a variable's IdInfo; the le_env when we find a Var. -- -- In addition the le_env records a list of tyvars free in the -- type application, just so we don't have to call freeVars on -- the type application repeatedly. -- -- The domain of the both envs is *pre-cloned* Ids, though -- -- The domain of the le_lvl_env is the *post-cloned* Ids initialEnv :: FloatOutSwitches -> LevelEnv initialEnv float_lams = LE { le_switches = float_lams , le_ctxt_lvl = tOP_LEVEL , le_lvl_env = emptyVarEnv , le_subst = emptySubst , le_env = emptyVarEnv } addLvl :: Level -> VarEnv Level -> OutVar -> VarEnv Level addLvl dest_lvl env v' = extendVarEnv env v' dest_lvl addLvls :: Level -> VarEnv Level -> [OutVar] -> VarEnv Level addLvls dest_lvl env vs = foldl (addLvl dest_lvl) env vs floatLams :: LevelEnv -> Maybe Int floatLams le = floatOutLambdas (le_switches le) floatConsts :: LevelEnv -> Bool floatConsts le = floatOutConstants (le_switches le) floatOverSat :: LevelEnv -> Bool floatOverSat le = floatOutOverSatApps (le_switches le) floatTopLvlOnly :: LevelEnv -> Bool floatTopLvlOnly le = floatToTopLevelOnly (le_switches le) setCtxtLvl :: LevelEnv -> Level -> LevelEnv setCtxtLvl env lvl = env { le_ctxt_lvl = lvl } -- extendCaseBndrEnv adds the mapping case-bndr->scrut-var if it can -- See Note [Binder-swap during float-out] extendCaseBndrEnv :: LevelEnv -> Id -- Pre-cloned case binder -> Expr LevelledBndr -- Post-cloned scrutinee -> LevelEnv extendCaseBndrEnv le@(LE { le_subst = subst, le_env = id_env }) case_bndr (Var scrut_var) = le { le_subst = extendSubstWithVar subst case_bndr scrut_var , le_env = add_id id_env (case_bndr, scrut_var) } extendCaseBndrEnv env _ _ = env maxFvLevel :: (Var -> Bool) -> LevelEnv -> DVarSet -> Level maxFvLevel max_me (LE { le_lvl_env = lvl_env, le_env = id_env }) var_set = foldDVarSet max_in tOP_LEVEL var_set where max_in in_var lvl = foldr max_out lvl (case lookupVarEnv id_env in_var of Just (abs_vars, _) -> abs_vars Nothing -> [in_var]) max_out out_var lvl | max_me out_var = case lookupVarEnv lvl_env out_var of Just lvl' -> maxLvl lvl' lvl Nothing -> lvl | otherwise = lvl -- Ignore some vars depending on max_me lookupVar :: LevelEnv -> Id -> LevelledExpr lookupVar le v = case lookupVarEnv (le_env le) v of Just (_, expr) -> expr _ -> Var v abstractVars :: Level -> LevelEnv -> DVarSet -> [OutVar] -- Find the variables in fvs, free vars of the target expresion, -- whose level is greater than the destination level -- These are the ones we are going to abstract out -- -- Note that to get reproducible builds, the variables need to be -- abstracted in deterministic order, not dependent on the values of -- Uniques. This is achieved by using DVarSets, deterministic free -- variable computation and deterministic sort. -- See Note [Unique Determinism] in Unique for explanation of why -- Uniques are not deterministic. abstractVars dest_lvl (LE { le_subst = subst, le_lvl_env = lvl_env }) in_fvs = -- NB: sortQuantVars might not put duplicates next to each other map zap $ sortQuantVars $ uniq [out_var | out_fv <- dVarSetElems (substDVarSet subst in_fvs) , out_var <- dVarSetElems (close out_fv) , abstract_me out_var ] -- NB: it's important to call abstract_me only on the OutIds the -- come from substDVarSet (not on fv, which is an InId) where uniq :: [Var] -> [Var] -- Remove duplicates, preserving order uniq = dVarSetElems . mkDVarSet abstract_me v = case lookupVarEnv lvl_env v of Just lvl -> dest_lvl `ltLvl` lvl Nothing -> False -- We are going to lambda-abstract, so nuke any IdInfo, -- and add the tyvars of the Id (if necessary) zap v | isId v = WARN( isStableUnfolding (idUnfolding v) || not (isEmptyRuleInfo (idSpecialisation v)), text "absVarsOf: discarding info on" <+> ppr v ) setIdInfo v vanillaIdInfo | otherwise = v close :: Var -> DVarSet -- Close over variables free in the type -- Result includes the input variable itself close v = foldDVarSet (unionDVarSet . close) (unitDVarSet v) (fvDVarSet $ varTypeTyCoFVs v) type LvlM result = UniqSM result initLvl :: UniqSupply -> UniqSM a -> a initLvl = initUs_ newPolyBndrs :: Level -> LevelEnv -> [OutVar] -> [InId] -> UniqSM (LevelEnv, [OutId]) -- The envt is extended to bind the new bndrs to dest_lvl, but -- the ctxt_lvl is unaffected newPolyBndrs dest_lvl env@(LE { le_lvl_env = lvl_env, le_subst = subst, le_env = id_env }) abs_vars bndrs = ASSERT( all (not . isCoVar) bndrs ) -- What would we add to the CoSubst in this case. No easy answer. do { uniqs <- getUniquesM ; let new_bndrs = zipWith mk_poly_bndr bndrs uniqs bndr_prs = bndrs `zip` new_bndrs env' = env { le_lvl_env = addLvls dest_lvl lvl_env new_bndrs , le_subst = foldl add_subst subst bndr_prs , le_env = foldl add_id id_env bndr_prs } ; return (env', new_bndrs) } where add_subst env (v, v') = extendIdSubst env v (mkVarApps (Var v') abs_vars) add_id env (v, v') = extendVarEnv env v ((v':abs_vars), mkVarApps (Var v') abs_vars) mk_poly_bndr bndr uniq = transferPolyIdInfo bndr abs_vars $ -- Note [transferPolyIdInfo] in Id.hs mkSysLocalOrCoVar (mkFastString str) uniq poly_ty where str = "poly_" ++ occNameString (getOccName bndr) poly_ty = mkLamTypes abs_vars (substTy subst (idType bndr)) newLvlVar :: LevelledExpr -- The RHS of the new binding -> Bool -- Whether it is bottom -> LvlM Id newLvlVar lvld_rhs is_bot = do { uniq <- getUniqueM ; return (add_bot_info (mk_id uniq)) } where add_bot_info var -- We could call annotateBotStr always, but the is_bot -- flag just tells us when we don't need to do so | is_bot = annotateBotStr var (exprBotStrictness_maybe de_tagged_rhs) | otherwise = var de_tagged_rhs = deTagExpr lvld_rhs rhs_ty = exprType de_tagged_rhs mk_id uniq -- See Note [Grand plan for static forms] in SimplCore. | isJust (collectStaticPtrSatArgs lvld_rhs) = mkExportedVanillaId (mkSystemVarName uniq (mkFastString "static_ptr")) rhs_ty | otherwise = mkLocalIdOrCoVar (mkSystemVarName uniq (mkFastString "lvl")) rhs_ty cloneCaseBndrs :: LevelEnv -> Level -> [Var] -> LvlM (LevelEnv, [Var]) cloneCaseBndrs env@(LE { le_subst = subst, le_lvl_env = lvl_env, le_env = id_env }) new_lvl vs = do { us <- getUniqueSupplyM ; let (subst', vs') = cloneBndrs subst us vs env' = env { le_ctxt_lvl = new_lvl , le_lvl_env = addLvls new_lvl lvl_env vs' , le_subst = subst' , le_env = foldl add_id id_env (vs `zip` vs') } ; return (env', vs') } cloneLetVars :: RecFlag -> LevelEnv -> Level -> [Var] -> LvlM (LevelEnv, [Var]) -- See Note [Need for cloning during float-out] -- Works for Ids bound by let(rec) -- The dest_lvl is attributed to the binders in the new env, -- but cloneVars doesn't affect the ctxt_lvl of the incoming env cloneLetVars is_rec env@(LE { le_subst = subst, le_lvl_env = lvl_env, le_env = id_env }) dest_lvl vs = do { us <- getUniqueSupplyM ; let (subst', vs1) = case is_rec of NonRecursive -> cloneBndrs subst us vs Recursive -> cloneRecIdBndrs subst us vs vs2 = map zap_demand_info vs1 -- See Note [Zapping the demand info] prs = vs `zip` vs2 env' = env { le_lvl_env = addLvls dest_lvl lvl_env vs2 , le_subst = subst' , le_env = foldl add_id id_env prs } ; return (env', vs2) } add_id :: IdEnv ([Var], LevelledExpr) -> (Var, Var) -> IdEnv ([Var], LevelledExpr) add_id id_env (v, v1) | isTyVar v = delVarEnv id_env v | otherwise = extendVarEnv id_env v ([v1], ASSERT(not (isCoVar v1)) Var v1) zap_demand_info :: Var -> Var zap_demand_info v | isId v = zapIdDemandInfo v | otherwise = v {- Note [Zapping the demand info] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ VERY IMPORTANT: we must zap the demand info if the thing is going to float out, because it may be less demanded than at its original binding site. Eg f :: Int -> Int f x = let v = 3*4 in v+x Here v is strict; but if we float v to top level, it isn't any more. -}
vTurbine/ghc
compiler/simplCore/SetLevels.hs
bsd-3-clause
48,953
0
21
14,305
7,846
4,170
3,676
-1
-1
module Data.Ranged ( module Data.Ranged.Boundaries, module Data.Ranged.Ranges, module Data.Ranged.RangedSet ) where import Data.Ranged.Boundaries import Data.Ranged.Ranges import Data.Ranged.RangedSet
beni55/alex
src/Data/Ranged.hs
bsd-3-clause
211
0
5
27
47
32
15
7
0
{-# LANGUAGE Trustworthy #-} ----------------------------------------------------------------------------- -- | -- Module : Data.STRef -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (uses Control.Monad.ST) -- -- Mutable references in the (strict) ST monad. -- ----------------------------------------------------------------------------- module Data.STRef ( -- * STRefs STRef, -- abstract newSTRef, readSTRef, writeSTRef, modifySTRef, modifySTRef' ) where import Prelude import GHC.ST import GHC.STRef -- | Mutate the contents of an 'STRef'. -- -- Be warned that 'modifySTRef' does not apply the function strictly. This -- means if the program calls 'modifySTRef' many times, but seldomly uses the -- value, thunks will pile up in memory resulting in a space leak. This is a -- common mistake made when using an STRef as a counter. For example, the -- following will leak memory and likely produce a stack overflow: -- -- >print $ runST $ do -- > ref <- newSTRef 0 -- > replicateM_ 1000000 $ modifySTRef ref (+1) -- > readSTRef ref -- -- To avoid this problem, use 'modifySTRef'' instead. modifySTRef :: STRef s a -> (a -> a) -> ST s () modifySTRef ref f = writeSTRef ref . f =<< readSTRef ref -- | Strict version of 'modifySTRef' -- -- /Since: 4.6.0.0/ modifySTRef' :: STRef s a -> (a -> a) -> ST s () modifySTRef' ref f = do x <- readSTRef ref let x' = f x x' `seq` writeSTRef ref x'
frantisekfarka/ghc-dsi
libraries/base/Data/STRef.hs
bsd-3-clause
1,666
0
10
368
206
122
84
18
1
module IdIn5 where {-To rename an identifier name, stop the cursor at any occurrence of the name, then input the new name in the mini-buffer, after that, select the 'rename' command from the 'Refactor' menu.-} --Any value variable name declared in this module can be renamed. --Rename top level 'x' to 'y' will fail. x=5 foo=x+3 bar z=x+y+z where y=3 main=(foo,bar x, foo)
kmate/HaRe
test/testdata/Renaming/IdIn5_TokOut.hs
bsd-3-clause
388
0
6
78
61
36
25
6
1
-- test tryPutMVar import Control.Concurrent main = do m <- newMVar () r <- tryPutMVar m () print r takeMVar m r <- tryPutMVar m () print r
siddhanathan/ghc
testsuite/tests/concurrent/should_run/conc028.hs
bsd-3-clause
154
0
9
42
70
30
40
8
1
module Noise ( value ) where import Data.Bits import Data.Int -- 2D integer noise function inf :: Int32 -> Int32 -> Double inf x y = 1.0 - (fromIntegral j / 1073741824.0) where m = x + y*57 n = (shiftR m 13) `xor` m j = (n * (n*n*15731 + 789221) + 1376312589) .&. 0x7fffffff -- Linear interpolation lerp :: Double -> Double -> Double -> Double lerp x y w = if w < 0 || w > 1 then error ("Invalid weight: " ++ show w) else x*(1.0-w) + y*w -- Cubic S-curve interpolation clerp :: Double -> Double -> Double -> Double clerp x y w = lerp x y cw where cw = ((-2)*w^3) + (3*w^2) -- Quintic S-curve interpolation qlerp :: Double -> Double -> Double -> Double qlerp x y w = lerp x y qw where qw = 6*w^5 - 15*w^4 + 10*w^3 -- Bilinear interpolation bilerp :: Double -> Double -> Double -> Double -> Double -> Double -> Double bilerp ll lr ul ur wx wy = lerp lower upper wy where (lower, upper) = (lerp ll lr wx, lerp ul ur wx) -- 2D value noise value :: Double -> Double -> Double value x y = bilerp ll lr ul ur wx wy where (ix, iy) = (floor x :: Int32, floor y :: Int32) (wx, wy) = (x - fromIntegral (floor x), y - fromIntegral (floor y)) (ll, lr) = (inf (ix+0) (iy+0), inf (ix+1) (iy+0)) (ul, ur) = (inf (ix+0) (iy+1), inf (ix+1) (iy+1))
fmenozzi/functional-programming
Noise.hs
mit
1,513
0
14
541
673
360
313
28
2
module Main where import Graphics.Rendering.Cairo import Proxy.PreProcessing.RowBased import Proxy.Types.Game myDraw :: Render () myDraw = do setSourceRGB 0 0 0 arc 200 200 100 0 (2*pi) stroke main :: IO () main = do mapRaw <- readFile "../../MapData/Map-Midnight Lagoon" let mapD = map (map walkable) $ mapA mapA = read mapRaw :: [[Tile]] pdw = 5000 pdh = 5000 withPDFSurface "myDraw.pdf" pdw pdh (\s -> renderWith s $ do mapToSquare mapD 0 0 showdecomposition (map helper (runLengthEncoding mapA)) showPage) battlefieldTest = [[f i | i <- [j..(50+j)]] | j <- [1..50]] where f i = True showdecomposition :: [((Double,Double),(Double,Double))] -> Render () showdecomposition [] = return () showdecomposition (((x,y),(z,w)):xs) = do rectangle ((y-1)*10) ((x-1)*10) ((w - y)*10) ((z - x)*10) setLineWidth 1 setSourceRGBA 0 0.1 1 0.5 strokePreserve setSourceRGBA 0 0 1 0.4 fill showdecomposition xs square :: Bool -> Double -> Double -> Double -> Render () square b x y h = do if b then setSourceRGB 1 1 1 else setSourceRGB 0 0 0 setLineWidth 5 moveTo x y lineTo (x+h) y lineTo (x+h) (y+h) lineTo x (y+h) closePath fill stroke mapToSquare :: [[Bool]] -> Double -> Double -> Render () mapToSquare [] _ _ = return () mapToSquare (xs:xss) x y = do listToSquare xs x y mapToSquare xss x (y+10) listToSquare :: [Bool] -> Double -> Double -> Render () listToSquare [] _ _ = return () listToSquare (b:xs) x y = do let h = 10 square b x y h listToSquare xs (x+h) y lineFromTo :: Double -> Double -> Double -> Double -> Render () lineFromTo x y z w = do setSourceRGB 0 0 0 setLineWidth 0.25 moveTo x y lineTo z w stroke {- horLines :: Double -> Double horLines x y = do let length = (0.25+10)*x + 0.25 noOfLines = y + 1 horLine z w = do if z == w then return () else lineFromTo 1 z (1+length) z horLine grid :: Double -> Double -> Double -> Double -> Render () grid n m = do horLines -}
mapinguari/SC_HS_Proxy
src/hello.hs
mit
2,234
0
17
702
865
429
436
60
2
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ScopedTypeVariables #-} module Yesod.Auth.OAuth ( authOAuth , oauthUrl , authTwitter , authTwitterUsingUserId , twitterUrl , authTumblr , tumblrUrl , module Web.Authenticate.OAuth ) where import Control.Applicative as A ((<$>), (<*>)) import Control.Arrow ((***)) import UnliftIO.Exception import Control.Monad.IO.Class import Data.ByteString (ByteString) import Data.Maybe import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8With, encodeUtf8) import Data.Text.Encoding.Error (lenientDecode) import Web.Authenticate.OAuth import Yesod.Auth import Yesod.Form import Yesod.Core data YesodOAuthException = CredentialError String Credential | SessionError String deriving Show instance Exception YesodOAuthException oauthUrl :: Text -> AuthRoute oauthUrl name = PluginR name ["forward"] authOAuth :: forall master. YesodAuth master => OAuth -- ^ 'OAuth' data-type for signing. -> (Credential -> IO (Creds master)) -- ^ How to extract ident. -> AuthPlugin master authOAuth oauth mkCreds = AuthPlugin name dispatch login where name = T.pack $ oauthServerName oauth url = PluginR name [] lookupTokenSecret = bsToText . fromMaybe "" . lookup "oauth_token_secret" . unCredential oauthSessionName :: Text oauthSessionName = "__oauth_token_secret" dispatch :: Text -> [Text] -> AuthHandler master TypedContent dispatch "GET" ["forward"] = do render <- getUrlRender tm <- getRouteToParent let oauth' = oauth { oauthCallback = Just $ encodeUtf8 $ render $ tm url } manager <- authHttpManager tok <- getTemporaryCredential oauth' manager setSession oauthSessionName $ lookupTokenSecret tok redirect $ authorizeUrl oauth' tok dispatch "GET" [] = do tokSec <- lookupSession oauthSessionName >>= \case Just t -> return t Nothing -> liftIO $ fail "lookupSession could not find session" deleteSession oauthSessionName reqTok <- if oauthVersion oauth == OAuth10 then do oaTok <- runInputGet $ ireq textField "oauth_token" return $ Credential [ ("oauth_token", encodeUtf8 oaTok) , ("oauth_token_secret", encodeUtf8 tokSec) ] else do (verifier, oaTok) <- runInputGet $ (,) A.<$> ireq textField "oauth_verifier" A.<*> ireq textField "oauth_token" return $ Credential [ ("oauth_verifier", encodeUtf8 verifier) , ("oauth_token", encodeUtf8 oaTok) , ("oauth_token_secret", encodeUtf8 tokSec) ] manager <- authHttpManager accTok <- getAccessToken oauth reqTok manager creds <- liftIO $ mkCreds accTok setCredsRedirect creds dispatch _ _ = notFound login tm = do render <- getUrlRender let oaUrl = render $ tm $ oauthUrl name [whamlet| <a href=#{oaUrl}>Login via #{name} |] mkExtractCreds :: Text -> String -> Credential -> IO (Creds m) mkExtractCreds name idName (Credential dic) = do let mcrId = decodeUtf8With lenientDecode <$> lookup (encodeUtf8 $ T.pack idName) dic case mcrId of Just crId -> return $ Creds name crId $ map (bsToText *** bsToText) dic Nothing -> throwIO $ CredentialError ("key not found: " ++ idName) (Credential dic) authTwitter' :: YesodAuth m => ByteString -- ^ Consumer Key -> ByteString -- ^ Consumer Secret -> String -> AuthPlugin m authTwitter' key secret idName = authOAuth (newOAuth { oauthServerName = "twitter" , oauthRequestUri = "https://api.twitter.com/oauth/request_token" , oauthAccessTokenUri = "https://api.twitter.com/oauth/access_token" , oauthAuthorizeUri = "https://api.twitter.com/oauth/authorize" , oauthSignatureMethod = HMACSHA1 , oauthConsumerKey = key , oauthConsumerSecret = secret , oauthVersion = OAuth10a }) (mkExtractCreds "twitter" idName) -- | This plugin uses Twitter's /screen_name/ as ID, which shouldn't be used for authentication because it is mutable. authTwitter :: YesodAuth m => ByteString -- ^ Consumer Key -> ByteString -- ^ Consumer Secret -> AuthPlugin m authTwitter key secret = authTwitter' key secret "screen_name" {-# DEPRECATED authTwitter "Use authTwitterUsingUserId instead" #-} -- | Twitter plugin which uses Twitter's /user_id/ as ID. -- -- For more information, see: https://github.com/yesodweb/yesod/pull/1168 -- -- @since 1.4.1 authTwitterUsingUserId :: YesodAuth m => ByteString -- ^ Consumer Key -> ByteString -- ^ Consumer Secret -> AuthPlugin m authTwitterUsingUserId key secret = authTwitter' key secret "user_id" twitterUrl :: AuthRoute twitterUrl = oauthUrl "twitter" authTumblr :: YesodAuth m => ByteString -- ^ Consumer Key -> ByteString -- ^ Consumer Secret -> AuthPlugin m authTumblr key secret = authOAuth (newOAuth { oauthServerName = "tumblr" , oauthRequestUri = "http://www.tumblr.com/oauth/request_token" , oauthAccessTokenUri = "http://www.tumblr.com/oauth/access_token" , oauthAuthorizeUri = "http://www.tumblr.com/oauth/authorize" , oauthSignatureMethod = HMACSHA1 , oauthConsumerKey = key , oauthConsumerSecret = secret , oauthVersion = OAuth10a }) (mkExtractCreds "tumblr" "name") tumblrUrl :: AuthRoute tumblrUrl = oauthUrl "tumblr" bsToText :: ByteString -> Text bsToText = decodeUtf8With lenientDecode
yesodweb/yesod
yesod-auth-oauth/Yesod/Auth/OAuth.hs
mit
6,653
0
17
2,230
1,265
674
591
136
5
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} module RWPAS.Direction ( Direction4(..) , Direction8(..) , deltaToDirection8 , direction4ToDelta , direction8ToDelta , direction4To8 , directions8 ) where import Data.Data import Data.SafeCopy import GHC.Generics import Linear.V2 import System.Random.MWC -- | The four directions. data Direction4 = DUp | DLeft | DRight | DDown deriving ( Eq, Ord, Show, Read, Typeable, Data, Generic, Enum ) -- | The eight directions. data Direction8 = D8Up | D8Left | D8Right | D8Down | D8UpLeft | D8UpRight | D8DownLeft | D8DownRight deriving ( Eq, Ord, Show, Read, Typeable, Data, Generic, Enum ) -- | `uniformR` is not very sensible but it is implemented. instance Variate Direction8 where uniform rng = do x <- uniformR (0, 7) rng return $ toEnum x uniformR (d1, d2) rng = do x <- uniformR (i1, i2) rng return $ toEnum x where i1 = fromEnum d1 i2 = fromEnum d2 -- | `uniformR` is not very sensible but it is implemented. instance Variate Direction4 where uniform rng = do x <- uniformR (0, 3) rng return $ toEnum x uniformR (d1, d2) rng = do x <- uniformR (i1, i2) rng return $ toEnum x where i1 = fromEnum d1 i2 = fromEnum d2 directions8 :: [Direction8] directions8 = [D8Up, D8Left, D8Right, D8Down ,D8UpLeft, D8UpRight, D8DownLeft, D8DownRight] deltaToDirection8 :: V2 Int -> Maybe Direction8 deltaToDirection8 (V2 1 0) = Just D8Right deltaToDirection8 (V2 (-1) 0) = Just D8Left deltaToDirection8 (V2 0 1) = Just D8Down deltaToDirection8 (V2 0 (-1)) = Just D8Up deltaToDirection8 (V2 1 1) = Just D8DownRight deltaToDirection8 (V2 1 (-1)) = Just D8UpRight deltaToDirection8 (V2 (-1) 1) = Just D8DownLeft deltaToDirection8 (V2 (-1) (-1)) = Just D8UpLeft deltaToDirection8 _ = Nothing {-# INLINE deltaToDirection8 #-} direction4ToDelta :: Direction4 -> V2 Int direction4ToDelta DUp = V2 0 (-1) direction4ToDelta DLeft = V2 (-1) 0 direction4ToDelta DRight = V2 1 0 direction4ToDelta DDown = V2 0 1 direction8ToDelta :: Direction8 -> V2 Int direction8ToDelta D8Up = V2 0 (-1) direction8ToDelta D8Left = V2 (-1) 0 direction8ToDelta D8Right = V2 1 0 direction8ToDelta D8Down = V2 0 1 direction8ToDelta D8UpLeft = V2 (-1) (-1) direction8ToDelta D8UpRight = V2 1 (-1) direction8ToDelta D8DownLeft = V2 (-1) 1 direction8ToDelta D8DownRight = V2 1 1 direction4To8 :: Direction4 -> Direction8 direction4To8 DUp = D8Up direction4To8 DDown = D8Down direction4To8 DLeft = D8Left direction4To8 DRight = D8Right deriveSafeCopy 0 'base ''Direction4 deriveSafeCopy 0 'base ''Direction8
Noeda/rwpas
src/RWPAS/Direction.hs
mit
2,693
0
10
540
926
483
443
85
1
{-| Various utility functions -} module Web.ZeroBin.Utils ( toWeb , makePassword ) where import Crypto.Random.Entropy (getEntropy) import Data.ByteString (ByteString) import Data.ByteString.Base64 (encode) import Data.ByteString.Char8 (unpack) -- | Encodes to base64 and drops padding '='. toWeb :: ByteString -- ^ the data to encode -> String -- ^ base64 string without padding toWeb = takeWhile (/= '=') . unpack . encode -- | Makes a random password makePassword :: Int -- ^ the number of bytes of entropy -> IO String -- ^ random byte-string encoded by 'toWeb' makePassword n = toWeb `fmap` getEntropy n
zalora/zerobin
src/Web/ZeroBin/Utils.hs
mit
644
0
8
130
123
75
48
13
1
-- This is some random code I found on the internet -- data JSONNumberOperation = Add Path Int -- deriving Show -- data JSONStringOperation = StringInsert Path Position Text -- | StringDelete Path Position Text -- deriving Show -- data JSONArrayOperation = ArrayInsert Path Position Value -- | ArrayDelete Path Position Value -- | ArrayReplace Path Position Value Value -- | ArrayMove Path Position Int -- deriving Show -- data JSONObjectOperation = Insert Path Property Value -- | Delete Path Property -- | Replace Path Property Value Value -- deriving Show -- instance FromJSON JSONNumberOperation where -- parseJSON (Object v) = Add <$> (v .: "p") <*> (v .: "na") -- parseJSON _ = fail "Not an Object"
thomasjm/ot.hs
src/Control/OperationalTransformation/Misc.hs
mit
968
0
2
381
20
19
1
1
0
{- Materials module. Exports all modules in Materials. -} module Graphics.ThreeJs.Materials ( module Graphics.ThreeJs.Materials.MeshBasicMaterial ) where import Graphics.ThreeJs.Materials.MeshBasicMaterial
sanghakchun/three-js-haste
src/Graphics/ThreeJs/Materials.hs
mit
216
0
5
28
25
18
7
4
0
import Text.Printf import Data.List {-- data Line = Line { a :: Double, b :: Double, c :: Double } lineFromTwoPoint (x1, y1) (x2, y2) = Line {a = y1-y2, b = x2-x1, c = (y2-y1)*x1-(x2-x1)*y1} pointDistFromLine (x, y) (Line a b c) = abs (a*x + b*y + c) / sqrt (a*a + b*b) maximiumPoint ps (Line a b c) (x, y) | ps == [] = (x, y) | otherwise = if pointDistFromLine (x', y') (Line a b c) > pointDistFromLine (x, y) (Line a b c) then maximiumPoint rx (Line a b c) (x', y') else maximiumPoint rx (Line a b c) (x, y) where ((x', y'):rx) = ps dist (x1, y1) (x2, y2) = sqrt ((x1-x2)**2 + (y1-y2)**2) leftPoint [] (x, y) = (x, y) leftPoint ((x', y'):ps) (x, y) = leftPoint ps (if x' < x then (x', y') else (x, y)) rightPoint [] (x, y) = (x, y) rightPoint ((x', y'):ps) (x, y) = rightPoint ps (if x' > x then (x', y') else (x, y)) quickHull [] (x1, y1) (x2, y2) = [] quickHull ps (x1, y1) (x2, y2) = let (sx, sy) = maximiumPoint ps (lineFromTwoPoint (x1, y1) (x2, y2)) (x1, y1) Line a b c = lineFromTwoPoint (x1, y1) (sx, sy) ps1 = quickHull (filter (\(x, y) -> a*x + b*y + c > 0) ps) (x1, y1) (sx, sy) Line a' b' c' = lineFromTwoPoint (x2, y2) (sx, sy) ps2 = quickHull (filter (\(x, y) -> a'*x + b'*y + c' > 0) ps) (x1, y1) (sx, sy) in concat [ps1, ps2, [(sx, sy)]] --} leftBellowPoint ps (x, y) | ps == [] = (x, y) | otherwise = leftBellowPoint rs ( if (or [x' < x, and [x' == x, y' < y]]) then (x', y') else (x, y) ) where (x', y'):rs = ps cross (x1, y1) (x2, y2) = x1*y2 - y1*x2 convexHull :: [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] convexHull points [] = convexHull (drop 1 points) (take 1 points) convexHull [] stack = stack convexHull points (x:[]) = convexHull (drop 1 points) [head points, x] convexHull p@((x, y):ps) stack@((x1, y1):(x2, y2):ss) = if cross (x-x1, y-y1) (x2-x1, y2-y1) >= 0 then convexHull ps ((x, y):stack) else convexHull p ((x2, y2):ss) dist :: (Int, Int) -> (Int, Int) -> Double dist (x1, y1) (x2, y2) = sqrt $ ( fromIntegral x1 - fromIntegral x2 )**2 + ( fromIntegral y1 - fromIntegral y2 )**2 -- solve :: [(Int, Int)] -> Double solve points = let lb@(lbx, lby) = leftBellowPoint points $ points !! 0 ps = sortBy (\(x1,y1) (x2, y2) -> if ( or [cross (x1-lbx, y1-lby) (x2-lbx, y2-lby) > 0, and [cross (x1-lbx, y1-lby) (x2-lbx, y2-lby) == 0, (x1-lbx)*(x1-lbx)+(y1-lby)*(y1-lby) < (x2-lbx)*(x2-lbx)+(y2-lby)*(y2-lby)] ] ) then LT else GT) points ans = convexHull ps [] in foldr (\(x1, y1) ((x2, y2), ac) -> ( (x1, y1), ac+dist (x1, y1) (x2, y2) ) ) (head ans, 0) (ans ++ take 1 ans) main = do n <- readLn :: IO Int content <- getContents let points = map (\[x, y] -> (x, y)). map (map (read::String->Int)). map words. lines $ content -- ans = solve points printf "%.1f\n" . snd. solve $ points -- printf "%.1f\n" ans
atupal/oj
hackerrank/practices/function_programming/recursion/convex_hull_fp.hs
mit
2,966
1
26
767
990
545
445
33
2
power :: (Eq a, Num a, Ord a) => a -> a -> a power _ 0 = 1 power a n | n < 0 = error "only non-negative number" | otherwise = a * power a (n - 1) -- power 2 3 -- = { applying power } -- 2 * power 2 2 -- = { applying power } -- 2 * 2 * power 2 1 -- = { applying power } -- 2 * 2 * 2 * power 2 0 -- = { applying power } -- 2 * 2 * 2 * 1 -- = { applying * } -- 8 main = do print $ 2 `power` 0 print $ 2 `power` 3 print $ 2 `power` (-3)
fabioyamate/programming-in-haskell
ch06/ex01.hs
mit
463
0
9
157
153
83
70
9
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE TemplateHaskell #-} module Circuit.Format.Acirc ( Circuit.Format.Acirc.read , Circuit.Format.Acirc.write , Circuit.Format.Acirc.show , writeWithTests , readWithTests , showWithTests , parse ) where import Circuit import Circuit.Parser import Circuit.Utils hiding ((%)) import qualified Circuit.Builder as B import qualified Circuit.Builder.Internals as B import Prelude hiding (show) import Control.Monad import Control.Monad.Trans (lift) import Data.Maybe (mapMaybe) import Formatting ((%)) import Lens.Micro.Platform import Text.Parsec hiding (spaces, parseTest, parse) import TextShow import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.IntMap as IM import qualified Data.IntSet as IS import qualified Formatting as F data AcircSt = AcircSt { _acirc_st_outputs :: [Ref] -- old refs from the previous circuit , _acirc_st_const_vals :: IM.IntMap Int , _acirc_st_secret_vals :: IM.IntMap Int , _acirc_st_tr :: IM.IntMap Ref } makeLenses ''AcircSt emptyAcircSt = AcircSt [] IM.empty IM.empty IM.empty type AcircParser g = ParseCirc g AcircSt -------------------------------------------------------------------------------- read :: Gate g => FilePath -> IO (Circuit g) read = fmap fst . readWithTests readWithTests :: Gate g => FilePath -> IO (Circuit g, [TestCase]) readWithTests fp = parse <$> readFile fp write :: FilePath -> Acirc -> IO () write fp c = T.writeFile fp (show c) writeWithTests :: FilePath -> Acirc -> IO () writeWithTests fp c = do ts <- replicateM 10 (genTest c) T.writeFile fp (showWithTests c ts) show :: Acirc -> T.Text show c = showWithTests c [] showWithTests :: Acirc -> [TestCase] -> T.Text showWithTests !c !ts = T.unlines (header ++ inputs ++ secrets ++ consts ++ gates) where header = [ T.append ":ninputs " (showt (ninputs c)) , T.append ":nrefs " (showt (c ^. circ_maxref)) , T.append ":consts " (T.unwords (map showt (IM.elems (_circ_const_vals c)))) , T.append ":secrets " (T.unwords (map showt (IM.elems (_circ_secret_vals c)))) , T.append ":outputs " (T.unwords (map (showt.getRef) (outputRefs c))) , T.append ":symlens " (T.unwords (map showt (c^..circ_symlen.each))) , T.append ":sigmas " (T.unwords (map (showt . (b2i :: Bool -> Int) . flip IS.member (c^.circ_sigma_vecs)) [0..nsymbols c-1])) ] ++ map showTest ts ++ [ ":start" ] inputs = mapMaybe gateTxt (inputRefs c) consts = mapMaybe gateTxt (constRefs c) secrets = mapMaybe gateTxt (secretRefs c) gates = mapMaybe gateTxt (gateRefs c) gateTxt :: Ref -> Maybe T.Text gateTxt !ref = case c ^. circ_refcount . at (getRef ref) of Nothing -> Nothing Just ct -> Just $ case c^.circ_refmap.at (getRef ref).non undefined of (ArithBase (Input id)) -> F.sformat (F.shown % " input " % F.shown % " : " % F.int) ref id ct (ArithBase (Const id)) -> F.sformat (F.shown % " const " % F.shown % " : " % F.int) ref id ct (ArithBase (Secret id)) -> F.sformat (F.shown % " secret " % F.shown % " : " % F.int) ref id ct (ArithAdd x y) -> F.sformat (F.shown % " add " % F.shown % " " % F.shown % " : " % F.int % F.stext) ref x y ct (saveStr ref) (ArithSub x y) -> F.sformat (F.shown % " sub " % F.shown % " " % F.shown % " : " % F.int % F.stext) ref x y ct (saveStr ref) (ArithMul x y) -> F.sformat (F.shown % " mul " % F.shown % " " % F.shown % " : " % F.int % F.stext) ref x y ct (saveStr ref) saveStr ref = if IS.member (getRef ref) (c^.circ_refsave) then " save" else if IS.member (getRef ref) (c^.circ_refskip) then " skip" else "" showTest :: TestCase -> T.Text showTest (!inp, !out) = T.concat [":test ", T.pack (showInts inp), " ", T.pack (showInts out) ] -------------------------------------------------------------------------------- -- parser parse :: Gate g => String -> (Circuit g, [TestCase]) parse s = runCircParser emptyAcircSt parser s where parser = do many $ char ':' >> choice [parseTest, parseOutputs, parseConsts, try parseSymlen, try parseSigma, try parseSecrets, skipParam] many parseRefLine lift . B.outputs =<< mapM tr =<< view acirc_st_outputs <$> getSt -- translate the outputs eof tr :: Ref -> AcircParser g Ref tr x = (IM.! getRef x) . view acirc_st_tr <$> getSt skipParam :: AcircParser g () skipParam = do skipMany (oneOf " \t" <|> alphaNum) endLine parseTest :: AcircParser g () parseTest = do string "test" spaces inps <- many digit spaces outs <- many digit let inp = readInts inps res = readInts outs addTest (inp, res) endLine parseOutputs :: AcircParser g () parseOutputs = do string "outputs" spaces refs <- many (parseRef <* spaces) modifySt (acirc_st_outputs .~ refs) endLine parseSecrets :: AcircParser g () parseSecrets = do string "secrets" spaces secs <- many (int <* spaces) modifySt (acirc_st_secret_vals .~ IM.fromList (zip [0..] secs)) endLine parseConsts :: AcircParser g () parseConsts = do string "consts" spaces cs <- many (spaces >> int) modifySt (acirc_st_const_vals .~ IM.fromList (zip [0..] cs)) endLine parseSymlen :: AcircParser g () parseSymlen = do string "symlens" spaces symlens <- many (spaces >> int) lift $ zipWithM B.setSymlen [0::SymId ..] symlens endLine parseSigma :: AcircParser g () parseSigma = do string "sigmas" spaces sigs <- many (spaces >> i2b <$> int) lift $ forM (zip [0::SymId ..] sigs) $ \(id, sig) -> do when sig (B.setSigma id) endLine parseRef :: AcircParser g Ref parseRef = Ref <$> int parseRefLine :: Gate g => AcircParser g () parseRefLine = do z <- parseRef spaces z' <- choice [parseConst, try parseSecret, parseInput, parseAdd, parseSub, parseMul] modifySt (acirc_st_tr . at (getRef z) ?~ z') parseTimesUsed z' endLine parseInput :: Gate g => AcircParser g Ref parseInput = do string "input" spaces id <- InputId <$> int lift $ B.inputBitN id parseConst :: Gate g => AcircParser g Ref parseConst = do string "const" spaces id <- int val <- (IM.! id) . view acirc_st_const_vals <$> getSt lift $ B.constant val parseSecret :: Gate g => AcircParser g Ref parseSecret = do string "secret" spaces id <- int val <- (IM.! id) . view acirc_st_secret_vals <$> getSt lift $ B.secret val parseNot :: Gate g => AcircParser g Ref parseNot = do string "not" spaces x <- tr =<< parseRef lift $ B.circNot x parseMul :: Gate g => AcircParser g Ref parseMul = do string "mul" spaces x <- tr =<< parseRef spaces y <- tr =<< parseRef lift $ B.circMul x y parseAdd :: Gate g => AcircParser g Ref parseAdd = do string "add" spaces x <- tr =<< parseRef spaces y <- tr =<< parseRef lift $ B.circAdd x y parseSub :: Gate g => AcircParser g Ref parseSub = do string "sub" spaces x <- tr =<< parseRef spaces y <- tr =<< parseRef lift $ B.circSub x y parseTimesUsed :: Ref -> AcircParser g () parseTimesUsed ref = optional $ do spaces char ':' spaces void int optional $ do spaces s <- try (string "save") <|> string "skip" case s of "save" -> lift $ B.markSave ref "skip" -> lift $ B.markSkip ref
spaceships/circuit-synthesis
src/Circuit/Format/Acirc.hs
mit
7,900
0
23
2,186
2,902
1,447
1,455
-1
-1
fact 0 = 1 fact 1 = 1 fact n = n * fact (n-1)
MaxHorstmann/myfirsthaskell
factorial.hs
mit
47
0
8
16
39
19
20
3
1
module Watcher.Arguments (getArguments) where import System.Directory import System.Environment getArguments :: IO [String] getArguments = do cmdArgs <- getArgs if null cmdArgs then getConfigFile else return cmdArgs getConfigFile :: IO [String] getConfigFile = do fExist <- doesFileExist ".watcher-config" if fExist then fmap (concatMap toArgsList . lines) (readFile ".watcher-config") >>= logArgs else return [] logArgs :: [String] -> IO [String] logArgs xs = do putStrLn ("-> Obtidos parâmetros do arquivo .watcher-config e construído comando: hs-file-watcher " ++ unwords xs) return xs toArgsList :: String -> [String] toArgsList [] = [] toArgsList args@(x:xs) | x == '\"' = takeWhile (/='\"') xs : toArgsList (drop ((+1) . length $ takeWhile (/='\"') xs) xs) | x == ' ' = toArgsList (drop 1 args) | otherwise = takeWhile (/=' ') args : toArgsList (drop ((+1) . length $ takeWhile (/=' ') args) args)
Miguel-Fontes/hs-file-watcher
src/Watcher/Arguments.hs
mit
982
0
13
214
357
183
174
25
2
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI, UnliftedFFITypes, DeriveDataTypeable, MagicHash #-} {- | GHCJS has two types of threads. Regular, asynchronous threads are started with `h$run`, are managed by the scheduler and run in the background. `h$run` returns immediately. Synchronous threads are started with `h$runSync`, which returns when the thread has run to completion. When a synchronous thread does an operation that would block, like accessing an MVar or an asynchronous FFI call, it cannot continue synchronously. There are two ways this can be resolved, depending on the second argument of the `h$runSync` call: * The action is aborted and the thread receives a 'WouldBlockException' * The thread continues asynchronously, `h$runSync` returns Note: when a synchronous thread encounters a black hole from another thread, it tries to steal the work from that thread to avoid blocking. In some cases that might not be possible, for example when the data accessed is produced by a lazy IO operation. This is resolved the same way as blocking on an IO action would. -} module GHCJS.Concurrent ( isThreadSynchronous , isContinueAsync , OnBlock (..) , WouldBlockException(..) , synchronously ) where import GHCJS.Prim import Control.Applicative import Control.Concurrent import qualified Control.Exception as Ex import GHC.Exts (ThreadId#) import GHC.Conc.Sync (ThreadId(..)) import Data.Bits (testBit) import Data.Data import Data.Typeable import Unsafe.Coerce data OnBlock = ContinueAsync | ThrowWouldBlock deriving (Data, Typeable, Enum, Show, Eq, Ord) {- | Runs the action synchronously, which means that the thread will not be preempted by the scheduler. If the thread encounters a blocking operation, the scheduler will switch to other threads. When the thread is scheduled again, it will still be non-preemptible. When the thread encounters a black hole from another thread, the scheduler will attempt to clear it by temporarily switching to that thread. -} synchronously :: IO a -> IO a synchronously x = do oldS <- js_setSynchronous True if oldS then x else x `Ex.finally` js_setSynchronous False {-# INLINE synchronously #-} makeAsynchronous :: ThreadId -> IO () makeAsynchronous (ThreadId tid) = js_makeAsynchronous tid {- | Returns whether the 'ThreadId' is a synchronous thread -} isThreadSynchronous :: ThreadId -> IO Bool isThreadSynchronous = fmap (`testBit` 0) . syncThreadState {- | Returns whether the 'ThreadId' will continue running async. Always returns 'True' when the thread is not synchronous. -} isContinueAsync :: ThreadId -> IO Bool isContinueAsync = fmap (`testBit` 1) . syncThreadState syncThreadState :: ThreadId-> IO Int syncThreadState (ThreadId tid) = js_syncThreadState tid -- ---------------------------------------------------------------------------- foreign import javascript unsafe "h$syncThreadState($1)" js_syncThreadState :: ThreadId# -> IO Int foreign import javascript unsafe "$r = h$currentThread.isSynchronous;\ \h$currentThread.isSynchronous = $1;" js_setSynchronous :: Bool -> IO Bool foreign import javascript unsafe "$1.isSynchronous = false;" js_makeAsynchronous :: ThreadId# -> IO ()
tavisrudd/ghcjs-base
GHCJS/Concurrent.hs
mit
3,575
8
10
862
391
218
173
41
2
{-# LANGUAGE TemplateHaskell #-} module Language.Paradocs.Rule where import Control.Lens import qualified Data.HashMap.Strict as HashMap import qualified Language.Paradocs.File as File import qualified Language.Paradocs.RuleName as RuleName import qualified Language.Paradocs.MacroEnv as MacroEnv import qualified Language.Paradocs.EscapeEnv as EscapeEnv data Rule = Rule { _ancestors :: [RuleName.AbsoluteRuleName], _macroEnv :: MacroEnv.MacroEnv, _escapeEnv :: EscapeEnv.EscapeEnv, _before :: Maybe File.File, _after :: Maybe File.File, _indent :: Maybe String } deriving (Show) makeLenses ''Rule empty :: Rule empty = Rule { _ancestors = [], _macroEnv = HashMap.empty, _escapeEnv = HashMap.empty, _before = Nothing, _after = Nothing, _indent = Nothing }
pasberth/paradocs
Language/Paradocs/Rule.hs
mit
941
0
10
275
194
124
70
27
1
module Main where import Control.DeepSeq (NFData(..)) import Criterion.Main import Data.Pocketmine.Block instance NFData BlockType decodingN :: Int -> [BlockType] decodingN i = take i $ map toEnum (cycle [0..255]) isUnknown (Unknown _) = True isUnknown _ = False main = defaultMain [ bgroup "decode" [ bench "init" $ nf (toEnum::Int->BlockType) 255 , bench "cycle" $ nf decodingN 65535 ] ]
greyson/HasCraft
test/BlockBenchmark.hs
gpl-2.0
436
0
12
105
157
83
74
12
1
-- Copyright (C) 2009 Ganesh Sittampalam -- -- BSD3 {-# LANGUAGE CPP, GADTs, PatternGuards, TypeOperators, NoMonomorphismRestriction, ViewPatterns, UndecidableInstances #-} module Darcs.Patch.Rebase ( Rebasing(..), RebaseItem(..), RebaseName(..), RebaseFixup(..) , simplifyPush, simplifyPushes , mkSuspended , takeHeadRebase, takeHeadRebaseFL, takeHeadRebaseRL , takeAnyRebase, takeAnyRebaseAndTrailingPatches , countToEdit ) where import Darcs.Patch ( RepoPatch ) import Darcs.Patch.Commute ( selfCommuter ) import Darcs.Patch.CommuteFn ( CommuteFn ) import Darcs.Patch.Conflict ( Conflict(..), CommuteNoConflicts(..) ) import Darcs.Patch.Debug ( PatchDebug(..) ) import Darcs.Patch.Effect ( Effect(..) ) import Darcs.Patch.FileHunk ( IsHunk(..) ) import Darcs.Patch.Format ( PatchListFormat(..), ListFormat, copyListFormat ) import Darcs.Patch.Matchable ( Matchable ) import Darcs.Patch.MaybeInternal ( MaybeInternal(..), InternalChecker(..) ) import Darcs.Patch.Merge ( Merge(..) ) import Darcs.Patch.Named ( Named(..), patchcontents, namepatch , commuterIdNamed ) import Darcs.Patch.PatchInfoAnd ( PatchInfoAnd, hopefully ) import Darcs.Patch.Patchy ( Invert(..), Commute(..), Patchy, Apply(..), ShowPatch(..), ReadPatch(..), PatchInspect(..) ) import Darcs.Patch.Prim ( PrimPatchBase, PrimOf, FromPrim(..), FromPrim(..), canonizeFL ) import Darcs.Patch.Read ( bracketedFL ) import Darcs.Patch.Rebase.Fixup ( RebaseFixup(..) ) import Darcs.Patch.Rebase.Name ( RebaseName(..) , commutePrimName, commuteNamePrim ) import Darcs.Patch.Rebase.NameHack ( NameHack(..) ) import Darcs.Patch.Rebase.Recontext ( RecontextRebase(..), RecontextRebase1(..), RecontextRebase2(..) ) import Darcs.Patch.Repair ( Check(..), RepairToFL(..) ) import Darcs.Patch.Set ( PatchSet(..) ) import Darcs.Patch.Show ( ShowPatchBasic(..) ) import Darcs.Patch.ReadMonads ( ParserM, lexString, myLex' ) import Darcs.Patch.Witnesses.Eq import Darcs.Patch.Witnesses.Ordered import Darcs.Patch.Witnesses.Sealed import Darcs.Patch.Witnesses.Show ( Show1(..), Show2(..), showsPrec2 , ShowDict(ShowDictClass), appPrec ) import Darcs.Patch.Witnesses.Unsafe ( unsafeCoerceP ) import qualified Darcs.Util.Diff as D ( DiffAlgorithm(MyersDiff) ) import Darcs.Util.IsoDate ( getIsoDateTime ) import Darcs.Util.Text ( formatParas ) import Darcs.Util.Printer ( vcat, text, blueText, ($$), (<+>) ) import Prelude hiding ( pi ) import Control.Applicative ( (<$>), (<|>) ) import Control.Arrow ( (***), second ) import Control.Monad ( when ) import Data.Maybe ( catMaybes ) import qualified Data.ByteString as B ( ByteString ) import qualified Data.ByteString.Char8 as BC ( pack ) #include "impossible.h" {- Notes Note [Rebase representation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The entire rebase state is stored in a single Suspended patch. This is both unnatural and inefficient: - Unnatural because the rebase state is not really a patch and treating it as one requires various hacks: - It has to be given a fake name: see mkSuspended - Since 'Named p' actually contains 'FL p', we have to assume/assert that the FL either contains a sequence of Normals or a single Suspended - When 'Named ps' commutes past 'Named (Suspended items :> NilFL)', we need to inject the name from 'Named ps' into 'items', which is a layering violation: see Darcs.Patch.Rebase.NameHack - We need to hide the patch in the UI: see Darcs.Patch.MaybeInternal - We need a conditional hook so that amend-record can change the Suspended patch itself: see Darcs.Patch.Rebase.Recontext (something like this might be necessary no matter what the representation) - Inefficient because we need to write the entire rebase state out each time, even though most operations will only affect a small portion near the beginning. - This also means that we need to commute the rebase patch back to the head of the repo lazily: we only do so when a rebase operation requires it. Otherwise, pulling in 100 patches would entail writing out the entire rebase patch to disk 100 times. The obvious alternative is to store the rebase state at the repository level, using inventories in some appropriate way. The main reason this wasn't done is that the repository handling code is quite fragile and hard to modify safely. Also, rebase relies heavily on witnesses to check correctness, and the witnesses on the Repository type are not as reliable as those on patch types, partly because of the cruft in the repository code, and partly because it's inherently harder to track witnesses when the objects being manipulated are stored on disk and being changed imperatively. If and when the repository code becomes easier to work with, rebase should be changed accordingly. -} -- TODO: move some of the docs of types to individual constructors -- once http://trac.haskell.org/haddock/ticket/43 is fixed. -- |A patch that lives in a repository where a rebase is in -- progress. Such a repository will consist of @Normal@ patches -- along with exactly one @Suspended@ patch. -- -- Most rebase operations will require the @Suspended@ patch -- to be at the end of the repository. -- -- @Normal@ represents a normal patch within a respository where a -- rebase is in progress. @Normal p@ is given the same on-disk -- representation as @p@, so a repository can be switched into -- and out of rebasing mode simply by adding or removing a -- @Suspended@ patch and setting the appropriate format flag. -- -- The single @Suspended@ patch contains the entire rebase -- state, in the form of 'RebaseItem's. -- -- Note that the witnesses are such that the @Suspended@ -- patch has no effect on the context of the rest of the -- repository; in a sense the patches within it are -- dangling off to one side from the main repository. -- -- See Note [Rebase representation] in the source for a discussion -- of the design choice to embed the rebase state in a single patch. data Rebasing p wX wY where Normal :: p wX wY -> Rebasing p wX wY Suspended :: FL (RebaseItem p) wX wY -> Rebasing p wX wX instance (Show2 p, Show2 (PrimOf p)) => Show (Rebasing p wX wY) where showsPrec d (Normal p) = showParen (d > appPrec) $ showString "Darcs.Patch.Rebase.Normal " . showsPrec2 (appPrec + 1) p showsPrec d (Suspended p) = showParen (d > appPrec) $ showString "Darcs.Patch.Rebase.Suspended " . showsPrec2 (appPrec + 1) p instance (Show2 p, Show2 (PrimOf p)) => Show1 (Rebasing p wX) where showDict1 = ShowDictClass instance (Show2 p, Show2 (PrimOf p)) => Show2 (Rebasing p) where showDict2 = ShowDictClass -- |A single item in the rebase state consists of either -- a patch that is being edited, or a fixup that adjusts -- the context so that a subsequent patch that is being edited -- \"makes sense\". -- -- @ToEdit@ holds a patch that is being edited. The name ('PatchInfo') of -- the patch will typically be the name the patch had before -- it was added to the rebase state; if it is moved back -- into the repository it must be given a fresh name to account -- for the fact that it will not necessarily have the same -- dependencies as the original patch. This is typically -- done by changing the @Ignore-This@ junk. -- -- @Fixup@ adjusts the context so that a subsequent @ToEdit@ patch -- is correct. Where possible, @Fixup@ changes are commuted -- as far as possible into the rebase state, so any remaining -- ones will typically cause a conflict when the @ToEdit@ patch -- is moved back into the repository. data RebaseItem p wX wY where ToEdit :: Named p wX wY -> RebaseItem p wX wY Fixup :: RebaseFixup p wX wY -> RebaseItem p wX wY instance (Show2 p, Show2 (PrimOf p)) => Show (RebaseItem p wX wY) where showsPrec d (ToEdit p) = showParen (d > appPrec) $ showString "ToEdit " . showsPrec2 (appPrec + 1) p showsPrec d (Fixup p) = showParen (d > appPrec) $ showString "Fixup " . showsPrec2 (appPrec + 1) p instance (Show2 p, Show2 (PrimOf p)) => Show1 (RebaseItem p wX) where showDict1 = ShowDictClass instance (Show2 p, Show2 (PrimOf p)) => Show2 (RebaseItem p) where showDict2 = ShowDictClass countToEdit :: FL (RebaseItem p) wX wY -> Int countToEdit NilFL = 0 countToEdit (ToEdit _ :>: ps) = 1 + countToEdit ps countToEdit (_ :>: ps) = countToEdit ps commuterRebasing :: (PrimPatchBase p, Commute p, Invert p, FromPrim p, Effect p) => D.DiffAlgorithm -> CommuteFn p p -> CommuteFn (Rebasing p) (Rebasing p) commuterRebasing _ commuter (Normal p :> Normal q) = do q' :> p' <- commuter (p :> q) return (Normal q' :> Normal p') -- Two rebases in sequence must have the same starting context, -- so they should trivially commute. -- This case shouldn't actually happen since each repo only has -- a single Suspended patch. commuterRebasing _ _ (p@(Suspended _) :> q@(Suspended _)) = return (q :> p) commuterRebasing da _ (Normal p :> Suspended qs) = return (unseal Suspended (addFixup da p qs) :> Normal p) commuterRebasing da _ (Suspended ps :> Normal q) = return (Normal q :> unseal Suspended (addFixup da (invert q) ps)) instance (PrimPatchBase p, FromPrim p, Effect p, Invert p, Commute p) => Commute (Rebasing p) where commute = commuterRebasing D.MyersDiff commute instance (PrimPatchBase p, FromPrim p, Effect p, Commute p) => NameHack (Rebasing p) where nameHack da = Just (pushIn . AddName, pushIn . DelName) where pushIn :: RebaseName p wX wX -> FL (Rebasing p) wX wY -> FL (Rebasing p) wX wY pushIn n (Suspended ps :>: NilFL) = unseal (\qs -> Suspended qs :>: NilFL) (simplifyPush da (NameFixup n) ps) pushIn _ ps = ps instance (PrimPatchBase p, FromPrim p, Effect p, Invert p, Commute p, CommuteNoConflicts p) => CommuteNoConflicts (Rebasing p) where commuteNoConflicts = commuterRebasing D.MyersDiff commuteNoConflicts instance (PrimPatchBase p, FromPrim p, Effect p, Invert p, Merge p) => Merge (Rebasing p) where merge (Normal p :\/: Normal q) = case merge (p :\/: q) of q' :/\: p' -> Normal q' :/\: Normal p' merge (p@(Suspended _) :\/: q@(Suspended _)) = q :/\: p merge (Normal p :\/: Suspended qs) = unseal Suspended (addFixup D.MyersDiff (invert p) qs) :/\: Normal p merge (Suspended ps :\/: Normal q) = Normal q :/\: unseal Suspended (addFixup D.MyersDiff (invert q) ps) instance (PrimPatchBase p, PatchInspect p) => PatchInspect (Rebasing p) where listTouchedFiles (Normal p) = listTouchedFiles p listTouchedFiles (Suspended ps) = concat $ mapFL ltfItem ps where ltfItem :: RebaseItem p wX wY -> [FilePath] ltfItem (ToEdit q) = listTouchedFiles q ltfItem (Fixup (PrimFixup q)) = listTouchedFiles q ltfItem (Fixup (NameFixup _)) = [] hunkMatches f (Normal p) = hunkMatches f p hunkMatches f (Suspended ps) = or $ mapFL hmItem ps where hmItem :: RebaseItem p wA wB -> Bool hmItem (ToEdit q) = hunkMatches f q hmItem (Fixup (PrimFixup q)) = hunkMatches f q hmItem (Fixup (NameFixup _)) = False instance Invert p => Invert (Rebasing p) where invert (Normal p) = Normal (invert p) invert (Suspended ps) = Suspended ps -- TODO is this sensible? instance Effect p => Effect (Rebasing p) where effect (Normal p) = effect p effect (Suspended _) = NilFL instance (PrimPatchBase p, PatchListFormat p, Patchy p, FromPrim p, Conflict p, Effect p, CommuteNoConflicts p, IsHunk p) => Patchy (Rebasing p) instance PatchDebug p => PatchDebug (Rebasing p) instance ( PrimPatchBase p, PatchListFormat p, Patchy p , FromPrim p, Conflict p, Effect p , PatchInspect p , CommuteNoConflicts p, IsHunk p ) => Matchable (Rebasing p) instance (Conflict p, FromPrim p, Effect p, Invert p, Commute p) => Conflict (Rebasing p) where resolveConflicts (Normal p) = resolveConflicts p resolveConflicts (Suspended _) = [] instance Apply p => Apply (Rebasing p) where type ApplyState (Rebasing p) = ApplyState p apply (Normal p) = apply p apply (Suspended _) = return () instance (PrimPatchBase p, PatchListFormat p, ShowPatchBasic p) => ShowPatchBasic (Rebasing p) where showPatch (Normal p) = showPatch p showPatch (Suspended ps) = blueText "rebase" <+> text "0.0" <+> blueText "{" $$ vcat (mapFL showPatch ps) $$ blueText "}" instance (PrimPatchBase p, PatchListFormat p, Apply p, CommuteNoConflicts p, Conflict p, IsHunk p, ShowPatch p) => ShowPatch (Rebasing p) where summary (Normal p) = summary p summary (Suspended ps) = summaryFL ps summaryFL ps = vcat (mapFL summary ps) -- TODO sort out summaries properly, considering expected conflicts instance (PrimPatchBase p, PatchListFormat p, ShowPatchBasic p) => ShowPatchBasic (RebaseItem p) where showPatch (ToEdit p) = blueText "rebase-toedit" <+> blueText "(" $$ showPatch p $$ blueText ")" showPatch (Fixup (PrimFixup p)) = blueText "rebase-fixup" <+> blueText "(" $$ showPatch p $$ blueText ")" showPatch (Fixup (NameFixup p)) = blueText "rebase-name" <+> blueText "(" $$ showPatch p $$ blueText ")" instance (PrimPatchBase p, PatchListFormat p, Apply p, CommuteNoConflicts p, Conflict p, IsHunk p, ShowPatch p) => ShowPatch (RebaseItem p) where summary (ToEdit p) = summary p summary (Fixup (PrimFixup p)) = summary p summary (Fixup (NameFixup n)) = summary n summaryFL ps = vcat (mapFL summary ps) -- TODO sort out summaries properly, considering expected conflicts instance (PrimPatchBase p, PatchListFormat p, ReadPatch p) => ReadPatch (RebaseItem p) where readPatch' = mapSeal ToEdit <$> readWith (BC.pack "rebase-toedit") <|> mapSeal (Fixup . PrimFixup) <$> readWith (BC.pack "rebase-fixup" ) <|> mapSeal (Fixup . NameFixup) <$> readWith (BC.pack "rebase-name" ) where readWith :: forall m q wX . (ParserM m, ReadPatch q) => B.ByteString -> m (Sealed (q wX)) readWith str = do lexString str lexString (BC.pack "(") res <- readPatch' lexString (BC.pack ")") return res instance PrimPatchBase p => PrimPatchBase (Rebasing p) where type PrimOf (Rebasing p) = PrimOf p instance (PrimPatchBase p, PatchListFormat p, ReadPatch p) => ReadPatch (Rebasing p) where readPatch' = do lexString (BC.pack "rebase") version <- myLex' when (version /= BC.pack "0.0") $ error $ "can't handle rebase version " ++ show version (lexString (BC.pack "{}") >> return (seal (Suspended NilFL))) <|> (unseal (Sealed . Suspended) <$> bracketedFL readPatch' '{' '}') <|> mapSeal Normal <$> readPatch' instance IsHunk p => IsHunk (Rebasing p) where isHunk (Normal p) = isHunk p isHunk (Suspended _) = Nothing instance FromPrim p => FromPrim (Rebasing p) where fromPrim p = Normal (fromPrim p) instance Check p => Check (Rebasing p) where isInconsistent (Normal p) = isInconsistent p isInconsistent (Suspended ps) = case catMaybes (mapFL isInconsistent ps) of [] -> Nothing xs -> Just (vcat xs) instance Check p => Check (RebaseItem p) where isInconsistent (Fixup _) = Nothing isInconsistent (ToEdit p) = isInconsistent p instance RepairToFL p => RepairToFL (Rebasing p) where applyAndTryToFixFL (Normal p) = fmap (second $ mapFL_FL Normal) <$> applyAndTryToFixFL p -- TODO: ideally we would apply ps in a sandbox to check the individual patches -- are consistent with each other. applyAndTryToFixFL (Suspended ps) = return . fmap (unlines *** ((:>: NilFL) . Suspended)) $ repairInternal ps -- Just repair the internals of the patch, without applying it to anything -- or checking against an external context. -- Included for the internal implementation of applyAndTryToFixFL for Rebasing, -- consider either generalising it for use everywhere, or removing once -- the implementation works in a sandbox and thus can use the "full" Repair on the -- contained patches. class RepairInternalFL p where repairInternalFL :: p wX wY -> Maybe ([String], FL p wX wY) class RepairInternal p where repairInternal :: p wX wY -> Maybe ([String], p wX wY) instance RepairInternalFL p => RepairInternal (FL p) where repairInternal NilFL = Nothing repairInternal (x :>: ys) = case (repairInternalFL x, repairInternal ys) of (Nothing , Nothing) -> Nothing (Just (e, rxs), Nothing) -> Just (e , rxs +>+ ys ) (Nothing , Just (e', rys)) -> Just (e' , x :>: rys) (Just (e, rxs), Just (e', rys)) -> Just (e ++ e', rxs +>+ rys) instance RepairInternalFL (RebaseItem p) where repairInternalFL (ToEdit _) = Nothing repairInternalFL (Fixup p) = fmap (second $ mapFL_FL Fixup) $ repairInternalFL p instance RepairInternalFL (RebaseFixup p) where repairInternalFL (PrimFixup _) = Nothing repairInternalFL (NameFixup _) = Nothing instance PatchListFormat p => PatchListFormat (Rebasing p) where patchListFormat = copyListFormat (patchListFormat :: ListFormat p) instance RepoPatch p => RepoPatch (Rebasing p) instance (Commute p, PrimPatchBase p, FromPrim p, Effect p) => RecontextRebase (Rebasing p) where recontextRebase = Just (RecontextRebase1 recontext) where recontext :: forall wY wZ . Named (Rebasing p) wY wZ -> (EqCheck wY wZ, RecontextRebase2 (Rebasing p) wY wZ) recontext (patchcontents -> (Suspended ps :>: NilFL)) = (IsEq, RecontextRebase2 (\fixups -> unseal mkSuspended(simplifyPushes D.MyersDiff (mapFL_FL translateFixup fixups) ps))) recontext _ = (NotEq, bug "trying to recontext rebase without rebase patch at head") translateFixup :: RebaseFixup (Rebasing p) wX wY -> RebaseFixup p wX wY translateFixup (PrimFixup p) = PrimFixup p translateFixup (NameFixup n) = NameFixup (translateName n) translateName :: RebaseName (Rebasing p) wX wY -> RebaseName p wX wY translateName (AddName name) = AddName name translateName (DelName name) = DelName name translateName (Rename old new) = Rename old new instance MaybeInternal (Rebasing p) where patchInternalChecker = Just (InternalChecker rebaseIsInternal) where rebaseIsInternal :: FL (Rebasing p) wX wY -> EqCheck wX wY rebaseIsInternal (Suspended _ :>: NilFL) = IsEq rebaseIsInternal _ = NotEq addFixup :: (PrimPatchBase p, Commute p, FromPrim p, Effect p) => D.DiffAlgorithm -> p wX wY -> FL (RebaseItem p) wY wZ -> Sealed (FL (RebaseItem p) wX) addFixup da p = simplifyPushes da (mapFL_FL PrimFixup (effect p)) canonizeNamePair :: (RebaseName p :> RebaseName p) wX wY -> FL (RebaseName p) wX wY canonizeNamePair (AddName n :> Rename old new) | n == old = AddName new :>: NilFL canonizeNamePair (Rename old new :> DelName n) | n == new = DelName old :>: NilFL canonizeNamePair (Rename old1 new1 :> Rename old2 new2) | new1 == old2 = Rename old1 new2 :>: NilFL canonizeNamePair (n1 :> n2) = n1 :>: n2 :>: NilFL -- |Given a list of rebase items, try to push a new fixup as far as possible into -- the list as possible, using both commutation and coalescing. If the fixup -- commutes past all the 'ToEdit' patches then it is dropped entirely. simplifyPush :: (PrimPatchBase p, Commute p, FromPrim p, Effect p) => D.DiffAlgorithm -> RebaseFixup p wX wY -> FL (RebaseItem p) wY wZ -> Sealed (FL (RebaseItem p) wX) simplifyPush _ _f NilFL = Sealed NilFL simplifyPush da (PrimFixup f1) (Fixup (PrimFixup f2) :>: ps) | IsEq <- isInverse = Sealed ps | otherwise = case commute (f1 :> f2) of Nothing -> Sealed (mapFL_FL (Fixup . PrimFixup) (canonizeFL da (f1 :>: f2 :>: NilFL)) +>+ ps) Just (f2' :> f1') -> mapSeal (Fixup (PrimFixup f2') :>:) (simplifyPush da (PrimFixup f1') ps) where isInverse = invert f1 =\/= f2 simplifyPush da (PrimFixup f) (Fixup (NameFixup n) :>: ps) = case commutePrimName (f :> n) of n' :> f' -> mapSeal (Fixup (NameFixup n') :>:) (simplifyPush da (PrimFixup f') ps) simplifyPush da (PrimFixup f) (ToEdit e :>: ps) = case commuterIdNamed selfCommuter (fromPrim f :> e) of Nothing -> Sealed (Fixup (PrimFixup f) :>: ToEdit e :>: ps) Just (e' :> f') -> mapSeal (ToEdit e' :>:) (simplifyPushes da (mapFL_FL PrimFixup (effect f')) ps) simplifyPush da (NameFixup n1) (Fixup (NameFixup n2) :>: ps) | IsEq <- isInverse = Sealed ps | otherwise = case commute (n1 :> n2) of Nothing -> Sealed (mapFL_FL (Fixup . NameFixup) (canonizeNamePair (n1 :> n2)) +>+ ps) Just (n2' :> n1') -> mapSeal (Fixup (NameFixup n2') :>:) (simplifyPush da (NameFixup n1') ps) where isInverse = invert n1 =\/= n2 simplifyPush da (NameFixup n) (Fixup (PrimFixup f) :>: ps) = case commuteNamePrim (n :> f) of f' :> n' -> mapSeal (Fixup (PrimFixup f') :>:) (simplifyPush da (NameFixup n') ps) simplifyPush da (NameFixup (AddName an)) (p@(ToEdit (NamedP pn deps _)) :>: ps) | an == pn = impossible | an `elem` deps = Sealed (Fixup (NameFixup (AddName an)) :>: p :>: ps) | otherwise = mapSeal (unsafeCoerceP p :>:) (simplifyPush da (NameFixup (AddName an)) ps) simplifyPush da (NameFixup (DelName dn)) (p@(ToEdit (NamedP pn deps _)) :>: ps) -- this case can arise if a patch is suspended then a fresh copy is pulled from another repo | dn == pn = Sealed (Fixup (NameFixup (DelName dn)) :>: p :>: ps) | dn `elem` deps = impossible | otherwise = mapSeal (unsafeCoerceP p :>:) (simplifyPush da (NameFixup (DelName dn)) ps) simplifyPush da (NameFixup (Rename old new)) (p@(ToEdit (NamedP pn deps body)) :>: ps) | old == pn = impossible | new == pn = impossible | old `elem` deps = impossible | new `elem` deps = let newdeps = map (\dep -> if new == dep then old else dep) deps in mapSeal (ToEdit (NamedP pn newdeps (unsafeCoerceP body)) :>:) (simplifyPush da (NameFixup (Rename old new)) ps) | otherwise = mapSeal (unsafeCoerceP p :>:) (simplifyPush da (NameFixup (Rename old new)) ps) -- |Like 'simplifyPush' but for a list of fixups. simplifyPushes :: (PrimPatchBase p, Commute p, FromPrim p, Effect p) => D.DiffAlgorithm -> FL (RebaseFixup p) wX wY -> FL (RebaseItem p) wY wZ -> Sealed (FL (RebaseItem p) wX) simplifyPushes _ NilFL ps = Sealed ps simplifyPushes da (f :>: fs) ps = unseal (simplifyPush da f) (simplifyPushes da fs ps) mkSuspended :: FL (RebaseItem p) wX wY -> IO (Named (Rebasing p) wX wX) mkSuspended ps = do let name = "DO NOT TOUCH: Rebase patch" let desc = formatParas 72 ["This patch is an internal implementation detail of rebase, used to store suspended patches, " ++ "and should not be visible in the user interface. Please report a bug if a darcs " ++ "command is showing you this patch."] date <- getIsoDateTime let author = "Invalid <invalid@invalid>" namepatch date name author desc (Suspended ps :>: NilFL) -- |given the repository contents, get the rebase container patch, and its contents -- The rebase patch can be anywhere in the repository and is returned without being -- commuted to the end. takeAnyRebase :: PatchSet (Rebasing p) wA wB -> (Sealed2 (PatchInfoAnd (Rebasing p)), Sealed2 (FL (RebaseItem p))) takeAnyRebase (PatchSet NilRL _) = -- it should never be behind a tag so we can stop now error "internal error: no suspended patch found" takeAnyRebase (PatchSet (p :<: ps) pss) | Suspended rs :>: NilFL <- patchcontents (hopefully p) = (Sealed2 p, Sealed2 rs) | otherwise = takeAnyRebase (PatchSet ps pss) -- |given the repository contents, get the rebase container patch, its contents, and the -- rest of the repository contents. Commutes the patch to the end of the repository -- if necessary. The rebase patch must be at the head of the repository. takeAnyRebaseAndTrailingPatches :: PatchSet (Rebasing p) wA wB -> FlippedSeal (PatchInfoAnd (Rebasing p) :> RL (PatchInfoAnd (Rebasing p))) wB takeAnyRebaseAndTrailingPatches (PatchSet NilRL _) = -- it should never be behind a tag so we can stop now error "internal error: no suspended patch found" takeAnyRebaseAndTrailingPatches (PatchSet (p :<: ps) pss) | Suspended _ :>: NilFL <- patchcontents (hopefully p) = FlippedSeal (p :> NilRL) | otherwise = case takeAnyRebaseAndTrailingPatches (PatchSet ps pss) of FlippedSeal (r :> ps') -> FlippedSeal (r :> (p :<: ps')) -- |given the repository contents, get the rebase container patch, its contents, and the -- rest of the repository contents. The rebase patch must be at the head of the repository. takeHeadRebase :: PatchSet (Rebasing p) wA wB -> (PatchInfoAnd (Rebasing p) wB wB, Sealed (FL (RebaseItem p) wB), PatchSet (Rebasing p) wA wB) takeHeadRebase (PatchSet NilRL _) = error "internal error: must have a rebase container patch at end of repository" takeHeadRebase (PatchSet (p :<: ps) pss) | Suspended rs :>: NilFL <- patchcontents (hopefully p) = (p, Sealed rs, PatchSet ps pss) | otherwise = error "internal error: must have a rebase container patch at end of repository" takeHeadRebaseRL :: RL (PatchInfoAnd (Rebasing p)) wA wB -> (PatchInfoAnd (Rebasing p) wB wB, Sealed (FL (RebaseItem p) wB), RL (PatchInfoAnd (Rebasing p)) wA wB) takeHeadRebaseRL NilRL = error "internal error: must have a suspended patch at end of repository" takeHeadRebaseRL (p :<: ps) | Suspended rs :>: NilFL <- patchcontents (hopefully p) = (p, Sealed rs, ps) | otherwise = error "internal error: must have a suspended patch at end of repository" takeHeadRebaseFL :: FL (PatchInfoAnd (Rebasing p)) wA wB -> (PatchInfoAnd (Rebasing p) wB wB, Sealed (FL (RebaseItem p) wB), FL (PatchInfoAnd (Rebasing p)) wA wB) takeHeadRebaseFL ps = let (a, b, c) = takeHeadRebaseRL (reverseFL ps) in (a, b, reverseRL c)
DavidAlphaFox/darcs
src/Darcs/Patch/Rebase.hs
gpl-2.0
26,538
0
17
5,886
7,811
4,022
3,789
-1
-1
import XMLTree -- PREGUNTA 2 -- tags:: XMLTree -> [Tag] tags (Fulla t _) = [t] tags (Node t _ (x:xs)) = (t:(concat (map tags (x:xs)))) -- PREGUNTA 3 -- type Condicio = (Atribut, (Valor -> Bool)) selectFW:: [Tag] -> (Tag,Condicio) -> XMLTree -> XMLTree selectFW l c a = (Node "resultat" (LParells []) (selectFW0 l c a)) selectFW0:: [Tag] -> (Tag,Condicio) -> XMLTree -> [XMLTree] selectFW0 _ _ (Fulla _ _) = [] selectFW0 _ _ (Node _ _ []) = [] selectFW0 l (s,(a,c)) (Node t (LParells set) sons) = if ((t == s) && (findandcheck a set c)) then (concat (map (selectFW0 l (s,(a,c))) sons) ++ selectFW1 l (Node t (LParells set) sons)) else (concat (map (selectFW0 l (s,(a,c))) sons)) selectFW1:: [Tag] -> XMLTree -> [XMLTree] selectFW1 l (Fulla t s) = if (find t l) then [(Fulla t s)] else [] selectFW1 l (Node t s sons) = (concat (map (selectFW1 l) sons)) ++ if (find t l) then [(Node t s sons)] else [] findandcheck:: Atribut -> [(Atribut,Valor)] -> (Valor->Bool)-> Bool findandcheck _ [] _ = True findandcheck a ((b,v):xs) c |a == b = (c v) |otherwise = findandcheck a xs c -- PREGUNTA 4 -- type DeweyPos = [Int] afegeixr:: XMLTree -> DeweyPos -> XMLTree -> XMLTree afegeixr (Node t s l) [a] xml = (Node t s (b ++ [xml] ++ e)) where b = (take a l) e = (drop a l) afegeixr (Node t s l) (x:xs) xml = (Node t s (b ++ [mid] ++ e)) where b = (take (x-1) l) e = (drop x l) mid = (afegeixr (nth x l) xs xml) afegeixl:: XMLTree -> DeweyPos -> XMLTree -> XMLTree afegeixl (Node t s l) [a] xml = (Node t s (b ++ [xml] ++ e)) where b = (take (a-1) l) e = (drop (a-1) l) afegeixl (Node t s l) (x:xs) xml = (Node t s (b ++ [mid] ++ e)) where b = (take (x-1) l) e = (drop x l) mid = (afegeixl (nth x l) xs xml) nth:: Int->[XMLTree]->XMLTree nth 1 (x:xs) = x nth y (x:xs) = (nth (y-1) (xs))
marccomino/Small_Programs_in_Haskell
Practica1/XMLops.hs
gpl-3.0
1,908
12
14
495
1,176
632
544
45
3
{- This file is part of HNH. HNH 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. HNH 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 HNH. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Francisco Ferreira -} module TransformMonad ( TransformM ,transformOk ,transformError ,runTransform ,nullTransform ,renderSteps ) where import ErrorMonad(ErrorM(..)) import Text.PrettyPrint.Leijen data TransformM a = TaM [(String, Doc)] (ErrorM a) runTransform :: TransformM a -> (ErrorM a, [(String , Doc)]) runTransform (TaM l r) = (r, l) transformOk :: Pretty a => String -> a -> TransformM a transformOk s a = (TaM [(s, pretty a)] (Success a)) transformError :: String -> TransformM a transformError s = (TaM [(s, empty)] (Error s)) instance Monad TransformM where return t = (TaM [] (Success t)) (TaM l (Success t)) >>= k = (TaM (l++l') t') where (TaM l' t') = k t (TaM l (Error s)) >>= k = (TaM l (Error s)) fail msg = TaM [] (Error msg) nullTransform ::Pretty a => a -> TransformM a nullTransform = transformOk "nullTransform" renderSteps :: [(String, Doc)] -> Doc renderSteps steps = let (titles, docs) = unzip steps titleDocs = map (\s -> line <> pretty ">>>" <+> pretty s <+> pretty "phase:" <> line) titles result = vsep $ combine titleDocs docs epigraph = pretty "Number of phases:" <> pretty ((length docs) - 1) in result <> line <> epigraph combine :: [Doc] -> [Doc] -> [Doc] combine (a:as) (b:bs) = a:b:(combine as bs) combine [] b = b combine a [] = a
fferreira/hnh
TransformMonad.hs
gpl-3.0
2,148
0
16
579
628
331
297
40
1
{-# LANGUAGE TemplateHaskell #-} module Utils.Yukari.Settings where import Control.Lens import Data.List (isPrefixOf) import Utils.Yukari.Types data YukariSettings = YukariSettings { _siteSettings :: SiteSettings , _spendSettings :: SpendSettings , _programSettings :: [ProgramSettings] , _logVerbosity :: Verbosity , _connectionRetries :: Integer , _maxPages :: Integer } data SiteSettings = SiteSettings { _username :: String , _password :: String , _baseSite :: String , _loginSite :: String , _searchSite :: String , _topWatch :: Maybe FilePath , _watchFunc :: Category -> Maybe FilePath , _filterFunc :: ABTorrent -> Bool , _groupFilterFunc :: ABTorrentGroup -> Bool , _clobberFiles :: Bool , _groupPreprocessor :: ABTorrentGroup -> ABTorrentGroup } data SpendSettings = SpendSettings { _yenSite :: String , _yenLeftOver :: Integer } data ProgramSettings = DryRun | SpendYen | DownloadTorrents deriving (Show, Eq) data Verbosity = Quiet | Low | High | Debug deriving (Show, Eq, Ord) makeLenses ''YukariSettings makeLenses ''SiteSettings makeLenses ''SpendSettings minimalSettings :: String -> String -> String -> SiteSettings minimalSettings u p l = SiteSettings { _username = u , _password = p , _baseSite = "" , _loginSite = l , _searchSite = "" , _topWatch = Nothing , _watchFunc = const Nothing , _groupFilterFunc = const True , _filterFunc = const True , _clobberFiles = False , _groupPreprocessor = id } -- | Some defaults for the current AnimeBytes site animebytesSettings :: YukariSettings animebytesSettings = YukariSettings { _siteSettings = abSiteSettings , _spendSettings = abSpendSettings , _programSettings = [] , _logVerbosity = Low , _connectionRetries = 3 , _maxPages = 10 } abSiteSettings :: SiteSettings abSiteSettings = SiteSettings { _username = "" , _password = "" , _baseSite = "https://animebytes.tv" , _loginSite = "https://animebytes.tv/login.php" , _searchSite = "https://animebytes.tv/torrents.php" , _topWatch = Nothing , _watchFunc = const Nothing , _groupFilterFunc = const True , _filterFunc = const False , _clobberFiles = False , _groupPreprocessor = fixImageLinks } where -- Images nowadays seem to start with this weird link that can't be accessed -- from a browser unless we're on the page already and directly click on it. -- We fix that here. fixImageLinks :: ABTorrentGroup -> ABTorrentGroup fixImageLinks = torrentImageURI %~ \i -> if "//" `isPrefixOf` i then "https:" ++ i else i abSpendSettings :: SpendSettings abSpendSettings = SpendSettings { _yenSite = "https://animebytes.tv/konbini.php" , _yenLeftOver = 0 }
Fuuzetsu/yukari
src/Utils/Yukari/Settings.hs
gpl-3.0
3,942
0
10
1,754
588
356
232
72
2
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, DataKinds #-} module Modernator.App where import Modernator.Types import Modernator.Commands import Modernator.API import Network.Wai (Application) import Data.Acid import Servant import Servant.Server.Experimental.Auth import Servant.Server.Experimental.Auth.Cookie import Crypto.Random (drgNew) import Data.Default (def) import Modernator.Cookies import Network.Wai (Request) import Control.Concurrent.STM.TVar (newTVarIO, TVar) import qualified Data.IxSet as IxSet import System.Directory (doesFileExist) import qualified Data.ByteString as BS import Data.Maybe (fromMaybe) -- | Serve our app app :: RandomSource -> ServerKey -> AcidState App -> TVar SessionChannelDB -> Application app rng uKey state sessionChannelDB = serveWithContext api (appContext uKey) (server rng uKey userSettings state sessionChannelDB) -- | Set up our application potentially with a path to the application state. mkApp :: Maybe FilePath -> FilePath -> IO Application mkApp Nothing keyDir = openLocalState emptyApp >>= commonAppSetup keyDir mkApp (Just path) keyDir = openLocalStateFrom path emptyApp >>= commonAppSetup keyDir boolToMaybe True = Just () boolToMaybe False = Nothing getKeys :: FilePath -> IO ServerKey getKeys keyDir = do userKeyM <- getKeyFromFile userPath uKey <- fromMaybe <$> mkServerKey 16 Nothing <*> pure userKeyM writeKey uKey userPath return (uKey) where userPath = keyDir ++ "user.key" writeKey key path = getServerKey key >>= \k -> BS.writeFile path k getKeyFromFile path = do pathM <- fmap (fmap (const path) . boolToMaybe) <$> doesFileExist $ path case pathM of Just p -> Just <$> (BS.readFile p >>= \bs -> mkServerKeyFromBytes bs) Nothing -> return Nothing commonAppSetup keyDir state = do rng <- mkRandomSource drgNew 1000 (uKey) <- getKeys keyDir -- Initialize session channels for existing sessions sessionIds <- fmap (map (\ (Session id _ _ _) -> id) . IxSet.toList . sessions) $ query state GetState channels <- mapM mkSessionChannel sessionIds sessionChannelDB <- newTVarIO $ IxSet.fromList channels return $ app rng uKey state sessionChannelDB type AppContext = '[ AuthHandler Request ModernatorCookie ] appContext :: ServerKey -> Context AppContext appContext uKey = ((defaultAuthHandler userSettings uKey :: AuthHandler Request ModernatorCookie) :. EmptyContext) -- cookies are valid for 1 week -- TODO: I think it's theoretically possible to make these cookies only -- valid for specific session ids, since the session id is in the URL. -- This will easily allow users to be authed to multiple sessions. -- TODO: Should also have SecureOnly flag, but without https on localhost cookies won't be set userSettings = def { acsCookieFlags = ["HttpOnly"], acsSessionField = "modernator", acsMaxAge = fromIntegral (3600 * 24 * 365 :: Integer) }
mojotech/modernator-haskell
src/Modernator/App.hs
gpl-3.0
2,930
0
17
509
744
387
357
53
2
{-# LANGUAGE CPP #-} module TickerTimeSerie ( TimeSerie (..) , DataItem (..) , TimeItem (..) , mkSineTimeSerie , showTime ) where #ifdef FAY import Prelude #endif -- | Data structure for the time serie data. The time serie will be -- rendered "as is", it's the server's responsibility to ensure the -- format of the time serie data TimeSerie = TimeSerie Double ([DataItem], [TimeItem]) deriving Show data DataItem = DataItem Int Double deriving Show data TimeItem = TimeItem Int Int deriving Show -- | Make a dummy - sine wave - time serie mkSineTimeSerie :: Int -> Int -> Double -> TimeSerie mkSineTimeSerie num start mx = let ns = [0 .. num-1] d = map mkItem ns t = [mkTime n | n <- ns, isMod5 (n+start)] in TimeSerie mx (d, t) where mkItem n = DataItem n $ mkValue (n+start) mkValue n = (1 + sin (freq * rad * fromIntegral n)) * (mx/2) mkTime n = TimeItem n (n+start) isMod5 n = n `mod` 5 == 0 rad = (2*pi)/fromIntegral num freq = 2 -- | Convert a number of seconds to format "hh:mm:ss" showTime :: Int -> String showTime duration = let sec = wrappedDuration `mod` secPerMin min' = (wrappedDuration `div` secPerMin) `mod` minPerHour hrs = wrappedDuration `div` secPerHour in asStr hrs ++ ":" ++ asStr min' ++ ":" ++ asStr sec where asStr n | n < 10 = '0':show n | otherwise = show n wrappedDuration = duration `mod` (100 * secPerHour) secPerMin = 60 minPerHour = 60 secPerHour = secPerMin * minPerHour
SneakingCat/fay-ticker
src/TickerTimeSerie.hs
gpl-3.0
1,638
0
13
492
500
275
225
40
1
module Hadolint.Rule.DL3037 (rule) where import qualified Data.Text as Text import Hadolint.Rule import qualified Hadolint.Shell as Shell import Language.Docker.Syntax rule :: Rule Shell.ParsedShell rule = simpleRule code severity message check where code = "DL3037" severity = DLWarningC message = "Specify version with `zypper install -y <package>=<version>`." check (Run (RunArgs args _)) = foldArguments (all versionFixed . zypperPackages) args check _ = True versionFixed package = "=" `Text.isInfixOf` package || ">=" `Text.isInfixOf` package || ">" `Text.isInfixOf` package || "<=" `Text.isInfixOf` package || "<" `Text.isInfixOf` package || ".rpm" `Text.isSuffixOf` package {-# INLINEABLE rule #-} zypperPackages :: Shell.ParsedShell -> [Text.Text] zypperPackages args = [ arg | cmd <- Shell.presentCommands args, Shell.cmdHasArgs "zypper" ["install", "in"] cmd, arg <- Shell.getArgsNoFlags cmd, arg /= "install", arg /= "in" ]
lukasmartinelli/hadolint
src/Hadolint/Rule/DL3037.hs
gpl-3.0
1,017
0
17
203
290
161
129
22
2
{-# LANGUAGE OverloadedStrings #-} -- Module : Main -- Copyright : (c) 2014-2015 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) module Main (main) where import Criterion import Criterion.Main import Data.List (sort) import Data.SemVer import Data.Text (Text, pack) import Data.Version (showVersion, parseVersion) import qualified Data.Version as Ver import Text.ParserCombinators.ReadP main :: IO () main = defaultMain [ bgroup "decoding" [ bgroup "semver" [ bgroup "fromText . pack" [ bench "1.2.3" $ nf (sv . pack) "1.2.3" , bench "1.2.3-alpha" $ nf (sv . pack) "1.2.3-alpha" , bench "1.2.3-alpha.1" $ nf (sv . pack) "1.2.3-alpha.1" , bench "1.2.3+123" $ nf (sv . pack) "1.2.3+123" , bench "1.2.3+sha.2ac" $ nf (sv . pack) "1.2.3+sha.2ac" , bench "1.2.3-beta.1+sha.exp.dc2" $ nf (sv . pack) "1.2.3-beta.1+sha.exp.dc2" ] ] , bgroup "version" [ bgroup "parseVersion" [ bench "1.2.3" $ nf dv "1.2.3" , bench "1.2.3-alpha" $ nf dv "1.2.3-alpha" , bench "1.2.3-alpha.1" $ nf dv "1.2.3-alpha.1" , bench "1.2.3+123" $ nf dv "1.2.3+123" , bench "1.2.3+sha.2ac" $ nf dv "1.2.3+sha.2ac" , bench "1.2.3-beta.1+sha.exp.dc2" $ nf dv "1.2.3-beta.1+sha.exp.dc2" ] ] ] , bgroup "encoding" [ bgroup "semver" [ bgroup "toLazyText" [ bench "1.2.3" $ nf toLazyText sv123 , bench "1.2.3-alpha" $ nf toLazyText sv123alpha , bench "1.2.3-alpha.1" $ nf toLazyText sv123alpha1 , bench "1.2.3+123" $ nf toLazyText sv123123 , bench "1.2.3+sha.2ac" $ nf toLazyText sv123sha2ac , bench "1.2.3-beta.1+sha.exp.dc2" $ nf toLazyText sv123beta1shaexpdc2 ] , bgroup "toString" [ bench "1.2.3" $ nf toString sv123 , bench "1.2.3-alpha" $ nf toString sv123alpha , bench "1.2.3-alpha.1" $ nf toString sv123alpha1 , bench "1.2.3+123" $ nf toString sv123123 , bench "1.2.3+sha.2ac" $ nf toString sv123sha2ac , bench "1.2.3-beta.1+sha.exp.dc2" $ nf toString sv123beta1shaexpdc2 ] ] , bgroup "version" [ bgroup "showVersion" [ bench "1.2.3" $ nf showVersion dv123 , bench "1.2.3-alpha" $ nf showVersion dv123alpha , bench "1.2.3-alpha.1" $ nf showVersion dv123alpha1 , bench "1.2.3+123" $ nf showVersion dv123123 , bench "1.2.3+sha.2ac" $ nf showVersion dv123sha2ac , bench "1.2.3-beta.1+sha.exp.dc2" $ nf showVersion dv123beta1shaexpdc2 ] ] ] , bgroup "sort" [ bench "semver" $ nf sort [ sv123 , sv123alpha , sv123alpha1 , sv123123 , sv123sha2ac , sv123beta1shaexpdc2 ] , bench "version" $ nf sort [ dv123 , dv123alpha , dv123alpha1 , dv123123 , dv123sha2ac , dv123beta1shaexpdc2 ] ] ] sv123, sv123alpha, sv123alpha1, sv123123 :: Version sv123sha2ac, sv123beta1shaexpdc2 :: Version sv123 = sv "1.2.3" sv123alpha = sv "1.2.3-alpha" sv123alpha1 = sv "1.2.3-alpha.1" sv123123 = sv "1.2.3+123" sv123sha2ac = sv "1.2.3+sha.2ac" sv123beta1shaexpdc2 = sv "1.2.3-beta.1+sha.exp.dc2" dv123, dv123alpha, dv123alpha1, dv123123 :: Ver.Version dv123sha2ac, dv123beta1shaexpdc2 :: Ver.Version dv123 = dv "1.2.3" dv123alpha = dv "1.2.3-alpha" dv123alpha1 = dv "1.2.3-alpha.1" dv123123 = dv "1.2.3+123" dv123sha2ac = dv "1.2.3+sha.2ac" dv123beta1shaexpdc2 = dv "1.2.3-beta.1+sha.exp.dc2" sv :: Text -> Version sv t = case fromText t of Left e -> error e Right x -> x dv :: String -> Ver.Version dv = fst . last . readP_to_S parseVersion
brendanhay/semver
bench/Main.hs
mpl-2.0
5,368
0
16
2,376
962
498
464
120
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.CloudSearch.Indexing.Datasources.Items.Push -- 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) -- -- Pushes an item onto a queue for later polling and updating. This API -- requires an admin or service account to execute. The service account -- used is the one whitelisted in the corresponding data source. -- -- /See:/ <https://developers.google.com/cloud-search/docs/guides/ Cloud Search API Reference> for @cloudsearch.indexing.datasources.items.push@. module Network.Google.Resource.CloudSearch.Indexing.Datasources.Items.Push ( -- * REST Resource IndexingDatasourcesItemsPushResource -- * Creating a Request , indexingDatasourcesItemsPush , IndexingDatasourcesItemsPush -- * Request Lenses , idipXgafv , idipUploadProtocol , idipAccessToken , idipUploadType , idipPayload , idipName , idipCallback ) where import Network.Google.CloudSearch.Types import Network.Google.Prelude -- | A resource alias for @cloudsearch.indexing.datasources.items.push@ method which the -- 'IndexingDatasourcesItemsPush' request conforms to. type IndexingDatasourcesItemsPushResource = "v1" :> "indexing" :> CaptureMode "name" "push" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] PushItemRequest :> Post '[JSON] Item -- | Pushes an item onto a queue for later polling and updating. This API -- requires an admin or service account to execute. The service account -- used is the one whitelisted in the corresponding data source. -- -- /See:/ 'indexingDatasourcesItemsPush' smart constructor. data IndexingDatasourcesItemsPush = IndexingDatasourcesItemsPush' { _idipXgafv :: !(Maybe Xgafv) , _idipUploadProtocol :: !(Maybe Text) , _idipAccessToken :: !(Maybe Text) , _idipUploadType :: !(Maybe Text) , _idipPayload :: !PushItemRequest , _idipName :: !Text , _idipCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'IndexingDatasourcesItemsPush' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'idipXgafv' -- -- * 'idipUploadProtocol' -- -- * 'idipAccessToken' -- -- * 'idipUploadType' -- -- * 'idipPayload' -- -- * 'idipName' -- -- * 'idipCallback' indexingDatasourcesItemsPush :: PushItemRequest -- ^ 'idipPayload' -> Text -- ^ 'idipName' -> IndexingDatasourcesItemsPush indexingDatasourcesItemsPush pIdipPayload_ pIdipName_ = IndexingDatasourcesItemsPush' { _idipXgafv = Nothing , _idipUploadProtocol = Nothing , _idipAccessToken = Nothing , _idipUploadType = Nothing , _idipPayload = pIdipPayload_ , _idipName = pIdipName_ , _idipCallback = Nothing } -- | V1 error format. idipXgafv :: Lens' IndexingDatasourcesItemsPush (Maybe Xgafv) idipXgafv = lens _idipXgafv (\ s a -> s{_idipXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). idipUploadProtocol :: Lens' IndexingDatasourcesItemsPush (Maybe Text) idipUploadProtocol = lens _idipUploadProtocol (\ s a -> s{_idipUploadProtocol = a}) -- | OAuth access token. idipAccessToken :: Lens' IndexingDatasourcesItemsPush (Maybe Text) idipAccessToken = lens _idipAccessToken (\ s a -> s{_idipAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). idipUploadType :: Lens' IndexingDatasourcesItemsPush (Maybe Text) idipUploadType = lens _idipUploadType (\ s a -> s{_idipUploadType = a}) -- | Multipart request metadata. idipPayload :: Lens' IndexingDatasourcesItemsPush PushItemRequest idipPayload = lens _idipPayload (\ s a -> s{_idipPayload = a}) -- | Name of the item to push into the indexing queue. Format: -- datasources\/{source_id}\/items\/{ID} This is a required field. The -- maximum length is 1536 characters. idipName :: Lens' IndexingDatasourcesItemsPush Text idipName = lens _idipName (\ s a -> s{_idipName = a}) -- | JSONP idipCallback :: Lens' IndexingDatasourcesItemsPush (Maybe Text) idipCallback = lens _idipCallback (\ s a -> s{_idipCallback = a}) instance GoogleRequest IndexingDatasourcesItemsPush where type Rs IndexingDatasourcesItemsPush = Item type Scopes IndexingDatasourcesItemsPush = '["https://www.googleapis.com/auth/cloud_search", "https://www.googleapis.com/auth/cloud_search.indexing"] requestClient IndexingDatasourcesItemsPush'{..} = go _idipName _idipXgafv _idipUploadProtocol _idipAccessToken _idipUploadType _idipCallback (Just AltJSON) _idipPayload cloudSearchService where go = buildClient (Proxy :: Proxy IndexingDatasourcesItemsPushResource) mempty
brendanhay/gogol
gogol-cloudsearch/gen/Network/Google/Resource/CloudSearch/Indexing/Datasources/Items/Push.hs
mpl-2.0
5,821
0
17
1,256
791
464
327
114
1
module Terrain where -- | only one primary terrain data PrimaryTerrain = Clear | NOGO1 -- no-go for wheeled | NOGO2 -- no-go for wheeled & tracked | NOGO3 -- no-go for vehicles & dismounts | Rough1 | Rough2 | Rough3 | Rough4 | Water deriving (Eq, Enum) instance Show PrimaryTerrain where show pt = case pt of Clear -> "Clear terrain" NOGO1 -> "No-Go for wheeled vehicles" NOGO2 -> "No-Go for wheeled and tracked vehicles" NOGO3 -> "No-Go for vehicles and dismounts" Rough1 -> "Rough terrain (light)" Rough2 -> "Rough terrain (medium)" Rough3 -> "Rough terrain (heavy)" Rough4 -> "Rough terrain (very heavy)" Water -> "No-Go for non-amphibious land units" instance Ord PrimaryTerrain where (<) a b = if null [a .. b] || a == b then False else True -- | list of secondary terrains data SecondaryTerrain = Losblock | Road | Woods | Town deriving (Eq) instance Show SecondaryTerrain where show st = case st of Losblock -> "Misc. LOS block" Road -> "Road" Woods -> "Woods" Town -> "Town" data Terrain = Terrain { trPrimary :: PrimaryTerrain, trSecondary :: [SecondaryTerrain] } deriving (Eq) instance Show Terrain where show (Terrain pt []) = show pt show (Terrain pt t) = show pt ++ " " ++ unwords (map (\x -> "+" ++ show x) t) -- convert a terrain combination to a string textOfTerrain :: Terrain -> String textOfTerrain t = primary ++ textOfSecondaryList (trSecondary t) where primary = case trPrimary t of Clear -> "cl" NOGO1 -> "n1" NOGO2 -> "n2" NOGO3 -> "n3" Rough1 -> "r1" Rough2 -> "r2" Rough3 -> "r3" Rough4 -> "r4" Water -> "wt" -- convert a list of sec. terrains to string textOfSecondaryList :: [SecondaryTerrain] -> String textOfSecondaryList [] = [] textOfSecondaryList (t:ts) = (tstr t) ++ textOfSecondaryList ts where tstr t = case t of Losblock -> "+l" Road -> "+r" Woods -> "+w" Town -> "+t"
nbrk/datmap2html
Terrain.hs
unlicense
2,506
0
13
1,019
540
288
252
61
9
module Kornel.LineHandler.Money ( setup ) where import qualified Data.Attoparsec.Text as P import Data.Char (isSpace) import qualified Data.Map as Map import Kornel.Common import Kornel.LineHandler import qualified Network.HTTP.Client.TLS as HTTPS import Network.HTTP.Simple import Prelude hiding (Handler, handle) setup :: (Help, HandlerRaw) setup = (cmdHelp, ) . onlySimple . pure $ \respond _ request -> case parseMaybe cmdParser request of Nothing -> pure () Just expr -> asyncWithLog "Money" $ money expr >>= mapM_ (respond . Privmsg) cmdParser :: P.Parser (Double, Text, [Text]) cmdParser = do P.skipSpace <* (P.asciiCI "@money" <|> P.asciiCI "@currency") amount <- skipSpace1 *> P.double from <- symb skipSpace1 <* (P.asciiCI "to" <|> P.asciiCI "in") to <- P.many1 symb P.skipSpace <* P.endOfInput pure (amount, from, to) where symb = toUpper <$> (skipSpace1 *> P.takeWhile1 (not . isSpace)) cmdHelp :: Help cmdHelp = Help [ ( ["money", "currency"] , "<amount> <from-symb> { to | in } <to-symb1>[ <to-symb2> …]") ] money :: (Double, Text, [Text]) -> IO (Maybe Text) money (amount, from, to) = do manager <- HTTPS.newTlsManager let request = setRequestManager manager . setRequestQueryString [ ("fsym", Just . encodeUtf8 $ from) , ("tsyms", Just . encodeUtf8 . intercalate "," $ to) ] $ "https://min-api.cryptocompare.com/data/price" response :: Map Text Double <- getResponseBody <$> httpJSON request pure . Just . render $ response where render :: Map Text Double -> Text render rates = tshow amount ++ " " ++ from ++ " is " ++ (intercalate ", or " . map (\(symb, rate) -> tshow (rate * amount) ++ " " ++ symb) . Map.toList $ rates) ++ "."
michalrus/kornel
src/Kornel/LineHandler/Money.hs
apache-2.0
1,941
0
20
549
624
333
291
-1
-1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} {- Copyright 2017 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Funblocks (funblockRoutes, ClientId(..)) where import Control.Monad import Control.Monad.Trans import Data.Aeson import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as LB import Data.List import Data.Maybe import qualified Data.Text as T import qualified Data.Text.Encoding as T import Network.HTTP.Conduit import Snap.Core import Snap.Util.FileServe import System.Directory import System.FilePath import Model import Util newtype ClientId = ClientId (Maybe T.Text) deriving (Eq) -- Retrieves the user for the current request. The request should have an -- id_token parameter with an id token retrieved from the Google -- authentication API. The user is returned if the id token is valid. getUser :: ClientId -> Snap User getUser clientId = getParam "id_token" >>= \ case Nothing -> pass Just id_token -> do let url = "https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=" ++ BC.unpack id_token decoded <- fmap decode $ liftIO $ simpleHttp url case decoded of Nothing -> pass Just user -> do when (clientId /= ClientId (Just (audience user))) pass return user getBuildMode :: Snap BuildMode getBuildMode = getParam "mode" >>= \ case Just "blocklyXML" -> return (BuildMode "blocklyXML") funblockRoutes :: ClientId -> [(B.ByteString, Snap ())] funblockRoutes clientId = [ ("floadProject", loadProjectHandler clientId) , ("fsaveProject", saveProjectHandler clientId) , ("fdeleteProject", deleteProjectHandler clientId) , ("flistFolder", listFolderHandler clientId) , ("fcreateFolder", createFolderHandler clientId) , ("fdeleteFolder", deleteFolderHandler clientId) , ("fshareFolder", shareFolderHandler clientId) , ("fshareContent", shareContentHandler clientId) , ("fmoveProject", moveProjectHandler clientId) , ("fsaveXMLhash", saveXMLHashHandler) , ("floadXML", loadXMLHandler) , ("blocks", serveFile "web/blocks.html") , ("funblocks", serveFile "web/blocks.html") ] createFolderHandler :: ClientId -> Snap () createFolderHandler clientId = do mode <- getBuildMode user <- getUser clientId Just path <- fmap (splitDirectories . BC.unpack) <$> getParam "path" let dirIds = map (nameToDirId . T.pack) path let finalDir = joinPath $ map dirBase dirIds liftIO $ ensureUserBaseDir mode (userId user) finalDir liftIO $ createDirectory $ userProjectDir mode (userId user) </> finalDir modifyResponse $ setContentType "text/plain" liftIO $ B.writeFile (userProjectDir mode (userId user) </> finalDir </> "dir.info") $ BC.pack $ last path deleteFolderHandler :: ClientId -> Snap () deleteFolderHandler clientId = do mode <- getBuildMode user <- getUser clientId Just path <- fmap (splitDirectories . BC.unpack) <$> getParam "path" let dirIds = map (nameToDirId . T.pack) path let finalDir = joinPath $ map dirBase dirIds liftIO $ ensureUserDir mode (userId user) finalDir let dir = userProjectDir mode (userId user) </> finalDir empty <- liftIO $ fmap (\ l1 -> length l1 == 3 && sort l1 == sort [".", "..", takeFileName dir]) (getDirectoryContents (takeDirectory dir)) liftIO $ removeDirectoryIfExists $ if empty then takeDirectory dir else dir loadProjectHandler :: ClientId -> Snap () loadProjectHandler clientId = do mode <- getBuildMode user <- getUser clientId Just name <- getParam "name" let projectName = T.decodeUtf8 name let projectId = nameToProjectId projectName Just path <- fmap (splitDirectories . BC.unpack) <$> getParam "path" let dirIds = map (nameToDirId . T.pack) path let finalDir = joinPath $ map dirBase dirIds liftIO $ ensureProjectDir mode (userId user) finalDir projectId let file = userProjectDir mode (userId user) </> finalDir </> projectFile projectId modifyResponse $ setContentType "application/json" serveFile file saveProjectHandler :: ClientId -> Snap () saveProjectHandler clientId = do mode <- getBuildMode user <- getUser clientId Just path <- fmap (splitDirectories . BC.unpack) <$> getParam "path" let dirIds = map (nameToDirId . T.pack) path let finalDir = joinPath $ map dirBase dirIds Just project <- decode . LB.fromStrict . fromJust <$> getParam "project" let projectId = nameToProjectId (projectName project) liftIO $ ensureProjectDir mode (userId user) finalDir projectId let file = userProjectDir mode (userId user) </> finalDir </> projectFile projectId liftIO $ LB.writeFile file $ encode project deleteProjectHandler :: ClientId -> Snap () deleteProjectHandler clientId = do mode <- getBuildMode user <- getUser clientId Just name <- getParam "name" let projectName = T.decodeUtf8 name let projectId = nameToProjectId projectName Just path <- fmap (splitDirectories . BC.unpack) <$> getParam "path" let dirIds = map (nameToDirId . T.pack) path let finalDir = joinPath $ map dirBase dirIds liftIO $ ensureProjectDir mode (userId user) finalDir projectId let file = userProjectDir mode (userId user) </> finalDir </> projectFile projectId empty <- liftIO $ fmap (\ l1 -> length l1 == 3 && sort l1 == sort [".", "..", takeFileName file]) (getDirectoryContents (dropFileName file)) liftIO $ if empty then removeDirectoryIfExists (dropFileName file) else removeFileIfExists file listFolderHandler :: ClientId -> Snap () listFolderHandler clientId = do mode <- getBuildMode user <- getUser clientId Just path <- fmap (splitDirectories . BC.unpack) <$> getParam "path" let dirIds = map (nameToDirId . T.pack) path let finalDir = joinPath $ map dirBase dirIds liftIO $ ensureUserBaseDir mode (userId user) finalDir liftIO $ ensureUserDir mode (userId user) finalDir liftIO $ migrateUser $ userProjectDir mode (userId user) let projectDir = userProjectDir mode (userId user) subHashedDirs <- liftIO $ listDirectoryWithPrefix $ projectDir </> finalDir files <- liftIO $ projectFileNames subHashedDirs dirs <- liftIO $ projectDirNames subHashedDirs modifyResponse $ setContentType "application/json" writeLBS (encode (Directory files dirs)) shareFolderHandler :: ClientId -> Snap () shareFolderHandler clientId = do mode <- getBuildMode user <- getUser clientId Just path <- fmap (splitDirectories . BC.unpack) <$> getParam "path" let dirIds = map (nameToDirId . T.pack) path let finalDir = joinPath $ map dirBase dirIds checkSum <- liftIO $ dirToCheckSum $ userProjectDir mode (userId user) </> finalDir liftIO $ ensureShareDir mode $ ShareId checkSum liftIO $ B.writeFile (shareRootDir mode </> shareLink (ShareId checkSum)) $ BC.pack (userProjectDir mode (userId user) </> finalDir) modifyResponse $ setContentType "text/plain" writeBS $ T.encodeUtf8 checkSum shareContentHandler :: ClientId -> Snap () shareContentHandler clientId = do mode <- getBuildMode Just shash <- getParam "shash" sharingFolder <- liftIO $ B.readFile (shareRootDir mode </> shareLink (ShareId $ T.decodeUtf8 shash)) user <- getUser clientId Just name <- getParam "name" let dirPath = dirBase $ nameToDirId $ T.decodeUtf8 name liftIO $ ensureUserBaseDir mode (userId user) dirPath liftIO $ copyDirIfExists (BC.unpack sharingFolder) $ userProjectDir mode (userId user) </> dirPath liftIO $ B.writeFile (userProjectDir mode (userId user) </> dirPath </> "dir.info") name moveProjectHandler :: ClientId -> Snap () moveProjectHandler clientId = do mode <- getBuildMode user <- getUser clientId Just moveTo <- fmap (splitDirectories . BC.unpack) <$> getParam "moveTo" let moveToDir = joinPath $ map (dirBase . nameToDirId . T.pack) moveTo Just moveFrom <- fmap (splitDirectories . BC.unpack) <$> getParam "moveFrom" let projectDir = userProjectDir mode (userId user) let moveFromDir = projectDir </> joinPath (map (dirBase . nameToDirId . T.pack) moveFrom) let parentFrom = if moveFrom == [] then [] else init moveFrom Just isFile <- getParam "isFile" case (moveTo == moveFrom, moveTo == parentFrom, isFile) of (False, _, "true") -> do Just name <- getParam "name" let projectId = nameToProjectId $ T.decodeUtf8 name file = moveFromDir </> projectFile projectId toFile = projectDir </> moveToDir </> projectFile projectId liftIO $ ensureProjectDir mode (userId user) moveToDir projectId liftIO $ copyFile file toFile empty <- liftIO $ fmap (\ l1 -> length l1 == 3 && sort l1 == sort [".", "..", takeFileName $ projectFile projectId]) (getDirectoryContents (dropFileName $ moveFromDir </> projectFile projectId)) liftIO $ if empty then removeDirectoryIfExists (dropFileName $ moveFromDir </> projectFile projectId) else removeFileIfExists $ moveFromDir </> projectFile projectId (_, False, "false") -> do let dirName = last $ splitDirectories moveFromDir let dir = moveToDir </> take 3 dirName </> dirName liftIO $ ensureUserBaseDir mode (userId user) dir liftIO $ copyDirIfExists moveFromDir $ projectDir </> dir empty <- liftIO $ fmap (\ l1 -> length l1 == 3 && sort l1 == sort [".", "..", takeFileName moveFromDir]) (getDirectoryContents (takeDirectory moveFromDir)) liftIO $ removeDirectoryIfExists $ if empty then takeDirectory moveFromDir else moveFromDir (_, _, _) -> return () saveXMLHashHandler :: Snap () saveXMLHashHandler = do mode <- getBuildMode unless (mode==BuildMode "blocklyXML") $ modifyResponse $ setResponseCode 500 Just source <- getParam "source" let programId = sourceToProgramId source liftIO $ ensureProgramDir mode programId liftIO $ B.writeFile (buildRootDir mode </> sourceXML programId) source modifyResponse $ setContentType "text/plain" writeBS (T.encodeUtf8 (unProgramId programId)) getHashParam :: Bool -> BuildMode -> Snap ProgramId getHashParam allowDeploy mode = getParam "hash" >>= \case Just h -> return (ProgramId (T.decodeUtf8 h)) Nothing | allowDeploy -> do Just dh <- getParam "dhash" let deployId = DeployId (T.decodeUtf8 dh) liftIO $ resolveDeployId mode deployId loadXMLHandler :: Snap () loadXMLHandler = do mode <- getBuildMode unless (mode==BuildMode "blocklyXML") $ modifyResponse $ setResponseCode 500 programId <- getHashParam False mode modifyResponse $ setContentType "text/plain" serveFile (buildRootDir mode </> sourceXML programId) getMode :: BuildMode -> String getMode (BuildMode m) = m
parvmor/codeworld
funblocks-server/src/Funblocks.hs
apache-2.0
11,771
0
23
2,640
3,491
1,663
1,828
225
6
{-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : System.Log.Logger.Handler -- Copyright : (C) 2015 Flowbox -- License : Apache-2.0 -- Maintainer : Wojciech Daniło <[email protected]> -- Stability : stable -- Portability : portable ----------------------------------------------------------------------------- module System.Log.Logger.Priority where import System.Log.Data (MonadRecord, appendRecord, Lvl(Lvl), readData, LevelData(LevelData), LookupDataSet) import System.Log.Logger.Handler (MonadLoggerHandler(addHandler)) import System.Log.Log (MonadLogger, LogFormat) import Control.Monad.State (StateT, runStateT) import Control.Monad.Trans (MonadTrans, lift) import Control.Monad.IO.Class (MonadIO) import Control.Applicative import qualified Control.Monad.State as State ---------------------------------------------------------------------- -- MonadPriorityLogger ---------------------------------------------------------------------- class MonadPriorityLogger m where getPriority :: m Int setPriority :: Enum a => a -> m () ---------------------------------------------------------------------- -- PriorityLoggerT ---------------------------------------------------------------------- newtype PriorityLoggerT m a = PriorityLoggerT { fromPriorityLoggerT :: StateT Int m a } deriving (Monad, MonadIO, Applicative, Functor, MonadTrans) type instance LogFormat (PriorityLoggerT m) = LogFormat m runPriorityLoggerT pri = fmap fst . flip runStateT (fromEnum pri) . fromPriorityLoggerT -- === Instances === instance Monad m => MonadPriorityLogger (PriorityLoggerT m) where getPriority = PriorityLoggerT State.get setPriority a = PriorityLoggerT . State.put $ fromEnum a instance (MonadLogger m, MonadRecord d m, LookupDataSet Lvl d) => MonadRecord d (PriorityLoggerT m) where appendRecord d = do priLimit <- getPriority let LevelData pri _ = readData Lvl d if priLimit <= pri then lift $ appendRecord d else return () instance (Monad m, MonadLoggerHandler h m) => MonadLoggerHandler h (PriorityLoggerT m)
wdanilo/haskell-logger
src/System/Log/Logger/Priority.hs
apache-2.0
2,269
0
11
360
463
261
202
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE TypeFamilies #-} #ifndef HLINT {-# LANGUAGE ViewPatterns #-} #endif {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE DeriveTraversable #-} module Concurrent.Internal.Counted where import Control.Applicative import Control.Monad import Control.Monad.Zip import Control.Monad.Fix import Data.Foldable import GHC.Exts as Exts import Prelude #ifdef HLINT {-# ANN module "HLint: ignore Eta reduce" #-} #endif -- | A simple list with a baked in memoization of the length data Counted a = Counted {-# UNPACK #-} !Int [a] deriving (Functor,Traversable,Eq,Ord,Read,Show) #ifndef HLINT pattern (:+) :: () => () => a -> Counted a -> Counted a pattern a :+ as <- Counted (subtract 1 -> i) (a : (Counted i -> as)) where a :+ Counted i as = Counted (i+1) (a:as) #endif instance Foldable Counted where foldMap f (Counted _ xs) = foldMap f xs foldr f z (Counted _ xs) = foldr f z xs length (Counted i _) = i null (Counted i _) = i == 0 toList (Counted _ xs) = xs instance Exts.IsList (Counted a) where type Item (Counted a) = a fromListN n xs = Counted n xs fromList xs = Counted (length xs) xs toList (Counted _ xs) = xs instance Applicative Counted where pure a = Counted 1 [a] Counted n fs <*> Counted m as = Counted (n*m) (fs <*> as) instance Monad Counted where return a = Counted 1 [a] fail _ = Counted 0 [] Counted _ as >>= f = Counted (sum (length <$> bs)) (bs >>= Exts.toList) -- one of these days i should try Twan's trick here where bs = fmap f as instance Alternative Counted where empty = Counted 0 [] Counted n as <|> Counted m bs = Counted (n + m) (as ++ bs) instance MonadPlus Counted where mzero = empty mplus = (<|>) instance MonadZip Counted where mzipWith f (Counted n as) (Counted m bs) = Counted (min n m) (mzipWith f as bs) munzip (Counted n as) = case munzip as of (bs,cs) -> (Counted n bs, Counted n cs) instance MonadFix Counted where mfix f = case fix (f . head . Exts.toList) of Counted _ [] -> Counted 0 [] Counted n (x:_) -> Counted n (x : mfix (tail . Exts.toList . f))
ekmett/concurrent
src/Concurrent/Internal/Counted.hs
bsd-2-clause
2,089
0
16
447
852
442
410
50
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | Cache information about previous builds module Stack.Build.Cache ( tryGetBuildCache , tryGetConfigCache , tryGetCabalMod , getInstalledExes , tryGetFlagCache , deleteCaches , markExeInstalled , markExeNotInstalled , writeFlagCache , writeBuildCache , writeConfigCache , writeCabalMod , setTestSuccess , unsetTestSuccess , checkTestSuccess , writePrecompiledCache , readPrecompiledCache -- Exported for testing , BuildCache(..) ) where import Control.DeepSeq (NFData) import Control.Exception.Enclosed (handleIO, tryAnyDeep) import Control.Monad (liftM) import Control.Monad.Catch (MonadThrow, MonadCatch) import Control.Monad.IO.Class import Control.Monad.Logger (MonadLogger, logDebug) import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Control (MonadBaseControl) import qualified Crypto.Hash.SHA256 as SHA256 import Data.Binary (Binary (..)) import qualified Data.Binary as Binary import Data.Binary.Tagged (HasStructuralInfo, HasSemanticVersion) import qualified Data.Binary.Tagged as BinaryTagged import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString.Base64.URL as B64URL import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as LBS import Data.Foldable (forM_) import Data.Map (Map) import Data.Maybe (fromMaybe, mapMaybe) import Data.Monoid ((<>)) import Data.Set (Set) import qualified Data.Set as Set import Data.Store (Store) import qualified Data.Store as Store import Data.Store.TypeHash (HasTypeHash, mkManyHasTypeHash) import Data.Store.VersionTagged import Data.Text (Text) import qualified Data.Text as T import Data.Traversable (forM) import GHC.Generics (Generic) import Path import Path.IO import Stack.Constants import Stack.Types import qualified System.FilePath as FilePath -- | Directory containing files to mark an executable as installed exeInstalledDir :: (MonadReader env m, HasEnvConfig env, MonadThrow m) => InstallLocation -> m (Path Abs Dir) exeInstalledDir Snap = (</> $(mkRelDir "installed-packages")) `liftM` installationRootDeps exeInstalledDir Local = (</> $(mkRelDir "installed-packages")) `liftM` installationRootLocal -- | Get all of the installed executables getInstalledExes :: (MonadReader env m, HasEnvConfig env, MonadIO m, MonadThrow m) => InstallLocation -> m [PackageIdentifier] getInstalledExes loc = do dir <- exeInstalledDir loc (_, files) <- liftIO $ handleIO (const $ return ([], [])) $ listDir dir return $ mapMaybe (parsePackageIdentifierFromString . toFilePath . filename) files -- | Mark the given executable as installed markExeInstalled :: (MonadReader env m, HasEnvConfig env, MonadIO m, MonadThrow m) => InstallLocation -> PackageIdentifier -> m () markExeInstalled loc ident = do dir <- exeInstalledDir loc ensureDir dir ident' <- parseRelFile $ packageIdentifierString ident let fp = toFilePath $ dir </> ident' -- TODO consideration for the future: list all of the executables -- installed, and invalidate this file in getInstalledExes if they no -- longer exist liftIO $ writeFile fp "Installed" -- | Mark the given executable as not installed markExeNotInstalled :: (MonadReader env m, HasEnvConfig env, MonadIO m, MonadCatch m) => InstallLocation -> PackageIdentifier -> m () markExeNotInstalled loc ident = do dir <- exeInstalledDir loc ident' <- parseRelFile $ packageIdentifierString ident ignoringAbsence (removeFile $ dir </> ident') -- | Stored on disk to know whether the flags have changed or any -- files have changed. data BuildCache = BuildCache { buildCacheTimes :: !(Map FilePath FileCacheInfo) -- ^ Modification times of files. } deriving (Generic, Eq, Show) instance Store BuildCache instance NFData BuildCache -- | Try to read the dirtiness cache for the given package directory. tryGetBuildCache :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m, HasEnvConfig env, MonadBaseControl IO m) => Path Abs Dir -> m (Maybe (Map FilePath FileCacheInfo)) tryGetBuildCache = liftM (fmap buildCacheTimes) . tryGetCache buildCacheFile -- | Try to read the dirtiness cache for the given package directory. tryGetConfigCache :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env, MonadBaseControl IO m, MonadLogger m) => Path Abs Dir -> m (Maybe ConfigCache) tryGetConfigCache = tryGetCache configCacheFile -- | Try to read the mod time of the cabal file from the last build tryGetCabalMod :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env, MonadBaseControl IO m, MonadLogger m) => Path Abs Dir -> m (Maybe ModTime) tryGetCabalMod = tryGetCache configCabalMod -- | Try to load a cache. tryGetCache :: (MonadIO m, Store a, HasTypeHash a, MonadBaseControl IO m, MonadLogger m) => (Path Abs Dir -> m (Path Abs File)) -> Path Abs Dir -> m (Maybe a) tryGetCache get' dir = do fp <- get' dir decodeFileMaybe fp -- | Write the dirtiness cache for this package's files. writeBuildCache :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env, MonadLogger m) => Path Abs Dir -> Map FilePath FileCacheInfo -> m () writeBuildCache dir times = writeCache dir buildCacheFile BuildCache { buildCacheTimes = times } -- | Write the dirtiness cache for this package's configuration. writeConfigCache :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env, MonadLogger m) => Path Abs Dir -> ConfigCache -> m () writeConfigCache dir = writeCache dir configCacheFile -- | See 'tryGetCabalMod' writeCabalMod :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env, MonadLogger m) => Path Abs Dir -> ModTime -> m () writeCabalMod dir = writeCache dir configCabalMod -- | Delete the caches for the project. deleteCaches :: (MonadIO m, MonadReader env m, MonadCatch m, HasEnvConfig env) => Path Abs Dir -> m () deleteCaches dir = do {- FIXME confirm that this is acceptable to remove bfp <- buildCacheFile dir removeFileIfExists bfp -} cfp <- configCacheFile dir ignoringAbsence (removeFile cfp) -- | Write to a cache. writeCache :: (Store a, NFData a, HasTypeHash a, Eq a, MonadIO m, MonadLogger m) => Path Abs Dir -> (Path Abs Dir -> m (Path Abs File)) -> a -> m () writeCache dir get' content = do fp <- get' dir taggedEncodeFile fp content flagCacheFile :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env) => Installed -> m (Path Abs File) flagCacheFile installed = do rel <- parseRelFile $ case installed of Library _ gid -> ghcPkgIdString gid Executable ident -> packageIdentifierString ident dir <- flagCacheLocal return $ dir </> rel -- | Loads the flag cache for the given installed extra-deps tryGetFlagCache :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env, MonadBaseControl IO m, MonadLogger m) => Installed -> m (Maybe ConfigCache) tryGetFlagCache gid = do fp <- flagCacheFile gid decodeFileMaybe fp writeFlagCache :: (MonadIO m, MonadReader env m, HasEnvConfig env, MonadThrow m, MonadLogger m, MonadBaseControl IO m) => Installed -> ConfigCache -> m () writeFlagCache gid cache = do file <- flagCacheFile gid ensureDir (parent file) taggedEncodeFile file cache -- | Mark a test suite as having succeeded setTestSuccess :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env, MonadLogger m) => Path Abs Dir -> m () setTestSuccess dir = writeCache dir testSuccessFile True -- | Mark a test suite as not having succeeded unsetTestSuccess :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env, MonadLogger m) => Path Abs Dir -> m () unsetTestSuccess dir = writeCache dir testSuccessFile False -- | Check if the test suite already passed checkTestSuccess :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env, MonadBaseControl IO m, MonadLogger m) => Path Abs Dir -> m Bool checkTestSuccess dir = liftM (fromMaybe False) (tryGetCache testSuccessFile dir) -------------------------------------- -- Precompiled Cache -- -- Idea is simple: cache information about packages built in other snapshots, -- and then for identical matches (same flags, config options, dependencies) -- just copy over the executables and reregister the libraries. -------------------------------------- -- | The file containing information on the given package/configuration -- combination. The filename contains a hash of the non-directory configure -- options for quick lookup if there's a match. -- -- It also returns an action yielding the location of the precompiled -- path based on the old binary encoding. -- -- We only pay attention to non-directory options. We don't want to avoid a -- cache hit just because it was installed in a different directory. precompiledCacheFile :: (MonadThrow m, MonadReader env m, HasEnvConfig env, MonadLogger m) => PackageIdentifier -> ConfigureOpts -> Set GhcPkgId -- ^ dependencies -> m (Path Abs File, m (Path Abs File)) precompiledCacheFile pkgident copts installedPackageIDs = do ec <- asks getEnvConfig compiler <- parseRelDir $ compilerVersionString $ envConfigCompilerVersion ec cabal <- parseRelDir $ versionString $ envConfigCabalVersion ec pkg <- parseRelDir $ packageIdentifierString pkgident platformRelDir <- platformGhcRelDir let input = (coNoDirs copts, installedPackageIDs) -- In Cabal versions 1.22 and later, the configure options contain the -- installed package IDs, which is what we need for a unique hash. -- Unfortunately, earlier Cabals don't have the information, so we must -- supplement it with the installed package IDs directly. -- See issue: https://github.com/commercialhaskell/stack/issues/1103 let oldHash = B16.encode $ SHA256.hash $ LBS.toStrict $ if envConfigCabalVersion ec >= $(mkVersion "1.22") then Binary.encode (coNoDirs copts) else Binary.encode input hashToPath hash = do hashPath <- parseRelFile $ S8.unpack hash return $ getStackRoot ec </> $(mkRelDir "precompiled") </> platformRelDir </> compiler </> cabal </> pkg </> hashPath $logDebug $ "Precompiled cache input = " <> T.pack (show input) newPath <- hashToPath $ B64URL.encode $ SHA256.hash $ Store.encode input return (newPath, hashToPath oldHash) -- | Write out information about a newly built package writePrecompiledCache :: (MonadThrow m, MonadReader env m, HasEnvConfig env, MonadIO m, MonadLogger m) => BaseConfigOpts -> PackageIdentifier -> ConfigureOpts -> Set GhcPkgId -- ^ dependencies -> Installed -- ^ library -> Set Text -- ^ executables -> m () writePrecompiledCache baseConfigOpts pkgident copts depIDs mghcPkgId exes = do (file, _) <- precompiledCacheFile pkgident copts depIDs ensureDir (parent file) ec <- asks getEnvConfig let stackRootRelative = makeRelative (getStackRoot ec) mlibpath <- case mghcPkgId of Executable _ -> return Nothing Library _ ipid -> liftM Just $ do ipid' <- parseRelFile $ ghcPkgIdString ipid ++ ".conf" relPath <- stackRootRelative $ bcoSnapDB baseConfigOpts </> ipid' return $ toFilePath $ relPath exes' <- forM (Set.toList exes) $ \exe -> do name <- parseRelFile $ T.unpack exe relPath <- stackRootRelative $ bcoSnapInstallRoot baseConfigOpts </> bindirSuffix </> name return $ toFilePath $ relPath taggedEncodeFile file PrecompiledCache { pcLibrary = mlibpath , pcExes = exes' } -- | Check the cache for a precompiled package matching the given -- configuration. readPrecompiledCache :: (MonadThrow m, MonadReader env m, HasEnvConfig env, MonadIO m, MonadLogger m, MonadBaseControl IO m) => PackageIdentifier -- ^ target package -> ConfigureOpts -> Set GhcPkgId -- ^ dependencies -> m (Maybe PrecompiledCache) readPrecompiledCache pkgident copts depIDs = do ec <- asks getEnvConfig let toAbsPath path = do if FilePath.isAbsolute path then path -- Only older version store absolute path else toFilePath (getStackRoot ec) FilePath.</> path let toAbsPC pc = PrecompiledCache { pcLibrary = fmap toAbsPath (pcLibrary pc) , pcExes = map toAbsPath (pcExes pc) } (file, getOldFile) <- precompiledCacheFile pkgident copts depIDs mres <- decodeFileMaybe file case mres of Just res -> return (Just $ toAbsPC res) Nothing -> do -- Fallback on trying the old binary format. oldFile <- getOldFile mpc <- fmap (fmap toAbsPC) $ binaryDecodeFileOrFailDeep oldFile -- Write out file in new format. Keep old file around for -- the benefit of older stack versions. forM_ mpc (taggedEncodeFile file) return mpc -- | Ensure that there are no lurking exceptions deep inside the parsed -- value... because that happens unfortunately. See -- https://github.com/commercialhaskell/stack/issues/554 binaryDecodeFileOrFailDeep :: (BinarySchema a, MonadIO m) => Path loc File -> m (Maybe a) binaryDecodeFileOrFailDeep fp = liftIO $ fmap (either (\_ -> Nothing) id) $ tryAnyDeep $ do eres <- BinaryTagged.taggedDecodeFileOrFail (toFilePath fp) case eres of Left _ -> return Nothing Right x -> return (Just x) type BinarySchema a = (Binary a, NFData a, HasStructuralInfo a, HasSemanticVersion a) $(mkManyHasTypeHash [ [t| BuildCache |] -- TODO: put this orphan elsewhere? Not sure if we want tons of -- instances of HasTypeHash or not. , [t| Bool |] ])
sjakobi/stack
src/Stack/Build/Cache.hs
bsd-3-clause
15,483
0
20
4,171
3,492
1,806
1,686
281
3
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Control.Monad.Trans.Control ( -- * Introduction -- $intro -- ** Nesting calls to the base monad -- $nesting -- ** A generic solution -- $generic -- ** Using monad-control and liftBaseWith -- $usage -- * MonadBaseControl MonadBaseControl (..), defaultLiftBaseWith -- * MonadBaseControl , MonadTransControl (..), defaultLiftWith -- * Utility functions , control, liftBaseOp, liftBaseOp_, liftBaseDiscard ) where import Control.Monad ((>=>), liftM) import Control.Monad.ST.Lazy (ST) import qualified Control.Monad.ST.Strict as Strict (ST) import Control.Monad.Trans.Error (ErrorT(ErrorT), runErrorT, Error) import Control.Monad.Trans.Identity (IdentityT(IdentityT), runIdentityT) import Control.Monad.Trans.Class (MonadTrans) import Control.Monad.Trans.List (ListT(ListT), runListT) import Control.Monad.Trans.Maybe (MaybeT(MaybeT), runMaybeT) import Control.Monad.Trans.RWS (RWST(RWST), runRWST) import qualified Control.Monad.Trans.RWS.Strict as Strict (RWST(RWST), runRWST) import Control.Monad.Trans.Reader (ReaderT(ReaderT), runReaderT) import Control.Monad.Trans.State (StateT(StateT), runStateT) import qualified Control.Monad.Trans.State.Strict as Strict (StateT (StateT), runStateT) import Control.Monad.Trans.Writer (WriterT(WriterT), runWriterT) import qualified Control.Monad.Trans.Writer.Strict as Strict (WriterT(WriterT), runWriterT) import Data.Functor.Identity (Identity) import Data.Monoid (Monoid, mempty) import GHC.Conc.Sync (STM) {- $intro What is the problem that 'monad-control' aims to solve? To answer that, let's back up a bit. We know that a monad represents some kind of "computational context". The question is, can we separate this context from the monad, and reconstitute it later? If we know the monadic types involved, then for some monads we can. Consider the 'State' monad: it's essentially a function from an existing state, to a pair of some new state and a value. It's fairly easy then to extract its state and later use it to "resume" that monad: @ import Control.Applicative import Control.Monad.Trans.State main = do let f = do { modify (+1); show <$> get } :: StateT Int IO String (x,y) <- runStateT f 0 print $ "x = " ++ show x -- x = "1" (x',y') <- runStateT f y print $ "x = " ++ show x' -- x = "2" @ In this way, we interleave between @StateT Int IO@ and 'IO', by completing the 'StateT' invocation, obtaining its state as a value, and starting a new 'StateT' block from the prior state. We've effectively resumed the earlier 'StateT' block. -} {- $nesting But what if we didn't, or couldn't, exit the 'StateT' block to run our 'IO' computation? In that case we'd need to use 'liftIO' to enter 'IO' and make a nested call to 'runStateT' inside that 'IO' block. Further, we'd want to restore any changes made to the inner 'StateT' within the outer 'StateT', after returning from the 'IO' action: @ import Control.Applicative import Control.Monad.Trans.State import Control.Monad.IO.Class main = do let f = do { modify (+1); show <$> get } :: StateT Int IO String flip runStateT 0 $ do x <- f y <- get y' <- liftIO $ do print $ "x = " ++ show x -- x = "1" (x',y') <- runStateT f y print $ "x = " ++ show x' -- x = "2" return y' put y' @ -} {- $generic This works fine for 'StateT', but how can we write it so that it works for any monad tranformer over IO? We'd need a function that might look like this: @ foo :: MonadIO m => m String -> m String foo f = do x <- f y <- getTheState y' <- liftIO $ do print $ "x = " ++ show x (x',y') <- runTheMonad f y print $ "x = " ++ show x' return y' putTheState y' @ But this is impossible, since we only know that 'm' is a 'Monad'. Even with a 'MonadState' constraint, we would not know about a function like 'runTheMonad'. This indicates we need a type class with at least three capabilities: getting the current monad tranformer's state, executing a new transformer within the base monad, and restoring the enclosing transformer's state upon returning from the base monad. This is exactly what 'MonadBaseControl' provides, from 'monad-control': @ class MonadBase b m => MonadBaseControl b m | m -> b where data StM m :: * -> * liftBaseWith :: (RunInBase m b -> b a) -> m a restoreM :: StM m a -> m a @ Taking this definition apart piece by piece: 1. The 'MonadBase' constraint exists so that 'MonadBaseControl' can be used over multiple base monads: 'IO', 'ST', 'STM', etc. 2. 'liftBaseWith' combines three things from our last example into one: it gets the current state from the monad transformer, wraps it an 'StM' type, lifts the given action into the base monad, and provides that action with a function which can be used to resume the enclosing monad within the base monad. When such a function exits, it returns a new 'StM' value. 3. 'restoreM' takes the encapsulated tranformer state as an 'StM' value, and applies it to the parent monad transformer so that any changes which may have occurred within the "inner" transformer are propagated out. (This also has the effect that later, repeated calls to 'restoreM' can "reset" the transformer state back to what it was previously.) -} {- $usage With that said, here's the same example from above, but now generic for any transformer supporting @MonadBaseControl IO@: @ import Control.Applicative import Control.Monad.Trans.State import Control.Monad.Trans.Control foo :: MonadBaseControl IO m => m String -> m String foo f = do x <- f y' <- liftBaseWith $ \runInIO -> do print $ "x = " ++ show x -- x = "1" x' <- runInIO f -- print $ "x = " ++ show x' return x' restoreM y' main = do let f = do { modify (+1); show <$> get } :: StateT Int IO String (x',y') <- flip runStateT 0 $ foo f print $ "x = " ++ show x' -- x = "2" @ One notable difference in this example is that the second 'print' statement in 'foo' becomes impossible, since the "monadic value" returned from the inner call to 'f' must be restored and executed within the outer monad. That is, @runInIO f@ is executed in IO, but it's result is an @StM m String@ rather than @IO String@, since the computation carries monadic context from the inner transformer. Converting this to a plain 'IO' computation would require calling a function like 'runStateT', which we cannot do without knowing which transformer is being used. As a convenience, since calling 'restoreM' after exiting 'liftBaseWith' is so common, you can use 'control' instead of @restoreM =<< liftBaseWith@: @ y' <- restoreM =<< liftBaseWith (\runInIO -> runInIO f) becomes... y' <- control $ \runInIO -> runInIO f @ Another common pattern is when you don't need to restore the inner transformer's state to the outer transformer, you just want to pass it down as an argument to some function in the base monad: @ foo :: MonadBaseControl IO m => m String -> m String foo f = do x <- f liftBaseDiscard forkIO $ f @ In this example, the first call to 'f' affects the state of 'm', while the inner call to 'f', though inheriting the state of 'm' in the new thread, but does not restore its effects to the parent monad transformer when it returns. Now that we have this machinery, we can use it to make any function in 'IO' directly usable from any supporting transformer. Take 'catch' for example: @ catch :: Exception e => IO a -> (e -> IO a) -> IO a @ What we'd like is a function that works for any @MonadBaseControl IO m@, rather than just 'IO'. With the 'control' function this is easy: @ catch :: (MonadBaseControl IO m, Exception e) => m a -> (e -> m a) -> m a catch f h = control $ \runInIO -> catch (runInIO f) (runInIO . h) @ You can find many function which are generalized like this in the packages 'lifted-base' and 'lifted-async'. -} -------------------------------------------------------------------------------- -- * MonadBaseControl -------------------------------------------------------------------------------- class (Monad m, Monad b) => MonadBaseControl b m | m -> b where -- | Monadic state of @m@. data StM m a :: * -- | @liftBaseWith@ is similar to 'liftIO' and 'liftBase' in that it -- lifts a base computation to the constructed monad. -- -- Instances should satisfy similar laws as the 'MonadIO' and 'MonadBase' -- laws: -- -- @liftBaseWith . const . return = return@ -- -- @liftBaseWith (const (m >>= f)) = -- liftBaseWith (const m) >>= liftBaseWith . const . f@ -- -- The difference with 'liftBase' is that before lifting the base -- computation @liftBaseWith@ captures the state of @m@. It then provides -- the base computation with a 'RunInBase' function that allows running -- @m@ computations in the base monad on the captured state. liftBaseWith :: ((m x -> b (StM m x)) -> b a) -> m a -- | Construct a @m@ computation from the monadic state of @m@ that is -- returned from a 'RunInBase' function. -- -- Instances should satisfy: -- -- @liftBaseWith (\\runInBase -> runInBase m) >>= restoreM = m@ restoreM :: StM m a -> m a -- | Default implementation of 'liftBaseWith'. Below is a prototypical -- instance of 'MonadBaseControl' for 'StateT': -- -- @ --instance MonadBaseControl b m => MonadBaseControl b (StateT s m) where -- newtype StM (StateT s m) a = StateST (StM m (a, s)) -- liftBaseWith f = StateT $ \\s -> -- defaultLiftBaseWith f (`runStateT` s) StateST (,s) -- restoreM (StateST m) = StateT . const . restoreM $ m -- @ defaultLiftBaseWith :: MonadBaseControl b m => ((t m x -> b (StM (t m) x)) -> b s) -- ^ Passed through from liftBaseWith -> (t m x -> m a) -- ^ Run the monad transformer -> (StM m a -> StM (t m) x) -- ^ Constructor for instance's StM -> (s -> r) -- ^ Transform returned state value -> m r defaultLiftBaseWith f h u g = liftM g $ liftBaseWith $ \runInBase -> f $ \k -> liftM u $ runInBase $ h k {-# INLINE defaultLiftBaseWith #-} -------------------------------------------------------------------------------- -- * MonadTransControl -------------------------------------------------------------------------------- class MonadTrans t => MonadTransControl t where -- | Monadic state of @t@. data StT t :: * -> * -- | @liftWith@ is similar to 'lift' in that it lifts a computation from -- the argument monad to the constructed monad. -- -- Instances should satisfy similar laws as the 'MonadTrans' laws: -- -- @liftWith . const . return = return@ -- -- @liftWith (const (m >>= f)) = liftWith (const m) >>= liftWith . const . f@ -- -- The difference with 'lift' is that before lifting the @m@ computation -- @liftWith@ captures the state of @t@. It then provides the @m@ -- computation with a 'Run' function that allows running @t n@ computations in -- @n@ (for all @n@) on the captured state. liftWith :: (Monad m, Monad n) => ((t n x -> n (StT t x)) -> m a) -> t m a -- | Construct a @t@ computation from the monadic state of @t@ that is -- returned from a 'Run' function. -- -- Instances should satisfy: -- -- @liftWith (\\run -> run t) >>= restoreT . return = t@ restoreT :: Monad m => StT t a -> t m a -- | Default implementation of 'liftWith'. Below is a prototypical instance -- of 'MonadTransControl' for 'StateT': -- -- @ --instance MonadTransControl (StateT s) where -- newtype StT (StateT s) a = StateST { unStateST :: (a, s) } -- liftWith f = StateT $ \\s -> -- defaultLiftWith f (`runStateT` s) StateST (,s) -- restoreT = StateT . const . return . unStateST -- @ defaultLiftWith :: (Monad m, Monad n) => ((x -> n y) -> m s) -- ^ Passed through from liftWith -> (x -> n a) -- ^ Run the monad transformer -> (a -> y) -- ^ Constructor for instance's StT -> (s -> r) -- ^ Transform returned state value -> m r defaultLiftWith f h u g = liftM g $ f $ liftM u . h {-# INLINE defaultLiftWith #-} -------------------------------------------------------------------------------- -- * Base Instances -------------------------------------------------------------------------------- instance MonadBaseControl IO IO where newtype StM IO a = StIO a liftBaseWith f = f $ liftM StIO restoreM (StIO x) = return x {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadBaseControl Maybe Maybe where newtype StM Maybe a = St a liftBaseWith f = f $ liftM St restoreM (St x) = return x {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadBaseControl (Either e) (Either e) where newtype StM (Either e) a = StE a liftBaseWith f = f $ liftM StE restoreM (StE x) = return x {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadBaseControl [] [] where newtype StM [] a = StL a liftBaseWith f = f $ liftM StL restoreM (StL x) = return x {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadBaseControl ((->) r) ((->) r) where newtype StM ((->) r) a = StF a liftBaseWith f = f $ liftM StF restoreM (StF x) = return x {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadBaseControl Identity Identity where newtype StM Identity a = StI a liftBaseWith f = f $ liftM StI restoreM (StI x) = return x {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadBaseControl STM STM where newtype StM STM a = StSTM a liftBaseWith f = f $ liftM StSTM restoreM (StSTM x) = return x {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadBaseControl (Strict.ST s) (Strict.ST s) where newtype StM (Strict.ST s) a = StSTS a liftBaseWith f = f $ liftM StSTS restoreM (StSTS x) = return x {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadBaseControl (ST s) (ST s) where newtype StM (ST s) a = StST a liftBaseWith f = f $ liftM StST restoreM (StST x) = return x {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} -------------------------------------------------------------------------------- -- * Transformer Instances -------------------------------------------------------------------------------- -- ListT instance MonadBaseControl b m => MonadBaseControl b (ListT m) where newtype StM (ListT m) a = ListTStM (StM m [a]) liftBaseWith f = ListT $ defaultLiftBaseWith f runListT ListTStM return restoreM (ListTStM m) = ListT . restoreM $ m {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadTransControl (ListT) where newtype StT ListT a = ListTStT { unListTStT :: [a] } liftWith f = ListT $ defaultLiftWith f runListT ListTStT return restoreT = ListT . return . unListTStT {-# INLINE liftWith #-} {-# INLINE restoreT #-} -- MaybeT instance MonadBaseControl b m => MonadBaseControl b (MaybeT m) where newtype StM (MaybeT m) a = MaybeTStM (StM m (Maybe a)) liftBaseWith f = MaybeT $ defaultLiftBaseWith f runMaybeT MaybeTStM return restoreM (MaybeTStM m) = MaybeT . restoreM $ m {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadTransControl (MaybeT) where newtype StT MaybeT a = MaybeTStT { unMaybeTStT :: Maybe a } liftWith f = MaybeT $ defaultLiftWith f runMaybeT MaybeTStT return restoreT = MaybeT . return . unMaybeTStT {-# INLINE liftWith #-} {-# INLINE restoreT #-} -- IdentityT instance MonadBaseControl b m => MonadBaseControl b (IdentityT m) where newtype StM (IdentityT m) a = IdentityTStM (StM m a) liftBaseWith f = IdentityT $ defaultLiftBaseWith f runIdentityT IdentityTStM id restoreM (IdentityTStM m) = IdentityT . restoreM $ m {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadTransControl (IdentityT) where newtype StT IdentityT a = IdentityTStT { unIdentityTStT :: a } liftWith f = IdentityT $ defaultLiftWith f runIdentityT IdentityTStT id restoreT = IdentityT . return . unIdentityTStT {-# INLINE liftWith #-} {-# INLINE restoreT #-} -- WriterT instance (MonadBaseControl b m, Monoid w) => MonadBaseControl b (WriterT w m) where newtype StM (WriterT w m) a = WriterTStM (StM m (a, w)) liftBaseWith f = WriterT $ defaultLiftBaseWith f runWriterT WriterTStM (\x -> (x, mempty)) restoreM (WriterTStM m) = WriterT . restoreM $ m {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance Monoid w => MonadTransControl (WriterT w) where newtype StT (WriterT w) a = WriterTStT { unWriterTStT :: (a, w) } liftWith f = WriterT $ defaultLiftWith f runWriterT WriterTStT (\x -> (x, mempty)) restoreT = WriterT . return . unWriterTStT {-# INLINE liftWith #-} {-# INLINE restoreT #-} instance (MonadBaseControl b m, Monoid w) => MonadBaseControl b (Strict.WriterT w m) where newtype StM (Strict.WriterT w m) a = StWriterTStM (StM m (a, w)) liftBaseWith f = Strict.WriterT $ defaultLiftBaseWith f Strict.runWriterT StWriterTStM (\x -> (x, mempty)) restoreM (StWriterTStM m) = Strict.WriterT . restoreM $ m {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance Monoid w => MonadTransControl (Strict.WriterT w) where newtype StT (Strict.WriterT w) a = StWriterTStT { unStWriterTStT :: (a, w) } liftWith f = Strict.WriterT $ defaultLiftWith f Strict.runWriterT StWriterTStT (\x -> (x, mempty)) restoreT = Strict.WriterT . return . unStWriterTStT {-# INLINE liftWith #-} {-# INLINE restoreT #-} -- ErrorT instance (MonadBaseControl b m, Error e) => MonadBaseControl b (ErrorT e m) where newtype StM (ErrorT e m) a = ErrorTStM (StM m (Either e a)) liftBaseWith f = ErrorT $ defaultLiftBaseWith f runErrorT ErrorTStM return restoreM (ErrorTStM m) = ErrorT . restoreM $ m {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance Error e => MonadTransControl (ErrorT e) where newtype StT (ErrorT e) a = ErrorTStT { unErrorTStT :: Either e a } liftWith f = ErrorT $ defaultLiftWith f runErrorT ErrorTStT return restoreT = ErrorT . return . unErrorTStT {-# INLINE liftWith #-} {-# INLINE restoreT #-} -- StateT instance MonadBaseControl b m => MonadBaseControl b (StateT s m) where newtype StM (StateT s m) a = StateTStM (StM m (a, s)) liftBaseWith f = StateT $ \s -> defaultLiftBaseWith f (`runStateT` s) StateTStM (\x -> (x,s)) restoreM (StateTStM m) = StateT . const . restoreM $ m {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadTransControl (StateT s) where newtype StT (StateT s) a = StateTStT { unStateTStT :: (a, s) } liftWith f = StateT $ \s -> defaultLiftWith f (`runStateT` s) StateTStT (\x -> (x,s)) restoreT = StateT . const . return . unStateTStT {-# INLINE liftWith #-} {-# INLINE restoreT #-} instance MonadBaseControl b m => MonadBaseControl b (Strict.StateT s m) where newtype StM (Strict.StateT s m) a = StStateTStM (StM m (a, s)) liftBaseWith f = Strict.StateT $ \s -> defaultLiftBaseWith f (`Strict.runStateT` s) StStateTStM (\x -> (x,s)) restoreM (StStateTStM m) = Strict.StateT . const . restoreM $ m {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadTransControl (Strict.StateT s) where newtype StT (Strict.StateT s) a = StStateTStT { unStStateTStT :: (a, s) } liftWith f = Strict.StateT $ \s -> defaultLiftWith f (`Strict.runStateT` s) StStateTStT (\x -> (x,s)) restoreT = Strict.StateT . const . return . unStStateTStT {-# INLINE liftWith #-} {-# INLINE restoreT #-} -- ReaderT instance MonadBaseControl b m => MonadBaseControl b (ReaderT r m) where newtype StM (ReaderT r m) a = ReaderTStM (StM m a) liftBaseWith f = ReaderT $ \r -> defaultLiftBaseWith f (`runReaderT` r) ReaderTStM id restoreM (ReaderTStM m) = ReaderT . const . restoreM $ m {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadTransControl (ReaderT r) where newtype StT (ReaderT r) a = ReaderTStT { unReaderTStT :: a } liftWith f = ReaderT $ \r -> defaultLiftWith f (`runReaderT` r) ReaderTStT id restoreT = ReaderT . const . return . unReaderTStT {-# INLINE liftWith #-} {-# INLINE restoreT #-} -- RWST instance (MonadBaseControl b m, Monoid w) => MonadBaseControl b (RWST r w s m) where newtype StM (RWST r w s m) a = RWSTStM (StM m (a, s ,w)) liftBaseWith f = RWST $ \r s -> defaultLiftBaseWith f (flip (`runRWST` r) s) RWSTStM (\x -> (x,s,mempty)) restoreM (RWSTStM m) = RWST . const . const . restoreM $ m {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance Monoid w => MonadTransControl (RWST r w s) where newtype StT (RWST r w s) a = RWSTStT { unRWSTStT :: (a, s ,w) } liftWith f = RWST $ \r s -> defaultLiftWith f (flip (`runRWST` r) s) RWSTStT (\x -> (x,s,mempty)) restoreT = RWST . const . const . return . unRWSTStT {-# INLINE liftWith #-} {-# INLINE restoreT #-} instance (MonadBaseControl b m, Monoid w) => MonadBaseControl b (Strict.RWST r w s m) where newtype StM (Strict.RWST r w s m) a = StRWSTStM (StM m (a, s, w)) liftBaseWith f = Strict.RWST $ \r s -> defaultLiftBaseWith f (flip (`Strict.runRWST` r) s) StRWSTStM (\x -> (x,s,mempty)) restoreM (StRWSTStM m) = Strict.RWST . const . const . restoreM $ m {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance Monoid w => MonadTransControl (Strict.RWST r w s) where newtype StT (Strict.RWST r w s) a = StRWSTStT { unStRWSTStT :: (a, s, w) } liftWith f = Strict.RWST $ \r s -> defaultLiftWith f (flip (`Strict.runRWST` r) s) StRWSTStT (\x -> (x,s,mempty)) restoreT = Strict.RWST . const . const . return . unStRWSTStT {-# INLINE liftWith #-} {-# INLINE restoreT #-} -------------------------------------------------------------------------------- -- * Utility functions -------------------------------------------------------------------------------- -- | An often used composition: @control = 'liftBaseWith' >>= 'restoreM'@ control :: MonadBaseControl b m => ((m x -> b (StM m x)) -> b (StM m a)) -> m a control = liftBaseWith >=> restoreM {-# INLINE control #-} -- | @liftBaseOp@ is a particular application of 'liftBaseWith' that allows -- lifting control operations of type: -- -- @((a -> b c) -> b c)@ to: @('MonadBaseControl' b m => (a -> m c) -> m c)@. -- -- For example: -- -- @liftBaseOp alloca :: 'MonadBaseControl' 'IO' m => (Ptr a -> m c) -> m c@ liftBaseOp :: MonadBaseControl b m => ((a -> b (StM m c)) -> b (StM m d)) -> (a -> m c) -> m d liftBaseOp f g = control $ \runInBase -> f $ runInBase . g {-# INLINE liftBaseOp #-} -- | @liftBaseOp_@ is a particular application of 'liftBaseWith' that allows -- lifting control operations of type: -- -- @(b a -> b a)@ to: @('MonadBaseControl' b m => m a -> m a)@. -- -- For example: -- -- @liftBaseOp_ mask_ :: 'MonadBaseControl' 'IO' m => m a -> m a@ liftBaseOp_ :: MonadBaseControl b m => (b (StM m a) -> b (StM m c)) -> m a -> m c liftBaseOp_ f m = control $ \runInBase -> f $ runInBase m {-# INLINE liftBaseOp_ #-} -- | @liftBaseDiscard@ is a particular application of 'liftBaseWith' that allows -- lifting control operations of type: -- -- @(b () -> b a)@ to: @('MonadBaseControl' b m => m () -> m a)@. -- -- Note that, while the argument computation @m ()@ has access to the captured -- state, all its side-effects in @m@ are discarded. It is run only for its -- side-effects in the base monad @b@. -- -- For example: -- -- @liftBaseDiscard forkIO :: 'MonadBaseControl' 'IO' m => m () -> m ThreadId@ liftBaseDiscard :: MonadBaseControl b m => (b (StM m c) -> b a) -> m c -> m a liftBaseDiscard f m = liftBaseWith $ \runInBase -> f $ runInBase m {-# INLINE liftBaseDiscard #-}
jwiegley/monad-base-control
Control/Monad/Trans/Control.hs
bsd-3-clause
24,888
0
15
5,945
4,516
2,494
2,022
282
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} module Tinfoil.Random.Internal( explodeBS , readBitsLE , dropMS , segmentsOf ) where import Data.Bits import Data.ByteString (ByteString) import qualified Data.ByteString as BS import P segmentsOf :: Int -> [a] -> [[a]] segmentsOf _ [] = [] segmentsOf n xs = as : segmentsOf n bs where (as, bs) = splitAt n xs dropMS :: Int -> [Bool] -> [Bool] dropMS n = reverse . drop n . reverse readBitsLE :: [Bool] -> Int readBitsLE = foldr' pack 0 where pack bt acc = (acc `shiftL` 1) .|. fromBool bt fromBool True = 1 fromBool False = 0 explodeBS :: ByteString -> [Bool] explodeBS = concatMap (\w -> testBit w <$> [0..7]) . BS.unpack
ambiata/tinfoil
src/Tinfoil/Random/Internal.hs
bsd-3-clause
798
0
10
191
274
153
121
25
2
{-# LANGUAGE CPP #-} module GhcPkgSpec where import Language.Haskell.GhcMod.GhcPkg import Language.Haskell.GhcMod.Types import System.Directory import System.FilePath ((</>)) import Test.Hspec spec :: Spec spec = do describe "getPackageDbStack" $ do #if !MIN_VERSION_Cabal(1,18,0) it "does not include a sandbox with Cabal < 1.18" $ do cwd <- getCurrentDirectory getPackageDbStack cwd `shouldReturn` [GlobalDb, UserDb] #endif it "parses a config file and extracts sandbox package db" $ do cwd <- getCurrentDirectory pkgDb <- getSandboxDb "test/data/" pkgDb `shouldBe` (cwd </> "test/data/.cabal-sandbox/i386-osx-ghc-7.6.3-packages.conf.d") it "throws an error if a config file is broken" $ do getSandboxDb "test/data/broken-sandbox" `shouldThrow` anyException
darthdeus/ghc-mod-ng
test/GhcPkgSpec.hs
bsd-3-clause
864
0
15
195
163
87
76
19
1
{-# LANGUAGE OverloadedStrings #-} -- | -- Module: $HEADER$ -- Description: Pronounceable passwords similar to what pwgen does. -- Copyright: (c) 2013 Peter Trsko -- License: BSD3 -- -- Maintainer: [email protected] -- Stability: experimental -- Portability: non-portable (OverloadedStrings) -- -- Configuration for generating pronounceable passwords similar to what pwgen -- <http://pwgen.sourceforge.net/> does. module Text.Pwgen.Pronounceable ( -- * GenPasswordConfig genPwConfig , genPwConfigBS ) where import Control.Applicative ((<$>)) import Data.Char (toLower, isUpper) import Data.Maybe (fromMaybe) import Data.Monoid (Monoid(mempty, mappend)) import Data.String (IsString) import Data.Word (Word32) import Control.Applicative.Predicate ((<||>), (>.), is) import Data.Array (Array) import qualified Data.Array.IArray as Array ((!), listArray) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BS (any, head, length) import Data.Default.Class (Default(def)) import Text.Pwgen (FromAscii, GenPasswordConfig(..)) import qualified Text.Pwgen as Pwgen ( isVowel , lowerConsonantsY , lowerVowels , numbers , symbols , upperConsonantsY , upperVowels ) -- | Character category. It's used to determine what kind of character we -- currently want to add to password and what character should be added next. data Category = Vowel | Consonant | Number | Symbol deriving (Eq) data State = State { previousWas :: Maybe (Category, Bool) -- ^ What symbol was generated previously. 'Nothing' is used only as -- initial state. , nextShouldBe :: Maybe Category -- ^ What symbol should be added next. If 'Nothing', then it randomly -- chooses from vowels and consonants. , hasSymbol :: Bool -- ^ Password already has symbol in it, don't check again. , hasUpper :: Bool -- ^ Password already has upper character in it, don't check again. , hasNumber :: Bool -- ^ Password already has number in it, don't check again. } instance Default State where def = State Nothing Nothing False False False data Input t = Input { inVowels :: t , inUpperBoundOfVowels :: Word32 , inConsonants :: t , inUpperBoundOfConsonants :: Word32 , inNumbers :: t -- ^ If zero, then no numbers will be present in a generated password. , inUpperBoundOfNumbers :: Word32 , inSymbols :: t , inUpperBoundOfSymbols :: Word32 -- ^ If zero, then no symbols will be present in a generated password. , inCheckForUpperCharacters :: Bool -- ^ If 'False', then password won't be rejected if it doesn't contain -- upper character. } -- | Function that simplifies creation of 'Input' values, while keeping a lot -- of genericness. mkInput :: (FromAscii u, IsString u) => (u -> Word32) -- ^ Get length of individual elements. It's then stored as the second item -- in a pair. -> (Word32 -> [(u, Word32)] -> t (u, Word32)) -- ^ Construct e.g. array of @(u, Word32)@ pairs. First argument is the -- upper bound, counting from 0. Value of upper bound is also valid index. -> Bool -- ^ Include upper characters. -> Bool -- ^ Include numbers. -> Bool -- ^ Include symbols. -> Input (t (u, Word32)) mkInput uLength mkContainer withUppers withNumbers withSymbols = Input { inVowels = mkContainer vowelsUpperBound vowels , inUpperBoundOfVowels = vowelsUpperBound , inConsonants = mkContainer consonantsUpperBound consonants , inUpperBoundOfConsonants = consonantsUpperBound , inNumbers = mkContainer numbersUpperBound numbers' , inUpperBoundOfNumbers = if withNumbers then numbersUpperBound else 0 , inSymbols = mkContainer symbolsUpperBound symbols' , inUpperBoundOfSymbols = if withSymbols then symbolsUpperBound else 0 , inCheckForUpperCharacters = not withUppers } where length' = fromIntegral . length vowels = map (\ x -> (x, uLength x)) . lowerVowels . lowerVowels . lowerVowels . (if withUppers then upperVowels else id) $ [] consonants = map (\ x -> (x, uLength x)) . lowerConsonants . lowerConsonants . lowerConsonants . (if withUppers then upperConsonants else id) $ [] numbers' = map (\ x -> (x, 1)) $ Pwgen.numbers (:) [] symbols' = map (\ x -> (x, 1)) $ Pwgen.symbols (:) [] vowelsUpperBound = length' vowels - 1 consonantsUpperBound = length' consonants - 1 numbersUpperBound = length' numbers' - 1 symbolsUpperBound = length' symbols' - 1 append :: [a] -> [a] -> [a] append = foldl (\ f -> (f .) . (:)) id lowerVowels :: (FromAscii a, IsString a) => [a] -> [a] lowerVowels = Pwgen.lowerVowels (:) . Pwgen.lowerVowels (:) . append ["ae", "ah", "ai", "ee", "ei", "ie", "oh", "oo"] lowerConsonants :: (FromAscii a, IsString a) => [a] -> [a] lowerConsonants = Pwgen.lowerConsonantsY (:) . Pwgen.lowerConsonantsY (:) . append ["ch", "gh", "ng", "ph", "qu", "sh", "th"] upperVowels :: (FromAscii a, IsString a) => [a] -> [a] upperVowels = Pwgen.upperVowels (:) . append [ "Ae", "aE", "Ah", "aH", "Ai", "aI", "Ee", "eE" , "Ei", "eI", "Ie", "iE", "Oh", "oH", "Oo", "oO" ] upperConsonants :: (FromAscii a, IsString a) => [a] -> [a] upperConsonants = Pwgen.upperConsonantsY (:) . append [ "Ch", "cH", "Gh", "gH", "Ng", "nG", "Ph" , "pH", "Qu", "qU", "Sh", "sH", "Th", "tH" ] -- | Generic configuration that doesn't rely on any particular string -- implementation. genPwConfig' :: (Monoid u) => (u -> Char) -- ^ Head function for @u@. -> (u -> Bool) -- ^ Function that checks if any character in @u@ is upper case. -> (t (u, Word32) -> Word32 -> (u, Word32)) -- ^ Index function for @t@ container with @(u, Word32)@ elements. -> Input (t (u, Word32)) -- ^ Input symbol sets, see 'Input' for details. -> GenPasswordConfig State (Input (t (u, Word32))) u u genPwConfig' head' isUpper' (!) input = GenPasswordConfig { genPwInIndex = index , genPwInMaxIndex = maxIndex , genPwStateTransformation = stateTransformation , genPwIn = input , genPwInitialState = initialState , genPwOutEmpty = mempty , genPwOutCons = flip mappend -- Concatenate in reverse order. , genPwOutCond = \ s _ -> (hasNumber <||> hasSymbol <||> hasUpper) s } where -- :: t -> (s, Word32) -> (a, Word32) index t (s, n) = case nextShouldBe s of -- In case of 'Nothing' we are randomly choosing from both, consonants -- and vowels. Nothing | n <= inUpperBoundOfVowels t -> inVowels t ! n | otherwise -> inConsonants t ! (n - inUpperBoundOfVowels t - 1) Just Vowel -> inVowels t ! n Just Consonant -> inConsonants t ! n Just Number -> inNumbers t ! n Just Symbol -> inSymbols t ! n -- :: s -> t -> Word32 maxIndex s t = case nextShouldBe s of Nothing -> inUpperBoundOfVowels t + inUpperBoundOfConsonants t + 1 Just Vowel -> inUpperBoundOfVowels t Just Consonant -> inUpperBoundOfConsonants t Just Number -> inUpperBoundOfNumbers t Just Symbol -> inUpperBoundOfSymbols t initialState = def { hasUpper = inCheckForUpperCharacters input , hasNumber = inUpperBoundOfNumbers input == 0 , hasSymbol = inUpperBoundOfSymbols input == 0 } -- :: (Applicative m, Functor m, Monad m) -- => (Word32 -> m Word32) -> s -> t -> (a, Word32) -> (u, Word32) -- -> m (Maybe s) stateTransformation genRand s t (xs, xlen) _ = do nextShouldBeNumber <- if inUpperBoundOfNumbers t == 0 then return False -- Numbers in password are disabled. else 3 >. genRand 10 nextShouldBeSymbol <- if inUpperBoundOfSymbols t == 0 then return False -- Symbols in password are disabled. else 2 >. genRand 10 let x = head' xs currentIs = ( fromMaybe (if Pwgen.isVowel x then Vowel else Consonant) $ nextShouldBe s , xlen > 0 ) case currentIs of (Consonant, isDipthong) | isDipthong && (is 'g' <||> is 'n') (toLower x) -> return Nothing -- "ng" and "gh" aren't allowed to be first in the password. | nextShouldBeNumber -> updateState s xs currentIs (Just Number) | nextShouldBeSymbol -> updateState s xs currentIs (Just Symbol) | otherwise -> updateState s xs currentIs (Just Vowel) (Vowel, isDipthong) | isDipthong && (fst <$> previousWas s) == Just Vowel -> return Nothing | nextShouldBeNumber -> updateState s xs currentIs (Just Number) | nextShouldBeSymbol -> updateState s xs currentIs (Just Symbol) | (fst <$> previousWas s) == Just Vowel || isDipthong -> updateState s xs currentIs (Just Consonant) | otherwise -> do nextShouldBeConsonant <- 3 >. genRand 10 updateState s xs currentIs . Just $ if nextShouldBeConsonant then Consonant else Vowel (Number, _) -> updateState s xs currentIs Nothing (Symbol, _) | (fst <$> previousWas s) == Just Vowel -> updateState s xs currentIs (Just Vowel) | otherwise -> do nextShouldBeConsonant <- 3 >. genRand 10 updateState s xs currentIs . Just $ if nextShouldBeConsonant then Consonant else Vowel updateState s xs currentIs@(cat, _) next = return $ Just State { previousWas = Just currentIs , nextShouldBe = next , hasSymbol = hasSymbol s || cat == Symbol , hasUpper = hasUpper s || isUpper' xs , hasNumber = hasNumber s || cat == Number } genPwConfigBS :: Bool -- ^ Include upper characters. -> Bool -- ^ Include numbers. -> Bool -- ^ Include symbols. -> GenPasswordConfig State (Input (Array Word32 (ByteString, Word32))) ByteString ByteString genPwConfigBS = ((genPwConfig' BS.head (BS.any isUpper) (Array.!) .) .) . mkInput (fromIntegral . BS.length) (Array.listArray . (,) 0) genPwConfig :: Bool -- ^ Include upper characters. -> Bool -- ^ Include numbers. -> Bool -- ^ Include symbols. -> GenPasswordConfig State (Input (Array Word32 (String, Word32))) String String genPwConfig = ((genPwConfig' head (any isUpper) (Array.!) .) .) . mkInput (fromIntegral . length) (Array.listArray . (,) 0)
trskop/hpwgen
src/Text/Pwgen/Pronounceable.hs
bsd-3-clause
10,752
0
19
2,910
2,664
1,483
1,181
185
17
{-# LANGUAGE CPP #-} #ifdef __GLASGOW_HASKELL__ {-# LANGUAGE DeriveDataTypeable #-} # if __GLASGOW_HASKELL__ >= 704 {-# LANGUAGE DeriveGeneric #-} # endif #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif #endif ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2012 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : portable -- -- The problem with locally nameless approaches is that original names are -- often useful for error reporting, or to allow for the user in an interactive -- theorem prover to convey some hint about the domain. A @'Name' n b@ is a value -- @b@ supplemented with a (discardable) name that may be useful for error -- reporting purposes. In particular, this name does not participate in -- comparisons for equality. -- -- This module is /not/ exported from "Bound" by default. You need to explicitly -- import it, due to the fact that 'Name' is a pretty common term in other -- people's code. ---------------------------------------------------------------------------- module Bound.Name ( Name(..) , _Name , name , abstractName , abstract1Name , instantiateName , instantiate1Name ) where import Bound.Scope import Bound.Var #if __GLASGOW_HASKELL__ < 710 import Control.Applicative #endif import Control.Comonad import Control.DeepSeq import Control.Monad (liftM, liftM2) #if __GLASGOW_HASKELL__ < 710 import Data.Foldable import Data.Monoid import Data.Traversable #endif import Data.Bifunctor import Data.Bifoldable import qualified Data.Binary as Binary import Data.Binary (Binary) import Data.Bitraversable import Data.Bytes.Serial import Data.Functor.Classes #ifdef __GLASGOW_HASKELL__ import Data.Data # if __GLASGOW_HASKELL__ >= 704 import GHC.Generics # endif #endif import Data.Hashable (Hashable(..)) import Data.Hashable.Lifted (Hashable1(..), Hashable2(..)) import Data.Profunctor import qualified Data.Serialize as Serialize import Data.Serialize (Serialize) ------------------------------------------------------------------------------- -- Names ------------------------------------------------------------------------------- -- | -- We track the choice of 'Name' @n@ as a forgettable property that does /not/ affect -- the result of ('==') or 'compare'. -- -- To compare names rather than values, use @('Data.Function.on' 'compare' 'name')@ instead. data Name n b = Name n b deriving ( Show , Read #ifdef __GLASGOW_HASKELL__ , Typeable , Data # if __GLASGOW_HASKELL__ >= 704 , Generic # endif #endif ) -- | Extract the 'name'. name :: Name n b -> n name (Name n _) = n {-# INLINE name #-} -- | -- -- This provides an 'Iso' that can be used to access the parts of a 'Name'. -- -- @ -- '_Name' :: Iso ('Name' n a) ('Name' m b) (n, a) (m, b) -- @ _Name :: (Profunctor p, Functor f) => p (n, a) (f (m,b)) -> p (Name n a) (f (Name m b)) _Name = dimap (\(Name n a) -> (n, a)) (fmap (uncurry Name)) {-# INLINE _Name #-} ------------------------------------------------------------------------------- -- Instances ------------------------------------------------------------------------------- instance Eq b => Eq (Name n b) where Name _ a == Name _ b = a == b {-# INLINE (==) #-} instance Hashable2 Name where liftHashWithSalt2 _ h s (Name _ a) = h s a {-# INLINE liftHashWithSalt2 #-} instance Hashable1 (Name n) where liftHashWithSalt h s (Name _ a) = h s a {-# INLINE liftHashWithSalt #-} instance Hashable a => Hashable (Name n a) where hashWithSalt m (Name _ a) = hashWithSalt m a {-# INLINE hashWithSalt #-} instance Ord b => Ord (Name n b) where Name _ a `compare` Name _ b = compare a b {-# INLINE compare #-} instance Functor (Name n) where fmap f (Name n a) = Name n (f a) {-# INLINE fmap #-} instance Foldable (Name n) where foldMap f (Name _ a) = f a {-# INLINE foldMap #-} instance Traversable (Name n) where traverse f (Name n a) = Name n <$> f a {-# INLINE traverse #-} instance Bifunctor Name where bimap f g (Name n a) = Name (f n) (g a) {-# INLINE bimap #-} instance Bifoldable Name where bifoldMap f g (Name n a) = f n `mappend` g a {-# INLINE bifoldMap #-} instance Bitraversable Name where bitraverse f g (Name n a) = Name <$> f n <*> g a {-# INLINE bitraverse #-} instance Comonad (Name n) where extract (Name _ b) = b {-# INLINE extract #-} extend f w@(Name n _) = Name n (f w) {-# INLINE extend #-} #if MIN_VERSION_transformers(0,5,0) || !MIN_VERSION_transformers(0,4,0) instance Eq2 Name where liftEq2 _ g (Name _ b) (Name _ d) = g b d instance Ord2 Name where liftCompare2 _ g (Name _ b) (Name _ d) = g b d instance Show2 Name where liftShowsPrec2 f _ h _ d (Name a b) = showsBinaryWith f h "Name" d a b instance Read2 Name where liftReadsPrec2 f _ h _ = readsData $ readsBinaryWith f h "Name" Name instance Eq1 (Name b) where liftEq f (Name _ b) (Name _ d) = f b d instance Ord1 (Name b) where liftCompare f (Name _ b) (Name _ d) = f b d instance Show b => Show1 (Name b) where liftShowsPrec f _ d (Name a b) = showsBinaryWith showsPrec f "Name" d a b instance Read b => Read1 (Name b) where liftReadsPrec f _ = readsData $ readsBinaryWith readsPrec f "Name" Name #else instance Eq1 (Name b) where eq1 = (==) instance Ord1 (Name b) where compare1 = compare instance Show b => Show1 (Name b) where showsPrec1 = showsPrec instance Read b => Read1 (Name b) where readsPrec1 = readsPrec --instance Eq2 Name where eq2 = (==) --instance Ord2 Name where compare2 = compare --instance Show2 Name where showsPrec2 = showsPrec --instance Read2 Name where readsPrec2 = readsPrec #endif instance Serial2 Name where serializeWith2 pb pf (Name b a) = pb b >> pf a {-# INLINE serializeWith2 #-} deserializeWith2 = liftM2 Name {-# INLINE deserializeWith2 #-} instance Serial b => Serial1 (Name b) where serializeWith = serializeWith2 serialize {-# INLINE serializeWith #-} deserializeWith = deserializeWith2 deserialize {-# INLINE deserializeWith #-} instance (Serial b, Serial a) => Serial (Name b a) where serialize = serializeWith2 serialize serialize {-# INLINE serialize #-} deserialize = deserializeWith2 deserialize deserialize {-# INLINE deserialize #-} instance (Binary b, Binary a) => Binary (Name b a) where put = serializeWith2 Binary.put Binary.put get = deserializeWith2 Binary.get Binary.get instance (Serialize b, Serialize a) => Serialize (Name b a) where put = serializeWith2 Serialize.put Serialize.put get = deserializeWith2 Serialize.get Serialize.get # if __GLASGOW_HASKELL__ >= 704 instance (NFData b, NFData a) => NFData (Name b a) # endif ------------------------------------------------------------------------------- -- Abstraction ------------------------------------------------------------------------------- -- | Abstraction, capturing named bound variables. abstractName :: Monad f => (a -> Maybe b) -> f a -> Scope (Name a b) f a abstractName f t = Scope (liftM k t) where k a = case f a of Just b -> B (Name a b) Nothing -> F (return a) {-# INLINE abstractName #-} -- | Abstract over a single variable abstract1Name :: (Monad f, Eq a) => a -> f a -> Scope (Name a ()) f a abstract1Name a = abstractName (\b -> if a == b then Just () else Nothing) {-# INLINE abstract1Name #-} ------------------------------------------------------------------------------- -- Instantiation ------------------------------------------------------------------------------- -- | Enter a scope, instantiating all bound variables, but discarding (comonadic) -- meta data, like its name instantiateName :: (Monad f, Comonad n) => (b -> f a) -> Scope (n b) f a -> f a instantiateName k e = unscope e >>= \v -> case v of B b -> k (extract b) F a -> a {-# INLINE instantiateName #-} -- | Enter a 'Scope' that binds one (named) variable, instantiating it. -- -- @'instantiate1Name' = 'instantiate1'@ instantiate1Name :: Monad f => f a -> Scope n f a -> f a instantiate1Name = instantiate1 {-# INLINE instantiate1Name #-}
treeowl/bound
src/Bound/Name.hs
bsd-3-clause
8,193
0
12
1,485
2,010
1,072
938
131
2
module Main where main :: IO () main = do putStrLn "Here we do the DEMO..."
qrilka/kontiki-demo
src/Main.hs
bsd-3-clause
81
0
7
21
25
13
12
4
1
-- ------------------------------------------------------------ {- | Module : Yuuko.Text.XML.HXT.DOM.Unicode Copyright : Copyright (C) 2005-2008 Uwe Schmidt License : MIT Maintainer : Uwe Schmidt ([email protected]) Stability : experimental Portability: portable Unicode and UTF-8 Conversion Functions -} -- ------------------------------------------------------------ module Yuuko.Text.XML.HXT.DOM.Unicode ( -- * Unicode Type declarations Unicode, UString, UTF8Char, UTF8String, UStringWithErrors, DecodingFct, DecodingFctEmbedErrors, -- * XML char predicates isXmlChar , isXmlLatin1Char , isXmlSpaceChar , isXml11SpaceChar , isXmlNameChar , isXmlNameStartChar , isXmlNCNameChar , isXmlNCNameStartChar , isXmlPubidChar , isXmlLetter , isXmlBaseChar , isXmlIdeographicChar , isXmlCombiningChar , isXmlDigit , isXmlExtender , isXmlControlOrPermanentlyUndefined -- * UTF-8 and Unicode conversion functions , utf8ToUnicode , utf8ToUnicodeEmbedErrors , latin1ToUnicode , ucs2ToUnicode , ucs2BigEndianToUnicode , ucs2LittleEndianToUnicode , utf16beToUnicode , utf16leToUnicode , unicodeCharToUtf8 , unicodeToUtf8 , unicodeToXmlEntity , unicodeToLatin1 , unicodeRemoveNoneAscii , unicodeRemoveNoneLatin1 , intToCharRef , intToCharRefHex , getDecodingFct , getDecodingFctEmbedErrors , getOutputEncodingFct , normalizeNL , guessEncoding ) where import Data.Char( toUpper ) import Yuuko.Text.XML.HXT.DOM.Util ( swap, partitionEither ) import Yuuko.Text.XML.HXT.DOM.IsoLatinTables import Yuuko.Text.XML.HXT.DOM.UTF8Decoding ( decodeUtf8, decodeUtf8EmbedErrors ) import Yuuko.Text.XML.HXT.DOM.Util ( intToHexString ) import Yuuko.Text.XML.HXT.DOM.XmlKeywords -- ------------------------------------------------------------ -- | Unicode is represented as the Char type -- Precondition for this is the support of Unicode character range -- in the compiler (e.g. ghc but not hugs) type Unicode = Char -- | the type for Unicode strings type UString = [Unicode] -- | UTF-8 charachters are represented by the Char type type UTF8Char = Char -- | UTF-8 strings are implemented as Haskell strings type UTF8String = String -- | Decoding function with a pair containing the result string and a list of decoding errors as result type DecodingFct = String -> (UString, [String]) type UStringWithErrors = [Either String Char] -- | Decoding function where decoding errors are interleaved with decoded characters type DecodingFctEmbedErrors = String -> UStringWithErrors -- ------------------------------------------------------------ -- -- Unicode predicates -- | -- test for a legal 1 byte XML char is1ByteXmlChar :: Unicode -> Bool is1ByteXmlChar c = c < '\x80' && ( c >= ' ' || c == '\n' || c == '\t' || c == '\r' ) -- | -- test for a legal latin1 XML char isXmlLatin1Char :: Unicode -> Bool isXmlLatin1Char i = is1ByteXmlChar i || (i >= '\x80' && i <= '\xff') -- ------------------------------------------------------------ -- | -- conversion from Unicode strings (UString) to UTF8 encoded strings. unicodeToUtf8 :: UString -> UTF8String unicodeToUtf8 = concatMap unicodeCharToUtf8 -- | -- conversion from Unicode (Char) to a UTF8 encoded string. unicodeCharToUtf8 :: Unicode -> UTF8String unicodeCharToUtf8 c | i >= 0 && i <= 0x0000007F -- 1 byte UTF8 (7 bits) = [ toEnum i ] | i >= 0x00000080 && i <= 0x000007FF -- 2 byte UTF8 (5 + 6 bits) = [ toEnum (0xC0 + i `div` 0x40) , toEnum (0x80 + i `mod` 0x40) ] | i >= 0x00000800 && i <= 0x0000FFFF -- 3 byte UTF8 (4 + 6 + 6 bits) = [ toEnum (0xE0 + i `div` 0x1000) , toEnum (0x80 + (i `div` 0x40) `mod` 0x40) , toEnum (0x80 + i `mod` 0x40) ] | i >= 0x00010000 && i <= 0x001FFFFF -- 4 byte UTF8 (3 + 6 + 6 + 6 bits) = [ toEnum (0xF0 + i `div` 0x40000) , toEnum (0x80 + (i `div` 0x1000) `mod` 0x40) , toEnum (0x80 + (i `div` 0x40) `mod` 0x40) , toEnum (0x80 + i `mod` 0x40) ] | i >= 0x00200000 && i <= 0x03FFFFFF -- 5 byte UTF8 (2 + 6 + 6 + 6 + 6 bits) = [ toEnum (0xF8 + i `div` 0x1000000) , toEnum (0x80 + (i `div` 0x40000) `mod` 0x40) , toEnum (0x80 + (i `div` 0x1000) `mod` 0x40) , toEnum (0x80 + (i `div` 0x40) `mod` 0x40) , toEnum (0x80 + i `mod` 0x40) ] | i >= 0x04000000 && i <= 0x7FFFFFFF -- 6 byte UTF8 (1 + 6 + 6 + 6 + 6 + 6 bits) = [ toEnum (0xFC + i `div` 0x40000000) , toEnum (0x80 + (i `div` 0x1000000) `mod` 0x40) , toEnum (0x80 + (i `div` 0x40000) `mod` 0x40) , toEnum (0x80 + (i `div` 0x1000) `mod` 0x40) , toEnum (0x80 + (i `div` 0x40) `mod` 0x40) , toEnum (0x80 + i `mod` 0x40) ] | otherwise -- other values not supported = error ("unicodeCharToUtf8: illegal integer argument " ++ show i) where i = fromEnum c -- ------------------------------------------------------------ -- | -- checking for valid XML characters isXmlChar :: Unicode -> Bool isXmlChar c = isInList c [ ('\x0009', '\x000A') , ('\x000D', '\x000D') , ('\x0020', '\xD7FF') , ('\xE000', '\xFFFD') , ('\x10000', '\x10FFFF') ] -- | -- checking for XML space character: \\\n, \\\r, \\\t and \" \" isXmlSpaceChar :: Unicode -> Bool isXmlSpaceChar c = c `elem` ['\x20', '\x09', '\x0D', '\x0A'] -- | -- checking for XML1.1 space character: additional space 0x85 and 0x2028 -- -- see also : 'isXmlSpaceChar' isXml11SpaceChar :: Unicode -> Bool isXml11SpaceChar c = c `elem` ['\x20', '\x09', '\x0D', '\x0A', '\x85', '\x2028'] -- | -- checking for XML name character isXmlNameChar :: Unicode -> Bool isXmlNameChar c = isXmlLetter c || isXmlDigit c || (c == '\x2D' || c == '\x2E') -- '-' | '.' || (c == '\x3A' || c == '\x5F') -- Letter | ':' | '_' || isXmlCombiningChar c || isXmlExtender c -- | -- checking for XML name start character -- -- see also : 'isXmlNameChar' isXmlNameStartChar :: Unicode -> Bool isXmlNameStartChar c = isXmlLetter c || (c == '\x3A' || c == '\x5F') -- Letter | ':' | '_' -- | -- checking for XML NCName character: no \":\" allowed -- -- see also : 'isXmlNameChar' isXmlNCNameChar :: Unicode -> Bool isXmlNCNameChar c = c /= '\x3A' && isXmlNameChar c -- | -- checking for XML NCName start character: no \":\" allowed -- -- see also : 'isXmlNameChar', 'isXmlNCNameChar' isXmlNCNameStartChar :: Unicode -> Bool isXmlNCNameStartChar c = c /= '\x3A' && isXmlNameStartChar c -- | -- checking for XML public id character isXmlPubidChar :: Unicode -> Bool isXmlPubidChar c = isInList c [ ('0', '9') , ('A', 'Z') , ('a', 'z') ] || ( c `elem` " \r\n-'()+,./:=?;!*#@$_%" ) -- | -- checking for XML letter isXmlLetter :: Unicode -> Bool isXmlLetter c = isXmlBaseChar c || isXmlIdeographicChar c -- | -- checking for XML base charater isXmlBaseChar :: Unicode -> Bool isXmlBaseChar c = isInList c [ ('\x0041', '\x005A') , ('\x0061', '\x007A') , ('\x00C0', '\x00D6') , ('\x00D8', '\x00F6') , ('\x00F8', '\x0131') , ('\x0134', '\x013E') , ('\x0141', '\x0148') , ('\x014A', '\x017E') , ('\x0180', '\x01C3') , ('\x01CD', '\x01F0') , ('\x01F4', '\x01F5') , ('\x01FA', '\x0217') , ('\x0250', '\x02A8') , ('\x02BB', '\x02C1') , ('\x0386', '\x0386') , ('\x0388', '\x038A') , ('\x038C', '\x038C') , ('\x038E', '\x03A1') , ('\x03A3', '\x03CE') , ('\x03D0', '\x03D6') , ('\x03DA', '\x03DA') , ('\x03DC', '\x03DC') , ('\x03DE', '\x03DE') , ('\x03E0', '\x03E0') , ('\x03E2', '\x03F3') , ('\x0401', '\x040C') , ('\x040E', '\x044F') , ('\x0451', '\x045C') , ('\x045E', '\x0481') , ('\x0490', '\x04C4') , ('\x04C7', '\x04C8') , ('\x04CB', '\x04CC') , ('\x04D0', '\x04EB') , ('\x04EE', '\x04F5') , ('\x04F8', '\x04F9') , ('\x0531', '\x0556') , ('\x0559', '\x0559') , ('\x0561', '\x0586') , ('\x05D0', '\x05EA') , ('\x05F0', '\x05F2') , ('\x0621', '\x063A') , ('\x0641', '\x064A') , ('\x0671', '\x06B7') , ('\x06BA', '\x06BE') , ('\x06C0', '\x06CE') , ('\x06D0', '\x06D3') , ('\x06D5', '\x06D5') , ('\x06E5', '\x06E6') , ('\x0905', '\x0939') , ('\x093D', '\x093D') , ('\x0958', '\x0961') , ('\x0985', '\x098C') , ('\x098F', '\x0990') , ('\x0993', '\x09A8') , ('\x09AA', '\x09B0') , ('\x09B2', '\x09B2') , ('\x09B6', '\x09B9') , ('\x09DC', '\x09DD') , ('\x09DF', '\x09E1') , ('\x09F0', '\x09F1') , ('\x0A05', '\x0A0A') , ('\x0A0F', '\x0A10') , ('\x0A13', '\x0A28') , ('\x0A2A', '\x0A30') , ('\x0A32', '\x0A33') , ('\x0A35', '\x0A36') , ('\x0A38', '\x0A39') , ('\x0A59', '\x0A5C') , ('\x0A5E', '\x0A5E') , ('\x0A72', '\x0A74') , ('\x0A85', '\x0A8B') , ('\x0A8D', '\x0A8D') , ('\x0A8F', '\x0A91') , ('\x0A93', '\x0AA8') , ('\x0AAA', '\x0AB0') , ('\x0AB2', '\x0AB3') , ('\x0AB5', '\x0AB9') , ('\x0ABD', '\x0ABD') , ('\x0AE0', '\x0AE0') , ('\x0B05', '\x0B0C') , ('\x0B0F', '\x0B10') , ('\x0B13', '\x0B28') , ('\x0B2A', '\x0B30') , ('\x0B32', '\x0B33') , ('\x0B36', '\x0B39') , ('\x0B3D', '\x0B3D') , ('\x0B5C', '\x0B5D') , ('\x0B5F', '\x0B61') , ('\x0B85', '\x0B8A') , ('\x0B8E', '\x0B90') , ('\x0B92', '\x0B95') , ('\x0B99', '\x0B9A') , ('\x0B9C', '\x0B9C') , ('\x0B9E', '\x0B9F') , ('\x0BA3', '\x0BA4') , ('\x0BA8', '\x0BAA') , ('\x0BAE', '\x0BB5') , ('\x0BB7', '\x0BB9') , ('\x0C05', '\x0C0C') , ('\x0C0E', '\x0C10') , ('\x0C12', '\x0C28') , ('\x0C2A', '\x0C33') , ('\x0C35', '\x0C39') , ('\x0C60', '\x0C61') , ('\x0C85', '\x0C8C') , ('\x0C8E', '\x0C90') , ('\x0C92', '\x0CA8') , ('\x0CAA', '\x0CB3') , ('\x0CB5', '\x0CB9') , ('\x0CDE', '\x0CDE') , ('\x0CE0', '\x0CE1') , ('\x0D05', '\x0D0C') , ('\x0D0E', '\x0D10') , ('\x0D12', '\x0D28') , ('\x0D2A', '\x0D39') , ('\x0D60', '\x0D61') , ('\x0E01', '\x0E2E') , ('\x0E30', '\x0E30') , ('\x0E32', '\x0E33') , ('\x0E40', '\x0E45') , ('\x0E81', '\x0E82') , ('\x0E84', '\x0E84') , ('\x0E87', '\x0E88') , ('\x0E8A', '\x0E8A') , ('\x0E8D', '\x0E8D') , ('\x0E94', '\x0E97') , ('\x0E99', '\x0E9F') , ('\x0EA1', '\x0EA3') , ('\x0EA5', '\x0EA5') , ('\x0EA7', '\x0EA7') , ('\x0EAA', '\x0EAB') , ('\x0EAD', '\x0EAE') , ('\x0EB0', '\x0EB0') , ('\x0EB2', '\x0EB3') , ('\x0EBD', '\x0EBD') , ('\x0EC0', '\x0EC4') , ('\x0F40', '\x0F47') , ('\x0F49', '\x0F69') , ('\x10A0', '\x10C5') , ('\x10D0', '\x10F6') , ('\x1100', '\x1100') , ('\x1102', '\x1103') , ('\x1105', '\x1107') , ('\x1109', '\x1109') , ('\x110B', '\x110C') , ('\x110E', '\x1112') , ('\x113C', '\x113C') , ('\x113E', '\x113E') , ('\x1140', '\x1140') , ('\x114C', '\x114C') , ('\x114E', '\x114E') , ('\x1150', '\x1150') , ('\x1154', '\x1155') , ('\x1159', '\x1159') , ('\x115F', '\x1161') , ('\x1163', '\x1163') , ('\x1165', '\x1165') , ('\x1167', '\x1167') , ('\x1169', '\x1169') , ('\x116D', '\x116E') , ('\x1172', '\x1173') , ('\x1175', '\x1175') , ('\x119E', '\x119E') , ('\x11A8', '\x11A8') , ('\x11AB', '\x11AB') , ('\x11AE', '\x11AF') , ('\x11B7', '\x11B8') , ('\x11BA', '\x11BA') , ('\x11BC', '\x11C2') , ('\x11EB', '\x11EB') , ('\x11F0', '\x11F0') , ('\x11F9', '\x11F9') , ('\x1E00', '\x1E9B') , ('\x1EA0', '\x1EF9') , ('\x1F00', '\x1F15') , ('\x1F18', '\x1F1D') , ('\x1F20', '\x1F45') , ('\x1F48', '\x1F4D') , ('\x1F50', '\x1F57') , ('\x1F59', '\x1F59') , ('\x1F5B', '\x1F5B') , ('\x1F5D', '\x1F5D') , ('\x1F5F', '\x1F7D') , ('\x1F80', '\x1FB4') , ('\x1FB6', '\x1FBC') , ('\x1FBE', '\x1FBE') , ('\x1FC2', '\x1FC4') , ('\x1FC6', '\x1FCC') , ('\x1FD0', '\x1FD3') , ('\x1FD6', '\x1FDB') , ('\x1FE0', '\x1FEC') , ('\x1FF2', '\x1FF4') , ('\x1FF6', '\x1FFC') , ('\x2126', '\x2126') , ('\x212A', '\x212B') , ('\x212E', '\x212E') , ('\x2180', '\x2182') , ('\x3041', '\x3094') , ('\x30A1', '\x30FA') , ('\x3105', '\x312C') , ('\xAC00', '\xD7A3') ] -- | -- checking for XML ideographic charater isXmlIdeographicChar :: Unicode -> Bool isXmlIdeographicChar c = isInList c [ ('\x3007', '\x3007') , ('\x3021', '\x3029') , ('\x4E00', '\x9FA5') ] -- | -- checking for XML combining charater isXmlCombiningChar :: Unicode -> Bool isXmlCombiningChar c = isInList c [ ('\x0300', '\x0345') , ('\x0360', '\x0361') , ('\x0483', '\x0486') , ('\x0591', '\x05A1') , ('\x05A3', '\x05B9') , ('\x05BB', '\x05BD') , ('\x05BF', '\x05BF') , ('\x05C1', '\x05C2') , ('\x05C4', '\x05C4') , ('\x064B', '\x0652') , ('\x0670', '\x0670') , ('\x06D6', '\x06DC') , ('\x06DD', '\x06DF') , ('\x06E0', '\x06E4') , ('\x06E7', '\x06E8') , ('\x06EA', '\x06ED') , ('\x0901', '\x0903') , ('\x093C', '\x093C') , ('\x093E', '\x094C') , ('\x094D', '\x094D') , ('\x0951', '\x0954') , ('\x0962', '\x0963') , ('\x0981', '\x0983') , ('\x09BC', '\x09BC') , ('\x09BE', '\x09BE') , ('\x09BF', '\x09BF') , ('\x09C0', '\x09C4') , ('\x09C7', '\x09C8') , ('\x09CB', '\x09CD') , ('\x09D7', '\x09D7') , ('\x09E2', '\x09E3') , ('\x0A02', '\x0A02') , ('\x0A3C', '\x0A3C') , ('\x0A3E', '\x0A3E') , ('\x0A3F', '\x0A3F') , ('\x0A40', '\x0A42') , ('\x0A47', '\x0A48') , ('\x0A4B', '\x0A4D') , ('\x0A70', '\x0A71') , ('\x0A81', '\x0A83') , ('\x0ABC', '\x0ABC') , ('\x0ABE', '\x0AC5') , ('\x0AC7', '\x0AC9') , ('\x0ACB', '\x0ACD') , ('\x0B01', '\x0B03') , ('\x0B3C', '\x0B3C') , ('\x0B3E', '\x0B43') , ('\x0B47', '\x0B48') , ('\x0B4B', '\x0B4D') , ('\x0B56', '\x0B57') , ('\x0B82', '\x0B83') , ('\x0BBE', '\x0BC2') , ('\x0BC6', '\x0BC8') , ('\x0BCA', '\x0BCD') , ('\x0BD7', '\x0BD7') , ('\x0C01', '\x0C03') , ('\x0C3E', '\x0C44') , ('\x0C46', '\x0C48') , ('\x0C4A', '\x0C4D') , ('\x0C55', '\x0C56') , ('\x0C82', '\x0C83') , ('\x0CBE', '\x0CC4') , ('\x0CC6', '\x0CC8') , ('\x0CCA', '\x0CCD') , ('\x0CD5', '\x0CD6') , ('\x0D02', '\x0D03') , ('\x0D3E', '\x0D43') , ('\x0D46', '\x0D48') , ('\x0D4A', '\x0D4D') , ('\x0D57', '\x0D57') , ('\x0E31', '\x0E31') , ('\x0E34', '\x0E3A') , ('\x0E47', '\x0E4E') , ('\x0EB1', '\x0EB1') , ('\x0EB4', '\x0EB9') , ('\x0EBB', '\x0EBC') , ('\x0EC8', '\x0ECD') , ('\x0F18', '\x0F19') , ('\x0F35', '\x0F35') , ('\x0F37', '\x0F37') , ('\x0F39', '\x0F39') , ('\x0F3E', '\x0F3E') , ('\x0F3F', '\x0F3F') , ('\x0F71', '\x0F84') , ('\x0F86', '\x0F8B') , ('\x0F90', '\x0F95') , ('\x0F97', '\x0F97') , ('\x0F99', '\x0FAD') , ('\x0FB1', '\x0FB7') , ('\x0FB9', '\x0FB9') , ('\x20D0', '\x20DC') , ('\x20E1', '\x20E1') , ('\x302A', '\x302F') , ('\x3099', '\x3099') , ('\x309A', '\x309A') ] -- | -- checking for XML digit isXmlDigit :: Unicode -> Bool isXmlDigit c = isInList c [ ('\x0030', '\x0039') , ('\x0660', '\x0669') , ('\x06F0', '\x06F9') , ('\x0966', '\x096F') , ('\x09E6', '\x09EF') , ('\x0A66', '\x0A6F') , ('\x0AE6', '\x0AEF') , ('\x0B66', '\x0B6F') , ('\x0BE7', '\x0BEF') , ('\x0C66', '\x0C6F') , ('\x0CE6', '\x0CEF') , ('\x0D66', '\x0D6F') , ('\x0E50', '\x0E59') , ('\x0ED0', '\x0ED9') , ('\x0F20', '\x0F29') ] -- | -- checking for XML extender isXmlExtender :: Unicode -> Bool isXmlExtender c = isInList c [ ('\x00B7', '\x00B7') , ('\x02D0', '\x02D0') , ('\x02D1', '\x02D1') , ('\x0387', '\x0387') , ('\x0640', '\x0640') , ('\x0E46', '\x0E46') , ('\x0EC6', '\x0EC6') , ('\x3005', '\x3005') , ('\x3031', '\x3035') , ('\x309D', '\x309E') , ('\x30FC', '\x30FE') ] -- | -- checking for XML control or permanently discouraged char -- -- see Errata to XML1.0 (http:\/\/www.w3.org\/XML\/xml-V10-2e-errata) No 46 -- -- Document authors are encouraged to avoid "compatibility characters", -- as defined in section 6.8 of [Unicode] (see also D21 in section 3.6 of [Unicode3]). -- The characters defined in the following ranges are also discouraged. -- They are either control characters or permanently undefined Unicode characters: isXmlControlOrPermanentlyUndefined :: Unicode -> Bool isXmlControlOrPermanentlyUndefined c = isInList c [ ('\x7F', '\x84') , ('\x86', '\x9F') , ('\xFDD0', '\xFDDF') , ('\x1FFFE', '\x1FFFF') , ('\x2FFFE', '\x2FFFF') , ('\x3FFFE', '\x3FFFF') , ('\x4FFFE', '\x4FFFF') , ('\x5FFFE', '\x5FFFF') , ('\x6FFFE', '\x6FFFF') , ('\x7FFFE', '\x7FFFF') , ('\x8FFFE', '\x8FFFF') , ('\x9FFFE', '\x9FFFF') , ('\xAFFFE', '\xAFFFF') , ('\xBFFFE', '\xBFFFF') , ('\xCFFFE', '\xCFFFF') , ('\xDFFFE', '\xDFFFF') , ('\xEFFFE', '\xEFFFF') , ('\xFFFFE', '\xFFFFF') , ('\x10FFFE', '\x10FFFF') ] -- ------------------------------------------------------------ isInList :: Unicode -> [(Unicode, Unicode)] -> Bool isInList i = foldr (\(lb, ub) b -> i >= lb && (i <= ub || b)) False {- The expression (i>=lb && i<=ub) || b would work more generally, but in a sorted list, the above one aborts the computation as early as possible. -} {- isInList' :: Unicode -> [(Unicode, Unicode)] -> Bool isInList' i ((lb, ub) : l) | i < lb = False | i <= ub = True | otherwise = isInList' i l isInList' _ [] = False {- works, but is not so fast -} isInList'' :: Unicode -> [(Unicode, Unicode)] -> Bool isInList'' i = any (flip isInRange i) -- move to an Utility module? isInRange :: Ord a => (a,a) -> a -> Bool isInRange (l,r) x = l<=x && x<=r propIsInList :: Bool propIsInList = all (\c -> let dict = [ ('\x0041', '\x005A'), ('\x0061', '\x007A') ] b0 = isInList c dict b1 = isInList' c dict b2 = isInList'' c dict in b0 == b1 && b0 == b2) ['\x00'..'\x100'] -} -- ------------------------------------------------------------ -- | -- code conversion from latin1 to Unicode latin1ToUnicode :: String -> UString latin1ToUnicode = id latinToUnicode :: [(Char, Char)] -> String -> UString latinToUnicode tt = map charToUni where charToUni c = foldr (\(src,dst) r -> case compare c src of EQ -> dst LT -> c {- not found in table -} GT -> r) c tt -- | conversion from ASCII to unicode with check for legal ASCII char set -- -- Structure of decoding function copied from 'Yuuko.Data.Char.UTF8.decode'. decodeAscii :: DecodingFct decodeAscii = swap . partitionEither . decodeAsciiEmbedErrors decodeAsciiEmbedErrors :: String -> UStringWithErrors decodeAsciiEmbedErrors str = map (\(c,pos) -> if isValid c then Right c else Left (toErrStr c pos)) posStr where posStr = zip str [(0::Int)..] toErrStr errChr pos = " at input position " ++ show pos ++ ": none ASCII char " ++ show errChr isValid x = x < '\x80' -- | -- UCS-2 big endian to Unicode conversion ucs2BigEndianToUnicode :: String -> UString ucs2BigEndianToUnicode (b : l : r) = toEnum (fromEnum b * 256 + fromEnum l) : ucs2BigEndianToUnicode r ucs2BigEndianToUnicode [] = [] ucs2BigEndianToUnicode _ = [] -- error "illegal UCS-2 byte input sequence with odd length" -- is ignored (garbage in, garbage out) -- ------------------------------------------------------------ -- | -- UCS-2 little endian to Unicode conversion ucs2LittleEndianToUnicode :: String -> UString ucs2LittleEndianToUnicode (l : b : r) = toEnum (fromEnum b * 256 + fromEnum l) : ucs2LittleEndianToUnicode r ucs2LittleEndianToUnicode [] = [] ucs2LittleEndianToUnicode [_] = [] -- error "illegal UCS-2 byte input sequence with odd length" -- is ignored -- ------------------------------------------------------------ -- | -- UCS-2 to UTF-8 conversion with byte order mark analysis ucs2ToUnicode :: String -> UString ucs2ToUnicode ('\xFE':'\xFF':s) -- 2 byte mark for big endian encoding = ucs2BigEndianToUnicode s ucs2ToUnicode ('\xFF':'\xFE':s) -- 2 byte mark for little endian encoding = ucs2LittleEndianToUnicode s ucs2ToUnicode s = ucs2BigEndianToUnicode s -- default: big endian -- ------------------------------------------------------------ -- | -- UTF-8 to Unicode conversion with deletion of leading byte order mark, as described in XML standard F.1 utf8ToUnicode :: DecodingFct utf8ToUnicode ('\xEF':'\xBB':'\xBF':s) -- remove byte order mark ( XML standard F.1 ) = decodeUtf8 s utf8ToUnicode s = decodeUtf8 s utf8ToUnicodeEmbedErrors :: DecodingFctEmbedErrors utf8ToUnicodeEmbedErrors ('\xEF':'\xBB':'\xBF':s) -- remove byte order mark ( XML standard F.1 ) = decodeUtf8EmbedErrors s utf8ToUnicodeEmbedErrors s = decodeUtf8EmbedErrors s -- ------------------------------------------------------------ -- | -- UTF-16 big endian to UTF-8 conversion with removal of byte order mark utf16beToUnicode :: String -> UString utf16beToUnicode ('\xFE':'\xFF':s) -- remove byte order mark = ucs2BigEndianToUnicode s utf16beToUnicode s = ucs2BigEndianToUnicode s -- ------------------------------------------------------------ -- | -- UTF-16 little endian to UTF-8 conversion with removal of byte order mark utf16leToUnicode :: String -> UString utf16leToUnicode ('\xFF':'\xFE':s) -- remove byte order mark = ucs2LittleEndianToUnicode s utf16leToUnicode s = ucs2LittleEndianToUnicode s -- ------------------------------------------------------------ -- | -- substitute all Unicode characters, that are not legal 1-byte -- UTF-8 XML characters by a character reference. -- -- This function can be used to translate all text nodes and -- attribute values into pure ascii. -- -- see also : 'unicodeToLatin1' unicodeToXmlEntity :: UString -> String unicodeToXmlEntity = escape is1ByteXmlChar (intToCharRef . fromEnum) -- | -- substitute all Unicode characters, that are not legal latin1 -- UTF-8 XML characters by a character reference. -- -- This function can be used to translate all text nodes and -- attribute values into ISO latin1. -- -- see also : 'unicodeToXmlEntity' unicodeToLatin1 :: UString -> String unicodeToLatin1 = escape isXmlLatin1Char (intToCharRef . fromEnum) -- | -- substitute selected characters -- The @check@ function returns 'True' whenever a character needs to substitution -- The function @esc@ computes a substitute. escape :: (Unicode -> Bool) -> (Unicode -> String) -> UString -> String escape check esc = concatMap (\uc -> if check uc then [uc] else esc uc) -- | -- removes all non ascii chars, may be used to transform -- a document into a pure ascii representation by removing -- all non ascii chars from tag and attibute names -- -- see also : 'unicodeRemoveNoneLatin1', 'unicodeToXmlEntity' unicodeRemoveNoneAscii :: UString -> String unicodeRemoveNoneAscii = filter is1ByteXmlChar -- | -- removes all non latin1 chars, may be used to transform -- a document into a pure ascii representation by removing -- all non ascii chars from tag and attibute names -- -- see also : 'unicodeRemoveNoneAscii', 'unicodeToLatin1' unicodeRemoveNoneLatin1 :: UString -> String unicodeRemoveNoneLatin1 = filter isXmlLatin1Char -- ------------------------------------------------------------ -- | -- convert an Unicode into a XML character reference. -- -- see also : 'intToCharRefHex' intToCharRef :: Int -> String intToCharRef i = "&#" ++ show i ++ ";" -- | -- convert an Unicode into a XML hexadecimal character reference. -- -- see also: 'intToCharRef' intToCharRefHex :: Int -> String intToCharRefHex i = "&#x" ++ h2 ++ ";" where h1 = intToHexString i h2 = if length h1 `mod` 2 == 1 then '0': h1 else h1 -- ------------------------------------------------------------ -- -- | White Space (XML Standard 2.3) and -- end of line handling (2.11) -- -- \#x0D and \#x0D\#x0A are mapped to \#x0A normalizeNL :: String -> String normalizeNL ('\r' : '\n' : rest) = '\n' : normalizeNL rest normalizeNL ('\r' : rest) = '\n' : normalizeNL rest normalizeNL (c : rest) = c : normalizeNL rest normalizeNL [] = [] -- ------------------------------------------------------------ -- | -- the table of supported character encoding schemes and the associated -- conversion functions into Unicode:q {- This table could be derived from decodingTableEither, but this way it is certainly more efficient. -} decodingTable :: [(String, DecodingFct)] decodingTable = [ (utf8, utf8ToUnicode ) , (isoLatin1, liftDecFct latin1ToUnicode ) , (usAscii, decodeAscii ) , (ucs2, liftDecFct ucs2ToUnicode ) , (utf16, liftDecFct ucs2ToUnicode ) , (utf16be, liftDecFct utf16beToUnicode ) , (utf16le, liftDecFct utf16leToUnicode ) , (iso8859_2, liftDecFct (latinToUnicode iso_8859_2) ) , (iso8859_3, liftDecFct (latinToUnicode iso_8859_3) ) , (iso8859_4, liftDecFct (latinToUnicode iso_8859_4) ) , (iso8859_5, liftDecFct (latinToUnicode iso_8859_5) ) , (iso8859_6, liftDecFct (latinToUnicode iso_8859_6) ) , (iso8859_7, liftDecFct (latinToUnicode iso_8859_7) ) , (iso8859_8, liftDecFct (latinToUnicode iso_8859_8) ) , (iso8859_9, liftDecFct (latinToUnicode iso_8859_9) ) , (iso8859_10, liftDecFct (latinToUnicode iso_8859_10) ) , (iso8859_11, liftDecFct (latinToUnicode iso_8859_11) ) , (iso8859_13, liftDecFct (latinToUnicode iso_8859_13) ) , (iso8859_14, liftDecFct (latinToUnicode iso_8859_14) ) , (iso8859_15, liftDecFct (latinToUnicode iso_8859_15) ) , (iso8859_16, liftDecFct (latinToUnicode iso_8859_16) ) , (unicodeString, liftDecFct id ) , ("", liftDecFct id ) -- default ] where liftDecFct df = \ s -> (df s, []) -- | -- the lookup function for selecting the decoding function getDecodingFct :: String -> Maybe DecodingFct getDecodingFct enc = lookup (map toUpper enc) decodingTable -- | -- Similar to 'decodingTable' but it embeds errors -- in the string of decoded characters. decodingTableEmbedErrors :: [(String, DecodingFctEmbedErrors)] decodingTableEmbedErrors = [ (utf8, utf8ToUnicodeEmbedErrors ) , (isoLatin1, liftDecFct latin1ToUnicode ) , (usAscii, decodeAsciiEmbedErrors ) , (ucs2, liftDecFct ucs2ToUnicode ) , (utf16, liftDecFct ucs2ToUnicode ) , (utf16be, liftDecFct utf16beToUnicode ) , (utf16le, liftDecFct utf16leToUnicode ) , (iso8859_2, liftDecFct (latinToUnicode iso_8859_2) ) , (iso8859_3, liftDecFct (latinToUnicode iso_8859_3) ) , (iso8859_4, liftDecFct (latinToUnicode iso_8859_4) ) , (iso8859_5, liftDecFct (latinToUnicode iso_8859_5) ) , (iso8859_6, liftDecFct (latinToUnicode iso_8859_6) ) , (iso8859_7, liftDecFct (latinToUnicode iso_8859_7) ) , (iso8859_8, liftDecFct (latinToUnicode iso_8859_8) ) , (iso8859_9, liftDecFct (latinToUnicode iso_8859_9) ) , (iso8859_10, liftDecFct (latinToUnicode iso_8859_10) ) , (iso8859_11, liftDecFct (latinToUnicode iso_8859_11) ) , (iso8859_13, liftDecFct (latinToUnicode iso_8859_13) ) , (iso8859_14, liftDecFct (latinToUnicode iso_8859_14) ) , (iso8859_15, liftDecFct (latinToUnicode iso_8859_15) ) , (iso8859_16, liftDecFct (latinToUnicode iso_8859_16) ) , (unicodeString, liftDecFct id ) , ("", liftDecFct id ) -- default ] where liftDecFct df = map Right . df -- | -- the lookup function for selecting the decoding function getDecodingFctEmbedErrors :: String -> Maybe DecodingFctEmbedErrors getDecodingFctEmbedErrors enc = lookup (map toUpper enc) decodingTableEmbedErrors -- | -- the table of supported output encoding schemes and the associated -- conversion functions from Unicode outputEncodingTable :: [(String, (UString -> String))] outputEncodingTable = [ (utf8, unicodeToUtf8 ) , (isoLatin1, unicodeToLatin1 ) , (usAscii, unicodeToXmlEntity ) , (ucs2, ucs2ToUnicode ) , (unicodeString, id ) , ("", unicodeToUtf8 ) -- default ] -- | -- the lookup function for selecting the encoding function getOutputEncodingFct :: String -> Maybe (String -> UString) getOutputEncodingFct enc = lookup (map toUpper enc) outputEncodingTable -- ------------------------------------------------------------ -- guessEncoding :: String -> String guessEncoding ('\xFF':'\xFE':'\x00':'\x00':_) = "UCS-4LE" -- with byte order mark guessEncoding ('\xFF':'\xFE':_) = "UTF-16LE" -- with byte order mark guessEncoding ('\xFE':'\xFF':'\x00':'\x00':_) = "UCS-4-3421" -- with byte order mark guessEncoding ('\xFE':'\xFF':_) = "UTF-16BE" -- with byte order mark guessEncoding ('\xEF':'\xBB':'\xBF':_) = utf8 -- with byte order mark guessEncoding ('\x00':'\x00':'\xFE':'\xFF':_) = "UCS-4BE" -- with byte order mark guessEncoding ('\x00':'\x00':'\xFF':'\xFE':_) = "UCS-4-2143" -- with byte order mark guessEncoding ('\x00':'\x00':'\x00':'\x3C':_) = "UCS-4BE" -- "<" of "<?xml" guessEncoding ('\x3C':'\x00':'\x00':'\x00':_) = "UCS-4LE" -- "<" of "<?xml" guessEncoding ('\x00':'\x00':'\x3C':'\x00':_) = "UCS-4-2143" -- "<" of "<?xml" guessEncoding ('\x00':'\x3C':'\x00':'\x00':_) = "UCS-4-3412" -- "<" of "<?xml" guessEncoding ('\x00':'\x3C':'\x00':'\x3F':_) = "UTF-16BE" -- "<?" of "<?xml" guessEncoding ('\x3C':'\x00':'\x3F':'\x00':_) = "UTF-16LE" -- "<?" of "<?xml" guessEncoding ('\x4C':'\x6F':'\xA7':'\x94':_) = "EBCDIC" -- "<?xm" of "<?xml" guessEncoding _ = "" -- no guess -- ------------------------------------------------------------
nfjinjing/yuuko
src/Yuuko/Text/XML/HXT/DOM/Unicode.hs
bsd-3-clause
31,323
392
13
7,795
7,498
4,573
2,925
706
3
{-# LANGUAGE Safe #-} module Language.SexpGrammar.Generic ( -- * GHC.Generics helpers with , match , Coproduct (..) ) where import Data.InvertibleGrammar.Generic
esmolanka/sexp-grammar
sexp-grammar/src/Language/SexpGrammar/Generic.hs
bsd-3-clause
176
0
5
35
30
21
9
7
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} -- | Description: servers for Servant APIs. module Servant.Route ( Decision(..), IsRouted(..), routingServer, ) where import Data.Aeson hiding (Error) import Data.ByteString (ByteString) import Data.Maybe import Data.Monoid import Data.Proxy import Data.String.Conversions (cs) import qualified Data.Text as T import GHC.TypeLits import Network.HTTP.Types hiding (Header (..), Status (..)) import Network.Wai import Servant.API import Servant.Common.Text import qualified Servant.Server.Internal as S -- | Use 'IsRouted' instances to -- -- > app :: Application -- > app = routingServer api server routingServer :: (IsRouted api, S.HasServer api) => Proxy api -> S.Server api -> Application routingServer p server = S.toApplication (S.route p server) type Status = (Int, ByteString) -- | Should the handler corresponding to a predicate be executed? data Decision = RunHandler -- ^ Yes, run the handler. | Error Status -- ^ Yes, but the request is bad, return an error. | Skip (Maybe Status) -- ^ No, try the next handler. instance Monoid Decision where mempty = Skip Nothing e@(Error _) `mappend` _ = e s@(Skip _) `mappend` _ = s RunHandler `mappend` r = r accept :: Decision accept = RunHandler reject :: Maybe (Int, ByteString) -> Decision reject = Skip invalid :: (Int, ByteString) -> Decision invalid = Error -- | TODO: Make correct. type Predicate = Request -> Decision type API = ("a" :> "b" :> QueryParam "poop" Int :> Get Int) :<|> (Capture "poopin" String :> QueryParam "inthe" String :> Post String) :<|> ("c" :> (Capture "cat" String :<|> Capture "dog" Int) :> Delete) -- | Perform routing according to normal rules for mapping URIs to \"physical\" -- resources. -- -- The 'match' method inspects the 'Request' to determine whether it should be -- handled by the @layout@ resource. This idea is to check /only/ that this is -- the correct handler, /not/ that the request is correct and complete. This -- ensures that we'll call a specific 'HasServer' instance which can return -- meaningful errors if required. class (S.HasServer layout) => IsRouted layout where -- | Check that a request matches this resource. -- -- Essentially: "Is this the physical resource that should handle the -- request?" match :: Proxy layout -> Predicate instance (IsRouted first, IsRouted rest, S.HasServer first, S.HasServer rest) => IsRouted (first :<|> rest) where match p req = match (Proxy :: Proxy first) req <> match (Proxy :: Proxy rest) req instance (KnownSymbol path, IsRouted sublayout) => IsRouted (path :> sublayout) where match _ req = case S.processedPathInfo req of (first : rest) | first == cs (symbolVal proxyPath) -> match (Proxy :: Proxy sublayout) req{ pathInfo = rest } _ -> reject Nothing where proxyPath = Proxy :: Proxy path -- | Check the patch contains a value for a 'Capture' and that it's instance (KnownSymbol capture, FromText a, IsRouted sublayout) => IsRouted (Capture capture a :> sublayout) where -- Check that there is a value in the path corresponding to the 'Capture'. match _ req = case S.processedPathInfo req of (first : rest) | (not . T.null $ first) -> match (Proxy :: Proxy sublayout) req{ pathInfo = rest } _ -> reject Nothing -- | Check the method. instance (ToJSON result) => IsRouted (Get result) where match _ = matchMethod methodGet -- | Check the method. instance (ToJSON result) => IsRouted (Put result) where match _ = matchMethod methodPut -- | Check the method. instance (ToJSON result) => IsRouted (Post result) where match _ = matchMethod methodPost -- | Check the method. instance IsRouted Delete where match _ = matchMethod methodDelete -- | Leave all routing decisions up to a 'Raw' endpoint. instance IsRouted Raw where match _ _ = accept -- | Check that the request has an acceptable HTTP method. matchMethod :: Method -> Predicate matchMethod method req = if requestMethod req == method then accept else reject $ Just (405, "Method Not Allowed") -- | Ignore when routing. instance (KnownSymbol sym, FromText a, IsRouted sublayout) => IsRouted (Header sym a :> sublayout) where match _ = match (Proxy :: Proxy sublayout) -- | Ignore when routing. instance (FromJSON a, IsRouted sublayout) => IsRouted (ReqBody a :> sublayout) where match _ = match (Proxy :: Proxy sublayout) -- | Ignore when routing. instance (KnownSymbol sym, FromText a, IsRouted sublayout) => IsRouted (QueryParam sym a :> sublayout) where match _ = match (Proxy :: Proxy sublayout) -- | Ignore when routing. instance (KnownSymbol sym, FromText a, IsRouted sublayout) => IsRouted (QueryParams sym a :> sublayout) where match _ = match (Proxy :: Proxy sublayout) -- | Ignore when routing. instance (KnownSymbol sym, IsRouted sublayout) => IsRouted (QueryFlag sym :> sublayout) where match _ = match (Proxy :: Proxy sublayout)
anchor/servant-route
lib/Servant/Route.hs
bsd-3-clause
5,394
0
15
1,211
1,342
730
612
100
2