code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
module MedicalAdvice.Advice where
import MedicalAdvice.Lib
data Advice = Suggestion String
| SuggestMedicalStaffVisit
| ContactMedicalStaff
deriving Show
getRandomAdvice :: IO Advice
getRandomAdvice = pickRandom
[ Suggestion "Eat more"
, Suggestion "Eat less"
, Suggestion "Exercise more"
, Suggestion "Exercise less"
, SuggestMedicalStaffVisit
, ContactMedicalStaff
]
| ToJans/learninghaskell | 0004AmISick/MedicalAdvice/Advice.hs | unlicense | 519 | 0 | 7 | 194 | 75 | 42 | 33 | 14 | 1 |
{-# LANGUAGE OverloadedStrings, RankNTypes #-}
module Handlers.Root where
import Data.Monoid ((<>))
import CourseStitch.Models (userName)
import CourseStitch.Models.RunDB
import CourseStitch.Handlers.User (getLoggedInUser)
import Database.Persist (entityVal)
import Data.Text.Lazy (fromStrict)
import Web.Scotty (ActionM, text)
import qualified Templates
import CourseStitch.Handlers.Utils (template)
root :: RunDB -> ActionM ()
root runDB = do
maybeUser <- getLoggedInUser runDB
case maybeUser of
Nothing -> text "Course stitch"
Just u -> template $ Templates.logoutForm
| coursestitch/coursestitch-api | src/Handlers/Root.hs | apache-2.0 | 600 | 0 | 11 | 91 | 158 | 90 | 68 | 17 | 2 |
{-# LANGUAGE Strict #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
module Bench.Packer where
import Bench.Types
import qualified Data.Packer as P
import Data.ByteString (ByteString)
{-# NOINLINE putBenchWord #-}
putBenchWord :: BenchWord -> ByteString
putBenchWord (BenchWord le64 be64 le32 be32 le16 be16 w8a w8b) =
P.runPacking benchWordSize $ do
P.putWord64LE le64
P.putWord64BE be64
P.putWord32LE le32
P.putWord32BE be32
P.putWord16LE le16
P.putWord16BE be16
P.putWord8 w8a
P.putWord8 w8b
{-# NOINLINE getBenchWord #-}
getBenchWord :: ByteString -> BenchWord
getBenchWord bs =
P.runUnpacking getter bs
where
getter = BenchWord
<$> P.getWord64LE
<*> P.getWord64BE
<*> P.getWord32LE
<*> P.getWord32BE
<*> P.getWord16LE
<*> P.getWord16BE
<*> P.getWord8
<*> P.getWord8
{-# NOINLINE sanityBenchWord #-}
sanityBenchWord :: BenchWord -> BenchWord
sanityBenchWord = getBenchWord . putBenchWord
| erikd/fastpack | bench/Bench/Packer.hs | bsd-2-clause | 1,059 | 0 | 15 | 280 | 241 | 121 | 120 | 34 | 1 |
{-# LANGUAGE DeriveDataTypeable, CPP #-}
-- | internal structures and utilities for Data.VCache.Seq
module Data.VCache.Seq.Type
( Seq(..)
, Elem(..)
, FingerTree(..)
, Digit(..)
, Node(..)
, VNode(..)
, Sized(..)
, seqErr
) where
import Prelude hiding (foldr)
import Control.Applicative
import Data.Foldable
import Data.Typeable (Typeable)
import Database.VCache
-- | Our Sequence type requires O(lg(N)) space in main memory, and has
-- between one to four direct elements in memory at each end of a large
-- sequence. Size of a sequence is computed in O(1) time.
data Seq a = Seq
{ q_space :: !VSpace
, q_data :: !(FingerTree (Elem a))
} deriving (Typeable)
-- wrapper for the Size class
newtype Elem a = Elem { unElem :: a }
deriving (Typeable)
-- spine of the finger tree
data FingerTree a
= Empty
| Single a
| Deep {-# UNPACK #-} !Int !(Digit a) (FingerTree (VNode a)) !(Digit a)
deriving (Typeable)
-- one to four direct elements
data Digit a
= One a
| Two a a
| Three a a a
| Four a a a a
deriving (Typeable)
-- indirection through VCache
data VNode a = VNode
{ n_size :: {-# UNPACK #-} !Int
, n_data :: !(VRef (Node a))
} deriving (Typeable)
-- 2-3 tree structure
data Node a
= Node2 a a
| Node3 a a a
deriving (Typeable)
instance VCacheable a => VCacheable (Seq a) where
put (Seq vc d) = put vc >> put d
get = Seq <$> get <*> get
instance VCacheable a => VCacheable (Elem a) where
put (Elem a) = put a
get = Elem <$> get
instance VCacheable a => VCacheable (Digit a) where
put (One a) = putWord8 1 >> put a
put (Two a b) = putWord8 2 >> put a >> put b
put (Three a b c) = putWord8 3 >> put a >> put b >> put c
put (Four a b c d) = putWord8 4 >> put a >> put b >> put c >> put d
get = getWord8 >>= \ n -> case n of
1 -> One <$> get
2 -> Two <$> get <*> get
3 -> Three <$> get <*> get <*> get
4 -> Four <$> get <*> get <*> get <*> get
_ -> fail $ seqErr $ "unexpected number of digits: " ++ show n
instance VCacheable a => VCacheable (Node a) where
put (Node2 a b) = putWord8 2 >> put a >> put b
put (Node3 a b c) = putWord8 3 >> put a >> put b >> put c
get = getWord8 >>= \ n -> case n of
2 -> Node2 <$> get <*> get
3 -> Node3 <$> get <*> get <*> get
_ -> fail $ seqErr $ "unexpected node size: " ++ show n
instance VCacheable a => VCacheable (VNode a) where
put (VNode sz ref) = putVarNat (toInteger sz) >> put ref
get = VNode <$> (fromInteger <$> getVarNat) <*> get
instance VCacheable a => VCacheable (FingerTree a) where
put Empty = putWord8 0
put (Single a) = putWord8 1 >> put a
put (Deep n l t r) = putWord8 2 >> putVarNat (toInteger n) >> put l >> put t >> put r
get = getWord8 >>= \ n -> case n of
0 -> pure Empty
1 -> Single <$> get
2 -> Deep <$> (fromInteger <$> getVarNat) <*> get <*> get <*> get
_ -> fail $ seqErr $ "unexpected FingerTree variant: " ++ show n
class Sized a where
sizeOf :: a -> Int
instance Sized (Elem a) where
{-# INLINE sizeOf #-}
sizeOf _ = 1
instance (Sized a) => Sized (Node a) where
sizeOf (Node2 a b) = sizeOf a + sizeOf b
sizeOf (Node3 a b c) = sizeOf a + sizeOf b + sizeOf c
instance Sized (VNode a) where
{-# INLINE sizeOf #-}
sizeOf = n_size
instance Sized a => Sized (Digit a) where
sizeOf (One a) = sizeOf a
sizeOf (Two a b) = sizeOf a + sizeOf b
sizeOf (Three a b c) = sizeOf a + sizeOf b + sizeOf c
sizeOf (Four a b c d) = sizeOf a + sizeOf b + sizeOf c + sizeOf d
instance Sized a => Sized (FingerTree a) where
{-# SPECIALIZE instance Sized (FingerTree (Elem a)) #-}
{-# SPECIALIZE instance Sized (FingerTree (VNode a)) #-}
sizeOf Empty = 0
sizeOf (Single x) = sizeOf x
sizeOf (Deep n _ _ _) = n
instance Foldable Seq where
foldr fn acc = foldr (fn . unElem) acc . q_data
#if MIN_VERSION_base(4,8,0)
length = sizeOf . q_data
null = null . q_data
#endif
-- foldr flipped for the way I prefer to use it
_foldr :: Foldable t => (elem -> accum -> accum) -> t elem -> accum -> accum
_foldr = flip . foldr
{-# INLINE _foldr #-}
instance Foldable FingerTree where
foldr _ acc Empty = acc
foldr fn acc (Single a) = fn a acc
foldr fn acc (Deep _ l t r) = _foldr fn l $ _foldr fn' t $ _foldr fn r acc
where fn' = _foldr fn . deref' . n_data
#if MIN_VERSION_base(4,8,0)
length = sizeOf
null Empty = True
null _ = False
#endif
instance Foldable Digit where
foldr fn acc (One a) = fn a acc
foldr fn acc (Two a b) = fn a $ fn b acc
foldr fn acc (Three a b c) = fn a $ fn b $ fn c acc
foldr fn acc (Four a b c d) = fn a $ fn b $ fn c $ fn d acc
instance Foldable Node where
foldr fn acc (Node2 a b) = fn a $ fn b acc
foldr fn acc (Node3 a b c) = fn a $ fn b $ fn c acc
seqErr :: String -> String
seqErr = (++) "Data.VCache.Seq: "
| dmbarbour/haskell-vcache-seq | hsrc_lib/Data/VCache/Seq/Type.hs | bsd-2-clause | 5,010 | 0 | 16 | 1,424 | 2,012 | 1,018 | 994 | 128 | 1 |
-- Copyright (c) 2015 Bart Massey
-- [This program is licensed under the "2-clause ('new') BSD License"]
-- Please see the file COPYING in the source
-- distribution of this software for license terms.
-- | Combine each possible prefix with each possible
-- suffix to produce a collection of strings.
(>>>) :: [String] -> [String] -> [String]
infixl 1 >>>
prefixes >>> suffixes = do
p <- prefixes
s <- suffixes
return (p ++ " " ++ s)
-- | Produce a list of all possible stories. This obviously
-- won't scale well beyond a certain point. (I have used a bit
-- of editorial license on the author's original story and fixed
-- some gender issues.)
stories :: [String]
stories =
["There once was"] >>> ["a princess", "a cat", "a little girl"] >>>
["who lived in"] >>> ["a shoe.", "a castle.", "an enchanted forest."] >>>
["She found a"] >>> ["giant", "frog", "treasure chest"] >>>
["when she got lost", "while strolling along"] >>>
["and immediately regretted it. Then a"] >>>
["lumberjack", "wolf", "magical pony"] >>>
["named"] >>> ["Pinkie Pie", "Courage", "Natasha"] >>>
["found her and"] >>> ["saved the day.", "granted her three wishes."] >>>
["The End."]
-- | Pick a story and read it. The user can pick; it would be
-- straightforward to pick randomly for them.
main :: IO ()
main = do
let len = length stories
putStrLn ("Enter a number from 1 to " ++ show len)
n <- readLn
putStrLn ""
putStrLn (stories !! (n - 1))
| BartMassey/haskell-basic-examples | bedtime.hs | bsd-2-clause | 1,486 | 0 | 18 | 318 | 303 | 170 | 133 | 24 | 1 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE OverloadedStrings #-}
module Control.Monad.Shmonad.Expression.Types where
import qualified Data.Text.Lazy as L
import Data.Char
import Data.Monoid
import Data.String (IsString, fromString)
import Data.Number.Nat
import System.Exit (ExitCode(..))
default (L.Text)
type Str = L.Text
type UniqueID = Nat
newtype Name = Name Str
deriving Eq
instance Show Name where
show (Name n) = L.unpack n
data VarID a = VarID
{ varID :: Maybe UniqueID -- must have this, unless coming from environment
, varName :: Name
}
-- | A Variable has a unique name.
class Variable a where
uniqueName :: VarID a -> Name
uniqueName (VarID vID vName)
= toName $ fromName vName <>
case vID of
Just n -> L.pack (show n)
Nothing -> ""
instance Variable Str
instance Variable Integer
-- | A standard FilePath (i.e. a string).
newtype Path = Path FilePath
deriving Eq
instance Show Path where
show (Path fp) = show fp
instance Variable Path
newtype ShBool = ShBool ExitCode
instance Show ShBool where
show (ShBool b) = case b of
ExitSuccess -> "(true)"
ExitFailure _ -> "(false)"
instance Variable ShBool
-- | A Variable may or may not be set when used as a value.
-- Programs using environment variables should handle both
-- cases explicitly.
instance Variable a => Variable (Maybe a)
-- | ShShow defaults to the typical Show instance, but can be customized
-- for different variable types.
class (Variable a, Show a) => ShShow a where
toShString :: a -> Str
toShString = L.pack . show
instance ShShow Str where
toShString = id
instance ShShow Integer
instance ShShow Path
instance IsString Name where
fromString = toName . L.pack
instance ShShow a => ShShow (Maybe a) where
toShString (Just x) = toShString x
toShString Nothing = "\"\""
data StrSum = forall a. ShShow a => StrSum { getCat :: a }
instance Show StrSum where
show (StrSum x) = show x
instance Variable StrSum
instance Monoid StrSum where
mempty = StrSum ("" :: Str)
StrSum x `mappend` StrSum y = StrSum $ toShString x <> toShString y
instance ShShow StrSum where
toShString (StrSum x) = toShString x
isValidName :: Str -> Bool
isValidName x = nonEmpty && allValidChars && notStartWithNumber
where nonEmpty = not (L.null x)
allValidChars = L.all (\c -> isAlphaNum c || c == '_') x
notStartWithNumber = not . isDigit $ L.head x
toName :: Str -> Name
toName x
| isValidName x = Name x
| otherwise = error $ L.unpack ("\"" <> x <> "\" is not a valid shell name.")
fromName :: Name -> Str
fromName (Name x) = x
| corajr/shmonad | src/Control/Monad/Shmonad/Expression/Types.hs | bsd-2-clause | 2,674 | 0 | 13 | 572 | 816 | 426 | 390 | 73 | 1 |
{-
@Issue(
"Check if this file is really needed"
type="task"
priority="low"
)
-}
module DockerHub
( module DockerHub.Build
, module DockerHub.Config
, module DockerHub.Data
, module DockerHub.Pull
) where
import DockerHub.Build
import DockerHub.Config
import DockerHub.Data
import DockerHub.Pull
| krystalcode/docker-hub | src/DockerHub.hs | bsd-3-clause | 348 | 0 | 5 | 89 | 51 | 33 | 18 | 9 | 0 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-|
Module : Numeric.AERN.RefinementOrder.RoundedLattice
Description : lattices with outwards and inwards rounded operations
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
Lattices with outwards and inwards rounded operations.
This module is hidden and reexported via its parent RefinementOrder.
-}
module Numeric.AERN.RefinementOrder.RoundedLattice
where
import Numeric.AERN.Basics.Exception
import Control.Monad.ST (ST)
import Numeric.AERN.Basics.Arbitrary
import Numeric.AERN.Basics.Effort
import Numeric.AERN.Misc.Maybe
import Numeric.AERN.Basics.PartialOrdering
import Numeric.AERN.RefinementOrder.Arbitrary
import Numeric.AERN.RefinementOrder.PartialComparison
import Numeric.AERN.Basics.Laws.RoundedOperation
import Numeric.AERN.Basics.Laws.OperationRelation
import Test.QuickCheck
import Test.Framework (testGroup, Test)
import Test.Framework.Providers.QuickCheck2 (testProperty)
infixr 3 </\>, >/\<, <⊓>, >⊓<, /\, ⊓
infixr 2 <\/>, >\/<, <⊔>, >⊔<, \/, ⊔
{-|
A type with outward-rounding lattice operations.
-}
class
(EffortIndicator (JoinMeetEffortIndicator t))
=>
RoundedLatticeEffort t
where
type JoinMeetEffortIndicator t
joinmeetDefaultEffort :: t -> JoinMeetEffortIndicator t
class (RoundedLatticeEffort t) => RoundedLattice t where
joinOutEff :: JoinMeetEffortIndicator t -> t -> t -> t
joinInEff :: JoinMeetEffortIndicator t -> t -> t -> t
meetOutEff :: JoinMeetEffortIndicator t -> t -> t -> t
meetInEff :: JoinMeetEffortIndicator t -> t -> t -> t
-- | Outward rounded join with default effort
joinOut :: (RoundedLattice t) => t -> t -> t
joinOut a = joinOutEff (joinmeetDefaultEffort a) a
-- | Outward rounded join with default effort
(<\/>) :: (RoundedLattice t) => t -> t -> t
(<\/>) = joinOut
(\/) :: (RoundedLattice t) => t -> t -> t
(\/) = (<\/>)
{-| Convenience Unicode notation for '<\/>' -}
(<⊔>) :: (RoundedLattice t) => t -> t -> t
(<⊔>) = (<\/>)
(⊔) :: (RoundedLattice t) => t -> t -> t
(⊔) = (<\/>)
-- | Inward rounded join with default effort
joinIn :: (RoundedLattice t) => t -> t -> t
joinIn a = joinInEff (joinmeetDefaultEffort a) a
-- | Inward rounded join with default effort
(>\/<) :: (RoundedLattice t) => t -> t -> t
(>\/<) = joinIn
{-| Convenience Unicode notation for '>\/<' -}
(>⊔<) :: (RoundedLattice t) => t -> t -> t
(>⊔<) = (>\/<)
-- | Outward rounded meet with default effort
meetOut :: (RoundedLattice t) => t -> t -> t
meetOut a = meetOutEff (joinmeetDefaultEffort a) a
-- | Outward rounded meet with default effort
(</\>) :: (RoundedLattice t) => t -> t -> t
(</\>) = meetOut
(/\) :: (RoundedLattice t) => t -> t -> t
(/\) = (</\>)
{-| Convenience Unicode notation for '</\>' -}
(<⊓>) :: (RoundedLattice t) => t -> t -> t
(<⊓>) = (</\>)
(⊓) :: (RoundedLattice t) => t -> t -> t
(⊓) = (<⊓>)
-- | Inward rounded meet with default effort
meetIn :: (RoundedLattice t) => t -> t -> t
meetIn a = meetInEff (joinmeetDefaultEffort a) a
-- | Inward rounded meet with default effort
(>/\<) :: (RoundedLattice t) => t -> t -> t
(>/\<) = meetIn
{-| Convenience Unicode notation for '>/\<' -}
(>⊓<) :: (RoundedLattice t) => t -> t -> t
(>⊓<) = (>/\<)
-- properties of RoundedLattice
propRoundedLatticeComparisonCompatible ::
(PartialComparison t, RoundedLattice t) =>
t ->
UniformlyOrderedPair t ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeComparisonCompatible _
(UniformlyOrderedPair (e1,e2))
(effortComp, effortInOut)
=
(downRoundedJoinOfOrderedPair (pLeqEff effortComp) (joinOutEff effortInOut) e1 e2)
&&
(upRoundedMeetOfOrderedPair (pLeqEff effortComp) (meetInEff effortInOut) e1 e2)
propRoundedLatticeJoinAboveBoth ::
(PartialComparison t, RoundedLattice t) =>
t ->
UniformlyOrderedPair t ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeJoinAboveBoth _
(UniformlyOrderedPair (e1,e2))
(effortComp, effortInOut)
=
joinAboveOperands (pLeqEff effortComp) (joinInEff effortInOut) e1 e2
propRoundedLatticeMeetBelowBoth ::
(PartialComparison t, RoundedLattice t) =>
t ->
UniformlyOrderedPair t ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeMeetBelowBoth _
(UniformlyOrderedPair (e1,e2))
(effortComp, effortInOut)
=
meetBelowOperands (pLeqEff effortComp) (meetOutEff effortInOut) e1 e2
propRoundedLatticeJoinIdempotent ::
(PartialComparison t, RoundedLattice t, Show t, HasLegalValues t) =>
t ->
(UniformlyOrderedSingleton t) ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeJoinIdempotent _
(UniformlyOrderedSingleton e)
(effortComp, effortInOut)
=
roundedIdempotent (pLeqEff effortComp) (joinInEff effortInOut) (joinOutEff effortInOut) e
propRoundedLatticeJoinCommutative ::
(PartialComparison t, RoundedLattice t, Show t, HasLegalValues t) =>
t ->
UniformlyOrderedPair t ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeJoinCommutative _
(UniformlyOrderedPair (e1,e2))
(effortComp, effortInOut)
=
roundedCommutative (pLeqEff effortComp) (joinInEff effortInOut) (joinOutEff effortInOut) e1 e2
propRoundedLatticeJoinAssocative ::
(PartialComparison t, RoundedLattice t, Show t, HasLegalValues t) =>
t ->
UniformlyOrderedTriple t ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeJoinAssocative _
(UniformlyOrderedTriple (e1,e2,e3))
(effortComp, effortInOut)
=
roundedAssociative (pLeqEff effortComp) (joinInEff effortInOut) (joinOutEff effortInOut) e1 e2 e3
propRoundedLatticeJoinMonotone ::
(RoundedLattice t, PartialComparison t, Show t, HasLegalValues t) =>
t ->
TwoLEPairs t ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeJoinMonotone _
(TwoLEPairs ((e1Lower,e1),(e2Lower,e2)))
(effortComp, effortInOut)
=
case pLeqEff effortComp rLower r of
Just b -> b
Nothing -> True
where
rLower = joinOutEff effortInOut e1Lower e2Lower
r = joinInEff effortInOut e1 e2
propRoundedLatticeMeetIdempotent ::
(PartialComparison t, RoundedLattice t, Show t, HasLegalValues t) =>
t ->
(UniformlyOrderedSingleton t) ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeMeetIdempotent _
(UniformlyOrderedSingleton e)
(effortComp, effortInOut)
=
roundedIdempotent (pLeqEff effortComp) (meetInEff effortInOut) (meetOutEff effortInOut) e
propRoundedLatticeMeetCommutative ::
(PartialComparison t, RoundedLattice t, Show t, HasLegalValues t) =>
t ->
UniformlyOrderedPair t ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeMeetCommutative _
(UniformlyOrderedPair (e1,e2))
(effortComp, effortInOut)
=
roundedCommutative (pLeqEff effortComp) (meetInEff effortInOut) (meetOutEff effortInOut) e1 e2
propRoundedLatticeMeetAssocative ::
(PartialComparison t, RoundedLattice t, Show t, HasLegalValues t) =>
t ->
UniformlyOrderedTriple t ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeMeetAssocative _
(UniformlyOrderedTriple (e1,e2,e3))
(effortComp, effortInOut)
=
roundedAssociative (pLeqEff effortComp) (meetInEff effortInOut) (meetOutEff effortInOut) e1 e2 e3
{- optional properties: -}
propRoundedLatticeModular ::
(PartialComparison t, RoundedLattice t, Show t, HasLegalValues t) =>
t ->
UniformlyOrderedTriple t ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeModular _
(UniformlyOrderedTriple (e1,e2,e3))
(effortComp, effortInOut)
=
roundedModular (pLeqEff effortComp) (meetInEff effortInOut) (joinInEff effortInOut) (meetOutEff effortInOut) (joinOutEff effortInOut) e1 e2 e3
propRoundedLatticeMeetMonotone ::
(RoundedLattice t, PartialComparison t, Show t, HasLegalValues t) =>
t ->
(TwoLEPairs t) ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeMeetMonotone _
(TwoLEPairs ((e1Lower,e1), (e2Lower,e2)))
(effortComp, effortInOut)
=
case pLeqEff effortComp rLower r of
Just b -> b
Nothing -> True
where
rLower = meetOutEff effortInOut e1Lower e2Lower
r = meetInEff effortInOut e1 e2
propRoundedLatticeDistributive ::
(PartialComparison t, RoundedLattice t, Show t, HasLegalValues t) =>
t ->
UniformlyOrderedTriple t ->
(PartialCompareEffortIndicator t,
JoinMeetEffortIndicator t) ->
Bool
propRoundedLatticeDistributive _
(UniformlyOrderedTriple (e1,e2,e3))
(effortComp, effortInOut)
=
(roundedLeftDistributive (pLeqEff effortComp) (meetInEff effortInOut) (joinInEff effortInOut) (meetOutEff effortInOut) (joinOutEff effortInOut) e1 e2 e3)
&&
(roundedLeftDistributive (pLeqEff effortComp) (joinInEff effortInOut) (meetInEff effortInOut) (joinOutEff effortInOut) (meetOutEff effortInOut) e1 e2 e3)
testsRoundedLatticeDistributive ::
(PartialComparison t,
RoundedLattice t,
Show t, HasLegalValues t,
ArbitraryOrderedTuple t)
=>
(String, t) ->
(Area t) ->
Test
testsRoundedLatticeDistributive (name, sample) area =
testGroup (name ++ " (⊓,⊔) rounded") $
[
testProperty "Comparison compatible" (area, propRoundedLatticeComparisonCompatible sample)
,
testProperty "join above" (area, propRoundedLatticeJoinAboveBoth sample)
,
testProperty "meet below" (area, propRoundedLatticeMeetBelowBoth sample)
,
testProperty "join idempotent" (area, propRoundedLatticeJoinIdempotent sample)
,
testProperty "join commutative" (area, propRoundedLatticeJoinCommutative sample)
,
testProperty "join associative" (area, propRoundedLatticeJoinAssocative sample)
,
testProperty "join monotone" (area, propRoundedLatticeJoinMonotone sample)
,
testProperty "meet idempotent" (area, propRoundedLatticeMeetIdempotent sample)
,
testProperty "meet commutative" (area, propRoundedLatticeMeetCommutative sample)
,
testProperty "meet associative" (area, propRoundedLatticeMeetAssocative sample)
,
testProperty "meet monotone" (area, propRoundedLatticeMeetMonotone sample)
,
testProperty "distributive" (area, propRoundedLatticeDistributive sample)
]
-- mutable versions (TODO) | michalkonecny/aern | aern-order/src/Numeric/AERN/RefinementOrder/RoundedLattice.hs | bsd-3-clause | 11,301 | 0 | 10 | 2,422 | 2,832 | 1,547 | 1,285 | 251 | 2 |
-- | Interface to Fixed-length DBM. See also,
-- <http://tokyocabinet.sourceforge.net/spex-en.html#tcfdbapi> for details
module Database.TokyoCabinet.FDB
(
-- $doc
-- * Constructors
FDB
, ECODE(..)
, OpenMode(..)
, ID(..)
-- * Basic API (tokyocabinet.idl compliant)
, new
, delete
, ecode
, errmsg
, tune
, open
, close
, put
, putkeep
, putcat
, out
, get
, vsiz
, iterinit
, iternext
, range
, fwmkeys
, addint
, adddouble
, sync
, optimize
, vanish
, copy
, path
, rnum
, fsiz
) where
import Database.TokyoCabinet.Error
import Database.TokyoCabinet.FDB.C
import Database.TokyoCabinet.FDB.Key
import Database.TokyoCabinet.Internal
import Database.TokyoCabinet.Sequence
import Database.TokyoCabinet.Storable
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.C.Types
import Foreign.Storable (peek)
import Foreign.Marshal (alloca, free)
import Foreign.Marshal.Array (peekArray)
import Foreign.Marshal.Utils (maybePeek)
import Data.Int
import Data.Word
import Control.Exception
-- $doc
-- Example
--
-- @
-- import Control.Monad
-- import Database.TokyoCabinet.FDB
-- @
--
-- @
-- main = do fdb <- new
-- -- open the database
-- open fdb \"casket.tcf\" [OWRITER, OCREAT] >>= err fdb
-- -- store records
-- puts fdb [(1, \"one\"), (12, \"twelve\"), (144, \"one forty four\")] >>=
-- err fdb . (all id)
-- -- retrieve records
-- get fdb (1 :: Int) >>= maybe (error \"something goes wrong\") putStrLn
-- -- close the database
-- close fdb >>= err fdb
-- where
-- puts :: FDB -> [(Int, String)] -> IO [Bool]
-- puts fdb = mapM (uncurry $ put fdb)
-- @
--
-- @
-- err :: FDB -> Bool -> IO ()
-- err fdb = flip unless $ ecode fdb >>= error . show
-- @
--
data FDB = FDB { unTCFDB :: !(ForeignPtr FDB') }
-- | Create a Fixed-length database object.
new :: IO FDB
new = FDB `fmap` (c_tcfdbnew >>= newForeignPtr tcfdbFinalizer)
-- | Free FDB resource forcibly.
-- FDB is kept by ForeignPtr, so Haskell runtime GC cleans up memory for
-- almost situation. Most always, you don't need to call this.
-- After call this, you must not touch FDB object. Its behavior is undefined.
delete :: FDB -> IO ()
delete fdb = finalizeForeignPtr $ unTCFDB fdb
-- | Return the last happened error code.
ecode :: FDB -> IO ECODE
ecode fdb =
withForeignPtr (unTCFDB fdb) $ \fdb' ->
cintToError `fmap` c_tcfdbecode fdb'
-- | Set the tuning parameters.
tune :: FDB -- ^ FDB object.
-> Int32 -- ^ the width of the value of each record.
-> Int64 -- ^ the limit size of the database file.
-> IO Bool -- ^ if successful, the return value is True.
tune fdb width limsiz =
withForeignPtr (unTCFDB fdb) $ \fdb' -> c_tcfdbtune fdb' width limsiz
-- | Open FDB database file.
open :: FDB -> String -> [OpenMode] -> IO Bool
open = openHelper c_tcfdbopen unTCFDB combineOpenMode
-- | Close the database file.
close :: FDB -> IO Bool
close fdb = withForeignPtr (unTCFDB fdb) c_tcfdbclose
type FunPut' = Ptr FDB' -> Int64 -> Ptr Word8 -> CInt -> IO Bool
putHelper' :: (Key k, Storable v) => FunPut' -> FDB -> k -> v -> IO Bool
putHelper' func fdb key val =
withForeignPtr (unTCFDB fdb) $ \fdb' ->
withPtrLen val $ \(vbuf, vsize) -> do
key' <- keyToInt key
func fdb' key' vbuf vsize
-- | Stora a record (key-value pair) on FDB. Key type must be
-- instance of Key class. Value type must be instance of Storable.
put :: (Key k, Storable v) => FDB -> k -> v -> IO Bool
put = putHelper' c_tcfdbput
-- | Store a new record. If a record with the same key exists in the
-- database, this function has no effect.
putkeep :: (Key k, Storable v) => FDB -> k -> v -> IO Bool
putkeep = putHelper' c_tcfdbputkeep
-- | Concatenate a value at the end of the existing record.
putcat :: (Key k, Storable v) => FDB -> k -> v -> IO Bool
putcat = putHelper' c_tcfdbputcat
-- | Delete a record.
out :: (Key k) => FDB -> k -> IO Bool
out fdb key =
withForeignPtr (unTCFDB fdb) $ \fdb' ->
c_tcfdbout fdb' =<< keyToInt key
-- | Return the value of record.
get :: (Key k, Storable v) => FDB -> k -> IO (Maybe v)
get fdb key =
withForeignPtr (unTCFDB fdb) $ \fdb' ->
alloca $ \sizbuf -> do
key' <- keyToInt key
vbuf <- c_tcfdbget fdb' key' sizbuf
vsize <- peek sizbuf
flip maybePeek vbuf $ \vbuf' -> peekPtrLen (vbuf', vsize)
-- | Return the byte size of value in a record.
vsiz :: (Key k) => FDB -> k -> IO (Maybe Int)
vsiz fdb key =
withForeignPtr (unTCFDB fdb) $ \fdb' -> do
vsize <- c_tcfdbvsiz fdb' =<< keyToInt key
return $ if vsize == (-1)
then Nothing
else Just (fromIntegral vsize)
-- | Initialize the iterator of a FDB object.
iterinit :: FDB -> IO Bool
iterinit fdb = withForeignPtr (unTCFDB fdb) c_tcfdbiterinit
-- | Return the next key of the iterator of a FDB object.
iternext :: (Key k) => FDB -> IO (Maybe k)
iternext fdb =
withForeignPtr (unTCFDB fdb) $ \fdb' -> do
i <- c_tcfdbiternext fdb'
return $ if i == 0
then Nothing
else Just (fromID $ ID i)
-- | Return list of keys in the specified range.
range :: (Key k1, Key k2) =>
FDB -- ^ FDB object
-> k1 -- ^ the lower limit of the range.
-> k1 -- ^ the upper limit of the range.
-> Int -- ^ the maximum number of keys to be fetched.
-> IO [k2] -- ^ keys in the specified range.
range fdb lower upper maxn =
withForeignPtr (unTCFDB fdb) $ \fdb' ->
alloca $ \sizbuf -> do
[l, u] <- mapM keyToInt [lower, upper]
rp <- c_tcfdbrange fdb' l u (fromIntegral maxn) sizbuf
size <- fromIntegral `fmap` peek sizbuf
keys <- peekArray size rp
free rp
return $ map (fromID . ID) keys
-- | Return list of forward matched keys.
fwmkeys :: (Storable k1, Storable k2, Sequence q) =>
FDB -> k1 -> Int -> IO (q k2)
fwmkeys fdb k maxn = smap fromString =<< fwmkeys' fdb k maxn
where fwmkeys' = fwmHelper c_tcfdbrange4 unTCFDB
-- | Increment the corresponding value. (The value specified by a key
-- is treated as integer.)
addint :: (Key k) => FDB -> k -> Int -> IO (Maybe Int)
addint fdb key num =
withForeignPtr (unTCFDB fdb) $ \fdb' -> do
key' <- keyToInt key
sumval <- c_tcfdbaddint fdb' key' (fromIntegral num)
return $ if sumval == cINT_MIN
then Nothing
else Just $ fromIntegral sumval
-- | Increment the corresponding value. (The value specified by a key
-- is treated as double.)
adddouble :: (Key k) => FDB -> k -> Double -> IO (Maybe Double)
adddouble fdb key num =
withForeignPtr (unTCFDB fdb) $ \fdb' -> do
key' <- keyToInt key
sumval <- c_tcfdbadddouble fdb' key' (realToFrac num)
return $ if isNaN sumval
then Nothing
else Just $ realToFrac sumval
-- | Synchronize updated contents of a database object with the file
-- and the device.
sync :: FDB -> IO Bool
sync fdb = withForeignPtr (unTCFDB fdb) c_tcfdbsync
-- | Optimize the file of a Hash database object.
optimize :: FDB -> Int32 -> Int64 -> IO Bool
optimize fdb width limsiz =
withForeignPtr (unTCFDB fdb) $ \fdb' -> c_tcfdboptimize fdb' width limsiz
-- | Delete all records.
vanish :: FDB -> IO Bool
vanish fdb = withForeignPtr (unTCFDB fdb) c_tcfdbvanish
-- | Copy the database file.
copy :: FDB -> String -> IO Bool
copy = copyHelper c_tcfdbcopy unTCFDB
-- | Return the file path of currentry opened database.
path :: FDB -> IO (Maybe String)
path = pathHelper c_tcfdbpath unTCFDB
-- | Return the number of records in the database.
rnum :: FDB -> IO Word64
rnum fdb = withForeignPtr (unTCFDB fdb) c_tcfdbrnum
-- | Return the size of the database file.
fsiz :: FDB -> IO Word64
fsiz fdb = withForeignPtr (unTCFDB fdb) c_tcfdbfsiz
keyToInt :: (Key k) => k -> IO Int64
keyToInt i = catchJust selector (evaluate (unID . toID $ i)) handler
where
selector :: ErrorCall -> Maybe ()
selector e = if show e == "Prelude.read: no parse"
then Just ()
else Nothing
handler _ = error "Database.TokyoCabinet.FDB: invalid key"
| tom-lpsd/tokyocabinet-haskell | Database/TokyoCabinet/FDB.hs | bsd-3-clause | 8,494 | 0 | 14 | 2,311 | 2,107 | 1,118 | 989 | 167 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
module Common.Numbers.Numbers (
factorial
, binomial
, multiBinomial
, powMod
, fastpow
, exgcd
, inverse
, inverse'
, inverseToM
, inverseTo
, crt2
, crt
, tonelliShanks
) where
import Data.Bits (Bits, (.&.), shiftR, shiftL)
import Data.Maybe (fromJust)
import qualified Data.Vector as V
factorial :: (Integral a) => a -> a
{-# INLINABLE factorial #-}
factorial n = product [1 .. n]
binomial :: (Integral a) => a -> a -> a
{-# INLINABLE binomial #-}
binomial a b = if a < b
then 0
else product [b + 1 .. a] `quot` product [1 .. (a - b)]
multiBinomial :: (Integral a) => [a] -> a
{-# INLINABLE multiBinomial #-}
multiBinomial xs = factorial (sum xs) `quot` product (map factorial xs)
powMod :: (Integral a, Bits b, Integral b) => a -> b -> a -> a
{-# INLINABLE powMod #-}
powMod a p m = helper a p m 1
where
helper _ 0 _ ret = ret
helper a p m ret = if (p .&. 1) == 1
then helper a' p' m (ret * a `rem` m)
else helper a' p' m ret
where
a' = a * a `rem` m
p' = p `shiftR` 1
fastpow :: (Num a, Bits b, Integral b) => a -> b -> a
{-# INLINABLE fastpow #-}
fastpow a p = helper a p 1
where
helper _ 0 ret = ret
helper a p ret = if (p .&. 1) == 1
then helper a' p' (ret * a)
else helper a' p' ret
where
a' = a * a
p' = p `shiftR` 1
exgcd :: (Integral a) => a -> a -> (a, a, a)
{-# INLINABLE exgcd #-}
exgcd a 0 = (a, 1, 0)
exgcd a b = (d, y, x - (a `quot` b) * y)
where
(d, x, y) = exgcd b (a `rem` b)
-- | p should be a prime.
inverse :: (Integral a) => a -> a -> a
{-# INLINABLE inverse #-}
inverse x p = if x' == 0
then undefined
else powMod x' (toInteger (p - 2)) p
where
x' = x `rem` p
-- | x and m should be co-prime.
-- | this version is preferred.
inverse' :: (Integral a) => a -> a -> a
{-# INLINABLE inverse' #-}
inverse' x m = if d /= 1
then undefined
else a `rem` m
where
(d, a, _) = exgcd x m
inverseToM :: (Monad m, Integral a) => Int -> a -> [m a]
{-# INLINABLE inverseToM #-}
inverseToM n m = V.toList cache
where
cache = V.fromList $ fail "undefined" : return 1 : map inv [2 .. n]
inv x = do
let (q, r) = m `quotRem` fromIntegral x
y <- cache V.! fromIntegral r
return $ y * (m - q) `rem` m
inverseTo :: (Integral a) => Int -> a -> [a]
{-# INLINABLE inverseTo #-}
inverseTo n m = map fromJust $ inverseToM n m
crt2 :: (Integral a) => (a, a) -> (a, a) -> a
{-# INLINABLE crt2 #-}
crt2 (p1, r1) (p2, r2) = (a + b) `rem` n
where
n = p1 * p2
a = inverse' p2 p1 * p2 `rem` n * r1 `mod` n
b = inverse' p1 p2 * p1 `rem` n * r2 `mod` n
crt :: (Integral a) => [(a, a)] -> a
{-# INLINABLE crt #-}
crt = loop 1 1
where
loop _ res [] = res
loop pp res ((p, r):rest) = loop (pp * p) (crt2 (pp, res) (p, r)) rest
legendre :: (Integral a, Bits a) => a -> a -> a
legendre n p = powMod n ((p - 1) `quot` 2) p
tonelliShanks :: forall a. (Integral a, Bits a) => a -> a -> Maybe a
{-# INLINABLE tonelliShanks #-}
tonelliShanks n p | legendre n p /= 1 = Nothing
| otherwise = Just r
where
(q, s) = until (odd . fst) (\(q0, s0) -> (q0 `quot` 2, s0 + 1)) (p - 1, 0)
z = head $ filter (\t -> legendre t p == p - 1) [1 .. ]
(r, _, _, _) = until (\(_, t, _, _) -> t == 1) iter (powMod n ((q+1) `quot` 2) p, powMod n q p, s, powMod z q p)
iter (r, t, m, c) = (r * b `rem` p, t * b2 `rem` p, i, b2)
where
i = fst $ head $ filter (\(_, x) -> x == 1) $ zip [0 .. m-1] $ iterate (\t0 -> t0 * t0 `rem` p) t
b = powMod c k p
b2 = b * b `rem` p
k = 1 `shiftL` (m - i - 1) :: a
| foreverbell/project-euler-solutions | lib/Common/Numbers/Numbers.hs | bsd-3-clause | 3,717 | 0 | 15 | 1,128 | 1,827 | 1,018 | 809 | 87 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Modules where
import Modules.JSON ()
import Modules.RecoverInstance (recoverInstance)
import Variants (loadPackageDescription)
import Targets (finalize)
import Types (
Repository,
Package(Package),
Version(Version),
Variant(Variant),
Target(Target),TargetType(LibraryTarget),
InstanceNode,Instance(Instance),
ModuleNode,Module(Module),ModuleName,ModuleAST,
FinalizedPackageDescription,TargetSection(LibrarySection))
import Database.PipesGremlin (
PG,scatter)
import Web.Neo (
NeoT,newNode,addNodeLabel,setNodeProperty,newEdge)
import Distribution.PackageDescription (
library,libModules,libBuildInfo,cppOptions,hsSourceDirs)
import Distribution.ModuleName (toFilePath)
import Language.Preprocessor.Cpphs
(runCpphs,
defaultCpphsOptions,CpphsOptions(boolopts),
defaultBoolOptions,BoolOptions(warnings))
import Control.Exception (evaluate)
import Control.DeepSeq (force)
import Language.Haskell.Exts.Annotated (parseFileContentsWithMode)
import Language.Haskell.Exts.Annotated.Fixity (baseFixities)
import Language.Haskell.Exts.Parser (ParseMode(..),defaultParseMode,ParseResult(ParseOk,ParseFailed))
import Language.Haskell.Exts.Pretty (prettyPrint)
import Control.Error (
runEitherT,EitherT,left,
runMaybeT,hoistMaybe,hoistEither,
scriptIO,fmapLT)
import Data.Map ((!))
import System.Directory (doesFileExist)
import Control.Monad (mzero,forM,filterM)
import Control.Monad.Trans (lift)
import Control.Monad.IO.Class (MonadIO,liftIO)
modulePG :: (MonadIO m) => Repository -> InstanceNode -> PG m (Module,ModuleNode)
modulePG repository instancenode = do
inst <- recoverInstance instancenode
eithermodule <- modules repository inst >>=
maybe
(lift (finalizationError instancenode) >> mzero)
scatter
either
(\e -> lift (insertModuleError e instancenode) >> mzero)
(\modul@(Module _ modulename moduleast) -> do
modulenode <- lift (insertModule modulename moduleast instancenode)
return (modul,modulenode))
eithermodule
modules :: (MonadIO m) => Repository -> Instance -> m (Maybe [Either ModuleError Module])
modules repository inst = runMaybeT (do
let (Instance (Target variant@(Variant version _) targettype _) _) = inst
finalizedPackageDescription <- getFinalizedPackageDescription repository variant >>= hoistMaybe
targetSection <- case targettype of
LibraryTarget -> hoistMaybe (library finalizedPackageDescription) >>= return . LibrarySection
let modulenames = enumModuleNames targetSection
forM modulenames (\modulename -> runEitherT (do
modulepath <- lookupModuleName repository version targetSection modulename
modulefile <- preprocess targetSection modulepath
moduleast <- parse modulepath modulefile
return (Module inst modulename moduleast))))
data ModuleError =
ModuleFileNotFound |
MultipleModuleFilesFound |
PreprocessorError String |
ParserError String
deriving (Show,Read)
type PreprocessorFlags = [String]
type ModuleFile = String
enumModuleNames :: TargetSection -> [ModuleName]
enumModuleNames (LibrarySection librarySection) = libModules librarySection
lookupModuleName :: (MonadIO m) => Repository -> Version -> TargetSection -> ModuleName -> EitherT ModuleError m FilePath
lookupModuleName repository version (LibrarySection librarySection) modulename = do
let sourcedirs = hsSourceDirs (libBuildInfo librarySection)
(Version (Package packagename) versionnumber) = version
packagepath = repository ! packagename ! versionnumber
potentialPaths = do
directory <- sourcedirs
extension <- [".hs",".lhs"]
return (packagepath ++ directory ++ "/" ++ toFilePath modulename ++ extension)
modulepaths <- liftIO (filterM doesFileExist potentialPaths)
case modulepaths of
[] -> left ModuleFileNotFound
[modulepath] -> return modulepath
_ -> left MultipleModuleFilesFound
preprocess :: (MonadIO m) => TargetSection -> FilePath -> EitherT ModuleError m ModuleFile
preprocess _ modulepath = do
let cpphsoptions = defaultCpphsOptions {boolopts = booloptions }
booloptions = defaultBoolOptions {warnings = False}
scriptIO (do
rawsource <- readFile modulepath
sourcecode <- runCpphs cpphsoptions modulepath rawsource
evaluate (force sourcecode))
`onException` PreprocessorError
onException :: (Monad m) => EitherT e m a -> (e -> u) -> EitherT u m a
onException = flip fmapLT
parse :: (MonadIO m) => FilePath -> ModuleFile -> EitherT ModuleError m ModuleAST
parse modulepath modulefile = do
let mode = defaultParseMode {parseFilename = modulepath, fixities = Just baseFixities}
eitherast <- scriptIO (do
parseresult <- return (parseFileContentsWithMode mode modulefile)
case parseresult of
ParseFailed _ message -> return (Left (ParserError message))
ParseOk ast -> return (Right ast))
`onException` ParserError
hoistEither eitherast
preprocessorflags :: TargetType -> FinalizedPackageDescription -> PreprocessorFlags
preprocessorflags LibraryTarget finalizedPackageDescription =
maybe [] (cppOptions . libBuildInfo) (library finalizedPackageDescription)
insertModule :: (Monad m) => ModuleName -> ModuleAST -> InstanceNode -> NeoT m ModuleNode
insertModule modulename moduleast instancenode = do
modulenode <- newNode
addNodeLabel "Module" modulenode
setNodeProperty "modulename" (show modulename) modulenode
setNodeProperty "modulesource" (prettyPrint moduleast) modulenode
_ <- newEdge "MODULE" instancenode modulenode
return modulenode
insertModuleError :: (Monad m) => ModuleError -> InstanceNode -> NeoT m ()
insertModuleError moduleerror instancenode = do
moduleerrornode <- newNode
addNodeLabel "Error" moduleerrornode
addNodeLabel "ModuleError" moduleerrornode
setNodeProperty "error" (show moduleerror) moduleerrornode
_ <- newEdge "ERROR" instancenode moduleerrornode
return ()
getFinalizedPackageDescription :: (MonadIO m) =>
Repository ->
Variant ->
m (Maybe FinalizedPackageDescription)
getFinalizedPackageDescription repository variant = do
let (Variant version configuration) = variant
packageDescription <- loadPackageDescription repository version
return (finalize configuration packageDescription)
finalizationError :: (Monad m) => InstanceNode -> NeoT m ()
finalizationError instancenode = do
finalizationerrornode <- newNode
addNodeLabel "Error" finalizationerrornode
addNodeLabel "FinalizationError" finalizationerrornode
_ <- newEdge "ERROR" instancenode finalizationerrornode
return ()
| phischu/cabal-analysis | src/Modules.hs | bsd-3-clause | 6,844 | 0 | 20 | 1,239 | 1,847 | 963 | 884 | 145 | 3 |
import Data.UI.Input.Keyboard.ModKey(ModKey(..), pretty)
import Data.Monoid(mempty)
import Data.UI.Input.Keyboard.Mods(ModState(..), ModsState(..))
import qualified Data.UI.Input.Keyboard.Mods as Mods
import qualified Data.UI.Input.Keyboard.Keys as Keys
main :: IO ()
main = do
print . pretty $ ModKey (mempty {shift=mempty{anyPressed=True}}) Keys.Escape
print . pretty $ ModKey (mempty {shift=mempty{anyPressed=True, leftPressed=True}})
Keys.Escape
print . pretty $ ModKey (mempty {shift=mempty{anyPressed=True, leftPressed=True, rightPressed=True}})
Keys.Escape
print . pretty $ ModKey (mempty {ctrl=mempty{anyPressed=True}, shift=mempty{anyPressed=True}})
(Keys.Letter 'a')
print . pretty $ ModKey (mempty {ctrl=mempty{anyPressed=True},
shift=mempty{anyPressed=True},
numLock=True, capsLock=True})
(Keys.Letter 'a')
| Peaker/keyboard | src/Test.hs | bsd-3-clause | 917 | 0 | 13 | 172 | 347 | 207 | 140 | 18 | 1 |
{-
Problem 5
What is the smallest positive number that is evenly divisible by all
of the numbers from 1 to 20?
Result
.00 s
Comment
Haskell provides a lcm function in the Prelude, but I re-implemented
it so that the problem is less of a stub.
-}
module Problem5 (solution) where
import Data.List
solution = foldl1' lcm' [1..20]
where lcm' a b = a `quot` gcd' a b * b
gcd' a 0 = a
gcd' a b = gcd' b (a `rem` b) | quchen/HaskellEuler | src/Problem5.hs | bsd-3-clause | 521 | 0 | 9 | 196 | 91 | 50 | 41 | 6 | 2 |
module Feldspar.Multicore.Reference where
import Feldspar
import Feldspar.Multicore.CoreId
import Feldspar.Multicore.Frontend
import Feldspar.Multicore.Representation
newtype LRef a = LRef { unLRef :: LArr a }
type DLRef a = LRef (Data a)
allocLRef :: PrimType a => CoreId -> Multicore (DLRef a)
allocLRef coreId = LRef <$> allocLArr coreId 1
class (MonadComp m, ArrayAccess LArr m) => LocalRefAccess m
where
getLRef :: PrimType a => DLRef a -> m (Data a)
setLRef :: PrimType a => DLRef a -> Data a -> m ()
instance LocalRefAccess Host
where
getLRef (LRef arr) = do
tmp <- newArr 1
readArr arr (0,0) tmp
getArr tmp 0
setLRef (LRef arr) value = do
tmp <- newArr 1
setArr tmp 0 value
writeArr arr (0,0) tmp
instance LocalRefAccess CoreComp
where
getLRef (LRef arr) = getLArr arr 0
setLRef (LRef arr) value = setLArr arr 0 value
| kmate/raw-feldspar-mcs | src/Feldspar/Multicore/Reference.hs | bsd-3-clause | 916 | 0 | 11 | 229 | 346 | 173 | 173 | -1 | -1 |
-- |
-- Module : Core.Vector.Common
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : portable
--
-- Common part for vectors
--
{-# LANGUAGE DeriveDataTypeable #-}
module Core.Vector.Common
( OutOfBound(..)
, OutOfBoundOperation(..)
) where
import Core.Internal.Base
-- | The type of operation that triggers an OutOfBound exception.
--
-- * OOB_Index: reading an immutable vector
-- * OOB_Read: reading a mutable vector
-- * OOB_Write: write a mutable vector
data OutOfBoundOperation = OOB_Read | OOB_Write | OOB_Index
deriving (Show,Eq,Typeable)
-- | Exception during an operation accessing the vector out of bound
--
-- Represent the type of operation, the index accessed, and the total length of the vector.
data OutOfBound = OutOfBound OutOfBoundOperation Int Int
deriving (Show,Typeable)
instance Exception OutOfBound
| vincenthz/hs-xyz-test | Core/Vector/Common.hs | bsd-3-clause | 939 | 0 | 6 | 175 | 106 | 70 | 36 | 10 | 0 |
module Accept (acceptLoop) where
import Control.Concurrent (forkFinally, runInUnboundThread)
import qualified Control.Exception as E
import Control.Monad (void)
import Network (sClose)
import Network.Socket (Socket, accept)
import Buffer
import Types
import Worker
acceptLoop :: Options -> Socket -> IO ()
acceptLoop opt s = do
arena <- if prepareRecvBuf opt then
prepareArena
else
prepareDummyArena
run $ acceptLoop' opt arena s
where
run
| acceptInUnbound opt = runInUnboundThread
| otherwise = id
acceptLoop' :: Options -> Arena -> Socket -> IO ()
acceptLoop' opt arena s = E.handle handler loop
where
loop = do
(sock, _) <- accept s
void $ forkFinally (worker opt arena sock) (const $ sClose sock)
loop
handler :: E.IOException -> IO ()
handler e = print e
| kazu-yamamoto/witty | src/Accept.hs | bsd-3-clause | 886 | 0 | 13 | 243 | 281 | 146 | 135 | 26 | 2 |
coinSums s = [1 | a <- [s,(s-200)..0],
b <- [a,(a-100)..0],
c <- [b,(b-50)..0],
d <- [c,(c-20)..0],
e <- [d,(d-10)..0],
f <- [e,(e-5)..0],
g <- [f,(f-2)..0]]
main = print . length . coinSums $ 200
| JacksonGariety/euler.hs | 031.hs | bsd-3-clause | 306 | 0 | 10 | 144 | 190 | 106 | 84 | 8 | 1 |
module Main where
import Network.Wai.Handler.Warp (run)
import App
main :: IO ()
main = app >>= run 8080 -- port should get from env var
| NorthParkSoftware/yournextgig-backend | app/Main.hs | bsd-3-clause | 139 | 0 | 6 | 27 | 42 | 25 | 17 | 5 | 1 |
module Network.TeleHash.Dht
(
dhtMaint
, insertIntoDht
, deleteFromDht
, getBucketContentsForHn
, getBucketContents
, dhtBucket
, distanceTo
, sortBucketByAge
) where
import Control.Exception
import Control.Monad.State
import Data.Bits
import Data.Char
import Data.List
import Data.Maybe
import System.Time
import Network.TeleHash.SwitchApi
import Network.TeleHash.Types
import Network.TeleHash.Utils
import qualified Data.Map as Map
import qualified Data.Set as Set
-- | Manage the DHT
-- See https://github.com/telehash/telehash.org/blob/master/dht.md
-- ---------------------------------------------------------------------
-- |Called periodically to maintain the DHT.
-- Spec calls for maintenance every 29 secs
dhtMaint :: TeleHash ()
dhtMaint = do
now <- io $ getClockTime
logR $ "dhtMaint entered at " ++ show now
dht <- gets swDht
k <- gets swDhtK
link_max <- gets swDhtLinkMax
forM_ (Map.assocs dht) $ \(d,_b) -> do
-- sort by age and send maintenance to only k links
bucket <- getBucketContents d
let sorted = sortBucketByAge bucket
if length sorted > 0
then logR $ "dhtMaint:processing bucket " ++ show d
else return ()
forM_ (take k sorted) $ \hc -> do
hstr <- showHashName now hc
if isNothing (hLinkAge hc) || hChanOut hc == nullChannelId
then do
logT $ "dhtMaint:not considering " ++ hstr ++ "," ++ show (hLinkAge hc,hChanOut hc)
return ()
else do
logR $ "dhtMaint:considering " ++ hstr
if isTimeOut now (hLinkAge hc) param_link_timeout_secs
then do
logT $ "dhtMaint:time for maintenance"
case hLinkChan hc of
Nothing -> do
logR $ "dhtMaint:expected a valid hLinkChan for " ++ show hc
assert False undefined
Just cid -> do
mc <- getChanMaybe cid
case mc of
Nothing -> do
logR $ "dhtMaint: bad hLinkChan, cannot to refresh link for " ++ show hc
Just _ -> return ()
void $ link_hn (hHashName hc) (Just cid)
else do
logT $ "dhtMaint:not for maintenance " ++ show (now,hLinkAge hc,param_link_timeout_secs)
return ()
linkSeeds
{-
js equivalent
// every link that needs to be maintained, ping them
function linkMaint(self)
{
// process every bucket
Object.keys(self.buckets).forEach(function(bucket){
// sort by age and send maintenance to only k links
var sorted = self.buckets[bucket].sort(function(a,b){ return a.age - b.age });
if(sorted.length) debug("link maintenance on bucket",bucket,sorted.length);
sorted.slice(0,defaults.link_k).forEach(function(hn){
if(!hn.linked || !hn.alive) return;
if((Date.now() - hn.linked.sentAt) < Math.ceil(defaults.link_timer/2)) return; // we sent to them recently
hn.linked.send({js:{seed:self.seed}});
});
});
}
-}
linkSeeds :: TeleHash ()
linkSeeds = do
sw <- get
forM_ (Set.toList (swSeeds sw)) $ \seed -> do
void $ link_hn seed Nothing
-- ---------------------------------------------------------------------
-- |Sort a hash bucket by descending age
sortBucketByAge :: [HashContainer] -> [HashContainer]
sortBucketByAge bucket = sortBy sf bucket
where
sf a b = compare (hLinkAge a) (hLinkAge b)
-- ---------------------------------------------------------------------
-- |Get the relevant bucket, and dereference all the HashNames
getBucketContents :: HashDistance -> TeleHash [HashContainer]
getBucketContents hd = do
sw <- get
let bucket = (Map.findWithDefault Set.empty hd (swDht sw))
hcs <- mapM getHN $ Set.toList bucket
return hcs
-- ---------------------------------------------------------------------
insertIntoDht :: HashName -> TeleHash ()
insertIntoDht hn = do
(distance,bucket) <- getBucketContentsForHn hn
logR $ "insertIntoDht:inserting " ++ show (distance,hn)
sw <- get
put $ sw { swDht = Map.insert distance (Set.insert hn bucket) (swDht sw) }
-- ---------------------------------------------------------------------
deleteFromDht :: HashName -> TeleHash ()
deleteFromDht hn = do
(distance,bucket) <- getBucketContentsForHn hn
logR $ "deleteFromDht:deleting " ++ show (distance,hn)
sw <- get
put $ sw { swDht = Map.insert distance (Set.delete hn bucket) (swDht sw) }
-- ---------------------------------------------------------------------
getBucketContentsForHn :: HashName -> TeleHash (HashDistance,Bucket)
getBucketContentsForHn hn = do
distance <- dhtBucket hn
sw <- get
case Map.lookup distance (swDht sw) of
Nothing -> return (distance,Set.empty)
Just b -> return (distance,b)
-- ---------------------------------------------------------------------
-- |Calculate the bucket as the hash distance between our hashname and
-- the passed in one
dhtBucket :: HashName -> TeleHash HashDistance
dhtBucket hn = do
sw <- get
return $ distanceTo (swId sw) hn
-- ---------------------------------------------------------------------
-- TODO: consider memoising this result, will be used a LOT
distanceTo :: HashName -> HashName -> HashDistance
distanceTo (HN this) (HN h) = go 252 diffs
where
go acc [] = acc
go _acc (-1:[]) = -1
go acc (-1:xs) = go (acc - 4) xs
go acc (x:_xs) = acc + x
diffs = map (\(a,b) -> sbtab !! (xor (digitToInt a) (digitToInt b))) $ zip this h
sbtab = [-1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3]
{-
-- javascript version
// XOR distance between two hex strings, high is furthest bit, 0 is closest bit, -1 is error
function dhash(h1, h2) {
// convert to nibbles, easier to understand
var n1 = hex2nib(h1);
var n2 = hex2nib(h2);
if(!n1.length || !n2.length) return -1;
// compare nibbles
var sbtab = [-1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3];
var ret = 252;
for (var i = 0; i < n1.length; i++) {
if(!n2[i]) return ret;
var diff = n1[i] ^ n2[i];
if (diff) return ret + sbtab[diff];
ret -= 4;
}
return ret;
}
// convert hex string to nibble array
function hex2nib(hex)
{
var ret = [];
for (var i = 0; i < hex.length / 2; i ++) {
var bite = parseInt(hex.substr(i * 2, 2), 16);
if (isNaN(bite)) return [];
ret[ret.length] = bite >> 4;
ret[ret.length] = bite & 0xf;
}
return ret;
}
-}
-- ---------------------------------------------------------------------
| alanz/htelehash | src/Network/TeleHash/Dht.hs | bsd-3-clause | 6,455 | 0 | 32 | 1,453 | 1,384 | 702 | 682 | 106 | 6 |
-- |
-- Module : Data.Array.Accelerate.CUDA.Array.Sugar
-- Copyright : [2008..2014] Manuel M T Chakravarty, Gabriele Keller
-- [2009..2014] Trevor L. McDonell
-- License : BSD3
--
-- Maintainer : Trevor L. McDonell <tmcdonell@cse.unsw.edu.au>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Data.Array.Accelerate.CUDA.Array.Sugar (
module Data.Array.Accelerate.Array.Sugar,
newArray, allocateArray, useArray, useArrayAsync,
) where
import Data.Array.Accelerate.CUDA.State
import Data.Array.Accelerate.CUDA.Array.Data
import Data.Array.Accelerate.Array.Sugar hiding (newArray, allocateArray)
import qualified Data.Array.Accelerate.Array.Sugar as Sugar
-- Create an array from its representation function, uploading the result to the
-- device
--
newArray :: (Shape sh, Elt e) => sh -> (sh -> e) -> CIO (Array sh e)
newArray sh f =
let arr = Sugar.newArray sh f
in do
useArray arr
return arr
-- Allocate a new, uninitialised Accelerate array on host and device
--
allocateArray :: (Shape dim, Elt e) => dim -> CIO (Array dim e)
allocateArray sh =
let arr = Sugar.allocateArray sh
in do
mallocArray arr
return arr
| kumasento/accelerate-cuda | Data/Array/Accelerate/CUDA/Array/Sugar.hs | bsd-3-clause | 1,241 | 0 | 10 | 250 | 251 | 148 | 103 | 19 | 1 |
module Fib where
import System
-- | Calculate Fibonacci number of given 'Num'.
--
-- >>> import System.IO
-- >>> hPutStrLn stderr "foobar"
-- foobar
fib :: (Num t, Num t1) => t -> t1
fib _ = undefined
| beni55/doctest-haskell | tests/integration/bugfixOutputToStdErr/Fib.hs | mit | 203 | 0 | 6 | 41 | 44 | 27 | 17 | 4 | 1 |
{-# LANGUAGE JavaScriptFFI #-}
{-
Copyright 2019 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 Blockly.TypeExpr ( Type(..)
,Type_
,createType
,fromList
,toJSArray
)
where
import GHCJS.Types
import GHCJS.Foreign
import GHCJS.Marshal
import qualified JavaScript.Array as JA
import qualified Data.Text as T
import Data.JSString.Text
import Data.Text (Text);
newtype TypeExpr = TypeExpr JSVal
data Type = Func Type Type
| Lit Text [Type]
| TypeVar Text
deriving (Show)
newtype Type_ = Type_ JSVal
createType :: Type -> Type_
createType (TypeVar text) = js_createVar (pack text)
createType (Lit text cs) = js_createLit (pack text) (toJSArray $ map createType cs)
createType (Func fst snd) = js_createFunc (createType fst) (createType snd)
fromList :: [Type] -> Type_
fromList tps = js_fromList $ toJSArray $ map createType tps
pack = textToJSString
unpack = textFromJSString
instance IsJSVal Type_
instance ToJSVal Type_ where
toJSVal (Type_ v) = return v
instance FromJSVal Type_ where
fromJSVal v = return $ Just $ Type_ v
toJSArray :: [Type_] -> JA.JSArray
toJSArray tps = JA.fromList $ map (\(Type_ a) -> a) tps
foreign import javascript unsafe "new Blockly.TypeExpr($1,$2)"
js_createTypeExpr :: JSString -> JA.JSArray -> JSVal
foreign import javascript unsafe "Type.Var($1)"
js_createVar :: JSString -> Type_
foreign import javascript unsafe "Type.Lit($1,$2)"
js_createLit :: JSString -> JA.JSArray -> Type_
foreign import javascript unsafe "Type.Func($1,$2)"
js_createFunc :: Type_ -> Type_ -> Type_
foreign import javascript unsafe "Type.fromList($1)"
js_fromList :: JA.JSArray -> Type_
| alphalambda/codeworld | funblocks-client/src/Blockly/TypeExpr.hs | apache-2.0 | 2,326 | 15 | 11 | 514 | 495 | 267 | 228 | 44 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | Parsing TAG grammars consistent with the XMG format.
module NLP.Partage4Xmg.Grammar
(
-- * Types
Family
, Tree
, TreeID
, NonTerm (..)
, Type (..)
, SubType
, AVM
, XAVM (..)
-- , topOnly
-- , botOnly
, Sym
, Attr
-- , Feat
, Val
, Var
-- * Functions
, parseGrammar
, readGrammar
, printGrammar
-- * Utils
, attrValQ
, -- onEps
) where
import Debug.Trace (trace)
import qualified Control.Monad.State.Strict as E
import qualified Control.Arrow as Arr
import Control.Applicative ((*>), (<$>), (<*>),
optional, (<|>))
import Control.Monad ((<=<))
import Data.Maybe (mapMaybe)
import qualified Data.Foldable as F
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import qualified Data.Text.Lazy.IO as L
import qualified Data.Tree as R
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import qualified Text.HTML.TagSoup as TagSoup
import Text.XML.PolySoup hiding (P, Q)
import qualified Text.XML.PolySoup as PolySoup
-- TODO: just to have Tree Ord instance?
import qualified NLP.Partage.DAG as DAG
-- import NLP.TAG.Vanilla.Core (View(..))
import NLP.Partage.FSTree2 (Loc(..))
-- import NLP.Partage4Xmg.Tree
-------------------------------------------------
-- Data types
-------------------------------------------------
-- | Parsing predicates.
type P a = PolySoup.P (XmlTree L.Text) a
type Q a = PolySoup.Q (XmlTree L.Text) a
-- instance View L.Text where
-- view = L.unpack
-- | Syntagmatic symbol.
type Sym = T.Text
-- | Attribute.
type Attr = T.Text
-- -- | Feature (simple, top or bottom)
-- type Feat = Loc Attr
-- | Attribute value.
type Val = S.Set T.Text
-- | Variable.
type Var = T.Text
-- | Attribute-value matrix. We are using a list and not e.g. a map on purpose,
-- so that it is possible to define a single feature with different values and
-- variables (something which might happen in practice).
type AVM = [(Attr, Either Val Var)]
-- | Non-terminal/node type.
data Type
= Std
| Foot
| Anchor
| Lex
| NAdj
-- ^ Null adjoining constraint
| Other SubType
deriving (Show, Eq, Ord)
-- | Node subtype (e.g. subst). Not handled in any special way.
type SubType = T.Text
-- | Non-terminal or terminal.
-- TODO: change the name.
data NonTerm = NonTerm
{ typ :: Type
, sym :: Sym
, avm :: XAVM }
deriving (Show, Eq, Ord)
-- | Mixed AVM.
data XAVM = XAVM
{ reg :: AVM
-- ^ Regular features
, top :: Maybe AVM
-- ^ The top AVM
, bot :: Maybe AVM
-- ^ The bottom AVM
} deriving (Show, Eq, Ord)
-- -- | Create a complex AVM with the top part only.
-- topOnly :: AVM -> AVM2
-- topOnly avm = AVM2 {top = Just avm, bot = Nothing}
--
--
-- -- | Create a complex AVM with the bottom part only.
-- botOnly :: AVM -> AVM2
-- botOnly avm = AVM2 {top = Nothing, bot = Just avm}
-- | Partage4Xmg tree.
type Tree = R.Tree NonTerm
-- | Name of a tree family.
type Family = T.Text
-- | Tree identifier.
type TreeID = T.Text
-------------------------------------------------
-- AVM
-------------------------------------------------
-- join v1 v2 = case (v2, v2) of
-- (Left x, Left y) -> S.union x y
-- (Right )
--
--
-- -- | Join two AVMs.
-- joinAVM :: AVM -> AVM ->
-- joinAVM avm1 avm2 =
-------------------------------------------------
-- Phon
-------------------------------------------------
-- -- | Remove phonologically empty nodes (and the corresponding subtrees)
-- rmPhonEps :: Tree -> Maybe (Tree)
-- rmPhonEps t
-- | phonEps (R.rootLabel t) = Nothing
-- | null (R.subForest t) = Just t
-- | otherwise = case mapMaybe rmPhonEps (R.subForest t) of
-- [] -> Nothing
-- xs -> Just $ t {R.subForest = xs}
-------------------------------------------------
-- Parsing
-------------------------------------------------
-- | Grammar parser (as a parser).
grammarP :: P [(Family, TreeID, Tree)]
grammarP = concat <$> every' grammarQ
-- | Grammar parser.
grammarQ :: Q [(Family, TreeID, Tree)]
grammarQ = concat <$> (true //> entryQ)
-- | Entry parser (family + one or more trees).
entryQ :: Q [(Family, TreeID, Tree)]
entryQ = named "entry" `joinR` do
famName <- first familyQ
trees <- every' treeQ
return [(famName, treeID, tree) | (treeID, tree) <- trees]
-- | Tree parser.
familyQ :: Q Family
familyQ = fmap L.toStrict $ named "family" `joinR` first (node name)
-- | Tree parser.
treeQ :: Q (TreeID, Tree)
treeQ = (named "tree" *> attr "id") `join`
(\tid -> (L.toStrict tid,) <$> first nodeQ)
-- | Node parser.
nodeQ :: Q Tree
nodeQ = (named "node" *> attr "type") `join` ( \typTxt -> R.Node
<$> first (nonTermQ typTxt)
<*> every' nodeQ )
-- | Non-terminal parser.
nonTermQ :: L.Text -> Q NonTerm
nonTermQ typ' = joinR (named "narg") $
first $ joinR (named "fs") $ do
sym' <- first symQ
avm' <- avmP
return $ NonTerm (parseTyp typ') sym' avm'
-- | Syntagmatic value parser.
symQ :: Q Sym
symQ = joinR (named "f" *> hasAttrVal "name" "cat") $
first $ node (named "sym" *> (L.toStrict <$> attr "value"))
-- | AVM parser.
avmQ :: L.Text -> Q [(Attr, Either Val Var)]
avmQ name' =
(named "f" *> hasAttrVal "name" name')
`joinR`
first (named "fs" `joinR` _avmP)
-- | Simple AVM parser.
_avmP :: P [(Attr, Either Val Var)]
_avmP = every attrValQ
-- | AVM parser.
avmP :: P XAVM
avmP = do
top' <- optional $ first $ avmQ "top"
bot' <- optional $ first $ avmQ "bot"
reg' <- _avmP
return $ XAVM
{ reg = reg'
, top = top'
, bot = bot' }
-- return $
-- [ (Top x, v) | (x, v) <- maybe [] id top' ] ++
-- [ (Bot x, v) | (x, v) <- maybe [] id bot' ] ++
-- concat [ (,v) <$> [Top x, Bot x]
-- | (x, v) <- sim' ]
-- | An attribute/value parser.
attrValQ :: Q (Attr, Either Val Var)
attrValQ = join (named "f" *> attr "name") $ \atr -> do
valVar <- first $ (Left <$> valQ)
<|> (Right <$> varQ)
return (L.toStrict atr, valVar)
-- | Attribute value parser.
valQ :: Q Val
valQ = simpleValQ <|> altValQ
-- | Attribute simple-value parser.
simpleValQ :: Q Val
simpleValQ = node $ named "sym" *> (S.singleton . L.toStrict <$> attr "value")
-- | Attribute alt-value parser.
altValQ :: Q Val
altValQ = joinR (named "vAlt") $
S.unions <$> every' simpleValQ
-- | Attribute variable parser.
varQ :: Q Var
varQ = node $ named "sym" *> (L.toStrict <$> attr "varname")
-- | Type parser.
parseTyp :: L.Text -> Type
parseTyp x = case x of
"std" -> Std
"lex" -> Lex
"anchor" -> Anchor
"foot" -> Foot
"nadj" -> NAdj
_ -> Other (L.toStrict x)
-- -- | Parse textual contents of the French TAG XML file.
-- parseGrammar :: L.Text -> [(Family, Tree)]
-- parseGrammar =
-- F.concat . evalP grammarP . parseForest . TagSoup.parseTags
-- | Parse textual contents of the French TAG XML file.
parseGrammar
:: L.Text
-> M.Map Family (M.Map Tree TreeID)
parseGrammar txt =
flip E.execState M.empty $
E.forM_ ts $
\(family, treeID, tree) ->
do length (show tree) + length (show treeID) `seq`
E.modify' (M.insertWith M.union
family
(M.singleton tree treeID))
where ts = F.concat . evalP grammarP . parseForest . TagSoup.parseTags $ txt
-- | Parse the stand-alone French TAG xml file.
-- readGrammar :: FilePath -> IO [(Family, Tree)]
readGrammar
:: FilePath
-> IO (M.Map Family (M.Map Tree TreeID))
readGrammar path = parseGrammar <$> L.readFile path
printGrammar
:: FilePath
-> IO ()
printGrammar =
let printTree (famName, ts) = do
putStrLn $ "### " ++ show famName ++ " ###"
E.forM_ (M.toList ts) $ \(tree, treeID) -> do
putStrLn $ "@@@ " ++ show treeID ++ " @@@"
putStrLn . R.drawTree . fmap show $ tree
in mapM_ printTree . M.toList <=< readGrammar
-------------------------------------------------
-- Utils
-------------------------------------------------
takeLeft :: Either a b -> Maybe a
takeLeft (Left x) = Just x
takeLeft _ = Nothing
| kawu/french-tag | src/NLP/Partage4Xmg/Grammar.hs | bsd-2-clause | 8,340 | 0 | 18 | 2,032 | 1,981 | 1,130 | 851 | -1 | -1 |
{-|
Module : Relation
Description : Relation module for the MPL DSL
Copyright : (c) Rohit Jha, 2015
License : BSD2
Maintainer : rohit305jha@gmail.com
Stability : Stable
Functionality for
* Generating element set
* Obtaining list of first element values
* Obtaining list of second element values
* Obtaining list of first element values for a specified element as a second element
* Obtaining list of second element values for a specified element as a first element
* Checking for reflexivity, symmetricity, anti-symmetricity, transitivity
* Union, intersection and difference of two relations
* Relation composition
* Power of relations
* Reflexive, Symmetric and Transitive closures
-}
module Relation
(
Relation(..),
relationToList,
listToRelation,
inverse,
getDomain,
getRange,
elements,
returnDomainElems,
returnRangeElems,
isReflexive,
isIrreflexive,
isSymmetric,
isAsymmetric,
isAntiSymmetric,
isTransitive,
rUnion,
rUnionL,
rIntersection,
rIntersectionL,
rDifference,
composite,
rPower,
reflClosure,
symmClosure,
tranClosure,
isEquivalent,
isWeakPartialOrder,
isWeakTotalOrder,
isStrictPartialOrder,
isStrictTotalOrder
)
where
import qualified Data.List as L
{-|
The 'Relation' data type is used for represnting relations (discrete mathematics).
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
-}
newtype Relation a = Relation [(a,a)] deriving (Eq)
instance (Show a) => Show (Relation a) where
showsPrec _ (Relation s) = showRelation s
showRelation [] str = showString "{}" str
showRelation (x:xs) str = showChar '{' (shows x (showl xs str))
where
showl [] str = showChar '}' str
showl (x:xs) str = showChar ',' (shows x (showl xs str))
{-|
The 'relationToList' function converts a 'Relation' to a list representation.
For example:
>>> r2
{(1,1),(2,2),(3,3)}
>>> relationToList r2
[(1,1),(2,2),(3,3)]
-}
relationToList :: Relation t -> [(t, t)]
relationToList (Relation r) = r
{-|
The 'listToRelation' function converts a list to a relation.
For example:
>>> let l = [(1,2),(2,3),(1,3)]
>>> let r = listToRelation l
>>> r
{(1,2),(2,3),(1,3)}
-}
listToRelation :: [(a, a)] -> Relation a
listToRelation r = Relation r
{-|
The 'inverse' function returns the inverse 'Relation' of a specified 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> inverse r1
{(1,1),(2,1),(3,1),(1,2),(2,2),(3,2),(1,3),(2,3),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
>>> inverse r2
{(1,1),(2,2),(3,3)}
-}
inverse :: Relation a -> Relation a
inverse (Relation a) = listToRelation [ (y,x) | (x,y) <- a ]
{-|
The 'getDomain' function returns the list of all "a" where (a,b) <- 'Relation'.
For example:
>>> getDomain (Relation [(1,2),(3,4),(2,5)])
[1,3,2]
>>> getDomain (Relation [])
[]
-}
getDomain :: Eq a => Relation a -> [a]
getDomain (Relation r) = L.nub [fst x | x <- r]
{-|
The 'getRange' function returns the list of all "b" where (a,b) <- 'Relation'.
For example:
>>> getRange (Relation [(1,2),(3,4),(2,5)])
[2,4,5]
>>> getRange (Relation [])
[]
-}
getRange :: Eq a => Relation a -> [a]
getRange (Relation r) = L.nub [snd x | x <- r]
{-|
The 'elements' function returns a list of all elements in a 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> elements r1
[1,2,3]
-}
elements :: Eq a => Relation a -> [a]
elements (Relation r) = getDomain (Relation r) `L.union` getRange (Relation r)
{-|
The 'returnFirstElems' function returns alist of all "a" where (a,b) <- 'Relation' and "b" is specified
For example:
>>> returnFirstElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 1
[]
>>> returnFirstElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 4
[3]
>>> returnFirstElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 3
[1,2,3]
-}
returnDomainElems :: Eq a => Relation a -> a -> [a]
returnDomainElems (Relation r) x = L.nub [a | a <- getDomain (Relation r), (a,x) `elem` r]
{-|
The 'returnSecondElems' function returns list of all 'b' where (a,b) <- Relation and 'a' is specified/
For example:
>>> returnSecondElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 3
[3,4]
>>> returnSecondElems (Relation [(1,2),(1,3),(2,5)]) 1
[2,3]
-}
returnRangeElems :: Eq a => Relation a -> a -> [a]
returnRangeElems (Relation r) x = L.nub [b | b <- getRange (Relation r), (x,b) `elem` r]
{-|
The 'isReflexive' function checks if a 'Relation' is reflexive or not.
For example:
>>> isReflexive (Relation [(1,1),(1,2),(2,2),(2,3)])
False
>>> isReflexive (Relation [(1,1),(1,2),(2,2)])
True
-}
isReflexive :: Eq t => Relation t -> Bool
isReflexive (Relation r) = and [(a,a) `elem` r | a <- elements (Relation r)]
{-|
The 'isIrreflexive' function checks if a 'Relation' is irreflexive or not.
For example:
>>> isIrreflexive (Relation [(1,1),(1,2),(2,2),(2,3)])
True
>>> isIrreflexive (Relation [(1,1),(1,2),(2,2)])
False
-}
isIrreflexive :: Eq t => Relation t -> Bool
isIrreflexive (Relation r) = not $ isReflexive (Relation r)
{-|
The 'isSymmetric' function checks if a 'Relation' is symmetric or not.
For example:
>>> isSymmetric (Relation [(1,1),(1,2),(2,2)])
False
>>> isSymmetric (Relation [(1,1),(1,2),(2,2),(2,1)])
True
-}
isSymmetric :: Eq a => Relation a -> Bool
isSymmetric (Relation r) = and [(b, a) `elem` r | a <- elements (Relation r), b <- elements (Relation r), (a, b) `elem` r]
{-|
The 'isAsymmetric' function checks if a 'Relation' is asymmetric or not.
For example:
>>> isAntiSymmetric (Relation [(1,2),(2,1)])
False
>>> isAntiSymmetric (Relation [(1,2),(1,3)])
True
-}
isAsymmetric :: Eq t => Relation t -> Bool
isAsymmetric (Relation r) = and [ (b,a) `notElem` r | a <- elements (Relation r), b <- elements (Relation r), (a,b) `elem` r]
{-|
The 'isAntiSymmetric' function checks if a 'Relation' is anti-symmetric or not.
For example:
>>> r2
{(1,1),(2,2),(3,3)}
>>> isAntiSymmetric r2
True
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> isAntiSymmetric r1
False
-}
isAntiSymmetric :: Eq a => Relation a -> Bool
isAntiSymmetric (Relation r) = and [ a == b | a <- elements (Relation r), b <- elements (Relation r), (a,b) `elem` r, (b,a) `elem` r]
{-|
The 'isTransitive' function checks if a 'Relation' is transitive or not.
For example:
>>> isTransitive (Relation [(1,1),(1,2),(2,1)])
False
>>> isTransitive (Relation [(1,1),(1,2),(2,1),(2,2)])
True
>>> isTransitive (Relation [(1,1),(2,2)])
True
-}
isTransitive :: Eq a => Relation a -> Bool
isTransitive (Relation r) = and [(a,c) `elem` r | a <- elements (Relation r), b <- elements (Relation r), c <- elements (Relation r), (a,b) `elem` r, (b,c) `elem` r]
{-|
The 'rUnion' function returns the union of two relations.
For example:
>>> rUnion (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{(1,1),(1,2),(2,2),(2,3)}
>>> rUnion (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,1),(1,2)}
-}
rUnion :: Ord a => Relation a -> Relation a -> Relation a
rUnion (Relation r1) (Relation r2) = Relation ((L.sort . L.nub) (r1 ++ [e | e <- r2, e `notElem` r1]))
{-|
The 'rUnionL' function returns the union of a list of 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
>>> rUnionL [r1,r2]
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
-}
{-rUnionL :: (Ord t1, Foldable t) => t (Relation t1) -> Relation t1-}
rUnionL :: (Ord t) => [Relation t] -> Relation t
rUnionL = foldl1 rUnion
{-|
The 'rIntersection' function returns the intersection of two relations.
For example:
>>> rIntersection (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,1)}
>>> rIntersection (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{}
-}
rIntersection :: Ord a => Relation a -> Relation a -> Relation a
rIntersection (Relation r1) (Relation r2) = Relation ((L.sort . L.nub) [e | e <- r1, e `elem` r2])
{-|
The 'rIntersectionL' function returns the intersection of a list of 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
>>> rIntersectionL [r1,r2]
{(1,1),(2,2),(3,3)}
-}
{-rIntersectionL :: (Ord a, Foldable t) => t (Relation a) -> Relation a-}
rIntersectionL :: (Ord a) => [Relation a] -> Relation a
rIntersectionL = foldl1 rIntersection
{-|
The 'rDifference' function returns the difference of two relations.
For example:
>>> rDifference (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,2)}
>>> rDifference (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{(1,1),(1,2)}
-}
rDifference :: Ord a => Relation a -> Relation a -> Relation a
rDifference (Relation r1) (Relation r2) = Relation ((L.sort . L.nub) [e | e <- r1, e `notElem` r2])
{-|
The 'composite' function returns the composite / concatenation of two relations.
For example:
>>> composite (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{(1,2),(1,3)}
>>> composite (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,1)}
-}
composite :: Eq a => Relation a -> Relation a -> Relation a
composite (Relation r1) (Relation r2) = Relation $ L.nub [(a,c) | a <- elements (Relation r1), b <- elements (Relation r1), b <- elements (Relation r2), c <- elements (Relation r2), (a,b) `elem` r1, (b,c) `elem` r2]
{-|
The 'rPower' function returns the power of a 'Relation'.
For example:
>>> let r4 = Relation [(1,2), (2,3), (2,4), (3,3)]
>>> r4
{(1,2),(2,3),(2,4),(3,3)}
>>> rPower r4 2
{(1,3),(1,4),(2,3),(3,3)}
>>> rPower r4 (-2)
{(3,1),(3,2),(3,3),(4,1)}
--| pow < 0 = rPower (Relation [(b, a) | (a, b) <- r]) (-pow)
-}
rPower :: (Eq a, Eq a1, Integral a1) => Relation a -> a1 -> Relation a
rPower (Relation r) pow
| pow < 0 = rPower (inverse (Relation r)) (-pow)
| pow == 1 = Relation r
| otherwise = composite (rPower (Relation r) (pow - 1)) (Relation r)
{-|
The 'reflClosure' function returns the Reflecive Closure of a 'Relation'.
For example:
>>> reflClosure (Relation [(1,1),(1,2),(4,5)])
{(1,1),(1,2),(2,2),(4,4),(4,5),(5,5)}
>>> reflClosure (Relation [(1,1),(1,3)])
{(1,1),(1,3),(3,3)}
-}
reflClosure :: Ord a => Relation a -> Relation a
reflClosure (Relation r) = rUnion (Relation r) (delta (Relation r))
where
delta (Relation r) = Relation [(a,b) | a <- elements (Relation r), b <- elements (Relation r), a == b]
{-|
The 'symmClosure' function returns the Symmetric Closure of a 'Relation'.
For example:
>>> symmClosure (Relation [(1,1),(1,2),(4,5)])
{(1,1),(1,2),(2,1),(4,5),(5,4)}
>>> symmClosure (Relation [(1,1),(1,3)])
{(1,1),(1,3),(3,1)}
-}
symmClosure :: Ord a => Relation a -> Relation a
symmClosure (Relation r) = rUnion (Relation r) (rPower (Relation r) (-1))
{-|
The 'tranClosure' function returns the Transitive Closure of a 'Relation'.
For example:
>>> tranClosure (Relation [(1,1),(1,2),(2,1)])
{(1,1),(1,2),(2,1),(2,2)}
>>> tranClosure (Relation [(1,1),(1,2),(1,3),(2,2),(3,1),(3,2)])
{(1,1),(1,2),(1,3),(2,2),(3,1),(3,2),(3,3)}
-}
tranClosure :: Ord a => Relation a -> Relation a
tranClosure (Relation r) = foldl1 rUnion [ rPower (Relation r) n | n <- [1 .. length (elements (Relation r)) ]]
{-|
The 'isEquivalent' function checks if a 'Relation' is equivalent (reflexive, symmetric and transitive).
For example:
>>> r2
{(1,1),(2,2),(3,3)}
>>> isEquivalent r2
True
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> isEquivalent r1
True
>>> isEquivalent (Relation [(1,2), (2,3)])
False
-}
isEquivalent :: Eq a => Relation a -> Bool
isEquivalent (Relation r) = isReflexive (Relation r) && isSymmetric (Relation r) && isTransitive (Relation r)
{-|
The 'isWeakPartialOrder' function checks if a 'Relation' is a weak partial order (reflexive, anti-symmetric and transitive).
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> isWeakPartialOrder r1
False
>>> r2
{(1,1),(2,2),(3,3)}
>>> isWeakPartialOrder r2
True
-}
isWeakPartialOrder :: Eq a => Relation a -> Bool
isWeakPartialOrder (Relation r) = isReflexive (Relation r) && isAntiSymmetric (Relation r) && isTransitive (Relation r)
{-|
The 'isWeakTotalOrder' function checks if a 'Relation' is a Weak Total Order, i.e. it is a Weak Partial Order and for all "a" and "b" in 'Relation' "r", (a,b) or (b,a) are elements of r.
-}
isWeakTotalOrder :: Eq a => Relation a -> Bool
isWeakTotalOrder (Relation r) = isWeakPartialOrder (Relation r) && and [ ((a,b) `elem` r) || ((b,a) `elem` r) | a <- elements (Relation r), b <- elements (Relation r) ]
{-|
The 'isStrictPartialOrder' function checks if a 'Relation' is a Strict Partial Order, i.e. it is irreflexive, asymmetric and transitive.
-}
isStrictPartialOrder :: Eq a => Relation a -> Bool
isStrictPartialOrder (Relation r) = isIrreflexive (Relation r) && isAsymmetric (Relation r) && isTransitive (Relation r)
{-|
The 'isStrictTotalOrder' function checks if a 'Relation' is a Strict Total Order, i.e. it is a Strict Partial Order, and for all "a" and "b" in 'Relation' "r", either (a,b) or (b,a) are elements of r or a == b.
-}
isStrictTotalOrder :: Eq a => Relation a -> Bool
isStrictTotalOrder (Relation r) = isStrictPartialOrder (Relation r) && and [ ((a,b) `elem` r) || ((b,a) `elem` r) || a==b | a <- elements (Relation r), b <- elements (Relation r) ]
-- SAMPLE RELATIONS --
r1 = Relation [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
r2 = Relation [(1,1),(2,2),(3,3)]
r3 = Relation []
| rohitjha/MPL | src/Relation.hs | bsd-2-clause | 14,854 | 0 | 14 | 3,654 | 2,872 | 1,507 | 1,365 | 105 | 2 |
-- |
-- Copyright : (c) Sam Truzjan 2014
-- License : BSD
-- Maintainer : pxqr.sta@gmail.com
-- Stability : experimental
-- Portability : portable
--
-- Cached data for tracker responses.
--
module Network.BitTorrent.Internal.Cache
( -- * Cache
Cached
, lastUpdated
, updateInterval
, minUpdateInterval
-- * Construction
, newCached
, newCached_
-- * Query
, isAlive
, isStalled
, isExpired
, canUpdate
, shouldUpdate
-- * Cached data
, tryTakeData
, unsafeTryTakeData
, takeData
) where
import Control.Applicative
import Data.Monoid
import Data.Default
import Data.Time
import Data.Time.Clock.POSIX
import System.IO.Unsafe
data Cached a = Cached
{ -- | Time of resource creation.
lastUpdated :: !POSIXTime
-- | Minimum invalidation timeout.
, minUpdateInterval :: !NominalDiffTime
-- | Resource lifetime.
, updateInterval :: !NominalDiffTime
-- | Resource data.
, cachedData :: a
} deriving (Show, Eq)
-- INVARIANT: minUpdateInterval <= updateInterval
instance Default (Cached a) where
def = mempty
instance Functor Cached where
fmap f (Cached t i m a) = Cached t i m (f a)
posixEpoch :: NominalDiffTime
posixEpoch = 1000000000000000000000000000000000000000000000000000000
instance Applicative Cached where
pure = Cached 0 posixEpoch posixEpoch
f <*> c = Cached
{ lastUpdated = undefined
, minUpdateInterval = undefined
, updateInterval = undefined
, cachedData = cachedData f (cachedData c)
}
instance Alternative Cached where
empty = mempty
(<|>) = error "cached alternative instance: not implemented"
instance Monad Cached where
return = pure
Cached {..} >>= f = Cached
{ lastUpdated = undefined
, updateInterval = undefined
, minUpdateInterval = undefined
, cachedData = undefined
}
instance Monoid (Cached a) where
mempty = Cached
{ lastUpdated = 0
, minUpdateInterval = 0
, updateInterval = 0
, cachedData = error "cached mempty: impossible happen"
}
mappend a b
| expirationTime a > expirationTime b = a
| otherwise = b
normalize :: NominalDiffTime -> NominalDiffTime
-> (NominalDiffTime, NominalDiffTime)
normalize a b
| a < b = (a, b)
| otherwise = (b, a)
{-# INLINE normalize #-}
newCached :: NominalDiffTime -> NominalDiffTime -> a -> IO (Cached a)
newCached minInterval interval x = do
t <- getPOSIXTime
let (mui, ui) = normalize minInterval interval
return Cached
{ lastUpdated = t
, minUpdateInterval = mui
, updateInterval = ui
, cachedData = x
}
newCached_ :: NominalDiffTime -> a -> IO (Cached a)
newCached_ interval x = newCached interval interval x
{-# INLINE newCached_ #-}
expirationTime :: Cached a -> POSIXTime
expirationTime Cached {..} = undefined
isAlive :: Cached a -> IO Bool
isAlive Cached {..} = do
currentTime <- getPOSIXTime
return $ lastUpdated + updateInterval > currentTime
isExpired :: Cached a -> IO Bool
isExpired Cached {..} = undefined
isStalled :: Cached a -> IO Bool
isStalled Cached {..} = undefined
canUpdate :: Cached a -> IO (Maybe NominalDiffTime)
canUpdate = undefined --isStaled
shouldUpdate :: Cached a -> IO (Maybe NominalDiffTime)
shouldUpdate = undefined -- isExpired
tryTakeData :: Cached a -> IO (Maybe a)
tryTakeData c = do
alive <- isAlive c
return $ if alive then Just (cachedData c) else Nothing
unsafeTryTakeData :: Cached a -> Maybe a
unsafeTryTakeData = unsafePerformIO . tryTakeData
invalidateData :: Cached a -> IO a -> IO (Cached a)
invalidateData Cached {..} action = do
t <- getPOSIXTime
x <- action
return Cached
{ lastUpdated = t
, updateInterval = updateInterval
, minUpdateInterval = minUpdateInterval
, cachedData = x
}
takeData :: Cached a -> IO a -> IO a
takeData c action = do
mdata <- tryTakeData c
case mdata of
Just a -> return a
Nothing -> do
c' <- invalidateData c action
takeData c' action
| DavidAlphaFox/bittorrent | src/Network/BitTorrent/Internal/Cache.hs | bsd-3-clause | 4,225 | 0 | 13 | 1,142 | 1,107 | 588 | 519 | -1 | -1 |
module Type.Unify (unify) where
import Control.Applicative ((<|>))
import Control.Monad.Error (ErrorT, throwError, runErrorT)
import Control.Monad.State as State
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import qualified Data.UnionFind.IO as UF
import Text.PrettyPrint (render)
import qualified AST.Annotation as A
import qualified AST.Variable as Var
import qualified Type.State as TS
import Type.Type
import Type.PrettyPrint
import qualified Type.Hint as Hint
import Elm.Utils ((|>))
unify :: A.Region -> Variable -> Variable -> StateT TS.SolverState IO ()
unify region variable1 variable2 =
do result <- runErrorT (unifyHelp region variable1 variable2)
either TS.addHint return result
-- ACTUALLY UNIFY STUFF
type Unify = ErrorT Hint.Hint (StateT TS.SolverState IO)
typeError
:: A.Region
-> Maybe String
-> UF.Point Descriptor
-> UF.Point Descriptor
-> Unify a
typeError region hint t1 t2 =
do msg <- liftIO (Hint.create region hint t1 t2)
throwError msg
unifyHelp :: A.Region -> Variable -> Variable -> Unify ()
unifyHelp region variable1 variable2 = do
equivalent <- liftIO $ UF.equivalent variable1 variable2
if equivalent
then return ()
else actuallyUnify region variable1 variable2
actuallyUnify :: A.Region -> Variable -> Variable -> Unify ()
actuallyUnify region variable1 variable2 = do
desc1 <- liftIO $ UF.descriptor variable1
desc2 <- liftIO $ UF.descriptor variable2
let unifyHelp' = unifyHelp region
(name', flex', rank', alias') = combinedDescriptors desc1 desc2
merge1 :: Unify ()
merge1 = liftIO $ do
if rank desc1 < rank desc2 then UF.union variable2 variable1
else UF.union variable1 variable2
UF.modifyDescriptor variable1 $ \desc ->
desc { structure = structure desc1
, flex = flex'
, name = name'
, alias = alias'
}
merge2 :: Unify ()
merge2 = liftIO $ do
if rank desc1 < rank desc2 then UF.union variable2 variable1
else UF.union variable1 variable2
UF.modifyDescriptor variable2 $ \desc ->
desc { structure = structure desc2
, flex = flex'
, name = name'
, alias = alias'
}
merge = if rank desc1 < rank desc2 then merge1 else merge2
fresh :: Maybe (Term1 Variable) -> Unify Variable
fresh structure = do
v <- liftIO . UF.fresh $ Descriptor
{ structure = structure
, rank = rank'
, flex = flex'
, name = name'
, copy = Nothing
, mark = noMark
, alias = alias'
}
lift (TS.register v)
flexAndUnify v = do
liftIO $ UF.modifyDescriptor v $ \desc -> desc { flex = Flexible }
unifyHelp' variable1 variable2
unifyNumber svar (Var.Canonical home name) =
case home of
Var.BuiltIn | name `elem` ["Int","Float"] -> flexAndUnify svar
Var.Local | List.isPrefixOf "number" name -> flexAndUnify svar
_ ->
let hint = "Looks like something besides an Int or Float is being used as a number."
in
typeError region (Just hint) variable1 variable2
comparableError maybe =
typeError region (Just $ Maybe.fromMaybe msg maybe) variable1 variable2
where
msg =
"Looks like you want something comparable, but the only valid comparable\n\
\types are Int, Float, Char, String, lists, or tuples."
appendableError maybe =
typeError region (Just $ Maybe.fromMaybe msg maybe) variable1 variable2
where
msg =
"Looks like you want something appendable, but the only Strings, Lists,\n\
\and Text can be appended with the (++) operator."
unifyComparable v (Var.Canonical home name) =
case home of
Var.BuiltIn | name `elem` ["Int","Float","Char","String"] -> flexAndUnify v
Var.Local | List.isPrefixOf "comparable" name -> flexAndUnify v
_ -> comparableError Nothing
unifyComparableStructure varSuper varFlex =
do struct <- liftIO $ collectApps varFlex
case struct of
Other -> comparableError Nothing
List v -> do flexAndUnify varSuper
unifyHelp' v =<< liftIO (variable $ Is Comparable)
Tuple vs
| length vs > 6 ->
comparableError $ Just "Cannot compare a tuple with more than 6 elements."
| otherwise ->
do flexAndUnify varSuper
cmpVars <- liftIO $ forM [1..length vs] $ \_ -> variable (Is Comparable)
zipWithM_ unifyHelp' vs cmpVars
unifyAppendable varSuper varFlex =
do struct <- liftIO $ collectApps varFlex
case struct of
List _ -> flexAndUnify varSuper
_ -> appendableError Nothing
rigidError var =
typeError region (Just hint) variable1 variable2
where
hint =
"Could not unify rigid type variable '" ++ render (pretty Never var) ++ "'.\n" ++
"The problem probably relates to the type variable being shared between a\n\
\top-level type annotation and a related let-bound type annotation."
superUnify =
case (flex desc1, flex desc2, name desc1, name desc2) of
(Is super1, Is super2, _, _)
| super1 == super2 -> merge
(Is Number, Is Comparable, _, _) -> merge1
(Is Comparable, Is Number, _, _) -> merge2
(Is Number, _, _, Just name) -> unifyNumber variable1 name
(_, Is Number, Just name, _) -> unifyNumber variable2 name
(Is Comparable, _, _, Just name) -> unifyComparable variable1 name
(_, Is Comparable, Just name, _) -> unifyComparable variable2 name
(Is Comparable, _, _, _) -> unifyComparableStructure variable1 variable2
(_, Is Comparable, _, _) -> unifyComparableStructure variable2 variable1
(Is Appendable, _, _, Just name)
| Var.isText name || Var.isPrim "String" name -> flexAndUnify variable1
(_, Is Appendable, Just name, _)
| Var.isText name || Var.isPrim "String" name -> flexAndUnify variable2
(Is Appendable, _, _, _) -> unifyAppendable variable1 variable2
(_, Is Appendable, _, _) -> unifyAppendable variable2 variable1
(Rigid, _, _, _) -> rigidError variable1
(_, Rigid, _, _) -> rigidError variable2
_ -> typeError region Nothing variable1 variable2
case (structure desc1, structure desc2) of
(Nothing, Nothing) | flex desc1 == Flexible && flex desc1 == Flexible -> merge
(Nothing, _) | flex desc1 == Flexible -> merge2
(_, Nothing) | flex desc2 == Flexible -> merge1
(Just (Var1 v), _) -> unifyHelp' v variable2
(_, Just (Var1 v)) -> unifyHelp' v variable1
(Nothing, _) -> superUnify
(_, Nothing) -> superUnify
(Just type1, Just type2) ->
case (type1,type2) of
(App1 term1 term2, App1 term1' term2') ->
do merge
unifyHelp' term1 term1'
unifyHelp' term2 term2'
(Fun1 term1 term2, Fun1 term1' term2') ->
do merge
unifyHelp' term1 term1'
unifyHelp' term2 term2'
(EmptyRecord1, EmptyRecord1) ->
return ()
(Record1 fields ext, EmptyRecord1) | Map.null fields -> unifyHelp' ext variable2
(EmptyRecord1, Record1 fields ext) | Map.null fields -> unifyHelp' ext variable1
(Record1 _ _, Record1 _ _) ->
recordUnify region fresh variable1 variable2
_ -> typeError region Nothing variable1 variable2
-- RECORD UNIFICATION
recordUnify
:: A.Region
-> (Maybe (Term1 Variable) -> Unify Variable)
-> Variable
-> Variable
-> Unify ()
recordUnify region fresh variable1 variable2 =
do (ExpandedRecord fields1 ext1) <- liftIO (gatherFields variable1)
(ExpandedRecord fields2 ext2) <- liftIO (gatherFields variable2)
unifyOverlappingFields region fields1 fields2
let freshRecord fields ext =
fresh (Just (Record1 fields ext))
let uniqueFields1 = diffFields fields1 fields2
let uniqueFields2 = diffFields fields2 fields1
let addFieldMismatchError missingFields =
let msg = fieldMismatchError missingFields
in
typeError region (Just msg) variable1 variable2
case (ext1, ext2) of
(Empty _, Empty _) ->
case Map.null uniqueFields1 && Map.null uniqueFields2 of
True -> return ()
False -> typeError region Nothing variable1 variable2
(Empty var1, Extension var2) ->
case (Map.null uniqueFields1, Map.null uniqueFields2) of
(_, False) -> addFieldMismatchError uniqueFields2
(True, True) -> unifyHelp region var1 var2
(False, True) ->
do subRecord <- freshRecord uniqueFields1 var1
unifyHelp region subRecord var2
(Extension var1, Empty var2) ->
case (Map.null uniqueFields1, Map.null uniqueFields2) of
(False, _) -> addFieldMismatchError uniqueFields1
(True, True) -> unifyHelp region var1 var2
(True, False) ->
do subRecord <- freshRecord uniqueFields2 var2
unifyHelp region var1 subRecord
(Extension var1, Extension var2) ->
case (Map.null uniqueFields1, Map.null uniqueFields2) of
(True, True) ->
unifyHelp region var1 var2
(True, False) ->
do subRecord <- freshRecord uniqueFields2 var2
unifyHelp region var1 subRecord
(False, True) ->
do subRecord <- freshRecord uniqueFields1 var1
unifyHelp region subRecord var2
(False, False) ->
do record1' <- freshRecord uniqueFields1 =<< fresh Nothing
record2' <- freshRecord uniqueFields2 =<< fresh Nothing
unifyHelp region record1' var2
unifyHelp region var1 record2'
unifyOverlappingFields
:: A.Region
-> Map.Map String [Variable]
-> Map.Map String [Variable]
-> Unify ()
unifyOverlappingFields region fields1 fields2 =
Map.intersectionWith (zipWith (unifyHelp region)) fields1 fields2
|> Map.elems
|> concat
|> sequence_
diffFields :: Map.Map String [a] -> Map.Map String [a] -> Map.Map String [a]
diffFields fields1 fields2 =
let eat (_:xs) (_:ys) = eat xs ys
eat xs _ = xs
in
Map.union (Map.intersectionWith eat fields1 fields2) fields1
|> Map.filter (not . null)
data ExpandedRecord = ExpandedRecord
{ _fields :: Map.Map String [Variable]
, _extension :: Extension
}
data Extension = Empty Variable | Extension Variable
gatherFields :: Variable -> IO ExpandedRecord
gatherFields var =
do desc <- UF.descriptor var
case structure desc of
(Just (Record1 fields ext)) ->
do (ExpandedRecord deeperFields rootExt) <- gatherFields ext
return (ExpandedRecord (Map.unionWith (++) fields deeperFields) rootExt)
(Just EmptyRecord1) ->
return (ExpandedRecord Map.empty (Empty var))
_ ->
return (ExpandedRecord Map.empty (Extension var))
-- assumes that one of the dicts has stuff in it
fieldMismatchError :: Map.Map String a -> String
fieldMismatchError missingFields =
case Map.keys missingFields of
[] -> ""
[key] ->
"Looks like a record is missing the field '" ++ key ++ "'.\n " ++
"Maybe there is a misspelling in a record access or record update?"
keys ->
"Looks like one record is missing fields "
++ List.intercalate ", " (init keys) ++ ", and " ++ last keys
combinedDescriptors :: Descriptor -> Descriptor
-> (Maybe Var.Canonical, Flex, Int, Maybe Var.Canonical)
combinedDescriptors desc1 desc2 =
(name', flex', rank', alias')
where
rank' :: Int
rank' = min (rank desc1) (rank desc2)
alias' :: Maybe Var.Canonical
alias' = alias desc1 <|> alias desc2
name' :: Maybe Var.Canonical
name' = case (name desc1, name desc2) of
(Just name1, Just name2) ->
case (flex desc1, flex desc2) of
(_, Flexible) -> Just name1
(Flexible, _) -> Just name2
(Is Number, Is _) -> Just name1
(Is _, Is Number) -> Just name2
(Is _, Is _) -> Just name1
(_, _) -> Nothing
(Just name1, _) -> Just name1
(_, Just name2) -> Just name2
_ -> Nothing
flex' :: Flex
flex' = case (flex desc1, flex desc2) of
(f, Flexible) -> f
(Flexible, f) -> f
(Is Number, Is _) -> Is Number
(Is _, Is Number) -> Is Number
(Is super, Is _) -> Is super
(_, _) -> Flexible
| JoeyEremondi/utrecht-apa-p1 | src/Type/Unify.hs | bsd-3-clause | 13,671 | 0 | 23 | 4,591 | 4,018 | 2,010 | 2,008 | 285 | 39 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.BuildTargets
-- Copyright : (c) Duncan Coutts 2012
-- License : BSD-like
--
-- Maintainer : duncan@community.haskell.org
--
-- Handling for user-specified build targets
-----------------------------------------------------------------------------
module Distribution.Simple.BuildTarget (
-- * Build targets
BuildTarget(..),
readBuildTargets,
-- * Parsing user build targets
UserBuildTarget,
readUserBuildTargets,
UserBuildTargetProblem(..),
reportUserBuildTargetProblems,
-- * Resolving build targets
resolveBuildTargets,
BuildTargetProblem(..),
reportBuildTargetProblems,
) where
import Distribution.Package
( Package(..), PackageId, packageName )
import Distribution.PackageDescription
( PackageDescription
, Executable(..)
, TestSuite(..), TestSuiteInterface(..), testModules
, Benchmark(..), BenchmarkInterface(..), benchmarkModules
, BuildInfo(..), libModules, exeModules )
import Distribution.ModuleName
( ModuleName, toFilePath )
import Distribution.Simple.LocalBuildInfo
( Component(..), ComponentName(..)
, pkgComponents, componentName, componentBuildInfo )
import Distribution.Text
( display )
import Distribution.Simple.Utils
( die, lowercase, equating )
import Data.List
( nub, stripPrefix, sortBy, groupBy, partition, intercalate )
import Data.Ord
import Data.Maybe
( listToMaybe, catMaybes )
import Data.Either
( partitionEithers )
import qualified Data.Map as Map
import Control.Monad
import Control.Applicative as AP (Alternative(..), Applicative(..))
import qualified Distribution.Compat.ReadP as Parse
import Distribution.Compat.ReadP
( (+++), (<++) )
import Data.Char
( isSpace, isAlphaNum )
import System.FilePath as FilePath
( dropExtension, normalise, splitDirectories, joinPath, splitPath
, hasTrailingPathSeparator )
import System.Directory
( doesFileExist, doesDirectoryExist )
-- ------------------------------------------------------------
-- * User build targets
-- ------------------------------------------------------------
-- | Various ways that a user may specify a build target.
--
data UserBuildTarget =
-- | A target specified by a single name. This could be a component
-- module or file.
--
-- > cabal build foo
-- > cabal build Data.Foo
-- > cabal build Data/Foo.hs Data/Foo.hsc
--
UserBuildTargetSingle String
-- | A target specified by a qualifier and name. This could be a component
-- name qualified by the component namespace kind, or a module or file
-- qualified by the component name.
--
-- > cabal build lib:foo exe:foo
-- > cabal build foo:Data.Foo
-- > cabal build foo:Data/Foo.hs
--
| UserBuildTargetDouble String String
-- A fully qualified target, either a module or file qualified by a
-- component name with the component namespace kind.
--
-- > cabal build lib:foo:Data/Foo.hs exe:foo:Data/Foo.hs
-- > cabal build lib:foo:Data.Foo exe:foo:Data.Foo
--
| UserBuildTargetTriple String String String
deriving (Show, Eq, Ord)
-- ------------------------------------------------------------
-- * Resolved build targets
-- ------------------------------------------------------------
-- | A fully resolved build target.
--
data BuildTarget =
-- | A specific component
--
BuildTargetComponent ComponentName
-- | A specific module within a specific component.
--
| BuildTargetModule ComponentName ModuleName
-- | A specific file within a specific component.
--
| BuildTargetFile ComponentName FilePath
deriving (Show,Eq)
-- ------------------------------------------------------------
-- * Do everything
-- ------------------------------------------------------------
readBuildTargets :: PackageDescription -> [String] -> IO [BuildTarget]
readBuildTargets pkg targetStrs = do
let (uproblems, utargets) = readUserBuildTargets targetStrs
reportUserBuildTargetProblems uproblems
utargets' <- mapM checkTargetExistsAsFile utargets
let (bproblems, btargets) = resolveBuildTargets pkg utargets'
reportBuildTargetProblems bproblems
return btargets
checkTargetExistsAsFile :: UserBuildTarget -> IO (UserBuildTarget, Bool)
checkTargetExistsAsFile t = do
fexists <- existsAsFile (fileComponentOfTarget t)
return (t, fexists)
where
existsAsFile f = do
exists <- doesFileExist f
case splitPath f of
(d:_) | hasTrailingPathSeparator d -> doesDirectoryExist d
(d:_:_) | not exists -> doesDirectoryExist d
_ -> return exists
fileComponentOfTarget (UserBuildTargetSingle s1) = s1
fileComponentOfTarget (UserBuildTargetDouble _ s2) = s2
fileComponentOfTarget (UserBuildTargetTriple _ _ s3) = s3
-- ------------------------------------------------------------
-- * Parsing user targets
-- ------------------------------------------------------------
readUserBuildTargets :: [String] -> ([UserBuildTargetProblem]
,[UserBuildTarget])
readUserBuildTargets = partitionEithers . map readUserBuildTarget
readUserBuildTarget :: String -> Either UserBuildTargetProblem
UserBuildTarget
readUserBuildTarget targetstr =
case readPToMaybe parseTargetApprox targetstr of
Nothing -> Left (UserBuildTargetUnrecognised targetstr)
Just tgt -> Right tgt
where
parseTargetApprox :: Parse.ReadP r UserBuildTarget
parseTargetApprox =
(do a <- tokenQ
return (UserBuildTargetSingle a))
+++ (do a <- token
_ <- Parse.char ':'
b <- tokenQ
return (UserBuildTargetDouble a b))
+++ (do a <- token
_ <- Parse.char ':'
b <- token
_ <- Parse.char ':'
c <- tokenQ
return (UserBuildTargetTriple a b c))
token = Parse.munch1 (\x -> not (isSpace x) && x /= ':')
tokenQ = parseHaskellString <++ token
parseHaskellString :: Parse.ReadP r String
parseHaskellString = Parse.readS_to_P reads
readPToMaybe :: Parse.ReadP a a -> String -> Maybe a
readPToMaybe p str = listToMaybe [ r | (r,s) <- Parse.readP_to_S p str
, all isSpace s ]
data UserBuildTargetProblem
= UserBuildTargetUnrecognised String
deriving Show
reportUserBuildTargetProblems :: [UserBuildTargetProblem] -> IO ()
reportUserBuildTargetProblems problems = do
case [ target | UserBuildTargetUnrecognised target <- problems ] of
[] -> return ()
target ->
die $ unlines
[ "Unrecognised build target '" ++ name ++ "'."
| name <- target ]
++ "Examples:\n"
++ " - build foo -- component name "
++ "(library, executable, test-suite or benchmark)\n"
++ " - build Data.Foo -- module name\n"
++ " - build Data/Foo.hsc -- file name\n"
++ " - build lib:foo exe:foo -- component qualified by kind\n"
++ " - build foo:Data.Foo -- module qualified by component\n"
++ " - build foo:Data/Foo.hsc -- file qualified by component"
showUserBuildTarget :: UserBuildTarget -> String
showUserBuildTarget = intercalate ":" . components
where
components (UserBuildTargetSingle s1) = [s1]
components (UserBuildTargetDouble s1 s2) = [s1,s2]
components (UserBuildTargetTriple s1 s2 s3) = [s1,s2,s3]
-- ------------------------------------------------------------
-- * Resolving user targets to build targets
-- ------------------------------------------------------------
{-
stargets =
[ BuildTargetComponent (CExeName "foo")
, BuildTargetModule (CExeName "foo") (mkMn "Foo")
, BuildTargetModule (CExeName "tst") (mkMn "Foo")
]
where
mkMn :: String -> ModuleName
mkMn = fromJust . simpleParse
ex_pkgid :: PackageIdentifier
Just ex_pkgid = simpleParse "thelib"
-}
-- | Given a bunch of user-specified targets, try to resolve what it is they
-- refer to.
--
resolveBuildTargets :: PackageDescription
-> [(UserBuildTarget, Bool)]
-> ([BuildTargetProblem], [BuildTarget])
resolveBuildTargets pkg = partitionEithers
. map (uncurry (resolveBuildTarget pkg))
resolveBuildTarget :: PackageDescription -> UserBuildTarget -> Bool
-> Either BuildTargetProblem BuildTarget
resolveBuildTarget pkg userTarget fexists =
case findMatch (matchBuildTarget pkg userTarget fexists) of
Unambiguous target -> Right target
Ambiguous targets -> Left (BuildTargetAmbiguous userTarget targets')
where targets' = disambiguateBuildTargets
(packageId pkg) userTarget
targets
None errs -> Left (classifyMatchErrors errs)
where
classifyMatchErrors errs
| not (null expected) = let (things, got:_) = unzip expected in
BuildTargetExpected userTarget things got
| not (null nosuch) = BuildTargetNoSuch userTarget nosuch
| otherwise = error $ "resolveBuildTarget: internal error in matching"
where
expected = [ (thing, got) | MatchErrorExpected thing got <- errs ]
nosuch = [ (thing, got) | MatchErrorNoSuch thing got <- errs ]
data BuildTargetProblem
= BuildTargetExpected UserBuildTarget [String] String
-- ^ [expected thing] (actually got)
| BuildTargetNoSuch UserBuildTarget [(String, String)]
-- ^ [(no such thing, actually got)]
| BuildTargetAmbiguous UserBuildTarget [(UserBuildTarget, BuildTarget)]
deriving Show
disambiguateBuildTargets :: PackageId -> UserBuildTarget -> [BuildTarget]
-> [(UserBuildTarget, BuildTarget)]
disambiguateBuildTargets pkgid original =
disambiguate (userTargetQualLevel original)
where
disambiguate ql ts
| null amb = unamb
| otherwise = unamb ++ disambiguate (succ ql) amb
where
(amb, unamb) = step ql ts
userTargetQualLevel (UserBuildTargetSingle _ ) = QL1
userTargetQualLevel (UserBuildTargetDouble _ _ ) = QL2
userTargetQualLevel (UserBuildTargetTriple _ _ _) = QL3
step :: QualLevel -> [BuildTarget]
-> ([BuildTarget], [(UserBuildTarget, BuildTarget)])
step ql = (\(amb, unamb) -> (map snd $ concat amb, concat unamb))
. partition (\g -> length g > 1)
. groupBy (equating fst)
. sortBy (comparing fst)
. map (\t -> (renderBuildTarget ql t pkgid, t))
data QualLevel = QL1 | QL2 | QL3
deriving (Enum, Show)
renderBuildTarget :: QualLevel -> BuildTarget -> PackageId -> UserBuildTarget
renderBuildTarget ql target pkgid =
case ql of
QL1 -> UserBuildTargetSingle s1 where s1 = single target
QL2 -> UserBuildTargetDouble s1 s2 where (s1, s2) = double target
QL3 -> UserBuildTargetTriple s1 s2 s3 where (s1, s2, s3) = triple target
where
single (BuildTargetComponent cn ) = dispCName cn
single (BuildTargetModule _ m) = display m
single (BuildTargetFile _ f) = f
double (BuildTargetComponent cn ) = (dispKind cn, dispCName cn)
double (BuildTargetModule cn m) = (dispCName cn, display m)
double (BuildTargetFile cn f) = (dispCName cn, f)
triple (BuildTargetComponent _ ) = error "triple BuildTargetComponent"
triple (BuildTargetModule cn m) = (dispKind cn, dispCName cn, display m)
triple (BuildTargetFile cn f) = (dispKind cn, dispCName cn, f)
dispCName = componentStringName pkgid
dispKind = showComponentKindShort . componentKind
reportBuildTargetProblems :: [BuildTargetProblem] -> IO ()
reportBuildTargetProblems problems = do
case [ (t, e, g) | BuildTargetExpected t e g <- problems ] of
[] -> return ()
targets ->
die $ unlines
[ "Unrecognised build target '" ++ showUserBuildTarget target
++ "'.\n"
++ "Expected a " ++ intercalate " or " expected
++ ", rather than '" ++ got ++ "'."
| (target, expected, got) <- targets ]
case [ (t, e) | BuildTargetNoSuch t e <- problems ] of
[] -> return ()
targets ->
die $ unlines
[ "Unknown build target '" ++ showUserBuildTarget target
++ "'.\nThere is no "
++ intercalate " or " [ mungeThing thing ++ " '" ++ got ++ "'"
| (thing, got) <- nosuch ] ++ "."
| (target, nosuch) <- targets ]
where
mungeThing "file" = "file target"
mungeThing thing = thing
case [ (t, ts) | BuildTargetAmbiguous t ts <- problems ] of
[] -> return ()
targets ->
die $ unlines
[ "Ambiguous build target '" ++ showUserBuildTarget target
++ "'. It could be:\n "
++ unlines [ " "++ showUserBuildTarget ut ++
" (" ++ showBuildTargetKind bt ++ ")"
| (ut, bt) <- amb ]
| (target, amb) <- targets ]
where
showBuildTargetKind (BuildTargetComponent _ ) = "component"
showBuildTargetKind (BuildTargetModule _ _) = "module"
showBuildTargetKind (BuildTargetFile _ _) = "file"
----------------------------------
-- Top level BuildTarget matcher
--
matchBuildTarget :: PackageDescription
-> UserBuildTarget -> Bool -> Match BuildTarget
matchBuildTarget pkg = \utarget fexists ->
case utarget of
UserBuildTargetSingle str1 ->
matchBuildTarget1 cinfo str1 fexists
UserBuildTargetDouble str1 str2 ->
matchBuildTarget2 cinfo str1 str2 fexists
UserBuildTargetTriple str1 str2 str3 ->
matchBuildTarget3 cinfo str1 str2 str3 fexists
where
cinfo = pkgComponentInfo pkg
matchBuildTarget1 :: [ComponentInfo] -> String -> Bool -> Match BuildTarget
matchBuildTarget1 cinfo str1 fexists =
matchComponent1 cinfo str1
`matchPlusShadowing` matchModule1 cinfo str1
`matchPlusShadowing` matchFile1 cinfo str1 fexists
matchBuildTarget2 :: [ComponentInfo] -> String -> String -> Bool
-> Match BuildTarget
matchBuildTarget2 cinfo str1 str2 fexists =
matchComponent2 cinfo str1 str2
`matchPlusShadowing` matchModule2 cinfo str1 str2
`matchPlusShadowing` matchFile2 cinfo str1 str2 fexists
matchBuildTarget3 :: [ComponentInfo] -> String -> String -> String -> Bool
-> Match BuildTarget
matchBuildTarget3 cinfo str1 str2 str3 fexists =
matchModule3 cinfo str1 str2 str3
`matchPlusShadowing` matchFile3 cinfo str1 str2 str3 fexists
data ComponentInfo = ComponentInfo {
cinfoName :: ComponentName,
cinfoStrName :: ComponentStringName,
cinfoSrcDirs :: [FilePath],
cinfoModules :: [ModuleName],
cinfoHsFiles :: [FilePath], -- other hs files (like main.hs)
cinfoCFiles :: [FilePath],
cinfoJsFiles :: [FilePath]
}
type ComponentStringName = String
pkgComponentInfo :: PackageDescription -> [ComponentInfo]
pkgComponentInfo pkg =
[ ComponentInfo {
cinfoName = componentName c,
cinfoStrName = componentStringName pkg (componentName c),
cinfoSrcDirs = hsSourceDirs bi,
cinfoModules = componentModules c,
cinfoHsFiles = componentHsFiles c,
cinfoCFiles = cSources bi,
cinfoJsFiles = jsSources bi
}
| c <- pkgComponents pkg
, let bi = componentBuildInfo c ]
componentStringName :: Package pkg => pkg -> ComponentName -> ComponentStringName
componentStringName pkg CLibName = display (packageName pkg)
componentStringName _ (CExeName name) = name
componentStringName _ (CTestName name) = name
componentStringName _ (CBenchName name) = name
componentModules :: Component -> [ModuleName]
componentModules (CLib lib) = libModules lib
componentModules (CExe exe) = exeModules exe
componentModules (CTest test) = testModules test
componentModules (CBench bench) = benchmarkModules bench
componentHsFiles :: Component -> [FilePath]
componentHsFiles (CExe exe) = [modulePath exe]
componentHsFiles (CTest TestSuite {
testInterface = TestSuiteExeV10 _ mainfile
}) = [mainfile]
componentHsFiles (CBench Benchmark {
benchmarkInterface = BenchmarkExeV10 _ mainfile
}) = [mainfile]
componentHsFiles _ = []
{-
ex_cs :: [ComponentInfo]
ex_cs =
[ (mkC (CExeName "foo") ["src1", "src1/src2"] ["Foo", "Src2.Bar", "Bar"])
, (mkC (CExeName "tst") ["src1", "test"] ["Foo"])
]
where
mkC n ds ms = ComponentInfo n (componentStringName pkgid n) ds (map mkMn ms)
mkMn :: String -> ModuleName
mkMn = fromJust . simpleParse
pkgid :: PackageIdentifier
Just pkgid = simpleParse "thelib"
-}
------------------------------
-- Matching component kinds
--
data ComponentKind = LibKind | ExeKind | TestKind | BenchKind
deriving (Eq, Ord, Show)
componentKind :: ComponentName -> ComponentKind
componentKind CLibName = LibKind
componentKind (CExeName _) = ExeKind
componentKind (CTestName _) = TestKind
componentKind (CBenchName _) = BenchKind
cinfoKind :: ComponentInfo -> ComponentKind
cinfoKind = componentKind . cinfoName
matchComponentKind :: String -> Match ComponentKind
matchComponentKind s
| s `elem` ["lib", "library"] = increaseConfidence >> return LibKind
| s `elem` ["exe", "executable"] = increaseConfidence >> return ExeKind
| s `elem` ["tst", "test", "test-suite"] = increaseConfidence
>> return TestKind
| s `elem` ["bench", "benchmark"] = increaseConfidence
>> return BenchKind
| otherwise = matchErrorExpected
"component kind" s
showComponentKind :: ComponentKind -> String
showComponentKind LibKind = "library"
showComponentKind ExeKind = "executable"
showComponentKind TestKind = "test-suite"
showComponentKind BenchKind = "benchmark"
showComponentKindShort :: ComponentKind -> String
showComponentKindShort LibKind = "lib"
showComponentKindShort ExeKind = "exe"
showComponentKindShort TestKind = "test"
showComponentKindShort BenchKind = "bench"
------------------------------
-- Matching component targets
--
matchComponent1 :: [ComponentInfo] -> String -> Match BuildTarget
matchComponent1 cs = \str1 -> do
guardComponentName str1
c <- matchComponentName cs str1
return (BuildTargetComponent (cinfoName c))
matchComponent2 :: [ComponentInfo] -> String -> String -> Match BuildTarget
matchComponent2 cs = \str1 str2 -> do
ckind <- matchComponentKind str1
guardComponentName str2
c <- matchComponentKindAndName cs ckind str2
return (BuildTargetComponent (cinfoName c))
-- utils:
guardComponentName :: String -> Match ()
guardComponentName s
| all validComponentChar s
&& not (null s) = increaseConfidence
| otherwise = matchErrorExpected "component name" s
where
validComponentChar c = isAlphaNum c || c == '.'
|| c == '_' || c == '-' || c == '\''
matchComponentName :: [ComponentInfo] -> String -> Match ComponentInfo
matchComponentName cs str =
orNoSuchThing "component" str
$ increaseConfidenceFor
$ matchInexactly caseFold
[ (cinfoStrName c, c) | c <- cs ]
str
matchComponentKindAndName :: [ComponentInfo] -> ComponentKind -> String
-> Match ComponentInfo
matchComponentKindAndName cs ckind str =
orNoSuchThing (showComponentKind ckind ++ " component") str
$ increaseConfidenceFor
$ matchInexactly (\(ck, cn) -> (ck, caseFold cn))
[ ((cinfoKind c, cinfoStrName c), c) | c <- cs ]
(ckind, str)
------------------------------
-- Matching module targets
--
matchModule1 :: [ComponentInfo] -> String -> Match BuildTarget
matchModule1 cs = \str1 -> do
guardModuleName str1
nubMatchErrors $ do
c <- tryEach cs
let ms = cinfoModules c
m <- matchModuleName ms str1
return (BuildTargetModule (cinfoName c) m)
matchModule2 :: [ComponentInfo] -> String -> String -> Match BuildTarget
matchModule2 cs = \str1 str2 -> do
guardComponentName str1
guardModuleName str2
c <- matchComponentName cs str1
let ms = cinfoModules c
m <- matchModuleName ms str2
return (BuildTargetModule (cinfoName c) m)
matchModule3 :: [ComponentInfo] -> String -> String -> String
-> Match BuildTarget
matchModule3 cs str1 str2 str3 = do
ckind <- matchComponentKind str1
guardComponentName str2
c <- matchComponentKindAndName cs ckind str2
guardModuleName str3
let ms = cinfoModules c
m <- matchModuleName ms str3
return (BuildTargetModule (cinfoName c) m)
-- utils:
guardModuleName :: String -> Match ()
guardModuleName s
| all validModuleChar s
&& not (null s) = increaseConfidence
| otherwise = matchErrorExpected "module name" s
where
validModuleChar c = isAlphaNum c || c == '.' || c == '_' || c == '\''
matchModuleName :: [ModuleName] -> String -> Match ModuleName
matchModuleName ms str =
orNoSuchThing "module" str
$ increaseConfidenceFor
$ matchInexactly caseFold
[ (display m, m)
| m <- ms ]
str
------------------------------
-- Matching file targets
--
matchFile1 :: [ComponentInfo] -> String -> Bool -> Match BuildTarget
matchFile1 cs str1 exists =
nubMatchErrors $ do
c <- tryEach cs
filepath <- matchComponentFile c str1 exists
return (BuildTargetFile (cinfoName c) filepath)
matchFile2 :: [ComponentInfo] -> String -> String -> Bool -> Match BuildTarget
matchFile2 cs str1 str2 exists = do
guardComponentName str1
c <- matchComponentName cs str1
filepath <- matchComponentFile c str2 exists
return (BuildTargetFile (cinfoName c) filepath)
matchFile3 :: [ComponentInfo] -> String -> String -> String -> Bool
-> Match BuildTarget
matchFile3 cs str1 str2 str3 exists = do
ckind <- matchComponentKind str1
guardComponentName str2
c <- matchComponentKindAndName cs ckind str2
filepath <- matchComponentFile c str3 exists
return (BuildTargetFile (cinfoName c) filepath)
matchComponentFile :: ComponentInfo -> String -> Bool -> Match FilePath
matchComponentFile c str fexists =
expecting "file" str $
matchPlus
(matchFileExists str fexists)
(matchPlusShadowing
(msum [ matchModuleFileRooted dirs ms str
, matchOtherFileRooted dirs hsFiles str ])
(msum [ matchModuleFileUnrooted ms str
, matchOtherFileUnrooted hsFiles str
, matchOtherFileUnrooted cFiles str
, matchOtherFileUnrooted jsFiles str ]))
where
dirs = cinfoSrcDirs c
ms = cinfoModules c
hsFiles = cinfoHsFiles c
cFiles = cinfoCFiles c
jsFiles = cinfoJsFiles c
-- utils
matchFileExists :: FilePath -> Bool -> Match a
matchFileExists _ False = mzero
matchFileExists fname True = do increaseConfidence
matchErrorNoSuch "file" fname
matchModuleFileUnrooted :: [ModuleName] -> String -> Match FilePath
matchModuleFileUnrooted ms str = do
let filepath = normalise str
_ <- matchModuleFileStem ms filepath
return filepath
matchModuleFileRooted :: [FilePath] -> [ModuleName] -> String -> Match FilePath
matchModuleFileRooted dirs ms str = nubMatches $ do
let filepath = normalise str
filepath' <- matchDirectoryPrefix dirs filepath
_ <- matchModuleFileStem ms filepath'
return filepath
matchModuleFileStem :: [ModuleName] -> FilePath -> Match ModuleName
matchModuleFileStem ms =
increaseConfidenceFor
. matchInexactly caseFold
[ (toFilePath m, m) | m <- ms ]
. dropExtension
matchOtherFileRooted :: [FilePath] -> [FilePath] -> FilePath -> Match FilePath
matchOtherFileRooted dirs fs str = do
let filepath = normalise str
filepath' <- matchDirectoryPrefix dirs filepath
_ <- matchFile fs filepath'
return filepath
matchOtherFileUnrooted :: [FilePath] -> FilePath -> Match FilePath
matchOtherFileUnrooted fs str = do
let filepath = normalise str
_ <- matchFile fs filepath
return filepath
matchFile :: [FilePath] -> FilePath -> Match FilePath
matchFile fs = increaseConfidenceFor
. matchInexactly caseFold [ (f, f) | f <- fs ]
matchDirectoryPrefix :: [FilePath] -> FilePath -> Match FilePath
matchDirectoryPrefix dirs filepath =
exactMatches $
catMaybes
[ stripDirectory (normalise dir) filepath | dir <- dirs ]
where
stripDirectory :: FilePath -> FilePath -> Maybe FilePath
stripDirectory dir fp =
joinPath `fmap` stripPrefix (splitDirectories dir) (splitDirectories fp)
------------------------------
-- Matching monad
--
-- | A matcher embodies a way to match some input as being some recognised
-- value. In particular it deals with multiple and ambiguous matches.
--
-- There are various matcher primitives ('matchExactly', 'matchInexactly'),
-- ways to combine matchers ('ambiguousWith', 'shadows') and finally we can
-- run a matcher against an input using 'findMatch'.
--
data Match a = NoMatch Confidence [MatchError]
| ExactMatch Confidence [a]
| InexactMatch Confidence [a]
deriving Show
type Confidence = Int
data MatchError = MatchErrorExpected String String
| MatchErrorNoSuch String String
deriving (Show, Eq)
instance Alternative Match where
empty = mzero
(<|>) = mplus
instance MonadPlus Match where
mzero = matchZero
mplus = matchPlus
matchZero :: Match a
matchZero = NoMatch 0 []
-- | Combine two matchers. Exact matches are used over inexact matches
-- but if we have multiple exact, or inexact then the we collect all the
-- ambiguous matches.
--
matchPlus :: Match a -> Match a -> Match a
matchPlus (ExactMatch d1 xs) (ExactMatch d2 xs') =
ExactMatch (max d1 d2) (xs ++ xs')
matchPlus a@(ExactMatch _ _ ) (InexactMatch _ _ ) = a
matchPlus a@(ExactMatch _ _ ) (NoMatch _ _ ) = a
matchPlus (InexactMatch _ _ ) b@(ExactMatch _ _ ) = b
matchPlus (InexactMatch d1 xs) (InexactMatch d2 xs') =
InexactMatch (max d1 d2) (xs ++ xs')
matchPlus a@(InexactMatch _ _ ) (NoMatch _ _ ) = a
matchPlus (NoMatch _ _ ) b@(ExactMatch _ _ ) = b
matchPlus (NoMatch _ _ ) b@(InexactMatch _ _ ) = b
matchPlus a@(NoMatch d1 ms) b@(NoMatch d2 ms')
| d1 > d2 = a
| d1 < d2 = b
| otherwise = NoMatch d1 (ms ++ ms')
-- | Combine two matchers. This is similar to 'ambiguousWith' with the
-- difference that an exact match from the left matcher shadows any exact
-- match on the right. Inexact matches are still collected however.
--
matchPlusShadowing :: Match a -> Match a -> Match a
matchPlusShadowing a@(ExactMatch _ _) (ExactMatch _ _) = a
matchPlusShadowing a b = matchPlus a b
instance Functor Match where
fmap _ (NoMatch d ms) = NoMatch d ms
fmap f (ExactMatch d xs) = ExactMatch d (fmap f xs)
fmap f (InexactMatch d xs) = InexactMatch d (fmap f xs)
instance Applicative Match where
pure a = ExactMatch 0 [a]
(<*>) = ap
instance Monad Match where
return = AP.pure
NoMatch d ms >>= _ = NoMatch d ms
ExactMatch d xs >>= f = addDepth d
$ foldr matchPlus matchZero (map f xs)
InexactMatch d xs >>= f = addDepth d . forceInexact
$ foldr matchPlus matchZero (map f xs)
addDepth :: Confidence -> Match a -> Match a
addDepth d' (NoMatch d msgs) = NoMatch (d'+d) msgs
addDepth d' (ExactMatch d xs) = ExactMatch (d'+d) xs
addDepth d' (InexactMatch d xs) = InexactMatch (d'+d) xs
forceInexact :: Match a -> Match a
forceInexact (ExactMatch d ys) = InexactMatch d ys
forceInexact m = m
------------------------------
-- Various match primitives
--
matchErrorExpected, matchErrorNoSuch :: String -> String -> Match a
matchErrorExpected thing got = NoMatch 0 [MatchErrorExpected thing got]
matchErrorNoSuch thing got = NoMatch 0 [MatchErrorNoSuch thing got]
expecting :: String -> String -> Match a -> Match a
expecting thing got (NoMatch 0 _) = matchErrorExpected thing got
expecting _ _ m = m
orNoSuchThing :: String -> String -> Match a -> Match a
orNoSuchThing thing got (NoMatch 0 _) = matchErrorNoSuch thing got
orNoSuchThing _ _ m = m
increaseConfidence :: Match ()
increaseConfidence = ExactMatch 1 [()]
increaseConfidenceFor :: Match a -> Match a
increaseConfidenceFor m = m >>= \r -> increaseConfidence >> return r
nubMatches :: Eq a => Match a -> Match a
nubMatches (NoMatch d msgs) = NoMatch d msgs
nubMatches (ExactMatch d xs) = ExactMatch d (nub xs)
nubMatches (InexactMatch d xs) = InexactMatch d (nub xs)
nubMatchErrors :: Match a -> Match a
nubMatchErrors (NoMatch d msgs) = NoMatch d (nub msgs)
nubMatchErrors (ExactMatch d xs) = ExactMatch d xs
nubMatchErrors (InexactMatch d xs) = InexactMatch d xs
-- | Lift a list of matches to an exact match.
--
exactMatches, inexactMatches :: [a] -> Match a
exactMatches [] = matchZero
exactMatches xs = ExactMatch 0 xs
inexactMatches [] = matchZero
inexactMatches xs = InexactMatch 0 xs
tryEach :: [a] -> Match a
tryEach = exactMatches
------------------------------
-- Top level match runner
--
-- | Given a matcher and a key to look up, use the matcher to find all the
-- possible matches. There may be 'None', a single 'Unambiguous' match or
-- you may have an 'Ambiguous' match with several possibilities.
--
findMatch :: Eq b => Match b -> MaybeAmbiguous b
findMatch match =
case match of
NoMatch _ msgs -> None (nub msgs)
ExactMatch _ xs -> checkAmbiguous xs
InexactMatch _ xs -> checkAmbiguous xs
where
checkAmbiguous xs = case nub xs of
[x] -> Unambiguous x
xs' -> Ambiguous xs'
data MaybeAmbiguous a = None [MatchError] | Unambiguous a | Ambiguous [a]
deriving Show
------------------------------
-- Basic matchers
--
{-
-- | A primitive matcher that looks up a value in a finite 'Map'. The
-- value must match exactly.
--
matchExactly :: forall a b. Ord a => [(a, b)] -> (a -> Match b)
matchExactly xs =
\x -> case Map.lookup x m of
Nothing -> matchZero
Just ys -> ExactMatch 0 ys
where
m :: Ord a => Map a [b]
m = Map.fromListWith (++) [ (k,[x]) | (k,x) <- xs ]
-}
-- | A primitive matcher that looks up a value in a finite 'Map'. It checks
-- for an exact or inexact match. We get an inexact match if the match
-- is not exact, but the canonical forms match. It takes a canonicalisation
-- function for this purpose.
--
-- So for example if we used string case fold as the canonicalisation
-- function, then we would get case insensitive matching (but it will still
-- report an exact match when the case matches too).
--
matchInexactly :: (Ord a, Ord a') =>
(a -> a') ->
[(a, b)] -> (a -> Match b)
matchInexactly cannonicalise xs =
\x -> case Map.lookup x m of
Just ys -> exactMatches ys
Nothing -> case Map.lookup (cannonicalise x) m' of
Just ys -> inexactMatches ys
Nothing -> matchZero
where
m = Map.fromListWith (++) [ (k,[x]) | (k,x) <- xs ]
-- the map of canonicalised keys to groups of inexact matches
m' = Map.mapKeysWith (++) cannonicalise m
------------------------------
-- Utils
--
caseFold :: String -> String
caseFold = lowercase
| trskop/cabal | Cabal/Distribution/Simple/BuildTarget.hs | bsd-3-clause | 32,644 | 0 | 22 | 8,536 | 7,901 | 4,070 | 3,831 | 587 | 9 |
{-# LANGUAGE CPP, ScopedTypeVariables #-}
module Main where
import Control.Concurrent (ThreadId, forkIO, myThreadId)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar, readMVar)
import qualified Control.Exception as E
import Control.Monad (liftM, when)
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as C
import Data.Maybe (fromJust)
import Network.Socket hiding (recv, recvFrom, send, sendTo)
import Network.Socket.ByteString
--- To tests for AF_CAN on Linux, you need to bring up a virtual (or real can
--- interface.). Run as root:
--- # modprobe can
--- # modprobe can_raw
--- # modprobe vcan
--- # sudo ip link add dev vcan0 type vcan
--- # ip link show vcan0
--- 3: can0: <NOARP,UP,LOWER_UP> mtu 16 qdisc noqueue state UNKNOWN link/can
--- Define HAVE_LINUX_CAN to run CAN tests as well.
--- #define HAVE_LINUX_CAN 1
-- #include "../include/HsNetworkConfig.h"
#if defined(HAVE_LINUX_CAN_H)
import Network.BSD (ifNameToIndex)
#endif
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (Assertion, (@=?))
------------------------------------------------------------------------
serverAddr :: String
serverAddr = "127.0.0.1"
testMsg :: S.ByteString
testMsg = C.pack "This is a test message."
------------------------------------------------------------------------
-- Tests
------------------------------------------------------------------------
-- Sending and receiving
testSend :: Assertion
testSend = tcpTest client server
where
server sock = recv sock 1024 >>= (@=?) testMsg
client sock = send sock testMsg
testSendAll :: Assertion
testSendAll = tcpTest client server
where
server sock = recv sock 1024 >>= (@=?) testMsg
client sock = sendAll sock testMsg
testSendTo :: Assertion
testSendTo = udpTest client server
where
server sock = recv sock 1024 >>= (@=?) testMsg
client sock serverPort = do
addr <- inet_addr serverAddr
sendTo sock testMsg (SockAddrInet serverPort addr)
testSendAllTo :: Assertion
testSendAllTo = udpTest client server
where
server sock = recv sock 1024 >>= (@=?) testMsg
client sock serverPort = do
addr <- inet_addr serverAddr
sendAllTo sock testMsg (SockAddrInet serverPort addr)
testSendMany :: Assertion
testSendMany = tcpTest client server
where
server sock = recv sock 1024 >>= (@=?) (S.append seg1 seg2)
client sock = sendMany sock [seg1, seg2]
seg1 = C.pack "This is a "
seg2 = C.pack "test message."
testSendManyTo :: Assertion
testSendManyTo = udpTest client server
where
server sock = recv sock 1024 >>= (@=?) (S.append seg1 seg2)
client sock serverPort = do
addr <- inet_addr serverAddr
sendManyTo sock [seg1, seg2] (SockAddrInet serverPort addr)
seg1 = C.pack "This is a "
seg2 = C.pack "test message."
testRecv :: Assertion
testRecv = tcpTest client server
where
server sock = recv sock 1024 >>= (@=?) testMsg
client sock = send sock testMsg
testOverFlowRecv :: Assertion
testOverFlowRecv = tcpTest client server
where
server sock = do seg1 <- recv sock (S.length testMsg - 3)
seg2 <- recv sock 1024
let msg = S.append seg1 seg2
testMsg @=? msg
client sock = send sock testMsg
testRecvFrom :: Assertion
testRecvFrom = tcpTest client server
where
server sock = do (msg, _) <- recvFrom sock 1024
testMsg @=? msg
client sock = do
serverPort <- getPeerPort sock
addr <- inet_addr serverAddr
sendTo sock testMsg (SockAddrInet serverPort addr)
testOverFlowRecvFrom :: Assertion
testOverFlowRecvFrom = tcpTest client server
where
server sock = do (seg1, _) <- recvFrom sock (S.length testMsg - 3)
(seg2, _) <- recvFrom sock 1024
let msg = S.append seg1 seg2
testMsg @=? msg
client sock = send sock testMsg
testUserTimeout :: Assertion
testUserTimeout = do
when (isSupportedSocketOption UserTimeout) $ do
sock <- socket AF_INET Stream defaultProtocol
setSocketOption sock UserTimeout 1000
getSocketOption sock UserTimeout >>= (@=?) 1000
setSocketOption sock UserTimeout 2000
getSocketOption sock UserTimeout >>= (@=?) 2000
sClose sock
{-
testGetPeerCred:: Assertion
testGetPeerCred =
test clientSetup clientAct serverSetup server
where
clientSetup = do
sock <- socket AF_UNIX Stream defaultProtocol
connect sock $ SockAddrUnix addr
return sock
serverSetup = do
sock <- socket AF_UNIX Stream defaultProtocol
bindSocket sock $ SockAddrUnix addr
listen sock 1
return sock
server sock = do
(clientSock, _) <- accept sock
serverAct clientSock
sClose clientSock
addr = "/tmp/testAddr1"
clientAct sock = withSocketsDo $ do
sendAll sock testMsg
(pid,uid,gid) <- getPeerCred sock
putStrLn $ unwords ["pid=",show pid,"uid=",show uid, "gid=", show gid]
serverAct sock = withSocketsDo $ do
msg <- recv sock 1024
putStrLn $ C.unpack msg
testGetPeerEid :: Assertion
testGetPeerEid =
test clientSetup clientAct serverSetup server
where
clientSetup = do
sock <- socket AF_UNIX Stream defaultProtocol
connect sock $ SockAddrUnix addr
return sock
serverSetup = do
sock <- socket AF_UNIX Stream defaultProtocol
bindSocket sock $ SockAddrUnix addr
listen sock 1
return sock
server sock = do
(clientSock, _) <- accept sock
serverAct clientSock
sClose clientSock
addr = "/tmp/testAddr2"
clientAct sock = withSocketsDo $ do
sendAll sock testMsg
(uid,gid) <- getPeerEid sock
putStrLn $ unwords ["uid=",show uid, "gid=", show gid]
serverAct sock = withSocketsDo $ do
msg <- recv sock 1024
putStrLn $ C.unpack msg
-}
#if defined(HAVE_LINUX_CAN_H)
canTestMsg = S.pack [ 0,0,0,0 -- can ID = 0
, 4,0,0,0 -- data length counter = 2 (bytes)
, 0x80,123,321,55 -- SYNC with some random extra bytes
, 0, 0, 0, 0 -- padding
]
testCanSend :: Assertion
testCanSend = canTest "vcan0" client server
where
server sock = recv sock 1024 >>= (@=?) canTestMsg
client sock = send sock canTestMsg
canTest :: String -> (Socket -> IO a) -> (Socket -> IO b) -> IO ()
canTest ifname clientAct serverAct = do
ifIndex <- liftM fromJust $ ifNameToIndex ifname
test (clientSetup ifIndex) clientAct (serverSetup ifIndex) serverAct
where
clientSetup ifIndex = do
sock <- socket AF_CAN Raw 1 -- protocol 1 = raw CAN
-- bind the socket to the interface
bind sock (SockAddrCan $ fromIntegral $ ifIndex)
return sock
serverSetup = clientSetup
#endif
------------------------------------------------------------------------
-- Other
------------------------------------------------------------------------
-- List of all tests
basicTests :: Test
basicTests = testGroup "Basic socket operations"
[
-- Sending and receiving
testCase "testSend" testSend
, testCase "testSendAll" testSendAll
, testCase "testSendTo" testSendTo
, testCase "testSendAllTo" testSendAllTo
, testCase "testSendMany" testSendMany
, testCase "testSendManyTo" testSendManyTo
, testCase "testRecv" testRecv
, testCase "testOverFlowRecv" testOverFlowRecv
, testCase "testRecvFrom" testRecvFrom
, testCase "testOverFlowRecvFrom" testOverFlowRecvFrom
, testCase "testUserTimeout" testUserTimeout
-- , testCase "testGetPeerCred" testGetPeerCred
-- , testCase "testGetPeerEid" testGetPeerEid
#if defined(HAVE_LINUX_CAN_H)
, testCase "testCanSend" testCanSend
#endif
]
tests :: [Test]
tests = [basicTests]
------------------------------------------------------------------------
-- Test helpers
-- | Returns the 'PortNumber' of the peer. Will throw an 'error' if
-- used on a non-IP socket.
getPeerPort :: Socket -> IO PortNumber
getPeerPort sock = do
sockAddr <- getPeerName sock
case sockAddr of
(SockAddrInet port _) -> return port
(SockAddrInet6 port _ _ _) -> return port
_ -> error "getPeerPort: only works with IP sockets"
-- | Establish a connection between client and server and then run
-- 'clientAct' and 'serverAct', in different threads. Both actions
-- get passed a connected 'Socket', used for communicating between
-- client and server. 'tcpTest' makes sure that the 'Socket' is
-- closed after the actions have run.
tcpTest :: (Socket -> IO a) -> (Socket -> IO b) -> IO ()
tcpTest clientAct serverAct = do
portVar <- newEmptyMVar
test (clientSetup portVar) clientAct (serverSetup portVar) server
where
clientSetup portVar = do
sock <- socket AF_INET Stream defaultProtocol
addr <- inet_addr serverAddr
serverPort <- readMVar portVar
connect sock $ SockAddrInet serverPort addr
return sock
serverSetup portVar = do
sock <- socket AF_INET Stream defaultProtocol
setSocketOption sock ReuseAddr 1
addr <- inet_addr serverAddr
bindSocket sock (SockAddrInet aNY_PORT addr)
listen sock 1
serverPort <- socketPort sock
putMVar portVar serverPort
return sock
server sock = do
(clientSock, _) <- accept sock
serverAct clientSock
sClose clientSock
-- | Create an unconnected 'Socket' for sending UDP and receiving
-- datagrams and then run 'clientAct' and 'serverAct'.
udpTest :: (Socket -> PortNumber -> IO a) -> (Socket -> IO b) -> IO ()
udpTest clientAct serverAct = do
portVar <- newEmptyMVar
test clientSetup (client portVar) (serverSetup portVar) serverAct
where
clientSetup = socket AF_INET Datagram defaultProtocol
client portVar sock = do
serverPort <- readMVar portVar
clientAct sock serverPort
serverSetup portVar = do
sock <- socket AF_INET Datagram defaultProtocol
setSocketOption sock ReuseAddr 1
addr <- inet_addr serverAddr
bindSocket sock (SockAddrInet aNY_PORT addr)
serverPort <- socketPort sock
putMVar portVar serverPort
return sock
-- | Run a client/server pair and synchronize them so that the server
-- is started before the client and the specified server action is
-- finished before the client closes the 'Socket'.
test :: IO Socket -> (Socket -> IO b) -> IO Socket -> (Socket -> IO c) -> IO ()
test clientSetup clientAct serverSetup serverAct = do
tid <- myThreadId
barrier <- newEmptyMVar
forkIO $ server barrier
client tid barrier
where
server barrier = do
E.bracket serverSetup sClose $ \sock -> do
serverReady
serverAct sock
putMVar barrier ()
where
-- | Signal to the client that it can proceed.
serverReady = putMVar barrier ()
client tid barrier = do
takeMVar barrier
-- Transfer exceptions to the main thread.
bracketWithReraise tid clientSetup sClose $ \res -> do
clientAct res
takeMVar barrier
-- | Like 'bracket' but catches and reraises the exception in another
-- thread, specified by the first argument.
bracketWithReraise :: ThreadId -> IO a -> (a -> IO b) -> (a -> IO ()) -> IO ()
bracketWithReraise tid before after thing =
E.bracket before after thing
`E.catch` \ (e :: E.SomeException) -> E.throwTo tid e
------------------------------------------------------------------------
-- Test harness
main :: IO ()
main = withSocketsDo $ defaultMain tests
| Mikehunan/network | tests/Simple.hs | bsd-3-clause | 11,956 | 0 | 14 | 3,007 | 2,445 | 1,229 | 1,216 | 172 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
#ifndef MIN_VERSION_profunctors
#define MIN_VERSION_profunctors(x,y,z) 1
#endif
#if __GLASGOW_HASKELL__ < 708 || !(MIN_VERSION_profunctors(4,4,0))
{-# LANGUAGE Trustworthy #-}
#endif
#if __GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ >= 704
{-# LANGUAGE NoPolyKinds #-}
{-# LANGUAGE NoDataKinds #-}
#endif
-------------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Getter
-- Copyright : (C) 2012-15 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : provisional
-- Portability : Rank2Types
--
--
-- A @'Getter' s a@ is just any function @(s -> a)@, which we've flipped
-- into continuation passing style, @(a -> r) -> s -> r@ and decorated
-- with 'Const' to obtain:
--
-- @type 'Getting' r s a = (a -> 'Const' r a) -> s -> 'Const' r s@
--
-- If we restrict access to knowledge about the type 'r', we could get:
--
-- @type 'Getter' s a = forall r. 'Getting' r s a@
--
-- However, for 'Getter' (but not for 'Getting') we actually permit any
-- functor @f@ which is an instance of both 'Functor' and 'Contravariant':
--
-- @type 'Getter' s a = forall f. ('Contravariant' f, 'Functor' f) => (a -> f a) -> s -> f s@
--
-- Everything you can do with a function, you can do with a 'Getter', but
-- note that because of the continuation passing style ('.') composes them
-- in the opposite order.
--
-- Since it is only a function, every 'Getter' obviously only retrieves a
-- single value for a given input.
--
-------------------------------------------------------------------------------
module Control.Lens.Getter
(
-- * Getters
Getter, IndexedGetter
, Getting, IndexedGetting
, Accessing
-- * Building Getters
, to
, ito
, like
, ilike
-- * Combinators for Getters and Folds
, (^.)
, view, views
, use, uses
, listening, listenings
-- * Indexed Getters
-- ** Indexed Getter Combinators
, (^@.)
, iview, iviews
, iuse, iuses
, ilistening, ilistenings
-- * Implementation Details
, Contravariant(..)
, coerce, coerced
, Const(..)
) where
import Control.Applicative
import Control.Lens.Internal.Getter
import Control.Lens.Internal.Indexed
import Control.Lens.Type
import Control.Monad.Reader.Class as Reader
import Control.Monad.State as State
import Control.Monad.Writer as Writer
import Data.Functor.Contravariant
import Data.Profunctor
import Data.Profunctor.Unsafe
-- $setup
-- >>> :set -XNoOverloadedStrings
-- >>> import Control.Lens
-- >>> import Data.List.Lens
-- >>> import Debug.SimpleReflect.Expr
-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)
-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f
-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g
infixl 8 ^., ^@.
-------------------------------------------------------------------------------
-- Getters
-------------------------------------------------------------------------------
-- | Build an (index-preserving) 'Getter' from an arbitrary Haskell function.
--
-- @
-- 'to' f '.' 'to' g ≡ 'to' (g '.' f)
-- @
--
-- @
-- a '^.' 'to' f ≡ f a
-- @
--
-- >>> a ^.to f
-- f a
--
-- >>> ("hello","world")^.to snd
-- "world"
--
-- >>> 5^.to succ
-- 6
--
-- >>> (0, -5)^._2.to abs
-- 5
--
-- @
-- 'to' :: (s -> a) -> 'IndexPreservingGetter' s a
-- @
to :: (Profunctor p, Contravariant f) => (s -> a) -> Optic' p f s a
to k = dimap k (contramap k)
{-# INLINE to #-}
-- |
-- @
-- 'ito' :: (s -> (i, a)) -> 'IndexedGetter' i s a
-- @
ito :: (Indexable i p, Contravariant f) => (s -> (i, a)) -> Over' p f s a
ito k = dimap k (contramap (snd . k)) . uncurry . indexed
{-# INLINE ito #-}
-- | Build an constant-valued (index-preserving) 'Getter' from an arbitrary Haskell value.
--
-- @
-- 'like' a '.' 'like' b ≡ 'like' b
-- a '^.' 'like' b ≡ b
-- a '^.' 'like' b ≡ a '^.' 'to' ('const' b)
-- @
--
-- This can be useful as a second case 'failing' a 'Fold'
-- e.g. @foo `failing` 'like' 0@
--
-- @
-- 'like' :: a -> 'IndexPreservingGetter' s a
-- @
like :: (Profunctor p, Contravariant f) => a -> Optic' p f s a
like a = to (const a)
{-# INLINE like #-}
-- |
-- @
-- 'ilike' :: i -> a -> 'IndexedGetter' i s a
-- @
ilike :: (Indexable i p, Contravariant f) => i -> a -> Over' p f s a
ilike i a = ito (const (i, a))
{-# INLINE ilike #-}
-- | When you see this in a type signature it indicates that you can
-- pass the function a 'Lens', 'Getter',
-- 'Control.Lens.Traversal.Traversal', 'Control.Lens.Fold.Fold',
-- 'Control.Lens.Prism.Prism', 'Control.Lens.Iso.Iso', or one of
-- the indexed variants, and it will just \"do the right thing\".
--
-- Most 'Getter' combinators are able to be used with both a 'Getter' or a
-- 'Control.Lens.Fold.Fold' in limited situations, to do so, they need to be
-- monomorphic in what we are going to extract with 'Control.Applicative.Const'. To be compatible
-- with 'Lens', 'Control.Lens.Traversal.Traversal' and
-- 'Control.Lens.Iso.Iso' we also restricted choices of the irrelevant @t@ and
-- @b@ parameters.
--
-- If a function accepts a @'Getting' r s a@, then when @r@ is a 'Data.Monoid.Monoid', then
-- you can pass a 'Control.Lens.Fold.Fold' (or
-- 'Control.Lens.Traversal.Traversal'), otherwise you can only pass this a
-- 'Getter' or 'Lens'.
type Getting r s a = (a -> Const r a) -> s -> Const r s
-- | Used to consume an 'Control.Lens.Fold.IndexedFold'.
type IndexedGetting i m s a = Indexed i a (Const m a) -> s -> Const m s
-- | This is a convenient alias used when consuming (indexed) getters and (indexed) folds
-- in a highly general fashion.
type Accessing p m s a = p a (Const m a) -> s -> Const m s
-------------------------------------------------------------------------------
-- Getting Values
-------------------------------------------------------------------------------
-- | View the value pointed to by a 'Getter', 'Control.Lens.Iso.Iso' or
-- 'Lens' or the result of folding over all the results of a
-- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that points
-- at a monoidal value.
--
-- @
-- 'view' '.' 'to' ≡ 'id'
-- @
--
-- >>> view (to f) a
-- f a
--
-- >>> view _2 (1,"hello")
-- "hello"
--
-- >>> view (to succ) 5
-- 6
--
-- >>> view (_2._1) ("hello",("world","!!!"))
-- "world"
--
--
-- As 'view' is commonly used to access the target of a 'Getter' or obtain a monoidal summary of the targets of a 'Fold',
-- It may be useful to think of it as having one of these more restricted signatures:
--
-- @
-- 'view' :: 'Getter' s a -> s -> a
-- 'view' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Fold.Fold' s m -> s -> m
-- 'view' :: 'Control.Lens.Iso.Iso'' s a -> s -> a
-- 'view' :: 'Lens'' s a -> s -> a
-- 'view' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Traversal.Traversal'' s m -> s -> m
-- @
--
-- In a more general setting, such as when working with a 'Monad' transformer stack you can use:
--
-- @
-- 'view' :: 'MonadReader' s m => 'Getter' s a -> m a
-- 'view' :: ('MonadReader' s m, 'Data.Monoid.Monoid' a) => 'Control.Lens.Fold.Fold' s a -> m a
-- 'view' :: 'MonadReader' s m => 'Control.Lens.Iso.Iso'' s a -> m a
-- 'view' :: 'MonadReader' s m => 'Lens'' s a -> m a
-- 'view' :: ('MonadReader' s m, 'Data.Monoid.Monoid' a) => 'Control.Lens.Traversal.Traversal'' s a -> m a
-- @
view :: MonadReader s m => Getting a s a -> m a
view l = Reader.asks (getConst #. l Const)
{-# INLINE view #-}
-- | View a function of the value pointed to by a 'Getter' or 'Lens' or the result of
-- folding over the result of mapping the targets of a 'Control.Lens.Fold.Fold' or
-- 'Control.Lens.Traversal.Traversal'.
--
-- @
-- 'views' l f ≡ 'view' (l '.' 'to' f)
-- @
--
-- >>> views (to f) g a
-- g (f a)
--
-- >>> views _2 length (1,"hello")
-- 5
--
-- As 'views' is commonly used to access the target of a 'Getter' or obtain a monoidal summary of the targets of a 'Fold',
-- It may be useful to think of it as having one of these more restricted signatures:
--
-- @
-- 'views' :: 'Getter' s a -> (a -> r) -> s -> r
-- 'views' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Fold.Fold' s a -> (a -> m) -> s -> m
-- 'views' :: 'Control.Lens.Iso.Iso'' s a -> (a -> r) -> s -> r
-- 'views' :: 'Lens'' s a -> (a -> r) -> s -> r
-- 'views' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Traversal.Traversal'' s a -> (a -> m) -> s -> m
-- @
--
-- In a more general setting, such as when working with a 'Monad' transformer stack you can use:
--
-- @
-- 'views' :: 'MonadReader' s m => 'Getter' s a -> (a -> r) -> m r
-- 'views' :: ('MonadReader' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Fold.Fold' s a -> (a -> r) -> m r
-- 'views' :: 'MonadReader' s m => 'Control.Lens.Iso.Iso'' s a -> (a -> r) -> m r
-- 'views' :: 'MonadReader' s m => 'Lens'' s a -> (a -> r) -> m r
-- 'views' :: ('MonadReader' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Traversal.Traversal'' s a -> (a -> r) -> m r
-- @
--
-- @
-- 'views' :: 'MonadReader' s m => 'Getting' r s a -> (a -> r) -> m r
-- @
views :: (Profunctor p, MonadReader s m) => Over' p (Const r) s a -> p a r -> m r
views l f = Reader.asks (getConst #. l (Const #. f))
{-# INLINE views #-}
-- | View the value pointed to by a 'Getter' or 'Lens' or the
-- result of folding over all the results of a 'Control.Lens.Fold.Fold' or
-- 'Control.Lens.Traversal.Traversal' that points at a monoidal values.
--
-- This is the same operation as 'view' with the arguments flipped.
--
-- The fixity and semantics are such that subsequent field accesses can be
-- performed with ('Prelude..').
--
-- >>> (a,b)^._2
-- b
--
-- >>> ("hello","world")^._2
-- "world"
--
-- >>> import Data.Complex
-- >>> ((0, 1 :+ 2), 3)^._1._2.to magnitude
-- 2.23606797749979
--
-- @
-- ('^.') :: s -> 'Getter' s a -> a
-- ('^.') :: 'Data.Monoid.Monoid' m => s -> 'Control.Lens.Fold.Fold' s m -> m
-- ('^.') :: s -> 'Control.Lens.Iso.Iso'' s a -> a
-- ('^.') :: s -> 'Lens'' s a -> a
-- ('^.') :: 'Data.Monoid.Monoid' m => s -> 'Control.Lens.Traversal.Traversal'' s m -> m
-- @
(^.) :: s -> Getting a s a -> a
s ^. l = getConst (l Const s)
{-# INLINE (^.) #-}
-------------------------------------------------------------------------------
-- MonadState
-------------------------------------------------------------------------------
-- | Use the target of a 'Lens', 'Control.Lens.Iso.Iso', or
-- 'Getter' in the current state, or use a summary of a
-- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that points
-- to a monoidal value.
--
-- >>> evalState (use _1) (a,b)
-- a
--
-- >>> evalState (use _1) ("hello","world")
-- "hello"
--
-- @
-- 'use' :: 'MonadState' s m => 'Getter' s a -> m a
-- 'use' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Fold.Fold' s r -> m r
-- 'use' :: 'MonadState' s m => 'Control.Lens.Iso.Iso'' s a -> m a
-- 'use' :: 'MonadState' s m => 'Lens'' s a -> m a
-- 'use' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Traversal.Traversal'' s r -> m r
-- @
use :: MonadState s m => Getting a s a -> m a
use l = State.gets (view l)
{-# INLINE use #-}
-- | Use the target of a 'Lens', 'Control.Lens.Iso.Iso' or
-- 'Getter' in the current state, or use a summary of a
-- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that
-- points to a monoidal value.
--
-- >>> evalState (uses _1 length) ("hello","world")
-- 5
--
-- @
-- 'uses' :: 'MonadState' s m => 'Getter' s a -> (a -> r) -> m r
-- 'uses' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Fold.Fold' s a -> (a -> r) -> m r
-- 'uses' :: 'MonadState' s m => 'Lens'' s a -> (a -> r) -> m r
-- 'uses' :: 'MonadState' s m => 'Control.Lens.Iso.Iso'' s a -> (a -> r) -> m r
-- 'uses' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Traversal.Traversal'' s a -> (a -> r) -> m r
-- @
--
-- @
-- 'uses' :: 'MonadState' s m => 'Getting' r s t a b -> (a -> r) -> m r
-- @
uses :: (Profunctor p, MonadState s m) => Over' p (Const r) s a -> p a r -> m r
uses l f = State.gets (views l f)
{-# INLINE uses #-}
-- | This is a generalized form of 'listen' that only extracts the portion of
-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'
-- then a monoidal summary of the parts of the log that are visited will be
-- returned.
--
-- @
-- 'listening' :: 'MonadWriter' w m => 'Getter' w u -> m a -> m (a, u)
-- 'listening' :: 'MonadWriter' w m => 'Lens'' w u -> m a -> m (a, u)
-- 'listening' :: 'MonadWriter' w m => 'Iso'' w u -> m a -> m (a, u)
-- 'listening' :: ('MonadWriter' w m, 'Monoid' u) => 'Fold' w u -> m a -> m (a, u)
-- 'listening' :: ('MonadWriter' w m, 'Monoid' u) => 'Traversal'' w u -> m a -> m (a, u)
-- 'listening' :: ('MonadWriter' w m, 'Monoid' u) => 'Prism'' w u -> m a -> m (a, u)
-- @
listening :: MonadWriter w m => Getting u w u -> m a -> m (a, u)
listening l m = do
(a, w) <- listen m
return (a, view l w)
{-# INLINE listening #-}
-- | This is a generalized form of 'listen' that only extracts the portion of
-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'
-- then a monoidal summary of the parts of the log that are visited will be
-- returned.
--
-- @
-- 'ilistening' :: 'MonadWriter' w m => 'IndexedGetter' i w u -> m a -> m (a, (i, u))
-- 'ilistening' :: 'MonadWriter' w m => 'IndexedLens'' i w u -> m a -> m (a, (i, u))
-- 'ilistening' :: ('MonadWriter' w m, 'Monoid' u) => 'IndexedFold' i w u -> m a -> m (a, (i, u))
-- 'ilistening' :: ('MonadWriter' w m, 'Monoid' u) => 'IndexedTraversal'' i w u -> m a -> m (a, (i, u))
-- @
ilistening :: MonadWriter w m => IndexedGetting i (i, u) w u -> m a -> m (a, (i, u))
ilistening l m = do
(a, w) <- listen m
return (a, iview l w)
{-# INLINE ilistening #-}
-- | This is a generalized form of 'listen' that only extracts the portion of
-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'
-- then a monoidal summary of the parts of the log that are visited will be
-- returned.
--
-- @
-- 'listenings' :: 'MonadWriter' w m => 'Getter' w u -> (u -> v) -> m a -> m (a, v)
-- 'listenings' :: 'MonadWriter' w m => 'Lens'' w u -> (u -> v) -> m a -> m (a, v)
-- 'listenings' :: 'MonadWriter' w m => 'Iso'' w u -> (u -> v) -> m a -> m (a, v)
-- 'listenings' :: ('MonadWriter' w m, 'Monoid' v) => 'Fold' w u -> (u -> v) -> m a -> m (a, v)
-- 'listenings' :: ('MonadWriter' w m, 'Monoid' v) => 'Traversal'' w u -> (u -> v) -> m a -> m (a, v)
-- 'listenings' :: ('MonadWriter' w m, 'Monoid' v) => 'Prism'' w u -> (u -> v) -> m a -> m (a, v)
-- @
listenings :: MonadWriter w m => Getting v w u -> (u -> v) -> m a -> m (a, v)
listenings l uv m = do
(a, w) <- listen m
return (a, views l uv w)
{-# INLINE listenings #-}
-- | This is a generalized form of 'listen' that only extracts the portion of
-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'
-- then a monoidal summary of the parts of the log that are visited will be
-- returned.
--
-- @
-- 'ilistenings' :: 'MonadWriter' w m => 'IndexedGetter' w u -> (i -> u -> v) -> m a -> m (a, v)
-- 'ilistenings' :: 'MonadWriter' w m => 'IndexedLens'' w u -> (i -> u -> v) -> m a -> m (a, v)
-- 'ilistenings' :: ('MonadWriter' w m, 'Monoid' v) => 'IndexedFold' w u -> (i -> u -> v) -> m a -> m (a, v)
-- 'ilistenings' :: ('MonadWriter' w m, 'Monoid' v) => 'IndexedTraversal'' w u -> (i -> u -> v) -> m a -> m (a, v)
-- @
ilistenings :: MonadWriter w m => IndexedGetting i v w u -> (i -> u -> v) -> m a -> m (a, v)
ilistenings l iuv m = do
(a, w) <- listen m
return (a, iviews l iuv w)
{-# INLINE ilistenings #-}
------------------------------------------------------------------------------
-- Indexed Getters
------------------------------------------------------------------------------
-- | View the index and value of an 'IndexedGetter' into the current environment as a pair.
--
-- When applied to an 'IndexedFold' the result will most likely be a nonsensical monoidal summary of
-- the indices tupled with a monoidal summary of the values and probably not whatever it is you wanted.
iview :: MonadReader s m => IndexedGetting i (i,a) s a -> m (i,a)
iview l = asks (getConst #. l (Indexed $ \i -> Const #. (,) i))
{-# INLINE iview #-}
-- | View a function of the index and value of an 'IndexedGetter' into the current environment.
--
-- When applied to an 'IndexedFold' the result will be a monoidal summary instead of a single answer.
--
-- @
-- 'iviews' ≡ 'Control.Lens.Fold.ifoldMapOf'
-- @
iviews :: MonadReader s m => IndexedGetting i r s a -> (i -> a -> r) -> m r
iviews l = views l .# Indexed
{-# INLINE iviews #-}
-- | Use the index and value of an 'IndexedGetter' into the current state as a pair.
--
-- When applied to an 'IndexedFold' the result will most likely be a nonsensical monoidal summary of
-- the indices tupled with a monoidal summary of the values and probably not whatever it is you wanted.
iuse :: MonadState s m => IndexedGetting i (i,a) s a -> m (i,a)
iuse l = gets (getConst #. l (Indexed $ \i -> Const #. (,) i))
{-# INLINE iuse #-}
-- | Use a function of the index and value of an 'IndexedGetter' into the current state.
--
-- When applied to an 'IndexedFold' the result will be a monoidal summary instead of a single answer.
iuses :: MonadState s m => IndexedGetting i r s a -> (i -> a -> r) -> m r
iuses l = uses l .# Indexed
{-# INLINE iuses #-}
-- | View the index and value of an 'IndexedGetter' or 'IndexedLens'.
--
-- This is the same operation as 'iview' with the arguments flipped.
--
-- The fixity and semantics are such that subsequent field accesses can be
-- performed with ('Prelude..').
--
-- @
-- ('^@.') :: s -> 'IndexedGetter' i s a -> (i, a)
-- ('^@.') :: s -> 'IndexedLens'' i s a -> (i, a)
-- @
--
-- The result probably doesn't have much meaning when applied to an 'IndexedFold'.
(^@.) :: s -> IndexedGetting i (i, a) s a -> (i, a)
s ^@. l = getConst $ l (Indexed $ \i -> Const #. (,) i) s
{-# INLINE (^@.) #-}
-- | Coerce a 'Getter'-compatible 'LensLike' to a 'LensLike''. This
-- is useful when using a 'Traversal' that is not simple as a 'Getter' or a
-- 'Fold'.
coerced :: (Functor f, Contravariant f) => LensLike f s t a b -> LensLike' f s a
coerced l f = coerce . l (coerce . f)
| Fuuzetsu/lens | src/Control/Lens/Getter.hs | bsd-3-clause | 18,880 | 0 | 14 | 4,193 | 2,046 | 1,256 | 790 | 103 | 1 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/ByteString/Builder.hs" #-}
{-# LANGUAGE CPP, BangPatterns #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-orphans #-}
{-# LANGUAGE Trustworthy #-}
{- | Copyright : (c) 2010 Jasper Van der Jeugt
(c) 2010 - 2011 Simon Meier
License : BSD3-style (see LICENSE)
Maintainer : Simon Meier <iridcode@gmail.com>
Portability : GHC
'Builder's are used to efficiently construct sequences of bytes from
smaller parts.
Typically,
such a construction is part of the implementation of an /encoding/, i.e.,
a function for converting Haskell values to sequences of bytes.
Examples of encodings are the generation of the sequence of bytes
representing a HTML document to be sent in a HTTP response by a
web application or the serialization of a Haskell value using
a fixed binary format.
For an /efficient implementation of an encoding/,
it is important that (a) little time is spent on converting
the Haskell values to the resulting sequence of bytes /and/
(b) that the representation of the resulting sequence
is such that it can be consumed efficiently.
'Builder's support (a) by providing an /O(1)/ concatentation operation
and efficient implementations of basic encodings for 'Char's, 'Int's,
and other standard Haskell values.
They support (b) by providing their result as a lazy 'L.ByteString',
which is internally just a linked list of pointers to /chunks/
of consecutive raw memory.
Lazy 'L.ByteString's can be efficiently consumed by functions that
write them to a file or send them over a network socket.
Note that each chunk boundary incurs expensive extra work (e.g., a system call)
that must be amortized over the work spent on consuming the chunk body.
'Builder's therefore take special care to ensure that the
average chunk size is large enough.
The precise meaning of large enough is application dependent.
The current implementation is tuned
for an average chunk size between 4kb and 32kb,
which should suit most applications.
As a simple example of an encoding implementation,
we show how to efficiently convert the following representation of mixed-data
tables to an UTF-8 encoded Comma-Separated-Values (CSV) table.
>data Cell = StringC String
> | IntC Int
> deriving( Eq, Ord, Show )
>
>type Row = [Cell]
>type Table = [Row]
We use the following imports and abbreviate 'mappend' to simplify reading.
@
import qualified "Data.ByteString.Lazy" as L
import "Data.ByteString.Builder"
import Data.Monoid
import Data.Foldable ('foldMap')
import Data.List ('intersperse')
infixr 4 \<\>
(\<\>) :: 'Monoid' m => m -> m -> m
(\<\>) = 'mappend'
@
CSV is a character-based representation of tables. For maximal modularity,
we could first render 'Table's as 'String's and then encode this 'String'
using some Unicode character encoding. However, this sacrifices performance
due to the intermediate 'String' representation being built and thrown away
right afterwards. We get rid of this intermediate 'String' representation by
fixing the character encoding to UTF-8 and using 'Builder's to convert
'Table's directly to UTF-8 encoded CSV tables represented as lazy
'L.ByteString's.
@
encodeUtf8CSV :: Table -> L.ByteString
encodeUtf8CSV = 'toLazyByteString' . renderTable
renderTable :: Table -> Builder
renderTable rs = 'mconcat' [renderRow r \<\> 'charUtf8' \'\\n\' | r <- rs]
renderRow :: Row -> Builder
renderRow [] = 'mempty'
renderRow (c:cs) =
renderCell c \<\> mconcat [ charUtf8 \',\' \<\> renderCell c\' | c\' <- cs ]
renderCell :: Cell -> Builder
renderCell (StringC cs) = renderString cs
renderCell (IntC i) = 'intDec' i
renderString :: String -> Builder
renderString cs = charUtf8 \'\"\' \<\> foldMap escape cs \<\> charUtf8 \'\"\'
where
escape \'\\\\\' = charUtf8 \'\\\\\' \<\> charUtf8 \'\\\\\'
escape \'\\\"\' = charUtf8 \'\\\\\' \<\> charUtf8 \'\\\"\'
escape c = charUtf8 c
@
Note that the ASCII encoding is a subset of the UTF-8 encoding,
which is why we can use the optimized function 'intDec' to
encode an 'Int' as a decimal number with UTF-8 encoded digits.
Using 'intDec' is more efficient than @'stringUtf8' . 'show'@,
as it avoids constructing an intermediate 'String'.
Avoiding this intermediate data structure significantly improves
performance because encoding 'Cell's is the core operation
for rendering CSV-tables.
See "Data.ByteString.Builder.Prim" for further
information on how to improve the performance of 'renderString'.
We demonstrate our UTF-8 CSV encoding function on the following table.
@
strings :: [String]
strings = [\"hello\", \"\\\"1\\\"\", \"λ-wörld\"]
table :: Table
table = [map StringC strings, map IntC [-3..3]]
@
The expression @encodeUtf8CSV table@ results in the following lazy
'L.ByteString'.
>Chunk "\"hello\",\"\\\"1\\\"\",\"\206\187-w\195\182rld\"\n-3,-2,-1,0,1,2,3\n" Empty
We can clearly see that we are converting to a /binary/ format. The \'λ\'
and \'ö\' characters, which have a Unicode codepoint above 127, are
expanded to their corresponding UTF-8 multi-byte representation.
We use the @criterion@ library (<http://hackage.haskell.org/package/criterion>)
to benchmark the efficiency of our encoding function on the following table.
>import Criterion.Main -- add this import to the ones above
>
>maxiTable :: Table
>maxiTable = take 1000 $ cycle table
>
>main :: IO ()
>main = defaultMain
> [ bench "encodeUtf8CSV maxiTable (original)" $
> whnf (L.length . encodeUtf8CSV) maxiTable
> ]
On a Core2 Duo 2.20GHz on a 32-bit Linux,
the above code takes 1ms to generate the 22'500 bytes long lazy 'L.ByteString'.
Looking again at the definitions above,
we see that we took care to avoid intermediate data structures,
as otherwise we would sacrifice performance.
For example,
the following (arguably simpler) definition of 'renderRow' is about 20% slower.
>renderRow :: Row -> Builder
>renderRow = mconcat . intersperse (charUtf8 ',') . map renderCell
Similarly, using /O(n)/ concatentations like '++' or the equivalent 'S.concat'
operations on strict and lazy 'L.ByteString's should be avoided.
The following definition of 'renderString' is also about 20% slower.
>renderString :: String -> Builder
>renderString cs = charUtf8 $ "\"" ++ concatMap escape cs ++ "\""
> where
> escape '\\' = "\\"
> escape '\"' = "\\\""
> escape c = return c
Apart from removing intermediate data-structures,
encodings can be optimized further by fine-tuning their execution
parameters using the functions in "Data.ByteString.Builder.Extra" and
their \"inner loops\" using the functions in
"Data.ByteString.Builder.Prim".
-}
module Data.ByteString.Builder
(
-- * The Builder type
Builder
-- * Executing Builders
-- | Internally, 'Builder's are buffer-filling functions. They are
-- executed by a /driver/ that provides them with an actual buffer to
-- fill. Once called with a buffer, a 'Builder' fills it and returns a
-- signal to the driver telling it that it is either done, has filled the
-- current buffer, or wants to directly insert a reference to a chunk of
-- memory. In the last two cases, the 'Builder' also returns a
-- continutation 'Builder' that the driver can call to fill the next
-- buffer. Here, we provide the two drivers that satisfy almost all use
-- cases. See "Data.ByteString.Builder.Extra", for information
-- about fine-tuning them.
, toLazyByteString
, hPutBuilder
-- * Creating Builders
-- ** Binary encodings
, byteString
, lazyByteString
, shortByteString
, int8
, word8
-- *** Big-endian
, int16BE
, int32BE
, int64BE
, word16BE
, word32BE
, word64BE
, floatBE
, doubleBE
-- *** Little-endian
, int16LE
, int32LE
, int64LE
, word16LE
, word32LE
, word64LE
, floatLE
, doubleLE
-- ** Character encodings
-- | Conversion from 'Char' and 'String' into 'Builder's in various encodings.
-- *** ASCII (Char7)
-- | The ASCII encoding is a 7-bit encoding. The /Char7/ encoding implemented here
-- works by truncating the Unicode codepoint to 7-bits, prefixing it
-- with a leading 0, and encoding the resulting 8-bits as a single byte.
-- For the codepoints 0-127 this corresponds the ASCII encoding.
, char7
, string7
-- *** ISO/IEC 8859-1 (Char8)
-- | The ISO/IEC 8859-1 encoding is an 8-bit encoding often known as Latin-1.
-- The /Char8/ encoding implemented here works by truncating the Unicode codepoint
-- to 8-bits and encoding them as a single byte. For the codepoints 0-255 this corresponds
-- to the ISO/IEC 8859-1 encoding.
, char8
, string8
-- *** UTF-8
-- | The UTF-8 encoding can encode /all/ Unicode codepoints. We recommend
-- using it always for encoding 'Char's and 'String's unless an application
-- really requires another encoding.
, charUtf8
, stringUtf8
, module Data.ByteString.Builder.ASCII
) where
import Data.ByteString.Builder.Internal
import qualified Data.ByteString.Builder.Prim as P
import qualified Data.ByteString.Lazy.Internal as L
import Data.ByteString.Builder.ASCII
import Data.String (IsString(..))
import System.IO (Handle)
import Foreign
-- HADDOCK only imports
import qualified Data.ByteString as S (concat)
import Data.Foldable (foldMap)
import Data.List (intersperse)
-- | Execute a 'Builder' and return the generated chunks as a lazy 'L.ByteString'.
-- The work is performed lazy, i.e., only when a chunk of the lazy 'L.ByteString'
-- is forced.
{-# NOINLINE toLazyByteString #-} -- ensure code is shared
toLazyByteString :: Builder -> L.ByteString
toLazyByteString = toLazyByteStringWith
(safeStrategy L.smallChunkSize L.defaultChunkSize) L.Empty
{- Not yet stable enough.
See note on 'hPut' in Data.ByteString.Builder.Internal
-}
-- | Output a 'Builder' to a 'Handle'.
-- The 'Builder' is executed directly on the buffer of the 'Handle'. If the
-- buffer is too small (or not present), then it is replaced with a large
-- enough buffer.
--
-- It is recommended that the 'Handle' is set to binary and
-- 'BlockBuffering' mode. See 'hSetBinaryMode' and 'hSetBuffering'.
--
-- This function is more efficient than @hPut . 'toLazyByteString'@ because in
-- many cases no buffer allocation has to be done. Moreover, the results of
-- several executions of short 'Builder's are concatenated in the 'Handle's
-- buffer, therefore avoiding unnecessary buffer flushes.
hPutBuilder :: Handle -> Builder -> IO ()
hPutBuilder h = hPut h . putBuilder
------------------------------------------------------------------------------
-- Binary encodings
------------------------------------------------------------------------------
-- | Encode a single signed byte as-is.
--
{-# INLINE int8 #-}
int8 :: Int8 -> Builder
int8 = P.primFixed P.int8
-- | Encode a single unsigned byte as-is.
--
{-# INLINE word8 #-}
word8 :: Word8 -> Builder
word8 = P.primFixed P.word8
------------------------------------------------------------------------------
-- Binary little-endian encodings
------------------------------------------------------------------------------
-- | Encode an 'Int16' in little endian format.
{-# INLINE int16LE #-}
int16LE :: Int16 -> Builder
int16LE = P.primFixed P.int16LE
-- | Encode an 'Int32' in little endian format.
{-# INLINE int32LE #-}
int32LE :: Int32 -> Builder
int32LE = P.primFixed P.int32LE
-- | Encode an 'Int64' in little endian format.
{-# INLINE int64LE #-}
int64LE :: Int64 -> Builder
int64LE = P.primFixed P.int64LE
-- | Encode a 'Word16' in little endian format.
{-# INLINE word16LE #-}
word16LE :: Word16 -> Builder
word16LE = P.primFixed P.word16LE
-- | Encode a 'Word32' in little endian format.
{-# INLINE word32LE #-}
word32LE :: Word32 -> Builder
word32LE = P.primFixed P.word32LE
-- | Encode a 'Word64' in little endian format.
{-# INLINE word64LE #-}
word64LE :: Word64 -> Builder
word64LE = P.primFixed P.word64LE
-- | Encode a 'Float' in little endian format.
{-# INLINE floatLE #-}
floatLE :: Float -> Builder
floatLE = P.primFixed P.floatLE
-- | Encode a 'Double' in little endian format.
{-# INLINE doubleLE #-}
doubleLE :: Double -> Builder
doubleLE = P.primFixed P.doubleLE
------------------------------------------------------------------------------
-- Binary big-endian encodings
------------------------------------------------------------------------------
-- | Encode an 'Int16' in big endian format.
{-# INLINE int16BE #-}
int16BE :: Int16 -> Builder
int16BE = P.primFixed P.int16BE
-- | Encode an 'Int32' in big endian format.
{-# INLINE int32BE #-}
int32BE :: Int32 -> Builder
int32BE = P.primFixed P.int32BE
-- | Encode an 'Int64' in big endian format.
{-# INLINE int64BE #-}
int64BE :: Int64 -> Builder
int64BE = P.primFixed P.int64BE
-- | Encode a 'Word16' in big endian format.
{-# INLINE word16BE #-}
word16BE :: Word16 -> Builder
word16BE = P.primFixed P.word16BE
-- | Encode a 'Word32' in big endian format.
{-# INLINE word32BE #-}
word32BE :: Word32 -> Builder
word32BE = P.primFixed P.word32BE
-- | Encode a 'Word64' in big endian format.
{-# INLINE word64BE #-}
word64BE :: Word64 -> Builder
word64BE = P.primFixed P.word64BE
-- | Encode a 'Float' in big endian format.
{-# INLINE floatBE #-}
floatBE :: Float -> Builder
floatBE = P.primFixed P.floatBE
-- | Encode a 'Double' in big endian format.
{-# INLINE doubleBE #-}
doubleBE :: Double -> Builder
doubleBE = P.primFixed P.doubleBE
------------------------------------------------------------------------------
-- ASCII encoding
------------------------------------------------------------------------------
-- | Char7 encode a 'Char'.
{-# INLINE char7 #-}
char7 :: Char -> Builder
char7 = P.primFixed P.char7
-- | Char7 encode a 'String'.
{-# INLINE string7 #-}
string7 :: String -> Builder
string7 = P.primMapListFixed P.char7
------------------------------------------------------------------------------
-- ISO/IEC 8859-1 encoding
------------------------------------------------------------------------------
-- | Char8 encode a 'Char'.
{-# INLINE char8 #-}
char8 :: Char -> Builder
char8 = P.primFixed P.char8
-- | Char8 encode a 'String'.
{-# INLINE string8 #-}
string8 :: String -> Builder
string8 = P.primMapListFixed P.char8
------------------------------------------------------------------------------
-- UTF-8 encoding
------------------------------------------------------------------------------
-- | UTF-8 encode a 'Char'.
{-# INLINE charUtf8 #-}
charUtf8 :: Char -> Builder
charUtf8 = P.primBounded P.charUtf8
-- | UTF-8 encode a 'String'.
{-# INLINE stringUtf8 #-}
stringUtf8 :: String -> Builder
stringUtf8 = P.primMapListBounded P.charUtf8
instance IsString Builder where
fromString = stringUtf8
| phischu/fragnix | tests/packages/scotty/Data.ByteString.Builder.hs | bsd-3-clause | 15,249 | 0 | 8 | 2,962 | 911 | 566 | 345 | 128 | 1 |
module HW1 where
--Data
------
type RealName = String
type UserName = String
type GroupName = String
type Message = String
data Post = Post UserName Message deriving (Show, Eq)
data To = UserID UserName | GroupID GroupName deriving (Show, Eq)
data User = User UserName RealName [UserName] [Post] deriving (Show, Eq)
data Group = Group GroupName [UserName] [Post] deriving (Show, Eq)
data DB = DB [User] [Group] deriving (Show, Eq)
--1. Commands
newUser :: DB -> User -> DB
addFriend :: DB -> UserName -> UserName -> DB
sendPost :: DB -> UserName -> Message -> [To] -> DB
newGroup :: DB -> GroupName -> DB
addMember :: DB -> GroupName -> UserName -> DB
removeMember :: DB -> GroupName -> UserName -> DB
--2. Queries
getFriendNames :: DB -> UserName -> [RealName]
getPosts :: DB -> To -> [Post]
listGroups :: DB -> UserName -> [Group]
suggestFriends :: DB -> User -> Int -> [User]
---- IMPLEMENTATIONS ----
exists [] id = False
exists (x:xs) id
| x==id = True
| otherwise = exists xs id
addToList lst elm
| (exists lst elm) = lst
| otherwise = elm:lst
dltFromList [] _ = []
dltFromList (cur:rest) elm
| cur==elm = rest
| otherwise = cur:(dltFromList rest elm)
userExists [] id = False
userExists ((User uname _ _ _):xs) id
| uname==id = True
| otherwise = userExists xs id
newUser (DB users groups) user@(User uname _ _ _)
| (userExists users uname)==False = DB (user:users) groups
| otherwise = DB users groups
addAsFriend [] _ _ = []
addAsFriend (user@(User uname rname friends posts):rest) us1 us2
| uname==us1= (User uname rname (addToList friends us2) posts):rest
| otherwise = user:(addAsFriend rest us1 us2)
addFriend (DB users groups) us1 us2 = (DB (addAsFriend
(addAsFriend users us1 us2) us2 us1) groups)
addPostU [] _ _ = []
addPostU (user@(User uname rname friends posts):rest) post rcv
| uname==rcv= (User uname rname friends (addToList posts post)):rest
| otherwise = user:(addPostU rest post rcv)
addPostM [] _ _ = []
addPostM (user@(User uname rname friends posts):rest) gusers post
| (exists gusers uname) = (User uname rname friends (addToList posts post)):
(addPostM rest gusers post)
| otherwise = user:(addPostM rest gusers post)
addPostG [] _ _ = []
addPostG (group@(Group gname gusers posts):rest) post rcv
| gname==rcv= (Group gname gusers (addToList posts post)):rest
| otherwise = group:(addPostG rest post rcv)
getMembers [] _ = []
getMembers ((Group gname gusers posts):rest) grp
| gname==grp= gusers
| otherwise = getMembers rest grp
sendPost db _ _ [] = db
sendPost (DB users groups) u1 msg (UserID to:tos) =
sendPost (DB (addPostU users (Post u1 msg) to) groups) u1 msg tos
sendPost (DB users groups) u1 msg (GroupID to:tos) =
sendPost (DB (addPostM users (getMembers groups to) pst) (addPostG groups pst to)) u1 msg tos
where pst = Post u1 msg
groupExists [] id = False
groupExists ((Group gname _ _):xs) id
| gname==id = True
| otherwise = groupExists xs id
newGroup db@(DB users groups) group
| (groupExists groups group) = db
| otherwise = DB users ((Group group [] []):groups)
addToGroup [] _ _ = []
addToGroup (cur@(Group gname gusers gposts):rest) group user
| gname==group = (Group gname (addToList gusers user) gposts):rest
| otherwise = cur:(addToGroup rest group user)
addMember (DB users groups) group user = (DB users (addToGroup groups group user))
removeFromGroup [] _ _ = []
removeFromGroup (cur@(Group gname gusers gposts):rest) group user
| gname==group = (Group gname (dltFromList gusers user) gposts):rest
| otherwise = cur:(removeFromGroup rest group user)
removeMember (DB users groups) group user = DB users (removeFromGroup groups group user)
getRealName [] _ = ""
getRealName ((User uname rname friends posts):rest) user
| uname==user = rname
| otherwise = getRealName rest user
getFriends [] _ = []
getFriends ((User uname _ friends _):rest) user
| uname==user = friends
| otherwise = getFriends rest user
getFriendNames (DB users groups) user
= [getRealName users x | x <- (getFriends users user)]
getPostU [] _ = []
getPostU ((User uname _ _ posts):rest) id
| uname==id = posts
| otherwise = getPostU rest id
getPostG [] _ = []
getPostG ((Group gname _ posts):rest) id
| gname==id = posts
| otherwise = getPostG rest id
getPosts (DB users groups) (UserID to) = getPostU users to
getPosts (DB users groups) (GroupID to) = getPostG groups to
listGroups (DB users groups) user
= filter (\(Group _ users _) -> exists users user) groups
intersect lst1 lst2 = [x | x<-lst1, exists lst2 x]
hasCommon lst1 lst2 lim = length (intersect lst1 lst2) >= lim
suggestFriends (DB users groups) (User uname _ uFriends _) lim
= filter (\(User x _ _ _) -> (not ((exists uFriends x) || uname==x)))
(filter (\(User _ _ friends _)->hasCommon uFriends friends lim) users)
| kadircet/CENG | 242/hw1/tester/benim.hs | gpl-3.0 | 4,849 | 102 | 14 | 934 | 2,454 | 1,229 | 1,225 | 111 | 1 |
{-# LANGUAGE BangPatterns,OverloadedStrings #-}
module Expr.Compile (
compileExpr,
getUnFun,
getOpFun ) where
import qualified MathOp as Math
import qualified TObj as T
import Expr.TExp
compileExpr fwr sc = comp
where comp e = case e of
Item (AStr s) -> CStrTok (sc s)
Item v -> CItem v
DepItem d -> DItem (updep d)
UnApp op v -> CApp op (comp v)
BinApp op a b -> CApp2 op (comp a) (comp b)
TernIf a b c -> CTern (comp a) (comp b) (comp c)
Paren e -> comp e
updep d = case d of
DFun f ex -> DFun f (map comp ex)
DCom cmd -> DCom (fwr cmd)
DVar vn -> DVar vn
getUnFun op = case op of
OpNot -> Math.opNot
OpNeg -> Math.opNegate
getOpFun !op = case op of
OpLt -> up Math.lessThan
OpPlus -> Math.plus
OpTimes -> Math.times
OpMinus -> Math.minus
OpDiv -> Math.divide
OpExp -> Math.pow
OpEql -> up Math.equals
OpNeql -> up Math.notEquals
OpGt -> up Math.greaterThan
OpLte -> up Math.lessThanEq
OpGte -> up Math.greaterThanEq
OpStrEq -> sup T.strEq
OpStrNe -> sup T.strNe
OpAnd -> cmdBool (&&)
OpOr -> cmdBool (||)
OpLShift -> Math.leftShift
OpRShift -> Math.rightShift
OpIn -> Math.opIn
where up f a b = return (f a b)
{-# INLINE up #-}
sup f a b = return (T.fromBool (f a b))
{-# INLINE getOpFun #-}
cmdBool f a b = do
ab <- T.asBool a
bb <- T.asBool b
return $! T.fromBool (ab `f` bb)
{-# INLINE cmdBool #-}
| muspellsson/hiccup | Expr/Compile.hs | lgpl-2.1 | 1,620 | 0 | 12 | 566 | 614 | 300 | 314 | 52 | 18 |
module Distribution.Client.Dependency.Modular
( modularResolver, SolverConfig(..)) where
-- Here, we try to map between the external cabal-install solver
-- interface and the internal interface that the solver actually
-- expects. There are a number of type conversions to perform: we
-- have to convert the package indices to the uniform index used
-- by the solver; we also have to convert the initial constraints;
-- and finally, we have to convert back the resulting install
-- plan.
import Data.Map as M
( fromListWith )
import Distribution.Client.Dependency.Modular.Assignment
( Assignment, toCPs )
import Distribution.Client.Dependency.Modular.Dependency
( RevDepMap )
import Distribution.Client.Dependency.Modular.ConfiguredConversion
( convCP )
import Distribution.Client.Dependency.Modular.IndexConversion
( convPIs )
import Distribution.Client.Dependency.Modular.Log
( logToProgress )
import Distribution.Client.Dependency.Modular.Package
( PN )
import Distribution.Client.Dependency.Modular.Solver
( SolverConfig(..), solve )
import Distribution.Client.Dependency.Types
( DependencyResolver, ResolverPackage
, PackageConstraint(..), unlabelPackageConstraint )
import Distribution.System
( Platform(..) )
-- | Ties the two worlds together: classic cabal-install vs. the modular
-- solver. Performs the necessary translations before and after.
modularResolver :: SolverConfig -> DependencyResolver
modularResolver sc (Platform arch os) cinfo iidx sidx pprefs pcs pns =
fmap (uncurry postprocess) $ -- convert install plan
logToProgress (maxBackjumps sc) $ -- convert log format into progress format
solve sc cinfo idx pprefs gcs pns
where
-- Indices have to be converted into solver-specific uniform index.
idx = convPIs os arch cinfo (shadowPkgs sc) (strongFlags sc) iidx sidx
-- Constraints have to be converted into a finite map indexed by PN.
gcs = M.fromListWith (++) (map pair pcs)
where
pair lpc = (pcName $ unlabelPackageConstraint lpc, [lpc])
-- Results have to be converted into an install plan.
postprocess :: Assignment -> RevDepMap -> [ResolverPackage]
postprocess a rdm = map (convCP iidx sidx) (toCPs a rdm)
-- Helper function to extract the PN from a constraint.
pcName :: PackageConstraint -> PN
pcName (PackageConstraintVersion pn _) = pn
pcName (PackageConstraintInstalled pn ) = pn
pcName (PackageConstraintSource pn ) = pn
pcName (PackageConstraintFlags pn _) = pn
pcName (PackageConstraintStanzas pn _) = pn
| randen/cabal | cabal-install/Distribution/Client/Dependency/Modular.hs | bsd-3-clause | 2,689 | 0 | 11 | 572 | 479 | 281 | 198 | 39 | 5 |
-- Functions for manipulating FilePaths
module PathUtils where
import System.Info(os)
-- Normalize file names:
normf ('.':x:s) | x==pathSep = normf s
normf s = s
pathSep = if os=="mingw32" then '\\' else '/'
| forste/haReFork | tools/base/lib/PathUtils.hs | bsd-3-clause | 211 | 0 | 8 | 36 | 73 | 40 | 33 | 5 | 2 |
-- Trac #1402
-- Broke the specialiser
module ShouldCompile where
newtype Gen a = MkGen{ unGen :: Int -> a }
choose :: Eq a => a -> Gen a
choose n = MkGen (\r -> n)
oneof = choose (1::Int)
| hferreiro/replay | testsuite/tests/simplCore/should_compile/spec003.hs | bsd-3-clause | 193 | 0 | 7 | 45 | 76 | 44 | 32 | 5 | 1 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE LambdaCase #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Database.Persist.Sql.Orphan.PersistQuery
( deleteWhereCount
, updateWhereCount
, decorateSQLWithLimitOffset
) where
import Control.Exception (throwIO)
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader (ReaderT, ask, withReaderT)
import Data.ByteString.Char8 (readInteger)
import Data.Conduit
import qualified Data.Conduit.List as CL
import Data.Int (Int64)
import Data.List (transpose, inits, find)
import Data.Maybe (isJust)
import Data.Monoid (Monoid (..), (<>))
import qualified Data.Text as T
import Data.Text (Text)
import Database.Persist hiding (updateField)
import Database.Persist.Sql.Util (
entityColumnNames, parseEntityValues, isIdField, updatePersistValue
, mkUpdateText, commaSeparated, dbIdColumns)
import Database.Persist.Sql.Types
import Database.Persist.Sql.Raw
import Database.Persist.Sql.Orphan.PersistStore (withRawQuery)
-- orphaned instance for convenience of modularity
instance PersistQueryRead SqlBackend where
count filts = do
conn <- ask
let wher = if null filts
then ""
else filterClause False conn filts
let sql = mconcat
[ "SELECT COUNT(*) FROM "
, connEscapeName conn $ entityDB t
, wher
]
withRawQuery sql (getFiltsValues conn filts) $ do
mm <- CL.head
case mm of
Just [PersistInt64 i] -> return $ fromIntegral i
Just [PersistDouble i] ->return $ fromIntegral (truncate i :: Int64) -- gb oracle
Just [PersistByteString i] -> case readInteger i of -- gb mssql
Just (ret,"") -> return $ fromIntegral ret
xs -> error $ "invalid number i["++show i++"] xs[" ++ show xs ++ "]"
Just xs -> error $ "count:invalid sql return xs["++show xs++"] sql["++show sql++"]"
Nothing -> error $ "count:invalid sql returned nothing sql["++show sql++"]"
where
t = entityDef $ dummyFromFilts filts
selectSourceRes filts opts = do
conn <- ask
srcRes <- rawQueryRes (sql conn) (getFiltsValues conn filts)
return $ fmap (.| CL.mapM parse) srcRes
where
(limit, offset, orders) = limitOffsetOrder opts
parse vals = case parseEntityValues t vals of
Left s -> liftIO $ throwIO $ PersistMarshalError s
Right row -> return row
t = entityDef $ dummyFromFilts filts
wher conn = if null filts
then ""
else filterClause False conn filts
ord conn =
case map (orderClause False conn) orders of
[] -> ""
ords -> " ORDER BY " <> T.intercalate "," ords
cols = commaSeparated . entityColumnNames t
sql conn = connLimitOffset conn (limit,offset) (not (null orders)) $ mconcat
[ "SELECT "
, cols conn
, " FROM "
, connEscapeName conn $ entityDB t
, wher conn
, ord conn
]
selectKeysRes filts opts = do
conn <- ask
srcRes <- rawQueryRes (sql conn) (getFiltsValues conn filts)
return $ fmap (.| CL.mapM parse) srcRes
where
t = entityDef $ dummyFromFilts filts
cols conn = T.intercalate "," $ dbIdColumns conn t
wher conn = if null filts
then ""
else filterClause False conn filts
sql conn = connLimitOffset conn (limit,offset) (not (null orders)) $ mconcat
[ "SELECT "
, cols conn
, " FROM "
, connEscapeName conn $ entityDB t
, wher conn
, ord conn
]
(limit, offset, orders) = limitOffsetOrder opts
ord conn =
case map (orderClause False conn) orders of
[] -> ""
ords -> " ORDER BY " <> T.intercalate "," ords
parse xs = do
keyvals <- case entityPrimary t of
Nothing ->
case xs of
[PersistInt64 x] -> return [PersistInt64 x]
[PersistDouble x] -> return [PersistInt64 (truncate x)] -- oracle returns Double
_ -> return xs
Just pdef ->
let pks = map fieldHaskell $ compositeFields pdef
keyvals = map snd $ filter (\(a, _) -> let ret=isJust (find (== a) pks) in ret) $ zip (map fieldHaskell $ entityFields t) xs
in return keyvals
case keyFromValues keyvals of
Right k -> return k
Left err -> error $ "selectKeysImpl: keyFromValues failed" <> show err
instance PersistQueryRead SqlReadBackend where
count filts = withReaderT persistBackend $ count filts
selectSourceRes filts opts = withReaderT persistBackend $ selectSourceRes filts opts
selectKeysRes filts opts = withReaderT persistBackend $ selectKeysRes filts opts
instance PersistQueryRead SqlWriteBackend where
count filts = withReaderT persistBackend $ count filts
selectSourceRes filts opts = withReaderT persistBackend $ selectSourceRes filts opts
selectKeysRes filts opts = withReaderT persistBackend $ selectKeysRes filts opts
instance PersistQueryWrite SqlBackend where
deleteWhere filts = do
_ <- deleteWhereCount filts
return ()
updateWhere filts upds = do
_ <- updateWhereCount filts upds
return ()
instance PersistQueryWrite SqlWriteBackend where
deleteWhere filts = withReaderT persistBackend $ deleteWhere filts
updateWhere filts upds = withReaderT persistBackend $ updateWhere filts upds
-- | Same as 'deleteWhere', but returns the number of rows affected.
--
-- @since 1.1.5
deleteWhereCount :: (PersistEntity val, MonadIO m, PersistEntityBackend val ~ SqlBackend, BackendCompatible SqlBackend backend)
=> [Filter val]
-> ReaderT backend m Int64
deleteWhereCount filts = withReaderT projectBackend $ do
conn <- ask
let t = entityDef $ dummyFromFilts filts
let wher = if null filts
then ""
else filterClause False conn filts
sql = mconcat
[ "DELETE FROM "
, connEscapeName conn $ entityDB t
, wher
]
rawExecuteCount sql $ getFiltsValues conn filts
-- | Same as 'updateWhere', but returns the number of rows affected.
--
-- @since 1.1.5
updateWhereCount :: (PersistEntity val, MonadIO m, SqlBackend ~ PersistEntityBackend val, BackendCompatible SqlBackend backend)
=> [Filter val]
-> [Update val]
-> ReaderT backend m Int64
updateWhereCount _ [] = return 0
updateWhereCount filts upds = withReaderT projectBackend $ do
conn <- ask
let wher = if null filts
then ""
else filterClause False conn filts
let sql = mconcat
[ "UPDATE "
, connEscapeName conn $ entityDB t
, " SET "
, T.intercalate "," $ map (mkUpdateText conn) upds
, wher
]
let dat = map updatePersistValue upds `Data.Monoid.mappend`
getFiltsValues conn filts
rawExecuteCount sql dat
where
t = entityDef $ dummyFromFilts filts
fieldName :: forall record typ. (PersistEntity record, PersistEntityBackend record ~ SqlBackend) => EntityField record typ -> DBName
fieldName f = fieldDB $ persistFieldDef f
dummyFromFilts :: [Filter v] -> Maybe v
dummyFromFilts _ = Nothing
getFiltsValues :: forall val. (PersistEntity val, PersistEntityBackend val ~ SqlBackend)
=> SqlBackend -> [Filter val] -> [PersistValue]
getFiltsValues conn = snd . filterClauseHelper False False conn OrNullNo
data OrNull = OrNullYes | OrNullNo
filterClauseHelper :: (PersistEntity val, PersistEntityBackend val ~ SqlBackend)
=> Bool -- ^ include table name?
-> Bool -- ^ include WHERE?
-> SqlBackend
-> OrNull
-> [Filter val]
-> (Text, [PersistValue])
filterClauseHelper includeTable includeWhere conn orNull filters =
(if not (T.null sql) && includeWhere
then " WHERE " <> sql
else sql, vals)
where
(sql, vals) = combineAND filters
combineAND = combine " AND "
combine s fs =
(T.intercalate s $ map wrapP a, mconcat b)
where
(a, b) = unzip $ map go fs
wrapP x = T.concat ["(", x, ")"]
go (BackendFilter _) = error "BackendFilter not expected"
go (FilterAnd []) = ("1=1", [])
go (FilterAnd fs) = combineAND fs
go (FilterOr []) = ("1=0", [])
go (FilterOr fs) = combine " OR " fs
go (Filter field value pfilter) =
let t = entityDef $ dummyFromFilts [Filter field value pfilter]
in case (isIdField field, entityPrimary t, allVals) of
(True, Just pdef, PersistList ys:_) ->
if length (compositeFields pdef) /= length ys
then error $ "wrong number of entries in compositeFields vs PersistList allVals=" ++ show allVals
else
case (allVals, pfilter, isCompFilter pfilter) of
([PersistList xs], Eq, _) ->
let sqlcl=T.intercalate " and " (map (\a -> connEscapeName conn (fieldDB a) <> showSqlFilter pfilter <> "? ") (compositeFields pdef))
in (wrapSql sqlcl,xs)
([PersistList xs], Ne, _) ->
let sqlcl=T.intercalate " or " (map (\a -> connEscapeName conn (fieldDB a) <> showSqlFilter pfilter <> "? ") (compositeFields pdef))
in (wrapSql sqlcl,xs)
(_, In, _) ->
let xxs = transpose (map fromPersistList allVals)
sqls=map (\(a,xs) -> connEscapeName conn (fieldDB a) <> showSqlFilter pfilter <> "(" <> T.intercalate "," (replicate (length xs) " ?") <> ") ") (zip (compositeFields pdef) xxs)
in (wrapSql (T.intercalate " and " (map wrapSql sqls)), concat xxs)
(_, NotIn, _) ->
let xxs = transpose (map fromPersistList allVals)
sqls=map (\(a,xs) -> connEscapeName conn (fieldDB a) <> showSqlFilter pfilter <> "(" <> T.intercalate "," (replicate (length xs) " ?") <> ") ") (zip (compositeFields pdef) xxs)
in (wrapSql (T.intercalate " or " (map wrapSql sqls)), concat xxs)
([PersistList xs], _, True) ->
let zs = tail (inits (compositeFields pdef))
sql1 = map (\b -> wrapSql (T.intercalate " and " (map (\(i,a) -> sql2 (i==length b) a) (zip [1..] b)))) zs
sql2 islast a = connEscapeName conn (fieldDB a) <> (if islast then showSqlFilter pfilter else showSqlFilter Eq) <> "? "
sqlcl = T.intercalate " or " sql1
in (wrapSql sqlcl, concat (tail (inits xs)))
(_, BackendSpecificFilter _, _) -> error "unhandled type BackendSpecificFilter for composite/non id primary keys"
_ -> error $ "unhandled type/filter for composite/non id primary keys pfilter=" ++ show pfilter ++ " persistList="++show allVals
(True, Just pdef, []) ->
error $ "empty list given as filter value filter=" ++ show pfilter ++ " persistList=" ++ show allVals ++ " pdef=" ++ show pdef
(True, Just pdef, _) ->
error $ "unhandled error for composite/non id primary keys filter=" ++ show pfilter ++ " persistList=" ++ show allVals ++ " pdef=" ++ show pdef
_ -> case (isNull, pfilter, length notNullVals) of
(True, Eq, _) -> (name <> " IS NULL", [])
(True, Ne, _) -> (name <> " IS NOT NULL", [])
(False, Ne, _) -> (T.concat
[ "("
, name
, " IS NULL OR "
, name
, " <> "
, qmarks
, ")"
], notNullVals)
-- We use 1=2 (and below 1=1) to avoid using TRUE and FALSE, since
-- not all databases support those words directly.
(_, In, 0) -> ("1=2" <> orNullSuffix, [])
(False, In, _) -> (name <> " IN " <> qmarks <> orNullSuffix, allVals)
(True, In, _) -> (T.concat
[ "("
, name
, " IS NULL OR "
, name
, " IN "
, qmarks
, ")"
], notNullVals)
(False, NotIn, 0) -> ("1=1", [])
(True, NotIn, 0) -> (name <> " IS NOT NULL", [])
(False, NotIn, _) -> (T.concat
[ "("
, name
, " IS NULL OR "
, name
, " NOT IN "
, qmarks
, ")"
], notNullVals)
(True, NotIn, _) -> (T.concat
[ "("
, name
, " IS NOT NULL AND "
, name
, " NOT IN "
, qmarks
, ")"
], notNullVals)
_ -> (name <> showSqlFilter pfilter <> "?" <> orNullSuffix, allVals)
where
isCompFilter Lt = True
isCompFilter Le = True
isCompFilter Gt = True
isCompFilter Ge = True
isCompFilter _ = False
wrapSql sqlcl = "(" <> sqlcl <> ")"
fromPersistList (PersistList xs) = xs
fromPersistList other = error $ "expected PersistList but found " ++ show other
filterValueToPersistValues :: forall a. PersistField a => FilterValue a -> [PersistValue]
filterValueToPersistValues = \case
FilterValue a -> [toPersistValue a]
FilterValues as -> toPersistValue <$> as
UnsafeValue x -> [toPersistValue x]
orNullSuffix =
case orNull of
OrNullYes -> mconcat [" OR ", name, " IS NULL"]
OrNullNo -> ""
isNull = PersistNull `elem` allVals
notNullVals = filter (/= PersistNull) allVals
allVals = filterValueToPersistValues value
tn = connEscapeName conn $ entityDB
$ entityDef $ dummyFromFilts [Filter field value pfilter]
name =
(if includeTable
then ((tn <> ".") <>)
else id)
$ connEscapeName conn $ fieldName field
qmarks = case value of
FilterValue{} -> "?"
UnsafeValue{} -> "?"
FilterValues xs ->
let parens a = "(" <> a <> ")"
commas = T.intercalate ","
toQs = fmap $ const "?"
nonNulls = filter (/= PersistNull) $ map toPersistValue xs
in parens . commas . toQs $ nonNulls
showSqlFilter Eq = "="
showSqlFilter Ne = "<>"
showSqlFilter Gt = ">"
showSqlFilter Lt = "<"
showSqlFilter Ge = ">="
showSqlFilter Le = "<="
showSqlFilter In = " IN "
showSqlFilter NotIn = " NOT IN "
showSqlFilter (BackendSpecificFilter s) = s
filterClause :: (PersistEntity val, PersistEntityBackend val ~ SqlBackend)
=> Bool -- ^ include table name?
-> SqlBackend
-> [Filter val]
-> Text
filterClause b c = fst . filterClauseHelper b True c OrNullNo
orderClause :: (PersistEntity val, PersistEntityBackend val ~ SqlBackend)
=> Bool -- ^ include the table name
-> SqlBackend
-> SelectOpt val
-> Text
orderClause includeTable conn o =
case o of
Asc x -> name x
Desc x -> name x <> " DESC"
_ -> error "orderClause: expected Asc or Desc, not limit or offset"
where
dummyFromOrder :: SelectOpt a -> Maybe a
dummyFromOrder _ = Nothing
tn = connEscapeName conn $ entityDB $ entityDef $ dummyFromOrder o
name :: (PersistEntityBackend record ~ SqlBackend, PersistEntity record)
=> EntityField record typ -> Text
name x =
(if includeTable
then ((tn <> ".") <>)
else id)
$ connEscapeName conn $ fieldName x
-- | Generates sql for limit and offset for postgres, sqlite and mysql.
decorateSQLWithLimitOffset::Text -> (Int,Int) -> Bool -> Text -> Text
decorateSQLWithLimitOffset nolimit (limit,offset) _ sql =
let
lim = case (limit, offset) of
(0, 0) -> ""
(0, _) -> T.cons ' ' nolimit
(_, _) -> " LIMIT " <> T.pack (show limit)
off = if offset == 0
then ""
else " OFFSET " <> T.pack (show offset)
in mconcat
[ sql
, lim
, off
]
| creichert/persistent | persistent/Database/Persist/Sql/Orphan/PersistQuery.hs | mit | 18,119 | 0 | 33 | 7,082 | 4,860 | 2,497 | 2,363 | -1 | -1 |
module Http.Uri
( UriParts (..)
, Login (..)
, uriParts )
where
import Text.ParserCombinators.Parsec
import Data.List
-- A URI parser
--
-- Based on http://www.w3.org/Addressing/URL/5_URI_BNF.html
data UriParts = UriParts
{ scheme :: String
, host :: String
, port :: Int
, login :: Maybe Login
, path :: String
} deriving (Show)
data Login = Login { user :: String
, password :: String
} deriving (Show)
uriDefaults :: UriParts
uriDefaults = UriParts { scheme = "http"
, host = ""
, port = 80
, login = Nothing
, path = "/"
}
uriParts :: String -> UriParts
uriParts uri = case parse parseURI "URL" uri of
Left err -> error $ "Parse error at " ++ show err
Right res -> res
reserved = oneOf ";/?:@&="
safe = oneOf "$-_.+"
extra = oneOf "!*'(),"
unreserved = alphaNum <|> safe <|> extra
escape = do char '%'; count 2 hexDigit
loginChars = many1 (unreserved <|> oneOf ";?&=") <|> escape
parseURI :: Parser UriParts
parseURI = do scheme <- parseScheme
login <- option (login uriDefaults) (try parseLogin)
host <- parseHost
port <- option (port uriDefaults) parsePort
path <- option (path uriDefaults) parsePath
return uriDefaults { scheme = scheme
, login = login
, path = path
, host = host
, port = port }
parseScheme :: Parser String
parseScheme = do init <- letter
rest <- many $ letter <|> digit <|> oneOf "+-."
string "://"
return $ init : rest
parsePassword :: Parser [String]
parsePassword = do char ':'
many loginChars
parseLogin :: Parser (Maybe Login)
parseLogin = do user <- many loginChars
pass <- option [] parsePassword
char '@'
return $ Just Login { user = concat user
, password = concat pass }
parseHost :: Parser String
parseHost = parseHostname <|> parseHostnumber
parseHostnumber :: Parser String
parseHostnumber = do p1 <- many1 digit
p2 <- char '.' >> many1 digit
p3 <- char '.' >> many1 digit
p4 <- char '.' >> many1 digit
return $ intercalate "." [p1,p2,p3,p4]
parseHostname :: Parser String
parseHostname = many1 (letter <|> oneOf ".-")
parsePort :: Parser Int
parsePort = do char ':'
port <- many1 digit
return (read port :: Int)
parsePath :: Parser String
parsePath = do char '/'
path <- many $ many1 (unreserved <|> reserved) <|> escape
eof
return $ '/' : concat path
| ndreynolds/hsURL | src/Http/Uri.hs | mit | 2,956 | 0 | 12 | 1,152 | 831 | 422 | 409 | 76 | 2 |
module SpaceState.Combat(startCombat)
where
import System.Random
import Data.List
import Data.Maybe
import Control.Monad
import Control.Monad.State as State
import Prelude hiding (catch)
import Graphics.Rendering.OpenGL as OpenGL
import Graphics.UI.SDL as SDL
import qualified Data.Edison.Assoc.StandardMap as M
import Combat
import Space
import Cargo
import TextScreen
import Politics
import SDLUtils
import Universe
import SpaceState.Common
import SpaceState.Game
import SpaceState.Init
import SpaceState.Difficulty
startCombat :: Maybe (String, Enemy, String) -- ^ If Nothing, use random enemy
-- and standard message. Otherwise
-- use given (msg, enemy, enemy allegiance).
-> StateT SpaceState IO (Bool, Bool) -- ^ (gameOver?, combatWon?)
startCombat n = do
state <- State.get
(s, en, enalleg) <- case n of
Nothing -> do
en' <- liftIO $ randomEnemy $ difficultyAIshift $ difficulty state
enalleg' <- liftIO $ randomAllegiance
s' <- return $
concat ["You spot another ship traveling nearby.\n",
"It seems to be a " ++ (describeEnemy en') ++ ".\n",
"The ship is part of the country of " ++ enalleg' ++ ".\n",
"Press ENTER to start a battle against the foreign ship\n",
"or ESCAPE to escape"]
return (s', en', enalleg')
Just m -> return m
c <- pressOneOfScreen
(liftIO $ makeTextScreen (100, 400)
[(gamefont state, Color4 1.0 1.0 1.0 1.0, s)]
(return ()))
[SDLK_RETURN, SDLK_ESCAPE]
if c == SDLK_RETURN
then do
enemyrot <- liftIO $ fromIntegral `fmap` randomRIO (-180, 180 :: Int)
enpos <- liftIO $ randPos ((0, 0), (50, 100))
plpos <- liftIO $ randPos ((100, 0), (150, 100))
let plrot = angleFromTo plpos enpos - 90
(newhealth, newpoints, mnewcargo) <- liftIO $ evalStateT combatLoop
(newCombat plalleg enalleg intermediate (plhealth state) plpos enpos plrot enemyrot en)
if newhealth == 0
then do
releaseKeys
gameover <- lostLife "You fought bravely, but your ship was blown to pieces." recoveryText
return (gameover, False)
else do
modify $ modPlHealth $ const newhealth
case mnewcargo of
Nothing -> do
liftIO $ makeTextScreen (100, 400) [(gamefont state, Color4 1.0 1.0 1.0 1.0, "The enemy is out of your sight.\n\n"),
(gamefont state, Color4 1.0 1.0 1.0 1.0, "Press ENTER to continue")] (return ())
liftIO $ getSpecificSDLChar SDLK_RETURN
releaseKeys
return (False, False)
Just newcargo -> do
when (not (M.null newcargo)) $ do
modify $ modPoints (+(newpoints * (diffcoeff $ difficulty state)))
(_, cargo', _, hold') <- liftIO $ execStateT
(takeScreen ("Captured cargo")
(gamefont state) (monofont state))
(newcargo, plcargo state, plcash state, plholdspace state)
modify $ modPlCargo (const cargo')
modify $ modPlHoldspace (const hold')
killed enalleg
releaseKeys
return (False, True)
else do
releaseKeys
return (False, False)
internationalAction :: String -> Int -> StateT SpaceState IO ()
internationalAction s f = modify $ modAllegAttitudes $ consequences f s allegiances relations
killed :: String -> StateT SpaceState IO ()
killed enalleg = internationalAction enalleg (-1)
| anttisalonen/starrover2 | src/SpaceState/Combat.hs | mit | 4,007 | 0 | 28 | 1,461 | 1,019 | 535 | 484 | 83 | 5 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Control.Applicative
import Test.Hspec
import Test.SmallCheck
import Test.SmallCheck.Series
import Test.Hspec.SmallCheck
import Data.Monoid ((<>))
import Data.Function
import Data.List
import Data.Aeson
import Data.Text (Text)
import Data.Text as T
import Data.SemVer
import Data.UUID
import GHC.Word
import Data.AppContainer.Types
instance Monad m => Serial m Word32 where
series = decDepth $ fromIntegral <$> (series :: Series m Int)
instance Monad m => Serial m UUID where
series = decDepth $ fromWords
<$> series
<*> series
<*> series
<*> series
instance Monad m => Serial m Text where
series = decDepth $ T.pack
<$> series
instance Monad m => Serial m Version where
series = decDepth $ version
<$> fmap getPositive series
<*> fmap getPositive series
<*> fmap getPositive series
<*> pure []
<*> pure []
instance Monad m => Serial m Label where
series = decDepth $ Label
<$> series <*> series
instance Monad m => Serial m ImageManifest where
series = decDepth $ ImageManifest
<$> series <*> series <*> series <*> pure Nothing <*> pure []
instance Monad m => Serial m ContainerRuntimeManifest where
series = decDepth $ ContainerRuntimeManifest
<$> series
<*> series
<*> pure []
<*> pure []
main :: IO ()
main = do
hspec spec
spec :: Spec
spec = do
describe "ImageManifest" $ do
it "x ≡ fromJSON (toJSON x)" $ property $ \(im :: ImageManifest) ->
Success im == fromJSON (toJSON im)
describe "ContainerRuntimeManifest" $ do
it "x ≡ fromJSON (toJSON x)" $ property $ \(im :: ContainerRuntimeManifest) ->
Success im == fromJSON (toJSON im)
| wereHamster/haskell-appc | test/Test.hs | mit | 2,177 | 0 | 15 | 666 | 563 | 290 | 273 | 63 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.Conduit.Process.Unix
( -- * Process tracking
-- $processTracker
-- ** Types
ProcessTracker
-- ** Functions
, initProcessTracker
-- * Monitored process
, MonitoredProcess
, monitorProcess
, terminateMonitoredProcess
, printStatus
) where
import Data.Text(Text, pack)
import Control.Applicative ((<$>), (<*>), pure)
import Control.Arrow ((***))
import Control.Concurrent (forkIO)
import Control.Concurrent (threadDelay)
import Control.Concurrent.MVar (MVar, modifyMVar, modifyMVar_,
newEmptyMVar, newMVar,
putMVar, readMVar, swapMVar,
takeMVar, tryReadMVar)
import Control.Exception (Exception, SomeException,
bracketOnError, finally,
handle, mask_,
throwIO, try)
import Control.Monad (void)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S8
import Data.Conduit (ConduitM, (.|), runConduit)
import Data.Conduit.Binary (sinkHandle, sourceHandle)
import qualified Data.Conduit.List as CL
import Data.IORef (IORef, newIORef, readIORef,
writeIORef)
import Data.Time (getCurrentTime)
import Data.Time (diffUTCTime)
import Data.Typeable (Typeable)
import Foreign.C.Types
import Prelude (Bool (..), Either (..), IO,
Maybe (..), Monad (..), Show,
const, error,
map, maybe, show,
($), ($!), (*), (<),
(==))
import System.Exit (ExitCode)
import System.IO (hClose)
import System.Posix.IO.ByteString ( closeFd, createPipe,
fdToHandle)
import System.Posix.Signals (sigKILL, signalProcess)
import System.Posix.Types (CPid (..))
import System.Process (CmdSpec (..), CreateProcess (..),
StdStream (..), createProcess,
terminateProcess, waitForProcess,
getPid)
import System.Process.Internals (ProcessHandle (..),
ProcessHandle__ (..))
import Data.Monoid ((<>)) -- sauron
processHandleMVar :: ProcessHandle -> MVar ProcessHandle__
#if MIN_VERSION_process(1, 6, 0)
processHandleMVar (ProcessHandle m _ _) = m
#elif MIN_VERSION_process(1, 2, 0)
processHandleMVar (ProcessHandle m _) = m
#else
processHandleMVar (ProcessHandle m) = m
#endif
withProcessHandle_
:: ProcessHandle
-> (ProcessHandle__ -> IO ProcessHandle__)
-> IO ()
withProcessHandle_ ph io = modifyMVar_ (processHandleMVar ph) io
-- | Kill a process by sending it the KILL (9) signal.
--
-- Since 0.1.0
killProcess :: ProcessHandle -> IO ()
killProcess ph = withProcessHandle_ ph $ \p_ ->
case p_ of
ClosedHandle _ -> return p_
OpenHandle h -> do
signalProcess sigKILL h
return p_
ignoreExceptions :: IO () -> IO ()
ignoreExceptions = handle (\(_ :: SomeException) -> return ())
-- $processTracker
--
-- Ensure that child processes are killed, regardless of how the parent process exits.
--
-- The technique used here is:
--
-- * Create a pipe.
--
-- * Fork a new child process that listens on the pipe.
--
-- * In the current process, send updates about processes that should be auto-killed.
--
-- * When the parent process dies, listening on the pipe in the child process will get an EOF.
--
-- * When the child process receives that EOF, it kills all processes it was told to auto-kill.
--
-- This code was originally written for Keter, but was moved to unix-process
-- conduit in the 0.2.1 release.
foreign import ccall unsafe "launch_process_tracker"
c_launch_process_tracker :: IO CInt
foreign import ccall unsafe "track_process"
c_track_process :: ProcessTracker -> CPid -> CInt -> IO ()
-- | Represents the child process which handles process cleanup.
--
-- Since 0.2.1
newtype ProcessTracker = ProcessTracker CInt
-- | Represents a child process which is currently being tracked by the cleanup
-- child process.
--
-- Since 0.2.1
data TrackedProcess = TrackedProcess !ProcessTracker !(IORef MaybePid) !(IO ExitCode)
data MaybePid = NoPid | Pid !CPid
-- | Fork off the child cleanup process.
--
-- This will ideally only be run once for your entire application.
--
-- Since 0.2.1
initProcessTracker :: IO ProcessTracker
initProcessTracker = do
i <- c_launch_process_tracker
if i == -1
then throwIO CannotLaunchProcessTracker
else return $! ProcessTracker i
-- | Since 0.2.1
data ProcessTrackerException = CannotLaunchProcessTracker
deriving (Show, Typeable)
instance Exception ProcessTrackerException
-- | Begin tracking the given process. If the 'ProcessHandle' refers to a
-- closed process, no tracking will occur. If the process is closed, then it
-- will be untracked automatically.
--
-- Note that you /must/ compile your program with @-threaded@; see
-- 'waitForProcess'.
--
-- Since 0.2.1
trackProcess :: ProcessTracker -> ProcessHandle -> IO TrackedProcess
trackProcess pt ph = mask_ $ do
mpid <- readMVar $ processHandleMVar ph
mpid' <- case mpid of
ClosedHandle{} -> return NoPid
OpenHandle pid -> do
c_track_process pt pid 1
return $ Pid pid
ipid <- newIORef mpid'
baton <- newEmptyMVar
let tp = TrackedProcess pt ipid (takeMVar baton)
case mpid' of
NoPid -> return ()
Pid _ -> void $ forkIO $ do
waitForProcess ph >>= putMVar baton
untrackProcess tp
return $! tp
-- | Explicitly remove the given process from the tracked process list in the
-- cleanup process.
--
-- Since 0.2.1
untrackProcess :: TrackedProcess -> IO ()
untrackProcess (TrackedProcess pt ipid _) = mask_ $ do
mpid <- readIORef ipid
case mpid of
NoPid -> return ()
Pid pid -> do
c_track_process pt pid 0
writeIORef ipid NoPid
-- | Fork and execute a subprocess, sending stdout and stderr to the specified
-- rotating log.
--
-- Since 0.2.1
forkExecuteLog :: ByteString -- ^ command
-> [ByteString] -- ^ args
-> Maybe [(ByteString, ByteString)] -- ^ environment
-> Maybe ByteString -- ^ working directory
-> Maybe (ConduitM () ByteString IO ()) -- ^ stdin
-> (ByteString -> IO ()) -- ^ both stdout and stderr will be sent to this location
-> IO ProcessHandle
forkExecuteLog cmd args menv mwdir mstdin rlog = bracketOnError
setupPipe
cleanupPipes
usePipes
where
setupPipe = bracketOnError
createPipe
(\(x, y) -> closeFd x `finally` closeFd y)
(\(x, y) -> (,) <$> fdToHandle x <*> fdToHandle y)
cleanupPipes (x, y) = hClose x `finally` hClose y
usePipes pipes@(readerH, writerH) = do
(min, _, _, ph) <- createProcess CreateProcess
{ cmdspec = RawCommand (S8.unpack cmd) (map S8.unpack args)
, cwd = S8.unpack <$> mwdir
, env = map (S8.unpack *** S8.unpack) <$> menv
, std_in = maybe Inherit (const CreatePipe) mstdin
, std_out = UseHandle writerH
, std_err = UseHandle writerH
, close_fds = True
, create_group = True
#if MIN_VERSION_process(1, 5, 0)
, use_process_jobs = False
#endif
#if MIN_VERSION_process(1, 2, 0)
, delegate_ctlc = False
#endif
#if MIN_VERSION_process(1, 3, 0)
, detach_console = True
, create_new_console = False
, new_session = True
#endif
#if MIN_VERSION_process(1, 4, 0)
, child_group = Nothing
, child_user = Nothing
#endif
}
ignoreExceptions $ addAttachMessage pipes ph
void $ forkIO $ ignoreExceptions $
(runConduit $ sourceHandle readerH .| CL.mapM_ rlog) `finally` hClose readerH
case (min, mstdin) of
(Just h, Just source) -> void $ forkIO $ ignoreExceptions $
(runConduit $ source .| sinkHandle h) `finally` hClose h
(Nothing, Nothing) -> return ()
_ -> error $ "Invariant violated: Data.Conduit.Process.Unix.forkExecuteLog"
return ph
addAttachMessage pipes ph = withProcessHandle_ ph $ \p_ -> do
now <- getCurrentTime
case p_ of
ClosedHandle ec -> do
rlog $ S8.concat
[ "\n\n"
, S8.pack $ show now
, ": Process immediately died with exit code "
, S8.pack $ show ec
, "\n\n"
]
cleanupPipes pipes
OpenHandle h -> do
rlog $ S8.concat
[ "\n\n"
, S8.pack $ show now
, ": Attached new process "
, S8.pack $ show h
, "\n\n"
]
return p_
data Status = NeedsRestart | NoRestart | Running ProcessHandle
-- | Run the given command, restarting if the process dies.
monitorProcess
:: (ByteString -> IO ()) -- ^ log
-> ProcessTracker
-> Maybe S8.ByteString -- ^ setuid
-> S8.ByteString -- ^ executable
-> S8.ByteString -- ^ working directory
-> [S8.ByteString] -- ^ command line parameter
-> [(S8.ByteString, S8.ByteString)] -- ^ environment
-> (ByteString -> IO ())
-> (ExitCode -> IO Bool) -- ^ should we restart?
-> IO MonitoredProcess
monitorProcess log processTracker msetuid exec dir args env' rlog shouldRestart = do
mstatus <- newMVar NeedsRestart
let loop mlast = do
next <- modifyMVar mstatus $ \status ->
case status of
NoRestart -> return (NoRestart, return ())
_ -> do
now <- getCurrentTime
case mlast of
Just last | diffUTCTime now last < 5 -> do
log $ "Process restarting too quickly, waiting before trying again: " `S8.append` exec
threadDelay $ 5 * 1000 * 1000
_ -> return ()
let (cmd, args') =
case msetuid of
Nothing -> (exec, args)
Just setuid -> ("sudo", "-E" : "-u" : setuid : "--" : exec : args)
res <- try $ forkExecuteLog
cmd
args'
(Just env')
(Just dir)
(Just $ return ())
rlog
case res of
Left e -> do
log $ "Data.Conduit.Process.Unix.monitorProcess: " `S8.append` S8.pack (show (e :: SomeException))
return (NeedsRestart, return ())
Right pid -> do
log $ "Process created: " `S8.append` exec
return (Running pid, do
TrackedProcess _ _ wait <- trackProcess processTracker pid
ec <- wait
shouldRestart' <- shouldRestart ec
if shouldRestart'
then loop (Just now)
else return ())
next
_ <- forkIO $ loop Nothing
return $ MonitoredProcess mstatus
-- | Abstract type containing information on a process which will be restarted.
newtype MonitoredProcess = MonitoredProcess (MVar Status)
printStatus :: MonitoredProcess -> IO Text
printStatus (MonitoredProcess mstatus) = do
mStatus <- tryReadMVar mstatus
case mStatus of
Nothing -> pure "no status set process"
Just NeedsRestart -> pure "needs-restart process"
Just NoRestart -> pure "no-restart process"
Just (Running running) -> do
x <- getPid running
case x of
Just y -> pure ("running process '" <> pack (show y) <> "'")
Nothing -> pure "just closed process"
-- | Terminate the process and prevent it from being restarted.
terminateMonitoredProcess :: MonitoredProcess -> IO ()
terminateMonitoredProcess (MonitoredProcess mstatus) = do
status <- swapMVar mstatus NoRestart
case status of
Running pid -> do
terminateProcess pid
threadDelay 1000000
killProcess pid
_ -> return ()
| snoyberg/keter | Data/Conduit/Process/Unix.hs | mit | 13,893 | 2 | 32 | 5,316 | 2,810 | 1,509 | 1,301 | 250 | 6 |
import Data.List
import Test.QuickCheck
import Control.Monad
import Data.Bits
import Data.Word
data Msg =
MsgFixArray [Msg]
| MsgArray16 [Msg]
| MsgArray32 [Msg]
| MsgFixMap [(Msg, Msg)]
| MsgMap16 [(Msg, Msg)]
| MsgMap32 [(Msg, Msg)]
| MsgNil
| MsgTrue
| MsgFalse
| MsgPFixNum Int
| MsgNFixNum Int
| MsgUInt8 Int
| MsgUInt16 Int
| MsgUInt32 Int
| MsgUInt64 Word
| MsgInt8 Int
| MsgInt16 Int
| MsgInt32 Int
| MsgInt64 Int
| MsgFloat32 Float
| MsgFloat64 Double
| MsgFixStr String
| MsgStr8 String
| MsgStr16 String
| MsgStr32 String
| MsgBin8 [Int]
| MsgBin16 [Int]
| MsgBin32 [Int]
| MsgFixExt1 Int [Int]
| MsgFixExt2 Int [Int]
| MsgFixExt4 Int [Int]
| MsgFixExt8 Int [Int]
| MsgFixExt16 Int [Int]
| MsgExt8 Int [Int]
| MsgExt16 Int [Int]
| MsgExt32 Int [Int]
binShow :: [Int] -> String
binShow xs = intercalate "," $ map (\x -> "cast[byte](" ++ show x ++ ")") xs
arrayShow :: [Msg] -> String
arrayShow xs = intercalate "," $ map msgShow xs
mapShow :: [(Msg, Msg)] -> String
mapShow xs = intercalate "," $ map (\(k, v) -> "(" ++ msgShow k ++ "," ++ msgShow v ++ ")") xs
msgShow :: Msg -> String
msgShow (MsgFixArray xs) = "FixArray(@[" ++ arrayShow xs ++ "])"
msgShow (MsgArray16 xs) = "Array16(@[" ++ arrayShow xs ++ "])"
msgShow (MsgArray32 xs) = "Array32(@[" ++ arrayShow xs ++ "])"
msgShow (MsgFixMap xs) = "FixMap(@[" ++ mapShow xs ++ "])"
msgShow (MsgMap16 xs) = "Map16(@[" ++ mapShow xs ++ "])"
msgShow (MsgMap32 xs) = "Map32(@[" ++ mapShow xs ++ "])"
msgShow MsgNil = "Nil"
msgShow MsgTrue = "True"
msgShow MsgFalse = "False"
msgShow (MsgPFixNum n) = "PFixNum(" ++ show n ++ "'u8)"
msgShow (MsgNFixNum n) = "NFixNum(" ++ show n ++ "'i8)"
msgShow (MsgUInt8 n) = "UInt8(" ++ show n ++ "'u8)"
msgShow (MsgUInt16 n) = "UInt16(" ++ show n ++ "'u16)"
msgShow (MsgUInt32 n) = "UInt32(" ++ show n ++ "'u32)"
msgShow (MsgUInt64 n) = "UInt64(" ++ show n ++ "'u64)"
msgShow (MsgInt8 n) = "Int8(" ++ show n ++ "'i8)"
msgShow (MsgInt16 n) = "Int16(" ++ show n ++ "'i16)"
msgShow (MsgInt32 n) = "Int32(" ++ show n ++ "'i32)"
msgShow (MsgInt64 n) = "Int64(" ++ show n ++ "'i64)"
msgShow (MsgFloat32 n) = "Float32(" ++ show n ++ ")"
msgShow (MsgFloat64 n) = "Float64(" ++ show n ++ ")"
msgShow (MsgFixStr s) = "FixStr(" ++ show s ++ ")"
msgShow (MsgStr8 s) = "Str8(" ++ show s ++ ")"
msgShow (MsgStr16 s) = "Str16(" ++ show s ++ ")"
msgShow (MsgStr32 s) = "Str32(" ++ show s ++ ")"
msgShow (MsgBin8 xs) = "Bin8(@[" ++ binShow xs ++ "])"
msgShow (MsgBin16 xs) = "Bin16(@[" ++ binShow xs ++ "])"
msgShow (MsgBin32 xs) = "Bin32(@[" ++ binShow xs ++ "])"
msgShow (MsgFixExt1 t xs) = "FixExt1((" ++ show t ++ "'i8" ++ ", @[" ++ binShow xs ++ "]))"
msgShow (MsgFixExt2 t xs) = "FixExt2((" ++ show t ++ "'i8" ++ ", @[" ++ binShow xs ++ "]))"
msgShow (MsgFixExt4 t xs) = "FixExt4((" ++ show t ++ "'i8" ++ ", @[" ++ binShow xs ++ "]))"
msgShow (MsgFixExt8 t xs) = "FixExt8((" ++ show t ++ "'i8" ++ ", @[" ++ binShow xs ++ "]))"
msgShow (MsgFixExt16 t xs) = "FixExt16((" ++ show t ++ "'i8" ++ ", @[" ++ binShow xs ++ "]))"
msgShow (MsgExt8 t xs) = "Ext8((" ++ show t ++ "'i8" ++ ", @[" ++ binShow xs ++ "]))"
msgShow (MsgExt16 t xs) = "Ext16((" ++ show t ++ "'i8" ++ ", @[" ++ binShow xs ++ "]))"
msgShow (MsgExt32 t xs) = "Ext32((" ++ show t ++ "'i8" ++ ", @[" ++ binShow xs ++ "]))"
instance Show Msg where
show = msgShow
randStr :: Int -> Gen String
randStr n = sequence [choose ('a', 'Z') | _ <- [1..n]]
randBinSeq :: Int -> Gen [Int]
randBinSeq n = sequence [choose (0, 255) | _ <- [1..n]]
randMsg :: Int -> Gen [Msg]
randMsg n = sequence [arbitrary | _ <- [1..n]]
randMap :: Int -> Gen [(Msg, Msg)]
randMap n = do
xs <- randMsg n
ys <- randMsg n
return $ zip xs ys
-- array weight
aw = 1
-- map weight
mw = 1
-- value weight
vw = 2
-- max signed
maxS n = (1 `shiftL` (n - 1)) - 1
-- max unsigned
maxUS n = (1 `shiftL` n) - 1
-- type is a signed 8-bit signed integer
-- type < 0 is reserved for future extension including 2-byte type information
extType :: Gen Int
extType = choose (0, 127)
instance Arbitrary Msg where
arbitrary = do
frequency [
(aw, liftM MsgFixArray $ choose (1, 7) >>= randMsg)
, (aw, liftM MsgArray16 $ choose (1, 10) >>= randMsg)
, (aw, liftM MsgArray32 $ choose (1, 10) >>= randMsg)
, (mw, liftM MsgFixMap $ choose (1, 5) >>= randMap)
, (mw, liftM MsgMap16 $ choose (1, 10) >>= randMap)
, (mw, liftM MsgMap32 $ choose (1, 10) >>= randMap)
, (vw, return MsgNil)
, (vw, return MsgTrue)
, (vw, return MsgFalse)
, (vw, liftM MsgPFixNum $ choose (0, 63))
, (vw, liftM MsgNFixNum $ choose (-32, -1))
, (vw, liftM MsgUInt8 $ choose (0, maxUS 8))
, (vw, liftM MsgUInt16 $ choose (0, maxUS 16))
, (vw, liftM MsgUInt32 $ choose (0, maxUS 32))
, (vw, liftM MsgUInt64 $ choose (0, maxUS 63))
, (vw, liftM MsgInt8 $ choose (-127, 127))
, (vw, liftM MsgInt16 $ choose (-127, 127))
, (vw, liftM MsgInt32 $ choose (-127, 127))
, (vw, liftM MsgInt64 $ choose (-127, 127))
, (vw, liftM MsgFloat32 $ arbitrary)
, (vw, liftM MsgFloat64 $ arbitrary)
, (vw, liftM MsgFixStr $ choose (0, 31) >>= randStr)
, (vw, liftM MsgStr8 $ choose (0, 31) >>= randStr)
, (vw, liftM MsgStr16 $ choose (0, 31) >>= randStr)
, (vw, liftM MsgStr32 $ choose (0, 31) >>= randStr)
, (vw, liftM MsgBin8 $ choose (0, 10) >>= randBinSeq)
, (vw, liftM MsgBin16 $ choose (0, 10) >>= randBinSeq)
, (vw, liftM MsgBin32 $ choose (0, 10) >>= randBinSeq)
, (vw, liftM2 MsgFixExt1 extType $ randBinSeq 1)
, (vw, liftM2 MsgFixExt2 extType $ randBinSeq 2)
, (vw, liftM2 MsgFixExt4 extType $ randBinSeq 4)
, (vw, liftM2 MsgFixExt8 extType $ randBinSeq 8)
, (vw, liftM2 MsgFixExt16 extType $ randBinSeq 16)
, (vw, liftM2 MsgExt8 extType $ choose (0, 10) >>= randBinSeq)
, (vw, liftM2 MsgExt16 extType $ choose (0, 10) >>= randBinSeq)
, (vw, liftM2 MsgExt32 extType $ choose (0, 10) >>= randBinSeq)
]
main = do
msges <- sequence $ [generate (arbitrary :: Gen Msg) | _ <- [1..1000]] :: IO [Msg]
forM_ msges (\msg -> print $ msg)
| akiradeveloper/msgpack-nim | GenTests/app/Main.hs | mit | 6,222 | 0 | 14 | 1,450 | 2,757 | 1,450 | 1,307 | 147 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Test.Hspec.SmallCheck (property) where
import Prelude ()
import Test.Hspec.SmallCheck.Compat
import Data.IORef
import Test.Hspec.Core.Spec
import Test.SmallCheck
import Test.SmallCheck.Drivers
import qualified Test.HUnit.Lang as HUnit
import Control.Exception (try)
import Data.Maybe
import Data.CallStack
import qualified Test.Hspec.SmallCheck.Types as T
property :: Testable IO a => a -> Property IO
property = test
srcLocToLocation :: SrcLoc -> Location
srcLocToLocation loc = Location {
locationFile = srcLocFile loc
, locationLine = srcLocStartLine loc
, locationColumn = srcLocStartCol loc
}
instance Testable IO (IO ()) where
test action = monadic $ do
r <- try action
return $ case r of
Right () -> test True
Left e -> case e of
HUnit.HUnitFailure loc reason -> test . failure $ case reason of
HUnit.Reason s -> T.Reason s
HUnit.ExpectedButGot prefix expected actual -> T.ExpectedActual (fromMaybe "" prefix) expected actual
where
failure :: T.Reason -> Either String String
failure = Left . show . T.Failure (srcLocToLocation <$> loc)
instance Example (Property IO) where
type Arg (Property IO) = ()
evaluateExample p c _ reportProgress = do
counter <- newIORef 0
let hook _ = do
modifyIORef counter succ
n <- readIORef counter
reportProgress (n, 0)
r <- smallCheckWithHook (paramsSmallCheckDepth c) hook p
return . Result "" $ case r of
Just e -> case T.parseResult (ppFailure e) of
(m, Just (T.Failure loc reason)) -> Failure loc $ case reason of
T.Reason err -> Reason (fromMaybe "" $ T.concatPrefix m err)
T.ExpectedActual prefix expected actual -> ExpectedButGot (T.concatPrefix m prefix) expected actual
(m, Nothing) -> Failure Nothing (Reason m)
Nothing -> Success
| hspec/hspec-smallcheck | src/Test/Hspec/SmallCheck.hs | mit | 2,145 | 0 | 23 | 553 | 645 | 329 | 316 | 51 | 1 |
module Main where
import Control.Monad.Reader
import Control.Monad.Except
import Control.Exception (try)
import Data.List
import Data.Time
import System.Directory
import System.FilePath
import System.Environment
import System.Console.GetOpt
import System.Console.Haskeline
import System.Console.Haskeline.History
import Text.Printf
import Exp.Lex
import Exp.Par
import Exp.Print
import Exp.Abs hiding (NoArg)
import Exp.Layout
import Exp.ErrM
import CTT
import Resolver
import qualified TypeChecker as TC
import qualified Eval as E
type Interpreter a = InputT IO a
-- Flag handling
data Flag = Debug | Help | Version | Time
deriving (Eq,Show)
options :: [OptDescr Flag]
options = [ Option "d" ["debug"] (NoArg Debug) "run in debugging mode"
, Option "" ["help"] (NoArg Help) "print help"
, Option "-t" ["time"] (NoArg Time) "measure time spent computing"
, Option "" ["version"] (NoArg Version) "print version number" ]
-- Version number, welcome message, usage and prompt strings
version, welcome, usage, prompt :: String
version = "1.0"
welcome = "cubical, version: " ++ version ++ " (:h for help)\n"
usage = "Usage: cubical [options] <file.ctt>\nOptions:"
prompt = "> "
lexer :: String -> [Token]
lexer = resolveLayout True . myLexer
showTree :: (Show a, Print a) => a -> IO ()
showTree tree = do
putStrLn $ "\n[Abstract Syntax]\n\n" ++ show tree
putStrLn $ "\n[Linearized tree]\n\n" ++ printTree tree
-- Used for auto completion
searchFunc :: [String] -> String -> [Completion]
searchFunc ns str = map simpleCompletion $ filter (str `isPrefixOf`) ns
settings :: [String] -> Settings IO
settings ns = Settings
{ historyFile = Nothing
, complete = completeWord Nothing " \t" $ return . searchFunc ns
, autoAddHistory = True }
main :: IO ()
main = do
args <- getArgs
case getOpt Permute options args of
(flags,files,[])
| Help `elem` flags -> putStrLn $ usageInfo usage options
| Version `elem` flags -> putStrLn version
| otherwise -> case files of
[] -> do
putStrLn welcome
runInputT (settings []) (loop flags [] [] TC.verboseEnv)
[f] -> do
putStrLn welcome
putStrLn $ "Loading " ++ show f
initLoop flags f emptyHistory
_ -> putStrLn $ "Input error: zero or one file expected\n\n" ++
usageInfo usage options
(_,_,errs) -> putStrLn $ "Input error: " ++ concat errs ++ "\n" ++
usageInfo usage options
-- Initialize the main loop
initLoop :: [Flag] -> FilePath -> History -> IO ()
initLoop flags f hist = do
-- Parse and type check files
(_,_,mods) <- imports True ([],[],[]) f
-- Translate to TT
let res = runResolver $ resolveModules mods
case res of
Left err -> do
putStrLn $ "Resolver failed: " ++ err
runInputT (settings []) (putHistory hist >> loop flags f [] TC.verboseEnv)
Right (adefs,names) -> do
(merr,tenv) <- TC.runDeclss TC.verboseEnv adefs
case merr of
Just err -> putStrLn $ "Type checking failed: " ++ err
Nothing -> putStrLn "File loaded."
-- Compute names for auto completion
runInputT (settings [n | (n,_) <- names]) (putHistory hist >> loop flags f names tenv)
-- The main loop
loop :: [Flag] -> FilePath -> [(CTT.Ident,SymKind)] -> TC.TEnv -> Interpreter ()
loop flags f names tenv = do
input <- getInputLine prompt
case input of
Nothing -> outputStrLn help >> loop flags f names tenv
Just ":q" -> return ()
Just ":r" -> getHistory >>= lift . initLoop flags f
Just (':':'l':' ':str)
| ' ' `elem` str -> do outputStrLn "Only one file allowed after :l"
loop flags f names tenv
| otherwise -> getHistory >>= lift . initLoop flags str
Just (':':'c':'d':' ':str) -> do lift (setCurrentDirectory str)
loop flags f names tenv
Just ":h" -> outputStrLn help >> loop flags f names tenv
Just str' ->
let (msg,str,mod) = case str' of
(':':'n':' ':str) ->
("NORMEVAL: ",str,E.normal [])
str -> ("EVAL: ",str,id)
in case pExp (lexer str) of
Bad err -> outputStrLn ("Parse error: " ++ err) >> loop flags f names tenv
Ok exp ->
case runResolver $ local (insertIdents names) $ resolveExp exp of
Left err -> do outputStrLn ("Resolver failed: " ++ err)
loop flags f names tenv
Right body -> do
x <- liftIO $ TC.runInfer tenv body
case x of
Left err -> do outputStrLn ("Could not type-check: " ++ err)
loop flags f names tenv
Right _ -> do
start <- liftIO getCurrentTime
let e = mod $ E.eval (TC.env tenv) body
-- Let's not crash if the evaluation raises an error:
liftIO $ catch (putStrLn (msg ++ show e))
(\e -> putStrLn ("Exception: " ++
show (e :: SomeException)))
stop <- liftIO getCurrentTime
-- Compute time and print nicely
let time = diffUTCTime stop start
secs = read (takeWhile (/='.') (init (show time)))
rest = read ('0':dropWhile (/='.') (init (show time)))
mins = secs `quot` 60
sec = printf "%.3f" (fromInteger (secs `rem` 60) + rest :: Float)
when (Time `elem` flags) $
outputStrLn $ "Time: " ++ show mins ++ "m" ++ sec ++ "s"
-- Only print in seconds:
-- when (Time `elem` flags) $ outputStrLn $ "Time: " ++ show time
loop flags f names tenv
-- (not ok,loaded,already loaded defs) -> to load ->
-- (new not ok, new loaded, new defs)
-- the bool determines if it should be verbose or not
imports :: Bool -> ([String],[String],[Module]) -> String ->
IO ([String],[String],[Module])
imports v st@(notok,loaded,mods) f
| f `elem` notok = putStrLn ("Looping imports in " ++ f) >> return ([],[],[])
| f `elem` loaded = return st
| otherwise = do
b <- doesFileExist f
let prefix = dropFileName f
if not b
then putStrLn (f ++ " does not exist") >> return ([],[],[])
else do
s <- readFile f
let ts = lexer s
case pModule ts of
Bad s -> do
putStrLn $ "Parse failed in " ++ show f ++ "\n" ++ show s
return ([],[],[])
Ok mod@(Module (AIdent (_,name)) imp decls) ->
let imp_ctt = [prefix ++ i ++ ".ctt" | Import (AIdent (_,i)) <- imp]
in do
when (name /= dropExtension (takeFileName f)) $
error $ "Module name mismatch " ++ show (f,name)
(notok1,loaded1,mods1) <-
foldM (imports v) (f:notok,loaded,mods) imp_ctt
when v $ putStrLn $ "Parsed " ++ show f ++ " successfully!"
return (notok,f:loaded1,mods1 ++ [mod])
help :: String
help = "\nAvailable commands:\n" ++
" <statement> infer type and evaluate statement\n" ++
" :n <statement> normalize statement\n" ++
" :q quit\n" ++
" :l <filename> loads filename (and resets environment before)\n" ++
" :cd <path> change directory to path\n" ++
" :r reload\n" ++
" :h display this message\n"
| DanGrayson/cubicaltt | Main.hs | mit | 7,583 | 0 | 35 | 2,400 | 2,444 | 1,250 | 1,194 | 162 | 11 |
module Network.Gazelle.Routes (
module Network.Gazelle.Routes.Artist,
module Network.Gazelle.Routes.Index,
module Network.Gazelle.Routes.Search,
module Network.Gazelle.Routes.Torrent
) where
import Network.Gazelle.Routes.Artist
import Network.Gazelle.Routes.Index
import Network.Gazelle.Routes.Search
import Network.Gazelle.Routes.Torrent
| mr/gazelle | src/Network/Gazelle/Routes.hs | mit | 356 | 0 | 5 | 38 | 69 | 50 | 19 | 9 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Data.Validator.I18n.Message where
import Data.Text (Text)
import qualified Data.Text as T
-- TODO Должно предоставить пользователю возможность добавлять свои сообщения
data ValidationMessage = MsgWhitespacesOnly
| MsgValueRequired
| MsgWrongEmail
deriving (Show, Eq)
russianValidationMessage :: ValidationMessage -> Text
russianValidationMessage MsgWhitespacesOnly =
"Значение не может состоять только из пробелов"
russianValidationMessage MsgValueRequired = "Эти данные необходимы"
russianValidationMessage MsgWrongEmail = "Неверный адрес эл.почты"
englishValidationMessage :: ValidationMessage -> Text
englishValidationMessage MsgWhitespacesOnly =
"Whitespace only value is not allowed"
englishValidationMessage MsgValueRequired = "This value is required"
englishValidationMessage MsgWrongEmail = "Wrong email address"
defaultValidationMessage :: ValidationMessage -> Text
defaultValidationMessage = englishValidationMessage
-------------------------------------------------------------------------------- | geraldus/DataValidation | src/Data/Validator/I18n/Message.hs | mit | 1,295 | 0 | 6 | 202 | 133 | 77 | 56 | 20 | 1 |
module Components where
import Sound.Pulse.Simple
import Signals
import Data.List
import qualified Data.Vector.Generic as V
import qualified Sound.File.Sndfile as SF
import qualified Sound.File.Sndfile.Buffer.Vector as BV
import qualified Control.Concurrent as CC
import Sound.File.Sndfile
type BasicOscillator = FrequencySignal -> AmplitudeSignal -> (Maybe PWMSignal) -> Signal
--------------------------------------
-- Raw Signal Generation Components
--------------------------------------
data SamplingRate = SamplingRate Integer
data Samples = Samples Integer
data Progression = Progression Float
data Slope = Slope Float
getSlope (Progression p) (SignalValue sv) = Slope $ (sv / p)
signalValueFromSlope (Progression p) (Slope s) = SignalValue $ p * s
data Cycle a = Cycle a
data Frequency = Frequency SafeValue
data Amplitude = Amplitude SafeValue
cycleFunc func (Cycle val_a ) (Cycle val_b ) = Cycle $ func val_a val_b
getProgression (Samples s) (SamplingRate sr) = Progression $ ((fromIntegral s) / (fromIntegral sr))
getNumSamples (Progression p) (SamplingRate sr) = Samples $ floor $ p * fromIntegral sr
fromCycleProgression (Cycle (Progression cp)) (Frequency f) = Progression (cp / f)
toCycleProgression (Progression tp) (Frequency f) = Cycle $ Progression (tp * f)
fromCycleSignalValue (Cycle (SignalValue sv)) (Amplitude a) = SignalValue (sv * a)
type BasicFunction = Cycle Progression -> Cycle Progression -> Cycle SignalValue
class Addable a where
(-:) :: a -> a -> a
(+:) :: a -> a -> a
instance Addable Progression where
(-:) (Progression a) (Progression b) = Progression (a - b)
(+:) (Progression a) (Progression b) = Progression (a + b)
instance Addable SignalValue where
(-:) (SignalValue a) (SignalValue b) = SignalValue (a - b)
(+:) (SignalValue a) (SignalValue b) = SignalValue (a + b)
instance (Addable a) => Addable (Cycle a) where
(-:) (Cycle a) (Cycle b) = Cycle (a -: b)
(+:) (Cycle a) (Cycle b) = Cycle (a +: b)
instance Eq Progression where
(==) (Progression a) (Progression b) = a == b
instance (Eq a) => Eq (Cycle a) where
(==) (Cycle a) (Cycle b) = a == b
instance Ord Progression where
compare (Progression a) (Progression b) = compare a b
instance (Ord a) => Ord (Cycle a) where
compare (Cycle a) (Cycle b) = compare a b
samplesPerCycle = Cycle $ SamplingRate 100000
oscillator :: BasicFunction -> BasicOscillator
oscillator basicFunc fSig aSig Nothing = oscillator basicFunc fSig aSig (Just $ specialize $ flatSignal 0.5)
oscillator basicFunc fSig aSig (Just pSig) = Signal $ oscillator_ fVals aVals pVals (Cycle (Progression 0)) where
fVals = sanitize fSig
aVals = sanitize aSig
pVals = sanitize pSig
oscillator_ :: [SafeValue] -> [SafeValue] -> [SafeValue] -> Cycle Progression -> [SignalValue]
oscillator_ fVals aVals pVals t | t >= (Cycle $ Progression 1) = oscillator_ fVals aVals pVals $ t -: (Cycle $ Progression 1)
| otherwise = (fromCycleSignalValue basicFunc_ (Amplitude aVal)): oscillatorRest
where
fVal:fRest = fVals
aVal:aRest = aVals
pVal:pRest = pVals
basicFunc_ = basicFunc (Cycle (Progression pVal)) t
oscillatorRest = oscillator_ fRest aRest pRest (t +: cycleProgressionDelta)
progressionDelta = getProgression (Samples 1) (SamplingRate samplesPerSecond)
-- Part of starting to incorporate the dubious Units.hs
-- Undoing this for now, maybe forever.
-- progressionDelta = __ 1 /: __ samplesPerSecond
cycleProgressionDelta = toCycleProgression progressionDelta (Frequency fVal)
osc_square = oscillator basicFunc where
basicFunc pw t | t < pw = Cycle $ SignalValue 1
| otherwise = Cycle $ SignalValue (-1)
osc_triangle = oscillator basicFunc where
basicFunc pw t | t < pw = (cycleFunc signalValueFromSlope t upslope) -: (Cycle $ SignalValue 1 )
| otherwise = (cycleFunc signalValueFromSlope (t -: pw) downslope) +: (Cycle $ SignalValue 1 )
where
upslope = cycleFunc getSlope pw (Cycle $ SignalValue 2)
downslope = cycleFunc getSlope ((Cycle $ Progression 1) -: pw) (Cycle $ SignalValue (-2) )
osc_sawtooth :: BasicOscillator
osc_sawtooth fSig aSig _ = osc_triangle fSig aSig $ Just (specialize $ flatSignal 1)
osc_sine = oscillator basicFunc where
basicFunc _ (Cycle (Progression t)) = Cycle $ SignalValue $ sin (2 * pi * t)
--------------------------------------
-- Basic Signal Manipulation Components
--------------------------------------
sig_adder :: [Signal] -> Signal
sig_adder insignals = toSignal outvalues where
invalues = map fromSignal insignals
-- transpose will automatically shrink the resultant lists as signals end. and sum of an empty list is safely zero
-- in other words, any signals that go through sig_adder, we don't need to worry about them ending. saves a lot of headache.
outvalues = map sum $ transpose invalues
sig_sequence :: [([Signal], Progression)] -> Signal
sig_sequence sequenceData = sig_sequence' sequenceData [flatSignal 0] where
sig_sequence' :: [([Signal], Progression)] -> [Signal] -> Signal
sig_sequence' [] existingSignals = sig_adder existingSignals
sig_sequence' ((newSignals, startingDelay):nextSeq) existingSignals = catSignals [beforeNewSignals, afterNewSignals] where
beforeNewSignals = (takeSeconds startingSeconds $ sig_adder existingSignals)
afterNewSignals = sig_sequence' nextSeq ( remainingOldSignals ++ newSignals ) where
remainingOldSignals = clearEmptySignals $ map (dropSeconds startingSeconds) existingSignals
Progression startingSeconds = startingDelay
envelope :: ([(SafeValue, Float)] -> Float -> SafeValue) -> [(SafeValue, Float)] -> Signal
envelope envFunc points = toSignal $ envelope_ points 0 where
envelope_ points t | t < (len * samplesPerSecond) = (envFunc points t): envelope_ points (t + 1)
| otherwise = envelope_ (tail points ) 0
where
(val, len):(next_val, _):_ = points
slideEnvelope = envelope func where
func points t = (val + (t * slope))
where
(val, len):(next_val, _):_ = points
slope = (next_val - val) / (len * samplesPerSecond)
stepEnvelope = envelope func where
func points _ = val
where
(val, len):_ = points
--------------------------------------
-- Sequencing Components
--------------------------------------
--------------------------------------
-- Sound Output Components
--------------------------------------
-- Mixer Output
buffersize = 1000
initPulse = simpleNew Nothing "example" Play Nothing "this is an example application" (SampleSpec (F32 LittleEndian) 44100 1) Nothing Nothing
outputSound s [] = do
return ()
outputSound s signal = do
let buffer = take buffersize signal
let rest = drop buffersize signal
CC.forkIO ( simpleWrite s buffer ) >> do
outputSound s rest
playRealtime :: SoundSignal -> IO ()
playRealtime soundSignal = do
s<-initPulse
outputSound s (sanitize soundSignal)
simpleDrain s
simpleFree s
play :: SoundSignal -> IO ()
play signal = do
s<-initPulse
simpleWrite s $ sanitize signal
simpleDrain s
simpleFree s
-- File Output
fileinfo = Info {frames = 1000, samplerate = 44100, channels = 1, seekable = False, format=Format {headerFormat =SF.HeaderFormatWav, sampleFormat = SF.SampleFormatPcm16, endianFormat = SF.EndianLittle }, sections = 1 }
writeSound :: SoundSignal -> FilePath -> IO ()
writeSound signal outPath = do
SF.writeFile fileinfo outPath $ BV.toBuffer $ V.fromList $ sanitize signal
return ()
| orblivion/Haskell-Synth | Components.hs | mit | 7,830 | 0 | 14 | 1,690 | 2,504 | 1,300 | 1,204 | 126 | 2 |
import Drawing
import Geometry
import Geometry.Utils(projection,Triangle(..))
main = drawPicture myPicture
myPicture points =
coordinates' 2
& drawPointsLabels [a,b,c,o] ["A","B","C","O"]
& drawSegment (a,b)
& drawSegment (b,c)
& drawSegment (c,a)
& red (drawSegment (o,c))
& drawCircle ((0,0),(0,1))
& messages [ "Triangle"
, "with base=" ++ shownum (dist a b)
, "and height=" ++ shownum (dist o c)
]
where
Triangle a b c = withHeight 4 . withBase 5 . fromPoints . take 3 $ points
o = projection (a,b) c
| alphalambda/k12math | contrib/MHills/GeometryLessons/code/student/lesson6c.hs | mit | 615 | 0 | 13 | 189 | 261 | 140 | 121 | 17 | 1 |
{-# LANGUAGE ConstraintKinds #-}
module Storyteller.Builder
( Builder(..)
, inline
, block
, build
) where
import Control.Applicative
import Control.Monad.State ( StateT )
import Control.Monad.IO.Class ( MonadIO )
import Data.List ( intercalate )
import Storyteller.Definition
type Base m = (Applicative m, Functor m, Monad m, MonadIO m)
class Builder b where
new :: b
string :: Base m => String -> StateT b m ()
string = const $ pure ()
control :: Base m => Control -> StateT b m ()
control = const $ pure ()
formatter :: Base m => Formatter -> [Inline] -> StateT b m ()
formatter = const $ const $ pure ()
operator :: Base m => Operator -> [[Inline]] -> StateT b m ()
operator = const $ const $ pure ()
directive :: Base m => Directive -> [Inline] -> [Block] -> StateT b m ()
directive = const $ const $ const $ pure ()
paragraph :: Base m => [Inline] -> StateT b m ()
paragraph = const $ pure ()
inline :: (Builder b, Base m) => Inline -> StateT b m ()
inline (Str str) = string str
inline (Fmt f xs) = formatter f xs
inline (Opr o xs) = operator o xs
inline (Dir d xs ys) = directive d xs ys
block :: (Builder b, Base m) => Block -> StateT b m ()
block (Ctl c) = control c
block (Par p) = mapM_ inline p
build :: (Builder b, Base m) => File -> StateT b m ()
build = mapM_ block . paragraphs
| Soares/Storyteller.hs | src/Storyteller/Builder.hs | mit | 1,355 | 0 | 12 | 322 | 628 | 324 | 304 | 36 | 1 |
module Archive ( extract
, build
, identify
, ArchiveType(..)
) where
import Archive.Extract
import Archive.Build
import Archive.Identify
import Archive.Types
| imuli/pack | src/Archive.hs | cc0-1.0 | 206 | 0 | 5 | 67 | 42 | 27 | 15 | 8 | 0 |
{-# LANGUAGE CPP #-}
-- | Debug facilities. Are only enabled with -DDEBUG
module Ssh.Debug (
debugRawStringData
, logTraceMessage
, logTraceMessageShow
, logTraceMessageAndShow
, printDebug
, printDebugLifted
, LogLevel(..)
, logLowLevelDebug
, logDebugExtended
, logDebug
, logWarning
) where
import Numeric
import Data.Char
import Data.List
import Data.List.Split
import Debug.Trace
import Ssh.String
import qualified Control.Monad.State as MS
import qualified Data.ByteString.Lazy as B
type LogLevel = Int
logLowLevelDebug, logDebug, logDebugExtended, logWarning :: LogLevel
logLowLevelDebug = 200 -- ^ For Very Low Level Debug Output
logDebugExtended = 150 -- ^ Somewhat extended debug output (i.e. also print out received/sent packets)
logDebug = 100 -- ^ Regular Debug Output
logWarning = 10 -- ^ Warnings
-- | The debug level that is currently in use. Log values <= 'debugLevel' will be logged. Use -DDEBUGLEVEL to set your own
debugLevel :: Int
-- | IO action that takes a log level and a log message. The message will get printed if the log level <= 'debugLevel'
printDebug :: LogLevel -> String -> IO ()
#ifdef DEBUG
#ifndef DEBUGLEVEL
debugLevel = logDebug
#else
debugLevel = DEBUGLEVEL
#endif
printDebug ll | ll <= debugLevel = putStrLn
| otherwise = \_ -> return ()
#else
debugLevel = logWarning
printDebug _ _ = return ()
#endif
-- | Variant of 'printDebug' that has been lifted with 'MS.liftIO'
printDebugLifted ll s = MS.liftIO $ printDebug ll s
-- logLevelRequired, currentLogLevel
printLogMessage :: LogLevel -> String -> b -> b
printLogMessage ll a b | ll <= debugLevel = trace a b
| otherwise = b
logTraceMessage' :: LogLevel -> String -> a -> a
logTraceMessage' = printLogMessage
-- | Similar to 'Debug.Trace.Show'
logTraceMessageShow :: (Show a) => LogLevel -> a -> b -> b
logTraceMessageShow ll a b = logTraceMessage' ll (show a) b
-- | Similar to 'Debug.Trace.Show'
logTraceMessage :: (Show a) => LogLevel -> String -> a -> a
logTraceMessage ll s a = logTraceMessage' ll s a
-- | Similar to 'Debug.Trace.Show'
logTraceMessageAndShow l a b = logTraceMessageAndShow l (a ++ show b) b
convertToHexString [] = []
convertToHexString (c:cs) | c < 16 = "0" ++ (showIntAtBase 16 intToDigit c "") ++ convertToHexString cs
| otherwise = (showIntAtBase 16 intToDigit c "") ++ convertToHexString cs
-- | Convert a string to a format similar to OpenSSH's dumping of buffers
debugRawStringData s = concat . concat . map ((++ ["\n"]) . intersperse " ") $ splitEvery 8 $ splitEvery 4 $ convertToHexString $ B.unpack s
| bcoppens/HaskellSshClient | src/Ssh/Debug.hs | gpl-3.0 | 2,709 | 0 | 14 | 591 | 586 | 322 | 264 | 46 | 1 |
{-|
Module : Database.KeyValue.LogOperations
Description : Operations on data and hint logs
Stability : Experimental
-}
module Database.KeyValue.LogOperations( hintExt
, recordExt
, getKeyAndValueLocs
, addNewRecord
, getKeysFromHintFiles
, putKeysFromRecordFiles
) where
import Control.Monad
import qualified Data.ByteString as B
import qualified Data.HashTable.IO as HT
import Data.Serialize.Get
import Data.Serialize.Put
import Database.KeyValue.Parsing
import Database.KeyValue.Types
import System.FilePath.Posix
import System.IO
import System.IO.Temp
-- | Extension of hint logs
hintExt :: String
hintExt = ".hkv"
-- | Extension of data logs
recordExt :: String
recordExt = ".rkv"
-- | Get key and value locations from hint files
getKeyAndValueLocs :: [FilePath] -> IO [(Key, ValueLoc)]
getKeyAndValueLocs hintFiles = do
l <- mapM getKeyAndValueLoc hintFiles
return (concat l)
-- | Get key and value locations from a single hint file
getKeyAndValueLoc :: FilePath -> IO [(Key, ValueLoc)]
getKeyAndValueLoc hintFile = do
recordHandle <- getRecordHandle hintFile
c <- B.readFile hintFile
case runGet parseHintLogs c of
Left _ -> error "Error occured in parsing hint file."
Right hintlogs -> return (map ((\(k, o) -> (k, ValueLoc o recordHandle)) . getKeyOffsetPair) hintlogs)
-- | Get the handle of the data log corresponding to a hint log
getRecordHandle :: FilePath -> IO Handle
getRecordHandle hintFile = do
ht <- openBinaryFile (replaceExtension hintFile recordExt) ReadMode
hSetBuffering ht NoBuffering
return ht
-- | Open a new data and the corresponding hint log
addNewRecord :: FilePath -> IO (Handle, Handle)
addNewRecord dir = do
(hintFile, hintHandle) <- openNewBinaryFile dir hintExt
recordHandle <- openBinaryFile (replaceExtension hintFile recordExt) ReadWriteMode
hSetBuffering hintHandle NoBuffering
hSetBuffering recordHandle NoBuffering
return (hintHandle, recordHandle)
-- | Get all the keys from the hint files
-- In case of conflict, keep the copy with the latest timestamp
getKeysFromHintFiles :: [FilePath] -> IO KeysTable
getKeysFromHintFiles hintFiles = do
table <- HT.new
allKeysList <- fmap concat (mapM getKeysFromHintFile hintFiles)
mapM_ (checkAndInsert table) allKeysList
return table
-- | Get all keys and timestamp from a hint file
getKeysFromHintFile :: FilePath -> IO [(Key, KeyUpdateInfo)]
getKeysFromHintFile file = do
-- TODO: Make this lazy
c <- B.readFile file
case runGet parseHintLogs c of
Left _ -> error "Error occured parsing hint log."
Right hintLogs -> return (map getKeyUpdateInfo hintLogs) where
getKeyUpdateInfo :: HintLog -> (Key, KeyUpdateInfo)
getKeyUpdateInfo l = (hKey l, (hTimestamp l, hOffset l == 0))
-- | Insert the key in hash map after checking for conflicts
checkAndInsert :: KeysTable -> (Key, KeyUpdateInfo) -> IO ()
checkAndInsert table (k, u) = do
v <- HT.lookup table k
case v of
Nothing -> HT.insert table k u
Just (t', _) -> when (fst u > t') $ HT.insert table k u
-- | Read records from data files and write it to merged data and hint file
putKeysFromRecordFiles :: Handle -> Handle -> KeysTable -> [FilePath] -> IO ()
putKeysFromRecordFiles hintHandle recordHandle table =
mapM_ (putKeysFromRecordFile hintHandle recordHandle table)
-- | Read record from a single data file and write it to merged data and hint file
putKeysFromRecordFile :: Handle -> Handle -> KeysTable -> FilePath -> IO ()
putKeysFromRecordFile hHt rHt t recordFile = do
-- TODO: Make this lazy
c <- B.readFile recordFile
case runGet parseDataLogs c of
Left _ -> error "Error occured parsing data log."
Right dataLogs -> mapM_ (putKeyFromDataLog hHt rHt t) dataLogs
-- | Write a data log to merged data and hint file if it is present in
-- the (Key, KeyUpdateInfo) hashmap obtained from hint files
putKeyFromDataLog :: Handle -> Handle -> KeysTable -> DataLog -> IO ()
putKeyFromDataLog hHt rHt t dataLog = do
let k = dKey dataLog
timestamp = dTimestamp dataLog
v <- HT.lookup t k
case v of
Nothing -> return ()
Just (_, True) -> return ()
Just (t', False) -> when (t' == timestamp) $ do
offset <- hFileSize rHt
B.hPut rHt (runPut (deserializeData k (dValue dataLog) timestamp))
B.hPut hHt (runPut (deserializeHint k (offset + 1) timestamp))
return ()
| TypeDB/keyvalue | Database/KeyValue/LogOperations.hs | gpl-3.0 | 4,692 | 0 | 19 | 1,133 | 1,158 | 586 | 572 | 85 | 3 |
--ch01 hola name
main = do
print "hello jesus"
| jmlb23/haskell | ch00/hello_name.hs | gpl-3.0 | 49 | 0 | 7 | 11 | 13 | 6 | 7 | 2 | 1 |
{- HierarchicalClustering
Gregory W. Schwartz
Collections the functions pertaining to the hierarchical clustering of the
records
-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE QuasiQuotes #-}
module HierarchicalClustering
( cluster
) where
-- Standard
import qualified Data.Vector as V
import Data.Tree
import Control.Monad
-- Cabal
-- Local
import qualified Foreign.R as R
import Foreign.R (SEXP, SEXPTYPE)
import Language.R.Instance as R
import Language.R.QQ
import qualified H.Prelude as H
import qualified H.Prelude.Interactive as H
-- Local
import Types
import CMatrix
import NewmanGirvan
clusterEmpty :: Height
-> ID
-> V.Vector (RowID, Record)
-> R s (Tree TreeData)
clusterEmpty !height !(ID label) !records = do
let treeData = TreeData { treeLabel = ID label
, treeSize = Size . V.length $ records
, treeHeight = height
, treeLocation = 0
, treeNGValue = 0
, treeRecords = records
}
return $ Node { rootLabel = treeData, subForest = [] }
clusterFull :: Height
-> ID
-> V.Vector (RowID, Record)
-> R.SomeSEXP s
-> R s (Tree TreeData)
clusterFull !height !(ID label) !records !b = do
c <- getC b
let x = (fromIntegral . V.length $ records) :: Double
part <- if
| V.length records == 2 -> [r| c(0, 1) |]
| V.length records < 5 -> [r| as.integer(sign(svd(c_hs, nu=2, nv=0)$u[,2]) < 0) |]
| otherwise -> [r| as.integer(sign(irlba(c_hs, nu=2, nv=0, right_only=FALSE, maxit=2)$u[,2]) < 0) |]
leftIndex <- [r| as.numeric(which(part_hs == 0)) |]
rightIndex <- [r| as.numeric(which(part_hs == 1)) |]
leftB <- [r| b_hs[leftIndex_hs,] |]
rightB <- [r| b_hs[rightIndex_hs,] |]
let getRecords index = V.map (\x -> records V.! (truncate x - 1))
. V.fromList
$ (H.fromSomeSEXP index :: [Double])
leftRecords = getRecords leftIndex
rightRecords = getRecords rightIndex
ngResultR <- ngModularity b part
let ngResult = (H.fromSomeSEXP ngResultR) :: Double
let treeData = TreeData { treeLabel = ID label
, treeSize = Size . V.length $ records
, treeHeight = height
, treeLocation = 0
, treeNGValue = ngResult
, treeRecords = records
}
resultM
| ngResult > 0 = do
left <- cluster (height + 1) (ID (label * 2)) leftRecords leftB
right <- cluster (height + 1) (ID (label * 2) + 1) rightRecords rightB
return $
Node { rootLabel = treeData { treeRecords = V.empty }
, subForest = [left, right]
}
| otherwise = return $ Node { rootLabel = treeData, subForest = [] }
result <- resultM
return result
cluster :: Height
-> ID
-> V.Vector (RowID, Record)
-> R.SomeSEXP s
-> R s (Tree TreeData)
cluster !height !(ID label) !records !b
| V.length records < 2 = clusterEmpty height (ID label) records
| otherwise = clusterFull height (ID label) records b
| GregorySchwartz/scan | src/HierarchicalClustering.hs | gpl-3.0 | 3,567 | 0 | 19 | 1,347 | 921 | 496 | 425 | 76 | 3 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.MEnv
(
GameData (..),
MEnv',
module MEnv,
module MEnv.Tick,
module MEnv.Keys,
module MEnv.Screen,
module MEnv.Sound,
module MEnv.Foreign,
module MEnv.Players,
module MEnv.System,
module MEnv.Resource,
) where
import MEnv
import MEnv.Tick
import MEnv.Keys
import MEnv.Screen
import MEnv.Sound
import MEnv.Foreign
import MEnv.Players
import MEnv.System
import MEnv.Resource
import Game.GameData
type MEnv' =
MEnv GameData
| karamellpelle/grid | designer/source/Game/MEnv.hs | gpl-3.0 | 1,248 | 0 | 5 | 254 | 146 | 100 | 46 | 25 | 0 |
------------------------------------------------------------------------------
--
-- Inductive.hs -- Functional Graph Library
--
-- (c) 1999-2007 by Martin Erwig [see file COPYRIGHT]
--
------------------------------------------------------------------------------
module Data.Graph.Inductive(
module Data.Graph.Inductive.Graph,
module Data.Graph.Inductive.Tree,
module Data.Graph.Inductive.Basic,
module Data.Graph.Inductive.Monad,
module Data.Graph.Inductive.Monad.IOArray,
module Data.Graph.Inductive.Query,
module Data.Graph.Inductive.Graphviz,
module Data.Graph.Inductive.NodeMap,
-- * Version Information
version
) where
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Tree
import Data.Graph.Inductive.Basic
import Data.Graph.Inductive.Monad
import Data.Graph.Inductive.Monad.IOArray
import Data.Graph.Inductive.Query
import Data.Graph.Inductive.Graphviz
import Data.Graph.Inductive.NodeMap
-- | Version info
version :: IO ()
version = putStrLn "\nFGL - Functional Graph Library, April 2007"
| ckaestne/CIDE | CIDE_Language_Haskell/test/FGL-layout/Graph/Inductive.hs | gpl-3.0 | 1,094 | 0 | 6 | 161 | 161 | 116 | 45 | 20 | 1 |
module HeroesAndCowards.HACModel where
import System.Random
import Data.Maybe
import GHC.Generics (Generic)
import qualified PureAgentsSeq as PA
type HACAgentPosition = (Double, Double)
data HACMsg = PositionRequest | PositionUpdate HACAgentPosition
data HACWorldType = Infinite | Border | Wraping deriving (Eq, Show)
data HACAgentState = HACAgentState {
pos :: HACAgentPosition,
hero :: Bool,
wt :: HACWorldType,
friend :: PA.AgentId,
enemy :: PA.AgentId,
friendPos :: Maybe HACAgentPosition,
enemyPos :: Maybe HACAgentPosition
} deriving (Show)
type HACEnvironment = Int
type HACAgent = PA.Agent HACMsg HACAgentState HACEnvironment
type HACTransformer = PA.AgentTransformer HACMsg HACAgentState HACEnvironment
type HACSimHandle = PA.SimHandle HACMsg HACAgentState HACEnvironment
hacMovementPerTimeUnit :: Double
hacMovementPerTimeUnit = 1.0
hacTransformer :: HACTransformer
hacTransformer ae (PA.Start) = ae
hacTransformer (a, e) (PA.Dt dt) = (hacDt a dt, e)
hacTransformer (a, e) (PA.Message (senderId, m)) = (hacMsg a m senderId, e)
hacMsg :: HACAgent -> HACMsg -> PA.AgentId -> HACAgent
-- MESSAGE-CASE: PositionUpdate
hacMsg a (PositionUpdate (x, y)) senderId
| senderId == friendId = PA.updateState a (\sOld -> sOld { friendPos = newPos })
| senderId == enemyId = PA.updateState a (\sOld -> sOld { enemyPos = newPos })
where
s = PA.state a
friendId = friend s
enemyId = enemy s
newPos = Just (x,y)
-- MESSAGE-CASE: PositionRequest
hacMsg a PositionRequest senderId = PA.sendMsg a (PositionUpdate currPos) senderId
where
s = PA.state a
currPos = pos s
hacDt :: HACAgent -> Double -> HACAgent
hacDt a dt = if ((isJust fPos) && (isJust ePos)) then
PA.writeState a'' s' -- NOTE: no new position/state will be calculated due to Haskells Laziness
else
a''
where
s = PA.state a
fPos = friendPos s
ePos = enemyPos s
oldPos = pos s
targetPos = decidePosition (fromJust fPos) (fromJust ePos) (hero s)
targetDir = vecNorm $ posDir oldPos targetPos
wtFunc = worldTransform (wt s)
stepWidth = hacMovementPerTimeUnit * dt
newPos = wtFunc $ addPos oldPos (multPos targetDir stepWidth)
s' = s{ pos = newPos }
a' = requestPosition a (friend s)
a'' = requestPosition a' (enemy s) -- TODO: replace by broadcast to neighbours
requestPosition :: HACAgent -> PA.AgentId -> HACAgent
requestPosition a receiverId = PA.sendMsg a PositionRequest receiverId
createHACTestAgents :: [HACAgent]
createHACTestAgents = [a0', a1', a2']
where
a0State = HACAgentState{ pos = (0.0, -0.5), hero = False, friend = 1, enemy = 2, wt = Border, friendPos = Nothing, enemyPos = Nothing }
a1State = HACAgentState{ pos = (0.5, 0.5), hero = False, friend = 0, enemy = 2, wt = Border, friendPos = Nothing, enemyPos = Nothing }
a2State = HACAgentState{ pos = (-0.5, 0.5), hero = False, friend = 0, enemy = 1, wt = Border, friendPos = Nothing, enemyPos = Nothing }
a0 = PA.createAgent 0 a0State hacTransformer
a1 = PA.createAgent 1 a1State hacTransformer
a2 = PA.createAgent 2 a2State hacTransformer
a0' = PA.addNeighbours a0 [a1, a2]
a1' = PA.addNeighbours a1 [a0, a2]
a2' = PA.addNeighbours a2 [a0, a1]
createRandomHACAgents :: RandomGen g => g -> Int -> Double -> ([HACAgent], g)
createRandomHACAgents gInit n p = (as', g')
where
(randStates, g') = createRandomStates gInit 0 n p
as = map (\idx -> PA.createAgent idx (randStates !! idx) hacTransformer) [0..n-1]
as' = map (\a -> PA.addNeighbours a as) as -- TODO: filter for friend and enemy
createRandomStates :: RandomGen g => g -> Int -> Int -> Double -> ([HACAgentState], g)
createRandomStates g id n p
| id == n = ([], g)
| otherwise = (rands, g'')
where
(randState, g') = randomAgentState g id n p
(ras, g'') = createRandomStates g' (id+1) n p
rands = randState : ras
----------------------------------------------------------------------------------------------------------------------
-- PRIVATES
----------------------------------------------------------------------------------------------------------------------
randomAgentState :: (RandomGen g) => g -> Int -> Int -> Double -> (HACAgentState, g)
randomAgentState g id maxAgents p = (s, g5)
where
allAgentIds = [0..maxAgents-1]
(randX, g') = randomR(-1.0, 1.0) g
(randY, g'') = randomR(-1.0, 1.0) g'
(randEnemy, g3) = drawRandomIgnoring g'' allAgentIds [id]
(randFriend, g4) = drawRandomIgnoring g3 allAgentIds [id, randEnemy]
(randHero, g5) = randomThresh g4 p
s = HACAgentState{ pos = (randX, randY),
hero = randHero,
friend = randFriend,
enemy = randEnemy,
wt = Border,
friendPos = Nothing,
enemyPos = Nothing }
randomThresh :: (RandomGen g) => g -> Double -> (Bool, g)
randomThresh g p = (flag, g')
where
(thresh, g') = randomR(0.0, 1.0) g
flag = thresh <= p
-- NOTE: this solution will recur forever if there are no possible solutions but will be MUCH faster for large xs and if xs is much larger than is and one knows there are solutions
drawRandomIgnoring :: (RandomGen g, Eq a) => g -> [a] -> [a] -> (a, g)
drawRandomIgnoring g xs is
| any (==randElem) is = drawRandomIgnoring g' xs is
| otherwise = (randElem, g')
where
(randIdx, g') = randomR(0, length xs - 1) g
randElem = xs !! randIdx
decidePosition :: HACAgentPosition -> HACAgentPosition -> Bool -> HACAgentPosition
decidePosition friendPos enemyPos hero
| hero = coverPosition
| otherwise = hidePosition
where
enemyFriendDir = posDir friendPos enemyPos
halfPos = multPos enemyFriendDir 0.5
coverPosition = addPos friendPos halfPos
hidePosition = subPos friendPos halfPos
multPos :: HACAgentPosition -> Double -> HACAgentPosition
multPos (x, y) s = (x*s, y*s)
addPos :: HACAgentPosition -> HACAgentPosition -> HACAgentPosition
addPos (x1, y1) (x2, y2) = (x1+x2, y1+y2)
subPos :: HACAgentPosition -> HACAgentPosition -> HACAgentPosition
subPos (x1, y1) (x2, y2) = (x1-x2, y1-y2)
posDir :: HACAgentPosition -> HACAgentPosition -> HACAgentPosition
posDir (x1, y1) (x2, y2) = (x2-x1, y2-y1)
vecLen :: HACAgentPosition -> Double
vecLen (x, y) = sqrt( x * x + y * y )
vecNorm :: HACAgentPosition -> HACAgentPosition
vecNorm (x, y)
| len == 0 = (0, 0)
| otherwise = (x / len, y / len)
where
len = vecLen (x, y)
clip :: HACAgentPosition -> HACAgentPosition
clip (x, y) = (clippedX, clippedY)
where
clippedX = max (-1.0) (min x 1.0)
clippedY = max (-1.0) (min y 1.0)
wrap :: HACAgentPosition -> HACAgentPosition
wrap (x, y) = (wrappedX, wrappedY)
where
wrappedX = wrapValue x
wrappedY = wrapValue y
wrapValue :: Double -> Double
wrapValue v
| v > 1.0 = -1.0
| v < -1.0 = 1.0
| otherwise = v
worldTransform :: HACWorldType -> (HACAgentPosition -> HACAgentPosition)
worldTransform wt
| wt == Border = clip
| wt == Wraping = wrap
| otherwise = id | thalerjonathan/phd | public/ArtIterating/code/haskell/PureAgentsSeq/src/HeroesAndCowards/HACModel.hs | gpl-3.0 | 7,524 | 0 | 13 | 1,975 | 2,434 | 1,342 | 1,092 | 145 | 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.Compute.DiskTypes.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of disk types available to the specified project.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.diskTypes.list@.
module Network.Google.Resource.Compute.DiskTypes.List
(
-- * REST Resource
DiskTypesListResource
-- * Creating a Request
, diskTypesList
, DiskTypesList
-- * Request Lenses
, dtlOrderBy
, dtlProject
, dtlZone
, dtlFilter
, dtlPageToken
, dtlMaxResults
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.diskTypes.list@ method which the
-- 'DiskTypesList' request conforms to.
type DiskTypesListResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"diskTypes" :>
QueryParam "orderBy" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :> Get '[JSON] DiskTypeList
-- | Retrieves a list of disk types available to the specified project.
--
-- /See:/ 'diskTypesList' smart constructor.
data DiskTypesList = DiskTypesList'
{ _dtlOrderBy :: !(Maybe Text)
, _dtlProject :: !Text
, _dtlZone :: !Text
, _dtlFilter :: !(Maybe Text)
, _dtlPageToken :: !(Maybe Text)
, _dtlMaxResults :: !(Textual Word32)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'DiskTypesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dtlOrderBy'
--
-- * 'dtlProject'
--
-- * 'dtlZone'
--
-- * 'dtlFilter'
--
-- * 'dtlPageToken'
--
-- * 'dtlMaxResults'
diskTypesList
:: Text -- ^ 'dtlProject'
-> Text -- ^ 'dtlZone'
-> DiskTypesList
diskTypesList pDtlProject_ pDtlZone_ =
DiskTypesList'
{ _dtlOrderBy = Nothing
, _dtlProject = pDtlProject_
, _dtlZone = pDtlZone_
, _dtlFilter = Nothing
, _dtlPageToken = Nothing
, _dtlMaxResults = 500
}
-- | Sorts list results by a certain order. By default, results are returned
-- in alphanumerical order based on the resource name. You can also sort
-- results in descending order based on the creation timestamp using
-- orderBy=\"creationTimestamp desc\". This sorts results based on the
-- creationTimestamp field in reverse chronological order (newest result
-- first). Use this to sort resources like operations so that the newest
-- operation is returned first. Currently, only sorting by name or
-- creationTimestamp desc is supported.
dtlOrderBy :: Lens' DiskTypesList (Maybe Text)
dtlOrderBy
= lens _dtlOrderBy (\ s a -> s{_dtlOrderBy = a})
-- | Project ID for this request.
dtlProject :: Lens' DiskTypesList Text
dtlProject
= lens _dtlProject (\ s a -> s{_dtlProject = a})
-- | The name of the zone for this request.
dtlZone :: Lens' DiskTypesList Text
dtlZone = lens _dtlZone (\ s a -> s{_dtlZone = a})
-- | Sets a filter expression for filtering listed resources, in the form
-- filter={expression}. Your {expression} must be in the format: field_name
-- comparison_string literal_string. The field_name is the name of the
-- field you want to compare. Only atomic field types are supported
-- (string, number, boolean). The comparison_string must be either eq
-- (equals) or ne (not equals). The literal_string is the string value to
-- filter to. The literal value must be valid for the type of field you are
-- filtering by (string, number, boolean). For string fields, the literal
-- value is interpreted as a regular expression using RE2 syntax. The
-- literal value must match the entire field. For example, to filter for
-- instances that do not have a name of example-instance, you would use
-- filter=name ne example-instance. You can filter on nested fields. For
-- example, you could filter on instances that have set the
-- scheduling.automaticRestart field to true. Use filtering on nested
-- fields to take advantage of labels to organize and search for results
-- based on label values. To filter on multiple expressions, provide each
-- separate expression within parentheses. For example,
-- (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple
-- expressions are treated as AND expressions, meaning that resources must
-- match all expressions to pass the filters.
dtlFilter :: Lens' DiskTypesList (Maybe Text)
dtlFilter
= lens _dtlFilter (\ s a -> s{_dtlFilter = a})
-- | Specifies a page token to use. Set pageToken to the nextPageToken
-- returned by a previous list request to get the next page of results.
dtlPageToken :: Lens' DiskTypesList (Maybe Text)
dtlPageToken
= lens _dtlPageToken (\ s a -> s{_dtlPageToken = a})
-- | The maximum number of results per page that should be returned. If the
-- number of available results is larger than maxResults, Compute Engine
-- returns a nextPageToken that can be used to get the next page of results
-- in subsequent list requests.
dtlMaxResults :: Lens' DiskTypesList Word32
dtlMaxResults
= lens _dtlMaxResults
(\ s a -> s{_dtlMaxResults = a})
. _Coerce
instance GoogleRequest DiskTypesList where
type Rs DiskTypesList = DiskTypeList
type Scopes DiskTypesList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient DiskTypesList'{..}
= go _dtlProject _dtlZone _dtlOrderBy _dtlFilter
_dtlPageToken
(Just _dtlMaxResults)
(Just AltJSON)
computeService
where go
= buildClient (Proxy :: Proxy DiskTypesListResource)
mempty
| rueshyna/gogol | gogol-compute/gen/Network/Google/Resource/Compute/DiskTypes/List.hs | mpl-2.0 | 6,785 | 0 | 19 | 1,528 | 751 | 450 | 301 | 104 | 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.FusionTables.Task.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of tasks.
--
-- /See:/ <https://developers.google.com/fusiontables Fusion Tables API Reference> for @fusiontables.task.list@.
module Network.Google.Resource.FusionTables.Task.List
(
-- * REST Resource
TaskListResource
-- * Creating a Request
, taskList'
, TaskList'
-- * Request Lenses
, tlPageToken
, tlTableId
, tlStartIndex
, tlMaxResults
) where
import Network.Google.FusionTables.Types
import Network.Google.Prelude
-- | A resource alias for @fusiontables.task.list@ method which the
-- 'TaskList'' request conforms to.
type TaskListResource =
"fusiontables" :>
"v2" :>
"tables" :>
Capture "tableId" Text :>
"tasks" :>
QueryParam "pageToken" Text :>
QueryParam "startIndex" (Textual Word32) :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :> Get '[JSON] TaskList
-- | Retrieves a list of tasks.
--
-- /See:/ 'taskList'' smart constructor.
data TaskList' = TaskList''
{ _tlPageToken :: !(Maybe Text)
, _tlTableId :: !Text
, _tlStartIndex :: !(Maybe (Textual Word32))
, _tlMaxResults :: !(Maybe (Textual Word32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'TaskList'' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tlPageToken'
--
-- * 'tlTableId'
--
-- * 'tlStartIndex'
--
-- * 'tlMaxResults'
taskList'
:: Text -- ^ 'tlTableId'
-> TaskList'
taskList' pTlTableId_ =
TaskList''
{ _tlPageToken = Nothing
, _tlTableId = pTlTableId_
, _tlStartIndex = Nothing
, _tlMaxResults = Nothing
}
-- | Continuation token specifying which result page to return.
tlPageToken :: Lens' TaskList' (Maybe Text)
tlPageToken
= lens _tlPageToken (\ s a -> s{_tlPageToken = a})
-- | Table whose tasks are being listed.
tlTableId :: Lens' TaskList' Text
tlTableId
= lens _tlTableId (\ s a -> s{_tlTableId = a})
-- | Index of the first result returned in the current page.
tlStartIndex :: Lens' TaskList' (Maybe Word32)
tlStartIndex
= lens _tlStartIndex (\ s a -> s{_tlStartIndex = a})
. mapping _Coerce
-- | Maximum number of tasks to return. Default is 5.
tlMaxResults :: Lens' TaskList' (Maybe Word32)
tlMaxResults
= lens _tlMaxResults (\ s a -> s{_tlMaxResults = a})
. mapping _Coerce
instance GoogleRequest TaskList' where
type Rs TaskList' = TaskList
type Scopes TaskList' =
'["https://www.googleapis.com/auth/fusiontables",
"https://www.googleapis.com/auth/fusiontables.readonly"]
requestClient TaskList''{..}
= go _tlTableId _tlPageToken _tlStartIndex
_tlMaxResults
(Just AltJSON)
fusionTablesService
where go
= buildClient (Proxy :: Proxy TaskListResource)
mempty
| rueshyna/gogol | gogol-fusiontables/gen/Network/Google/Resource/FusionTables/Task/List.hs | mpl-2.0 | 3,801 | 0 | 16 | 936 | 587 | 341 | 246 | 83 | 1 |
func reallyreallyreallyreallyreallyreallyreallyreallyreallyreallylongvariable reallyreallyreallyreallyreallyreallyreallyreallyreallyreallylongvariable
= x
| lspitzner/brittany | data/Test81.hs | agpl-3.0 | 157 | 0 | 5 | 7 | 11 | 5 | 6 | 2 | 1 |
import Test.QuickCheck
import Data.List (sort)
import Data.Char (toUpper)
-- Exercises: using QuickCheck
-- 1. Division
divisor :: Gen Float
divisor = arbitrary `suchThat` (/= 0)
half x = x / 2
halfIdentity = (*2) . half
prop_half :: Property
prop_half =
forAll divisor
(\x -> (half x) * 2 == x)
prop_identity :: Property
prop_identity =
forAll divisor
(\x -> (halfIdentity x) == x)
-- 2. Sorting
genList :: (Arbitrary a, Eq a) => Gen [a]
genList = do
a <- arbitrary
b <- arbitrary `suchThat` (/= a)
c <- arbitrary `suchThat` (`notElem` [a, b])
return [a, b, c]
listOrdered :: (Ord a) => [a] -> Bool
listOrdered xs = snd $ foldr go (Nothing, True) xs
where go y (Nothing, t) = (Just y, t)
go y (Just x, t) = (Just y, x >= y)
prop_listOrdered :: Property
prop_listOrdered =
forAll (genList :: Gen String)
(\x -> listOrdered $ sort x)
-- 3. Addition
associative :: Eq a => (a -> a -> a) -> a -> a -> a -> Bool
associative f x y z = x `f` (y `f` z) == (x `f` y) `f` z
commutative :: Eq a => (a -> a -> a) -> a -> a -> Bool
commutative f x y = x `f` y == y `f` x
genTuple :: (Arbitrary a, Arbitrary b) => Gen (a, b)
genTuple = arbitrary
genThreeple :: (Arbitrary a, Arbitrary b, Arbitrary c) =>
Gen (a, b, c)
genThreeple = arbitrary
untrurry :: (a -> b -> c -> d) -> ((a, b, c) -> d)
untrurry f (a, b, c) = f a b c
prop_plusAssoc :: Property
prop_plusAssoc =
forAll (genThreeple :: Gen (Int, Int, Int))
(untrurry $ associative (+))
prop_plusComm :: Property
prop_plusComm =
forAll (genTuple :: Gen (Int, Int))
(uncurry $ commutative (+))
-- 4. Multiplication
prop_timesAssoc :: Property
prop_timesAssoc =
forAll (genThreeple :: Gen (Int, Int, Int))
(untrurry $ associative (*))
prop_timesComm :: Property
prop_timesComm =
forAll (genTuple :: Gen (Int, Int))
(uncurry $ commutative (*))
-- 5. div vs mod
quotVsRem :: Integral a => a -> a -> Bool
quotVsRem x y = (quot x y) * y + (rem x y) == x
divVsMod :: Integral a => a -> a -> Bool
divVsMod x y = (div x y) * y + (mod x y) == x
genTupleNonZero :: (Arbitrary a, Num a, Eq a) => Gen (a, a)
genTupleNonZero = do
x <- arbitrary `suchThat` (/= 0)
y <- arbitrary `suchThat` (/= 0)
return (x, y)
prop_quotRem :: Property
prop_quotRem =
forAll (genTupleNonZero :: Gen (Int, Int))
(uncurry quotVsRem)
prop_divMod :: Property
prop_divMod =
forAll (genTupleNonZero :: Gen (Int, Int))
(uncurry divVsMod)
-- 6. (^)
genTuplePos :: (Arbitrary a, Num a, Ord a) => Gen (a, a)
genTuplePos = do
x <- arbitrary `suchThat` (> 1)
y <- arbitrary `suchThat` (> 1)
return (x, y)
genThreeplePos :: (Arbitrary a, Num a, Ord a) => Gen (a, a, a)
genThreeplePos = do
x <- arbitrary `suchThat` (> 1)
y <- arbitrary `suchThat` (> 1)
z <- arbitrary `suchThat` (> 1)
return (x, y, z)
prop_hatAssoc :: Property
prop_hatAssoc =
forAll (genThreeplePos :: Gen (Int, Int, Int))
(untrurry $ associative (^))
prop_hatComm :: Property
prop_hatComm =
forAll (genTuplePos :: Gen (Int, Int))
(uncurry $ commutative (^))
-- 7. reverse reverse list == list
prop_reverse :: Property
prop_reverse =
forAll (genList :: Gen [Int])
(\x -> (reverse . reverse) x == id x)
-- 8. ($)
prop_dollar :: Property
prop_dollar =
forAll divisor
(\x -> ((-) x $ x + x) == (-) x (x + x))
-- 9. Check functions
prop_concat :: Property
prop_concat =
forAll (genTuple :: Gen ([Int], [Int]))
(\(x, y) -> foldr (:) y x == (++) x y)
prop_concat' :: Property
prop_concat' =
forAll (genTuple :: Gen ([Int], [Int]))
(\(x, y) -> foldr (++) [] [x, y] == concat [x, y])
-- 10. Check property
prop_lengthTake :: Property
prop_lengthTake =
forAll (genTuple :: Gen (Int, [Int]))
(\(n, xs) -> length (take n xs) == n)
-- 11. show . read
prop_showRead :: Property
prop_showRead =
forAll (genList :: Gen String)
(\x -> (read (show x)) == x)
-- Failure
genPos :: (Num a, Arbitrary a, Ord a) => Gen a
genPos = arbitrary `suchThat` (> 0)
square x = x * x
squareId = square . sqrt
prop_square :: Property
prop_square =
forAll (genPos :: Gen Float)
(\x -> squareId x == x)
-- Idempotence
twice f = f . f
fourTimes = twice . twice
capitalizeWord :: String -> String
capitalizeWord = map toUpper
prop_capitalizeWord :: Property
prop_capitalizeWord =
forAll (genList :: Gen String)
(\x -> capitalizeWord x == twice capitalizeWord x
&&
capitalizeWord x == fourTimes capitalizeWord x)
prop_sort :: Property
prop_sort =
forAll (genList :: Gen String)
(\x -> sort x == twice sort x
&&
sort x == fourTimes sort x)
-- Make Gen for Fool
data Fool = Fulse | Frue deriving (Eq, Show)
-- 1. Equal probabilities
genFool :: Gen Fool
genFool = elements [Fulse, Frue]
-- 2. 2/3 Fulse, 1/3 Frue
genUnfair :: Gen Fool
genUnfair = elements [Frue, Fulse, Fulse]
-- Main
main :: IO ()
main = do
putStrLn "\nhalf"
quickCheck prop_half
putStrLn "\nhalfIdentity"
quickCheck prop_identity
putStrLn "\nCheck ordering"
quickCheck prop_listOrdered
putStrLn "\nCheck plusAssociative"
quickCheck prop_plusAssoc
putStrLn "\nCheck plusCommutative"
quickCheck prop_plusComm
putStrLn "\nCheck timesAssociative"
quickCheck prop_timesAssoc
putStrLn "\nCheck timesCommutative"
quickCheck prop_timesComm
putStrLn "\nCheck quotVsRem"
quickCheck prop_quotRem
putStrLn "\nCheck divVsMod"
quickCheck prop_divMod
putStrLn "\nCheck if exponentiation is commutative"
quickCheck prop_hatComm
putStrLn "\nCheck if exponentiation is associative"
quickCheck prop_hatAssoc
putStrLn "\nCheck if reverse . reverse == id"
quickCheck prop_reverse
putStrLn "\nCheck ($)"
quickCheck prop_dollar
putStrLn "\nCompare foldr (:) and (++)"
quickCheck prop_concat
putStrLn "\nCompare foldr (++) [] and concat"
quickCheck prop_concat'
putStrLn "\nCheck length n take == n"
quickCheck prop_lengthTake
putStrLn "\nCheck show . read == id"
quickCheck prop_showRead
putStrLn "\nCheck square . sqrt with Float"
quickCheck prop_square
putStrLn "\nCheck idempotence capitalizeWord"
quickCheck prop_capitalizeWord
putStrLn "\nCheck idempotence sort"
quickCheck prop_sort
| dmvianna/haskellbook | src/Ch14Ex-tests.hs | unlicense | 6,176 | 0 | 12 | 1,314 | 2,378 | 1,272 | 1,106 | 187 | 2 |
module Network.Haskoin.Crypto.ECDSA.Tests (tests) where
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Data.Bits (testBit)
import qualified Data.ByteString as BS (index, length)
import Network.Haskoin.Test
import Network.Haskoin.Crypto
import Network.Haskoin.Util
tests :: [Test]
tests =
[ testGroup "ECDSA signatures"
[ testProperty "Verify signature" testVerifySig
, testProperty "S component <= order/2" $
\(ArbitrarySignature _ _ sig) -> halfOrderSig sig
]
, testGroup "ECDSA Binary"
[ testProperty "Encoded signature is canonical" $
\(ArbitrarySignature _ _ sig) -> testIsCanonical sig
]
]
{- ECDSA Signatures -}
halfOrderSig :: Signature -> Bool
halfOrderSig = isCanonicalHalfOrder
testVerifySig :: ArbitrarySignature -> Bool
testVerifySig (ArbitrarySignature msg key sig) =
verifySig msg sig pubkey
where
pubkey = derivePubKey key
{- ECDSA Binary -}
-- github.com/bitcoin/bitcoin/blob/master/src/script.cpp
-- from function IsCanonicalSignature
testIsCanonical :: Signature -> Bool
testIsCanonical sig = not $
-- Non-canonical signature: too short
(len < 8) ||
-- Non-canonical signature: too long
(len > 72) ||
-- Non-canonical signature: wrong type
(BS.index s 0 /= 0x30) ||
-- Non-canonical signature: wrong length marker
(BS.index s 1 /= len - 2) ||
-- Non-canonical signature: S length misplaced
(5 + rlen >= len) ||
-- Non-canonical signature: R+S length mismatch
(rlen + slen + 6 /= len) ||
-- Non-canonical signature: R value type mismatch
(BS.index s 2 /= 0x02) ||
-- Non-canonical signature: R length is zero
(rlen == 0) ||
-- Non-canonical signature: R value negative
(testBit (BS.index s 4) 7) ||
-- Non-canonical signature: R value excessively padded
( rlen > 1
&& BS.index s 4 == 0
&& not (testBit (BS.index s 5) 7)
) ||
-- Non-canonical signature: S value type mismatch
(BS.index s (fromIntegral rlen+4) /= 0x02) ||
-- Non-canonical signature: S length is zero
(slen == 0) ||
-- Non-canonical signature: S value negative
(testBit (BS.index s (fromIntegral rlen+6)) 7) ||
-- Non-canonical signature: S value excessively padded
( slen > 1
&& BS.index s (fromIntegral rlen+6) == 0
&& not (testBit (BS.index s (fromIntegral rlen+7)) 7)
)
where
s = encode' sig
len = fromIntegral $ BS.length s
rlen = BS.index s 3
slen = BS.index s (fromIntegral rlen + 5)
| tphyahoo/haskoin | haskoin-core/tests/Network/Haskoin/Crypto/ECDSA/Tests.hs | unlicense | 2,583 | 0 | 20 | 599 | 667 | 361 | 306 | 48 | 1 |
-- Copyright 2021 Google LLC
--
-- 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
--
-- https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE CPP #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main where
#ifdef SOLUTION
import qualified Solution as C
#else
import qualified Codelab as C
#endif
import Internal (check, test, Tests)
main :: IO ()
main = check tests
tests :: Tests
tests =
[ test "hours (Minutes 271)" 4 $ C.hours (C.Minutes 271)
, test "hours (Minutes 15)" 0 $ C.hours (C.Minutes 15)
, test "timeDistance (Minutes 15) (Minutes 25)" (C.Minutes 10) $ C.timeDistance (C.Minutes 15) (C.Minutes 25)
, test "timeDistance (Minutes 99) (Minutes 47)" (C.Minutes 52) $ C.timeDistance (C.Minutes 99) (C.Minutes 47)
, test "pointDistance (1, 1) (1, 3)" 2 $ C.pointDistance (1, 1) (1, 3)
, test "pointDistance (3, 4) (0, 0)" 5 $ C.pointDistance (3, 4) (0, 0)
]
deriving instance Eq C.Minutes
deriving instance Show C.Minutes
| google/haskell-trainings | haskell_101/codelab/02_datatypes/src/Main.hs | apache-2.0 | 1,446 | 0 | 10 | 255 | 289 | 161 | 128 | 18 | 1 |
import Data.Array
import Common.Numbers.Primes (primesTo, testPrime)
primeList = primesTo 9999 :: [Int]
primeArray = listArray (0, (length primeList) - 1) primeList
canCatArray = listArray (0, (length primeList) - 1) [ catArray (fst p) (snd p) | p <- (zip primeList [0 .. ]) ] where
check x y = (testPrime (cat x y)) && (testPrime (cat y x)) where
cat x y = read $ (show x) ++ (show y)
catArray x index = listArray (0, index - 1) [ check x y | y <- take index primeList ]
main = print $ minimum [ dfs i [i] 1 | i <- [0 .. (length primeList) - 1] ] where
dfs :: Int -> [Int] -> Int -> Int -- cur, (p:ps), size, result
dfs _ ps 5 = score ps where
score = foldl (\s index -> s + primeArray!index) 0
dfs cur ps size = minimum $ maxBound : rec where
canAdd x ps = and [ (canCatArray!index)!x | index <- ps ]
rec = [ dfs next (next:ps) (size + 1) | next <- [0 .. cur-1], canAdd next ps ]
| foreverbell/project-euler-solutions | src/60.hs | bsd-3-clause | 940 | 0 | 13 | 243 | 478 | 251 | 227 | 15 | 2 |
atom :: (Delta d) => d
-> Env aam -> Store d aam -> Atom -> Set (Val d aam)
atom d _ _ (LitA l) = setSingleton $ lit d l
atom _ e s (Var x) = case mapLookup x e of
Nothing -> setEmpty
Just l -> mapLookup l s
atom d e s (Prim o a) = eachInSet (atom d e s a) $ \ v ->
case op d o v of
Nothing -> setEmpty
Just v' -> setSingleton v'
atom d e _ (Lam xs c) = setSingleton $ clo d xs c e
| davdar/quals | writeup-old/sections/03AAMByExample/03AbstractSemantics/00Atom.hs | bsd-3-clause | 402 | 0 | 12 | 120 | 238 | 114 | 124 | 11 | 3 |
-- Copyright 2019 Google LLC
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- https://developers.google.com/open-source/licenses/bsd
{-# LANGUAGE CPP #-}
-- | This module overloads some combinators so they can be used in
-- different contexts: for expressions, types and/or patterns.
module GHC.SourceGen.Overloaded
( Par(..)
, App(..)
, HasTuple(..)
, tuple
, unboxedTuple
, HasList(..)
, Var(..)
, BVar(..)
) where
import GHC.Hs.Type
( HsType(..)
, HsTyVarBndr(..)
)
import GHC.Hs (IE(..), IEWrappedName(..))
#if !MIN_VERSION_ghc(8,6,0)
import PlaceHolder(PlaceHolder(..))
#endif
import GHC.Hs
( HsExpr(..)
, Pat(..)
, HsTupArg(..)
, HsTupleSort(..)
)
#if MIN_VERSION_ghc(9,0,0)
import GHC.Types.Basic (Boxity(..))
import GHC.Core.DataCon (dataConName)
import GHC.Types.Name.Reader (nameRdrName)
import GHC.Builtin.Types (consDataCon_RDR, nilDataCon, unitDataCon)
import GHC.Types.Var (Specificity(..))
#else
import BasicTypes (Boxity(..))
import DataCon (dataConName)
import RdrName (nameRdrName)
import TysWiredIn (consDataCon_RDR, nilDataCon, unitDataCon)
#endif
import GHC.SourceGen.Expr.Internal
import GHC.SourceGen.Name.Internal
import GHC.SourceGen.Syntax.Internal
import GHC.SourceGen.Type.Internal
-- | A class for wrapping terms in parentheses.
class Par e where
par :: e -> e
instance Par HsExpr' where
par = withEpAnnNotUsed HsPar . mkLocated
instance Par Pat' where
par = withEpAnnNotUsed ParPat . builtPat
instance Par HsType' where
par = withEpAnnNotUsed HsParTy . mkLocated
-- | A class for term application.
--
-- These functions may add additional parentheses to the AST.
-- GHC's pretty-printing functions expect those parentheses
-- to already be present, because GHC preserves parentheses when it
-- parses the AST from a source file.
class App e where
-- | Prefix-apply a term:
--
-- > f x
-- > =====
-- > var "f" @@ var "x"
--
-- > (+) x
-- > =====
-- > var "+" @@ var "x"
--
-- Also parenthesizes the right-hand side in order to preserve its
-- semantics when pretty-printed, but tries to do so only when
-- necessary:
--
-- > f x y
-- > =====
-- > var "f" @@ var "x" @@ var "y"
-- > -- equivalently:
-- > (var "f" @@ var "x") @@ var "y"
--
-- > f (g x)
-- > =====
-- > var "f" @@ (var "g" @@ var "x")
--
-- > f (g x)
-- > =====
-- > var "f" @@ par (var "g" @@ par (var "x"))
(@@) :: e -> e -> e
-- | Infix-apply an operator or function.
--
-- For example:
--
-- > x + y
-- > =====
-- > op (var "x") "+" (var "y")
--
-- Also parenthesizes the right-hand side in order to preserve its
-- semantics when pretty-printed, but tries to do so only when necessary:
--
-- > f x + g y
-- > =====
-- > op (var "f" @@ var "x") "+" (var "g" @@ var "y")
--
-- > x + (y + z)
-- > =====
-- > op (var "x") "+" (op (var "y") "+" (var "z"))
--
-- > f x `plus` g y
-- > =====
-- > op (var "f" @@ var "x") "plus" (var "g" @@ var "y")
op :: e -> RdrNameStr -> e -> e
infixl 2 @@
instance App HsExpr' where
op x o y
= withEpAnnNotUsed OpApp
(parenthesizeExprForOp $ mkLocated x)
(mkLocated $ var o)
#if !MIN_VERSION_ghc(8,6,0)
PlaceHolder
#endif
(parenthesizeExprForOp $ mkLocated y)
x @@ y = withEpAnnNotUsed HsApp (parenthesizeExprForOp $ mkLocated x)
(parenthesizeExprForApp $ mkLocated y)
instance App HsType' where
op x o y
= noExt HsOpTy (parenthesizeTypeForOp $ mkLocated x)
(typeRdrName o)
(parenthesizeTypeForOp $ mkLocated y)
x @@ y = noExt HsAppTy
(parenthesizeTypeForOp $ mkLocated x)
(parenthesizeTypeForApp $ mkLocated y)
class HasTuple e where
unit :: e
tupleOf :: Boxity -> [e] -> e
tuple, unboxedTuple :: HasTuple e => [e] -> e
tuple = tupleOf Boxed
unboxedTuple = tupleOf Unboxed
instance HasTuple HsExpr' where
tupleOf b ts =
explicitTuple
(map (withEpAnnNotUsed Present . mkLocated) ts)
b
where
#if MIN_VERSION_ghc(9,2,0)
explicitTuple = withEpAnnNotUsed ExplicitTuple
#else
explicitTuple = noExt ExplicitTuple . map builtLoc
#endif
unit = noExt HsVar unitDataConName
unitDataConName :: LIdP
unitDataConName = mkLocated $ nameRdrName $ dataConName $ unitDataCon
instance HasTuple HsType' where
tupleOf b = withEpAnnNotUsed HsTupleTy b' . map mkLocated
where
b' = case b of
Unboxed -> HsUnboxedTuple
-- See the note [Unit tuples] in HsType.hs for why
-- this isn't just HsBoxed.
Boxed -> HsBoxedOrConstraintTuple
unit = tupleOf Boxed []
instance HasTuple Pat' where
tupleOf b ps =
withEpAnnNotUsed TuplePat (map builtPat ps) b
#if !MIN_VERSION_ghc(8,6,0)
[]
#endif
unit = noExt VarPat unitDataConName
-- | An explicit list of terms.
--
-- > [x, y]
-- > =====
-- > list [var "x", var "y"]
--
-- NOTE: for types, use either @listTy@ or @promotedListTy@.
class HasList e where
list :: [e] -> e
-- | The empty list @[]@.
nil :: e
-- | The list cons constructor @(:)@.
cons :: e
-- TODO: allow something like "consOp" which applies (:) as an operator, but using
-- the built-in RdrName.
nilDataConName :: LIdP
nilDataConName = mkLocated $ nameRdrName $ dataConName $ nilDataCon
instance HasList HsExpr' where
list = withPlaceHolder (withEpAnnNotUsed explicitList) . map mkLocated
where
#if MIN_VERSION_ghc(9,2,0)
explicitList = ExplicitList
#else
explicitList x = ExplicitList x Nothing
#endif
nil = noExt HsVar nilDataConName
cons = noExt HsVar $ mkLocated consDataCon_RDR
instance HasList Pat' where
#if MIN_VERSION_ghc(8,6,0)
list = withEpAnnNotUsed ListPat . map builtPat
#else
list ps = ListPat (map builtPat ps) PlaceHolder Nothing
#endif
nil = noExt VarPat nilDataConName
cons = noExt VarPat $ mkLocated $ consDataCon_RDR
-- | Terms that can contain references to locally-bound variables.
--
-- Depending on the context, @'bvar' \"a\"@ could refer to either a
-- pattern variable or a type variable.
class BVar a where
bvar :: OccNameStr -> a
-- | Terms that can contain references to named things. They may be actual variables,
-- functions, or constructors. For example, @'var' \"a\"@ and @'var' \"A\"@
-- are equally valid.
-- Depending on the context, the former could refer to either a function,
-- value, type variable, or pattern; and the latter could refer to either a type
-- constructor or a data constructor,
class BVar a => Var a where
var :: RdrNameStr -> a
instance BVar Pat' where
bvar = noExt VarPat . valueRdrName . UnqualStr
instance Var HsExpr' where
var = noExt HsVar . valueRdrName
instance BVar HsExpr' where
bvar = var . UnqualStr
instance Var HsType' where
var = withEpAnnNotUsed HsTyVar notPromoted . typeRdrName
instance BVar HsType' where
bvar = var . UnqualStr
#if MIN_VERSION_ghc(9,0,0)
instance BVar HsTyVarBndr' where
bvar = withEpAnnNotUsed UserTyVar () . typeRdrName . UnqualStr
instance BVar HsTyVarBndrS' where
bvar = withEpAnnNotUsed UserTyVar SpecifiedSpec . typeRdrName . UnqualStr
#else
instance BVar HsTyVarBndr' where
bvar = withEpAnnNotUsed UserTyVar . typeRdrName . UnqualStr
#endif
instance Var IE' where
var n = noExt IEVar $ mkLocated $ IEName $ exportRdrName n
instance BVar IE' where
bvar = var . UnqualStr
| google/ghc-source-gen | src/GHC/SourceGen/Overloaded.hs | bsd-3-clause | 7,754 | 0 | 11 | 1,948 | 1,340 | 771 | 569 | 118 | 1 |
{-# LANGUAGE DeriveDataTypeable, TypeSynonymInstances, CPP, ScopedTypeVariables, FlexibleInstances, GADTs #-}
{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}
-- hexpat, a Haskell wrapper for expat
-- Copyright (C) 2008 Evan Martin <martine@danga.com>
-- Copyright (C) 2009 Stephen Blackheath <http://blacksapphire.com/antispam>
-- | This module provides functions to parse an XML document to a lazy
-- stream of SAX events.
module Text.XML.Expat.SAX (
-- * XML primitives
Encoding(..),
XMLParseError(..),
XMLParseLocation(..),
-- * SAX-style parse
ParseOptions(..),
SAXEvent(..),
parse,
parseG,
parseLocations,
parseLocationsG,
parseLocationsThrowing,
parseThrowing,
defaultParseOptions,
-- * Variants that throw exceptions
XMLParseException(..),
-- * Abstraction of string types
GenericXMLString(..)
) where
import Control.Concurrent.MVar
import Control.Exception as Exc
import Text.XML.Expat.Internal.IO
import Data.Bits
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Internal as I
import Data.Int
import Data.ByteString.Internal (c2w, w2c, c_strlen)
import qualified Data.Monoid as M
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Codec.Binary.UTF8.String as U8
import Data.List.Class (List(..), ListItem(..), cons, fromList, mapL)
import Data.Typeable
import Data.Word
import Control.Applicative
import Control.DeepSeq
import Control.Monad
import System.IO.Unsafe
import Foreign.C
import Foreign.ForeignPtr
import Foreign.Marshal.Array
import Foreign.Ptr
import Foreign.Storable
data ParseOptions tag text = ParseOptions
{ overrideEncoding :: Maybe Encoding
-- ^ The encoding parameter, if provided, overrides the document's
-- encoding declaration.
, entityDecoder :: Maybe (tag -> Maybe text)
-- ^ If provided, entity references (i.e. @ @ and friends) will
-- be decoded into text using the supplied lookup function
}
defaultParseOptions :: ParseOptions tag text
defaultParseOptions = ParseOptions Nothing Nothing
-- | An abstraction for any string type you want to use as xml text (that is,
-- attribute values or element text content). If you want to use a
-- new string type with /hexpat/, you must make it an instance of
-- 'GenericXMLString'.
class (M.Monoid s, Eq s) => GenericXMLString s where
gxNullString :: s -> Bool
gxToString :: s -> String
gxFromString :: String -> s
gxFromChar :: Char -> s
gxHead :: s -> Char
gxTail :: s -> s
gxBreakOn :: Char -> s -> (s, s)
gxFromByteString :: B.ByteString -> s
gxToByteString :: s -> B.ByteString
instance GenericXMLString String where
gxNullString = null
gxToString = id
gxFromString = id
gxFromChar c = [c]
gxHead = head
gxTail = tail
gxBreakOn c = break (==c)
gxFromByteString = U8.decode . B.unpack
gxToByteString = B.pack . map c2w . U8.encodeString
instance GenericXMLString B.ByteString where
gxNullString = B.null
gxToString = U8.decodeString . map w2c . B.unpack
gxFromString = B.pack . map c2w . U8.encodeString
gxFromChar = B.singleton . c2w
gxHead = w2c . B.head
gxTail = B.tail
gxBreakOn c = B.break (== c2w c)
gxFromByteString = id
gxToByteString = id
instance GenericXMLString T.Text where
gxNullString = T.null
gxToString = T.unpack
gxFromString = T.pack
gxFromChar = T.singleton
gxHead = T.head
gxTail = T.tail
#if MIN_VERSION_text(0,11,0)
gxBreakOn c = T.break (==c)
#elif MIN_VERSION_text(0,10,0)
-- breakBy gets renamed to break between 0.10.0.0 and 0.10.0.1.
-- There's no 'break' function that is consistent between these two
-- versions so we work around it using other functions.
gxBreakOn c t = (T.takeWhile (/=c) t, T.dropWhile (/=c) t)
#else
gxBreakOn c = T.breakBy (==c)
#endif
gxFromByteString = TE.decodeUtf8
gxToByteString = TE.encodeUtf8
data SAXEvent tag text =
XMLDeclaration text (Maybe text) (Maybe Bool) |
StartElement tag [(tag, text)] |
EndElement tag |
CharacterData text |
StartCData |
EndCData |
ProcessingInstruction text text |
Comment text |
FailDocument XMLParseError
deriving (Eq, Show)
instance (NFData tag, NFData text) => NFData (SAXEvent tag text) where
rnf (XMLDeclaration ver mEnc mSD) = rnf ver `seq` rnf mEnc `seq` rnf mSD
rnf (StartElement tag atts) = rnf tag `seq` rnf atts
rnf (EndElement tag) = rnf tag
rnf (CharacterData text) = rnf text
rnf StartCData = ()
rnf EndCData = ()
rnf (ProcessingInstruction target text) = rnf target `seq` rnf text
rnf (Comment text) = rnf text
rnf (FailDocument err) = rnf err
-- | Parse a generalized list of ByteStrings containing XML to SAX events.
-- In the event of an error, FailDocument is the last element of the output list.
parseG :: forall tag text l . (GenericXMLString tag, GenericXMLString text, List l) =>
ParseOptions tag text -- ^ Parse options
-> l ByteString -- ^ Input text (a lazy ByteString)
-> l (SAXEvent tag text)
{-# NOINLINE parseG #-}
parseG opts inputBlocks = mapL (return . fst) $ parseImpl opts inputBlocks False noExtra failureA
where noExtra _ offset = return ((), offset)
failureA _ = return ()
-- | Parse a generalized list of ByteStrings containing XML to SAX events.
-- In the event of an error, FailDocument is the last element of the output list.
parseLocationsG :: forall tag text l . (GenericXMLString tag, GenericXMLString text, List l) =>
ParseOptions tag text -- ^ Parse options
-> l ByteString -- ^ Input text (a lazy ByteString)
-> l (SAXEvent tag text, XMLParseLocation)
{-# NOINLINE parseLocationsG #-}
parseLocationsG opts inputBlocks = parseImpl opts inputBlocks True fetchLocation id
where
fetchLocation pBuf offset = do
[a, b, c, d] <- peekArray 4 (pBuf `plusPtr` offset :: Ptr Int64)
return (XMLParseLocation a b c d, offset + 32)
parseImpl :: forall a tag text l . (GenericXMLString tag, GenericXMLString text, List l) =>
ParseOptions tag text -- ^ Parse options
-> l ByteString -- ^ Input text (a lazy ByteString)
-> Bool -- ^ True to add locations to binary output
-> (Ptr Word8 -> Int -> IO (a, Int)) -- ^ Fetch extra data
-> (IO XMLParseLocation -> IO a) -- ^ Fetch a value for failure case
-> l (SAXEvent tag text, a)
parseImpl opts inputBlocks addLocations extra failureA = runParser inputBlocks parse cacheRef
where
(parse, getLocation, cacheRef) = unsafePerformIO $ do
(parse, getLocation) <- hexpatNewParser
(overrideEncoding opts)
((\decode -> fmap gxToByteString . decode . gxFromByteString) <$> entityDecoder opts)
addLocations
cacheRef <- newMVar Nothing
return (parse, getLocation, cacheRef)
runParser iblks parse cacheRef = joinL $ do
li <- runList iblks
return $ unsafePerformIO $ do
mCached <- takeMVar cacheRef
case mCached of
Just l -> do
putMVar cacheRef mCached
return l
Nothing -> do
(saxen, rema) <- case li of
Nil -> do
(buf, len, mError) <- parse B.empty True
saxen <- parseBuf buf len extra
rema <- handleFailure mError mzero
return (saxen, rema)
Cons blk t -> {-unsafeInterleaveIO $-} do
(buf, len, mError) <- parse blk False
saxen <- parseBuf buf len extra
cacheRef' <- newMVar Nothing
rema <- handleFailure mError (runParser t parse cacheRef')
return (saxen, rema)
let l = fromList saxen `mplus` rema
putMVar cacheRef (Just l)
return l
where
handleFailure (Just err) _ = do a <- failureA getLocation
return $ (FailDocument err, a) `cons` mzero
handleFailure Nothing l = return l
parseBuf :: (GenericXMLString tag, GenericXMLString text) =>
ForeignPtr Word8 -> CInt -> (Ptr Word8 -> Int -> IO (a, Int)) -> IO [(SAXEvent tag text, a)]
parseBuf buf _ processExtra = withForeignPtr buf $ \pBuf -> doit [] pBuf 0
where
roundUp32 offset = (offset + 3) .&. complement 3
doit acc pBuf offset0 = offset0 `seq` do
typ <- peek (pBuf `plusPtr` offset0 :: Ptr Word32)
(a, offset) <- processExtra pBuf (offset0 + 4)
case typ of
0 -> return (reverse acc)
1 -> do
nAtts <- peek (pBuf `plusPtr` offset :: Ptr Word32)
let pName = pBuf `plusPtr` (offset + 4)
lName <- fromIntegral <$> c_strlen pName
let name = gxFromByteString $ I.fromForeignPtr buf (offset + 4) lName
(atts, offset') <- foldM (\(atts, offset) _ -> do
let pAtt = pBuf `plusPtr` offset
lAtt <- fromIntegral <$> c_strlen pAtt
let att = gxFromByteString $ I.fromForeignPtr buf offset lAtt
offset' = offset + lAtt + 1
pValue = pBuf `plusPtr` offset'
lValue <- fromIntegral <$> c_strlen pValue
let value = gxFromByteString $ I.fromForeignPtr buf offset' lValue
return ((att, value):atts, offset' + lValue + 1)
) ([], offset + 4 + lName + 1) [1,3..nAtts]
doit ((StartElement name (reverse atts), a) : acc) pBuf (roundUp32 offset')
2 -> do
let pName = pBuf `plusPtr` offset
lName <- fromIntegral <$> c_strlen pName
let name = gxFromByteString $ I.fromForeignPtr buf offset lName
offset' = offset + lName + 1
doit ((EndElement name, a) : acc) pBuf (roundUp32 offset')
3 -> do
len <- fromIntegral <$> peek (pBuf `plusPtr` offset :: Ptr Word32)
let text = gxFromByteString $ I.fromForeignPtr buf (offset + 4) len
offset' = offset + 4 + len
doit ((CharacterData text, a) : acc) pBuf (roundUp32 offset')
4 -> do
let pEnc = pBuf `plusPtr` offset
lEnc <- fromIntegral <$> c_strlen pEnc
let enc = gxFromByteString $ I.fromForeignPtr buf offset lEnc
offset' = offset + lEnc + 1
pVer = pBuf `plusPtr` offset'
pVerFirst <- peek (castPtr pVer :: Ptr Word8)
(mVer, offset'') <- case pVerFirst of
0 -> return (Nothing, offset' + 1)
1 -> do
lVer <- fromIntegral <$> c_strlen (pVer `plusPtr` 1)
return (Just $ gxFromByteString $ I.fromForeignPtr buf (offset' + 1) lVer, offset' + 1 + lVer + 1)
_ -> error "hexpat: bad data from C land"
cSta <- peek (pBuf `plusPtr` offset'' :: Ptr Int8)
let sta = if cSta < 0 then Nothing else
if cSta == 0 then Just False else
Just True
doit ((XMLDeclaration enc mVer sta, a) : acc) pBuf (roundUp32 (offset'' + 1))
5 -> doit ((StartCData, a) : acc) pBuf offset
6 -> doit ((EndCData, a) : acc) pBuf offset
7 -> do
let pTarget = pBuf `plusPtr` offset
lTarget <- fromIntegral <$> c_strlen pTarget
let target = gxFromByteString $ I.fromForeignPtr buf offset lTarget
offset' = offset + lTarget + 1
pData = pBuf `plusPtr` offset'
lData <- fromIntegral <$> c_strlen pData
let dat = gxFromByteString $ I.fromForeignPtr buf offset' lData
doit ((ProcessingInstruction target dat, a) : acc) pBuf (roundUp32 (offset' + lData + 1))
8 -> do
let pText = pBuf `plusPtr` offset
lText <- fromIntegral <$> c_strlen pText
let text = gxFromByteString $ I.fromForeignPtr buf offset lText
doit ((Comment text, a) : acc) pBuf (roundUp32 (offset + lText + 1))
_ -> error "hexpat: bad data from C land"
-- | Lazily parse XML to SAX events. In the event of an error, FailDocument is
-- the last element of the output list.
parse :: (GenericXMLString tag, GenericXMLString text) =>
ParseOptions tag text -- ^ Parse options
-> L.ByteString -- ^ Input text (a lazy ByteString)
-> [SAXEvent tag text]
parse opts input = parseG opts (L.toChunks input)
-- | An exception indicating an XML parse error, used by the /..Throwing/ variants.
data XMLParseException = XMLParseException XMLParseError
deriving (Eq, Show, Typeable)
instance Exception XMLParseException where
-- | A variant of parseSAX that gives a document location with each SAX event.
parseLocations :: (GenericXMLString tag, GenericXMLString text) =>
ParseOptions tag text -- ^ Parse options
-> L.ByteString -- ^ Input text (a lazy ByteString)
-> [(SAXEvent tag text, XMLParseLocation)]
parseLocations opts input = parseLocationsG opts (L.toChunks input)
-- | Lazily parse XML to SAX events. In the event of an error, throw
-- 'XMLParseException'.
--
-- @parseThrowing@ can throw an exception from pure code, which is generally a bad
-- way to handle errors, because Haskell\'s lazy evaluation means it\'s hard to
-- predict where it will be thrown from. However, it may be acceptable in
-- situations where it's not expected during normal operation, depending on the
-- design of your program.
parseThrowing :: (GenericXMLString tag, GenericXMLString text) =>
ParseOptions tag text -- ^ Parse options
-> L.ByteString -- ^ input text (a lazy ByteString)
-> [SAXEvent tag text]
parseThrowing opts bs = map freakOut $ parse opts bs
where
freakOut (FailDocument err) = Exc.throw $ XMLParseException err
freakOut other = other
-- | A variant of parseSAX that gives a document location with each SAX event.
-- In the event of an error, throw 'XMLParseException'.
--
-- @parseLocationsThrowing@ can throw an exception from pure code, which is generally a bad
-- way to handle errors, because Haskell\'s lazy evaluation means it\'s hard to
-- predict where it will be thrown from. However, it may be acceptable in
-- situations where it's not expected during normal operation, depending on the
-- design of your program.
parseLocationsThrowing :: (GenericXMLString tag, GenericXMLString text) =>
ParseOptions tag text -- ^ Optional encoding override
-> L.ByteString -- ^ Input text (a lazy ByteString)
-> [(SAXEvent tag text, XMLParseLocation)]
parseLocationsThrowing opts bs = map freakOut $ parseLocations opts bs
where
freakOut (FailDocument err, _) = Exc.throw $ XMLParseException err
freakOut other = other
| the-real-blackh/hexpat | Text/XML/Expat/SAX.hs | bsd-3-clause | 15,634 | 0 | 27 | 4,708 | 3,814 | 2,022 | 1,792 | 266 | 14 |
{-# LANGUAGE CPP, GADTs, NondecreasingIndentation #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE BangPatterns #-}
#if __GLASGOW_HASKELL__ <= 808
-- GHC 8.10 deprecates this flag, but GHC 8.8 needs it
-- The default iteration limit is a bit too low for the definitions
-- in this module.
{-# OPTIONS_GHC -fmax-pmcheck-iterations=10000000 #-}
#endif
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2004
--
-----------------------------------------------------------------------------
-- This is a big module, but, if you pay attention to
-- (a) the sectioning, and (b) the type signatures, the
-- structure should not be too overwhelming.
module X86.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
extractUnwindPoints,
invertCondBranches,
InstrBlock
)
where
#include "HsVersions.h"
-- NCG stuff:
import GhcPrelude
import X86.Instr
import X86.Cond
import X86.Regs
import X86.Ppr ( )
import X86.RegInfo
import GHC.Platform.Regs
import CPrim
import GHC.Cmm.DebugBlock ( DebugBlock(..), UnwindPoint(..), UnwindTable
, UnwindExpr(UwReg), toUnwindExpr )
import Instruction
import PIC
import NCGMonad ( NatM, getNewRegNat, getNewLabelNat, setDeltaNat
, getDeltaNat, getBlockIdNat, getPicBaseNat, getNewRegPairNat
, getPicBaseMaybeNat, getDebugBlock, getFileId
, addImmediateSuccessorNat, updateCfgNat)
import CFG
import Format
import Reg
import GHC.Platform
-- Our intermediate code:
import BasicTypes
import GHC.Cmm.BlockId
import Module ( primUnitId )
import GHC.Cmm.Utils
import GHC.Cmm.Switch
import GHC.Cmm
import GHC.Cmm.Dataflow.Block
import GHC.Cmm.Dataflow.Collections
import GHC.Cmm.Dataflow.Graph
import GHC.Cmm.Dataflow.Label
import GHC.Cmm.CLabel
import CoreSyn ( Tickish(..) )
import SrcLoc ( srcSpanFile, srcSpanStartLine, srcSpanStartCol )
-- The rest:
import ForeignCall ( CCallConv(..) )
import OrdList
import Outputable
import FastString
import DynFlags
import Util
import UniqSupply ( getUniqueM )
import Control.Monad
import Data.Bits
import Data.Foldable (fold)
import Data.Int
import Data.Maybe
import Data.Word
import qualified Data.Map as M
is32BitPlatform :: NatM Bool
is32BitPlatform = do
dflags <- getDynFlags
return $ target32Bit (targetPlatform dflags)
sse2Enabled :: NatM Bool
sse2Enabled = do
dflags <- getDynFlags
case platformArch (targetPlatform dflags) of
-- We Assume SSE1 and SSE2 operations are available on both
-- x86 and x86_64. Historically we didn't default to SSE2 and
-- SSE1 on x86, which results in defacto nondeterminism for how
-- rounding behaves in the associated x87 floating point instructions
-- because variations in the spill/fpu stack placement of arguments for
-- operations would change the precision and final result of what
-- would otherwise be the same expressions with respect to single or
-- double precision IEEE floating point computations.
ArchX86_64 -> return True
ArchX86 -> return True
_ -> panic "trying to generate x86/x86_64 on the wrong platform"
sse4_2Enabled :: NatM Bool
sse4_2Enabled = do
dflags <- getDynFlags
return (isSse4_2Enabled dflags)
cmmTopCodeGen
:: RawCmmDecl
-> NatM [NatCmmDecl (Alignment, RawCmmStatics) Instr]
cmmTopCodeGen (CmmProc info lab live graph) = do
let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
picBaseMb <- getPicBaseMaybeNat
dflags <- getDynFlags
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
tops = proc : concat statics
os = platformOS $ targetPlatform dflags
case picBaseMb of
Just picBase -> initializePicBase_x86 ArchX86 os picBase tops
Nothing -> return tops
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec (mkAlignment 1, dat)] -- no translation, we just use CmmStatic
{- Note [Verifying basic blocks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want to guarantee a few things about the results
of instruction selection.
Namely that each basic blocks consists of:
* A (potentially empty) sequence of straight line instructions
followed by
* A (potentially empty) sequence of jump like instructions.
We can verify this by going through the instructions and
making sure that any non-jumpish instruction can't appear
after a jumpish instruction.
There are gotchas however:
* CALLs are strictly speaking control flow but here we care
not about them. Hence we treat them as regular instructions.
It's safe for them to appear inside a basic block
as (ignoring side effects inside the call) they will result in
straight line code.
* NEWBLOCK marks the start of a new basic block so can
be followed by any instructions.
-}
-- Verifying basic blocks is cheap, but not cheap enough to enable it unconditionally.
verifyBasicBlock :: [Instr] -> ()
verifyBasicBlock instrs
| debugIsOn = go False instrs
| otherwise = ()
where
go _ [] = ()
go atEnd (i:instr)
= case i of
-- Start a new basic block
NEWBLOCK {} -> go False instr
-- Calls are not viable block terminators
CALL {} | atEnd -> faultyBlockWith i
| not atEnd -> go atEnd instr
-- All instructions ok, check if we reached the end and continue.
_ | not atEnd -> go (isJumpishInstr i) instr
-- Only jumps allowed at the end of basic blocks.
| otherwise -> if isJumpishInstr i
then go True instr
else faultyBlockWith i
faultyBlockWith i
= pprPanic "Non control flow instructions after end of basic block."
(ppr i <+> text "in:" $$ vcat (map ppr instrs))
basicBlockCodeGen
:: CmmBlock
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl (Alignment, RawCmmStatics) Instr])
basicBlockCodeGen block = do
let (_, nodes, tail) = blockSplit block
id = entryLabel block
stmts = blockToList nodes
-- Generate location directive
dbg <- getDebugBlock (entryLabel block)
loc_instrs <- case dblSourceTick =<< dbg of
Just (SourceNote span name)
-> do fileId <- getFileId (srcSpanFile span)
let line = srcSpanStartLine span; col = srcSpanStartCol span
return $ unitOL $ LOCATION fileId line col name
_ -> return nilOL
(mid_instrs,mid_bid) <- stmtsToInstrs id stmts
(!tail_instrs,_) <- stmtToInstrs mid_bid tail
let instrs = loc_instrs `appOL` mid_instrs `appOL` tail_instrs
return $! verifyBasicBlock (fromOL instrs)
instrs' <- fold <$> traverse addSpUnwindings instrs
-- code generation may introduce new basic block boundaries, which
-- are indicated by the NEWBLOCK instruction. We must split up the
-- instruction stream into basic blocks again. Also, we extract
-- LDATAs here too.
let
(top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs'
mkBlocks (NEWBLOCK id) (instrs,blocks,statics)
= ([], BasicBlock id instrs : blocks, statics)
mkBlocks (LDATA sec dat) (instrs,blocks,statics)
= (instrs, blocks, CmmData sec dat:statics)
mkBlocks instr (instrs,blocks,statics)
= (instr:instrs, blocks, statics)
return (BasicBlock id top : other_blocks, statics)
-- | Convert 'DELTA' instructions into 'UNWIND' instructions to capture changes
-- in the @sp@ register. See Note [What is this unwinding business?] in Debug
-- for details.
addSpUnwindings :: Instr -> NatM (OrdList Instr)
addSpUnwindings instr@(DELTA d) = do
dflags <- getDynFlags
if debugLevel dflags >= 1
then do lbl <- mkAsmTempLabel <$> getUniqueM
let unwind = M.singleton MachSp (Just $ UwReg MachSp $ negate d)
return $ toOL [ instr, UNWIND lbl unwind ]
else return (unitOL instr)
addSpUnwindings instr = return $ unitOL instr
{- Note [Keeping track of the current block]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When generating instructions for Cmm we sometimes require
the current block for things like retry loops.
We also sometimes change the current block, if a MachOP
results in branching control flow.
Issues arise if we have two statements in the same block,
which both depend on the current block id *and* change the
basic block after them. This happens for atomic primops
in the X86 backend where we want to update the CFG data structure
when introducing new basic blocks.
For example in #17334 we got this Cmm code:
c3Bf: // global
(_s3t1::I64) = call MO_AtomicRMW W64 AMO_And(_s3sQ::P64 + 88, 18);
(_s3t4::I64) = call MO_AtomicRMW W64 AMO_Or(_s3sQ::P64 + 88, 0);
_s3sT::I64 = _s3sV::I64;
goto c3B1;
This resulted in two new basic blocks being inserted:
c3Bf:
movl $18,%vI_n3Bo
movq 88(%vI_s3sQ),%rax
jmp _n3Bp
n3Bp:
...
cmpxchgq %vI_n3Bq,88(%vI_s3sQ)
jne _n3Bp
...
jmp _n3Bs
n3Bs:
...
cmpxchgq %vI_n3Bt,88(%vI_s3sQ)
jne _n3Bs
...
jmp _c3B1
...
Based on the Cmm we called stmtToInstrs we translated both atomic operations under
the assumption they would be placed into their Cmm basic block `c3Bf`.
However for the retry loop we introduce new labels, so this is not the case
for the second statement.
This resulted in a desync between the explicit control flow graph
we construct as a separate data type and the actual control flow graph in the code.
Instead we now return the new basic block if a statement causes a change
in the current block and use the block for all following statements.
For this reason genCCall is also split into two parts.
One for calls which *won't* change the basic blocks in
which successive instructions will be placed.
A different one for calls which *are* known to change the
basic block.
-}
-- See Note [Keeping track of the current block] for why
-- we pass the BlockId.
stmtsToInstrs :: BlockId -- ^ Basic block these statement will start to be placed in.
-> [CmmNode O O] -- ^ Cmm Statement
-> NatM (InstrBlock, BlockId) -- ^ Resulting instruction
stmtsToInstrs bid stmts =
go bid stmts nilOL
where
go bid [] instrs = return (instrs,bid)
go bid (s:stmts) instrs = do
(instrs',bid') <- stmtToInstrs bid s
-- If the statement introduced a new block, we use that one
let !newBid = fromMaybe bid bid'
go newBid stmts (instrs `appOL` instrs')
-- | `bid` refers to the current block and is used to update the CFG
-- if new blocks are inserted in the control flow.
-- See Note [Keeping track of the current block] for more details.
stmtToInstrs :: BlockId -- ^ Basic block this statement will start to be placed in.
-> CmmNode e x
-> NatM (InstrBlock, Maybe BlockId)
-- ^ Instructions, and bid of new block if successive
-- statements are placed in a different basic block.
stmtToInstrs bid stmt = do
dflags <- getDynFlags
is32Bit <- is32BitPlatform
case stmt of
CmmUnsafeForeignCall target result_regs args
-> genCCall dflags is32Bit target result_regs args bid
_ -> (,Nothing) <$> case stmt of
CmmComment s -> return (unitOL (COMMENT s))
CmmTick {} -> return nilOL
CmmUnwind regs -> do
let to_unwind_entry :: (GlobalReg, Maybe CmmExpr) -> UnwindTable
to_unwind_entry (reg, expr) = M.singleton reg (fmap toUnwindExpr expr)
case foldMap to_unwind_entry regs of
tbl | M.null tbl -> return nilOL
| otherwise -> do
lbl <- mkAsmTempLabel <$> getUniqueM
return $ unitOL $ UNWIND lbl tbl
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode format reg src
| is32Bit && isWord64 ty -> assignReg_I64Code reg src
| otherwise -> assignReg_IntCode format reg src
where ty = cmmRegType dflags reg
format = cmmTypeFormat ty
CmmStore addr src
| isFloatType ty -> assignMem_FltCode format addr src
| is32Bit && isWord64 ty -> assignMem_I64Code addr src
| otherwise -> assignMem_IntCode format addr src
where ty = cmmExprType dflags src
format = cmmTypeFormat ty
CmmBranch id -> return $ genBranch id
--We try to arrange blocks such that the likely branch is the fallthrough
--in GHC.Cmm.ContFlowOpt. So we can assume the condition is likely false here.
CmmCondBranch arg true false _ -> genCondBranch bid true false arg
CmmSwitch arg ids -> do dflags <- getDynFlags
genSwitch dflags arg ids
CmmCall { cml_target = arg
, cml_args_regs = gregs } -> do
dflags <- getDynFlags
genJump arg (jumpRegs dflags gregs)
_ ->
panic "stmtToInstrs: statement should have been cps'd away"
jumpRegs :: DynFlags -> [GlobalReg] -> [Reg]
jumpRegs dflags gregs = [ RegReal r | Just r <- map (globalRegMaybe platform) gregs ]
where platform = targetPlatform dflags
--------------------------------------------------------------------------------
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal yields the insns in the correct order.
--
type InstrBlock
= OrdList Instr
-- | Condition codes passed up the tree.
--
data CondCode
= CondCode Bool Cond InstrBlock
-- | a.k.a "Register64"
-- Reg is the lower 32-bit temporary which contains the result.
-- Use getHiVRegFromLo to find the other VRegUnique.
--
-- Rules of this simplified insn selection game are therefore that
-- the returned Reg may be modified
--
data ChildCode64
= ChildCode64
InstrBlock
Reg
-- | Register's passed up the tree. If the stix code forces the register
-- to live in a pre-decided machine register, it comes out as @Fixed@;
-- otherwise, it comes out as @Any@, and the parent can decide which
-- register to put it in.
--
data Register
= Fixed Format Reg InstrBlock
| Any Format (Reg -> InstrBlock)
swizzleRegisterRep :: Register -> Format -> Register
swizzleRegisterRep (Fixed _ reg code) format = Fixed format reg code
swizzleRegisterRep (Any _ codefn) format = Any format codefn
-- | Grab the Reg for a CmmReg
getRegisterReg :: Platform -> CmmReg -> Reg
getRegisterReg _ (CmmLocal (LocalReg u pk))
= -- by Assuming SSE2, Int,Word,Float,Double all can be register allocated
let fmt = cmmTypeFormat pk in
RegVirtual (mkVirtualReg u fmt)
getRegisterReg platform (CmmGlobal mid)
= case globalRegMaybe platform mid of
Just reg -> RegReal $ reg
Nothing -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid)
-- By this stage, the only MagicIds remaining should be the
-- ones which map to a real machine register on this
-- platform. Hence ...
-- | Memory addressing modes passed up the tree.
data Amode
= Amode AddrMode InstrBlock
{-
Now, given a tree (the argument to a CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
-- | Check whether an integer will fit in 32 bits.
-- A CmmInt is intended to be truncated to the appropriate
-- number of bits, so here we truncate it to Int64. This is
-- important because e.g. -1 as a CmmInt might be either
-- -1 or 18446744073709551615.
--
is32BitInteger :: Integer -> Bool
is32BitInteger i = i64 <= 0x7fffffff && i64 >= -0x80000000
where i64 = fromIntegral i :: Int64
-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic
jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel)
where blockLabel = blockLbl blockid
-- -----------------------------------------------------------------------------
-- General things for putting together code sequences
-- Expand CmmRegOff. ToDo: should we do it this way around, or convert
-- CmmExprs into CmmRegOff?
mangleIndexTree :: DynFlags -> CmmReg -> Int -> CmmExpr
mangleIndexTree dflags reg off
= CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)]
where width = typeWidth (cmmRegType dflags reg)
-- | The dual to getAnyReg: compute an expression into a register, but
-- we don't mind which one it is.
getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock)
getSomeReg expr = do
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed _ reg code ->
return (reg, code)
assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_I64Code addrTree valueTree = do
Amode addr addr_code <- getAmode addrTree
ChildCode64 vcode rlo <- iselExpr64 valueTree
let
rhi = getHiVRegFromLo rlo
-- Little-endian store
mov_lo = MOV II32 (OpReg rlo) (OpAddr addr)
mov_hi = MOV II32 (OpReg rhi) (OpAddr (fromJust (addrOffset addr 4)))
return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
assignReg_I64Code :: CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_I64Code (CmmLocal (LocalReg u_dst _)) valueTree = do
ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
let
r_dst_lo = RegVirtual $ mkVirtualReg u_dst II32
r_dst_hi = getHiVRegFromLo r_dst_lo
r_src_hi = getHiVRegFromLo r_src_lo
mov_lo = MOV II32 (OpReg r_src_lo) (OpReg r_dst_lo)
mov_hi = MOV II32 (OpReg r_src_hi) (OpReg r_dst_hi)
return (
vcode `snocOL` mov_lo `snocOL` mov_hi
)
assignReg_I64Code _ _
= panic "assignReg_I64Code(i386): invalid lvalue"
iselExpr64 :: CmmExpr -> NatM ChildCode64
iselExpr64 (CmmLit (CmmInt i _)) = do
(rlo,rhi) <- getNewRegPairNat II32
let
r = fromIntegral (fromIntegral i :: Word32)
q = fromIntegral (fromIntegral (i `shiftR` 32) :: Word32)
code = toOL [
MOV II32 (OpImm (ImmInteger r)) (OpReg rlo),
MOV II32 (OpImm (ImmInteger q)) (OpReg rhi)
]
return (ChildCode64 code rlo)
iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do
Amode addr addr_code <- getAmode addrTree
(rlo,rhi) <- getNewRegPairNat II32
let
mov_lo = MOV II32 (OpAddr addr) (OpReg rlo)
mov_hi = MOV II32 (OpAddr (fromJust (addrOffset addr 4))) (OpReg rhi)
return (
ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
)
iselExpr64 (CmmReg (CmmLocal (LocalReg vu ty))) | isWord64 ty
= return (ChildCode64 nilOL (RegVirtual $ mkVirtualReg vu II32))
-- we handle addition, but rather badly
iselExpr64 (CmmMachOp (MO_Add _) [e1, CmmLit (CmmInt i _)]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
(rlo,rhi) <- getNewRegPairNat II32
let
r = fromIntegral (fromIntegral i :: Word32)
q = fromIntegral (fromIntegral (i `shiftR` 32) :: Word32)
r1hi = getHiVRegFromLo r1lo
code = code1 `appOL`
toOL [ MOV II32 (OpReg r1lo) (OpReg rlo),
ADD II32 (OpImm (ImmInteger r)) (OpReg rlo),
MOV II32 (OpReg r1hi) (OpReg rhi),
ADC II32 (OpImm (ImmInteger q)) (OpReg rhi) ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ MOV II32 (OpReg r1lo) (OpReg rlo),
ADD II32 (OpReg r2lo) (OpReg rlo),
MOV II32 (OpReg r1hi) (OpReg rhi),
ADC II32 (OpReg r2hi) (OpReg rhi) ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Sub _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ MOV II32 (OpReg r1lo) (OpReg rlo),
SUB II32 (OpReg r2lo) (OpReg rlo),
MOV II32 (OpReg r1hi) (OpReg rhi),
SBB II32 (OpReg r2hi) (OpReg rhi) ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_UU_Conv _ W64) [expr]) = do
fn <- getAnyReg expr
r_dst_lo <- getNewRegNat II32
let r_dst_hi = getHiVRegFromLo r_dst_lo
code = fn r_dst_lo
return (
ChildCode64 (code `snocOL`
MOV II32 (OpImm (ImmInt 0)) (OpReg r_dst_hi))
r_dst_lo
)
iselExpr64 (CmmMachOp (MO_SS_Conv W32 W64) [expr]) = do
fn <- getAnyReg expr
r_dst_lo <- getNewRegNat II32
let r_dst_hi = getHiVRegFromLo r_dst_lo
code = fn r_dst_lo
return (
ChildCode64 (code `snocOL`
MOV II32 (OpReg r_dst_lo) (OpReg eax) `snocOL`
CLTD II32 `snocOL`
MOV II32 (OpReg eax) (OpReg r_dst_lo) `snocOL`
MOV II32 (OpReg edx) (OpReg r_dst_hi))
r_dst_lo
)
iselExpr64 expr
= pprPanic "iselExpr64(i386)" (ppr expr)
--------------------------------------------------------------------------------
getRegister :: CmmExpr -> NatM Register
getRegister e = do dflags <- getDynFlags
is32Bit <- is32BitPlatform
getRegister' dflags is32Bit e
getRegister' :: DynFlags -> Bool -> CmmExpr -> NatM Register
getRegister' dflags is32Bit (CmmReg reg)
= case reg of
CmmGlobal PicBaseReg
| is32Bit ->
-- on x86_64, we have %rip for PicBaseReg, but it's not
-- a full-featured register, it can only be used for
-- rip-relative addressing.
do reg' <- getPicBaseNat (archWordFormat is32Bit)
return (Fixed (archWordFormat is32Bit) reg' nilOL)
_ ->
do
let
fmt = cmmTypeFormat (cmmRegType dflags reg)
format = fmt
--
let platform = targetPlatform dflags
return (Fixed format
(getRegisterReg platform reg)
nilOL)
getRegister' dflags is32Bit (CmmRegOff r n)
= getRegister' dflags is32Bit $ mangleIndexTree dflags r n
getRegister' dflags is32Bit (CmmMachOp (MO_AlignmentCheck align _) [e])
= addAlignmentCheck align <$> getRegister' dflags is32Bit e
-- for 32-bit architectures, support some 64 -> 32 bit conversions:
-- TO_W_(x), TO_W_(x >> 32)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W64 W32) [x])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W64 W32) [x])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' _ _ (CmmLit lit@(CmmFloat f w)) =
float_const_sse2 where
float_const_sse2
| f == 0.0 = do
let
format = floatFormat w
code dst = unitOL (XOR format (OpReg dst) (OpReg dst))
-- I don't know why there are xorpd, xorps, and pxor instructions.
-- They all appear to do the same thing --SDM
return (Any format code)
| otherwise = do
Amode addr code <- memConstant (mkAlignment $ widthInBytes w) lit
loadFloatAmode w addr code
-- catch simple cases of zero- or sign-extended load
getRegister' _ _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVZxL II8) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_SS_Conv W8 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVSxL II8) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVZxL II16) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVSxL II16) addr
return (Any II32 code)
-- catch simple cases of zero- or sign-extended load
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVZxL II8) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W8 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II8) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVZxL II16) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II16) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOV II32) addr -- 32-bit loads zero-extend
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II32) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg),
CmmLit displacement])
| not is32Bit = do
return $ Any II64 (\dst -> unitOL $
LEA II64 (OpAddr (ripRel (litToImm displacement))) (OpReg dst))
getRegister' dflags is32Bit (CmmMachOp mop [x]) = do -- unary MachOps
case mop of
MO_F_Neg w -> sse2NegCode w x
MO_S_Neg w -> triv_ucode NEGI (intFormat w)
MO_Not w -> triv_ucode NOT (intFormat w)
-- Nop conversions
MO_UU_Conv W32 W8 -> toI8Reg W32 x
MO_SS_Conv W32 W8 -> toI8Reg W32 x
MO_XX_Conv W32 W8 -> toI8Reg W32 x
MO_UU_Conv W16 W8 -> toI8Reg W16 x
MO_SS_Conv W16 W8 -> toI8Reg W16 x
MO_XX_Conv W16 W8 -> toI8Reg W16 x
MO_UU_Conv W32 W16 -> toI16Reg W32 x
MO_SS_Conv W32 W16 -> toI16Reg W32 x
MO_XX_Conv W32 W16 -> toI16Reg W32 x
MO_UU_Conv W64 W32 | not is32Bit -> conversionNop II64 x
MO_SS_Conv W64 W32 | not is32Bit -> conversionNop II64 x
MO_XX_Conv W64 W32 | not is32Bit -> conversionNop II64 x
MO_UU_Conv W64 W16 | not is32Bit -> toI16Reg W64 x
MO_SS_Conv W64 W16 | not is32Bit -> toI16Reg W64 x
MO_XX_Conv W64 W16 | not is32Bit -> toI16Reg W64 x
MO_UU_Conv W64 W8 | not is32Bit -> toI8Reg W64 x
MO_SS_Conv W64 W8 | not is32Bit -> toI8Reg W64 x
MO_XX_Conv W64 W8 | not is32Bit -> toI8Reg W64 x
MO_UU_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intFormat rep1) x
MO_SS_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intFormat rep1) x
MO_XX_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intFormat rep1) x
-- widenings
MO_UU_Conv W8 W32 -> integerExtend W8 W32 MOVZxL x
MO_UU_Conv W16 W32 -> integerExtend W16 W32 MOVZxL x
MO_UU_Conv W8 W16 -> integerExtend W8 W16 MOVZxL x
MO_SS_Conv W8 W32 -> integerExtend W8 W32 MOVSxL x
MO_SS_Conv W16 W32 -> integerExtend W16 W32 MOVSxL x
MO_SS_Conv W8 W16 -> integerExtend W8 W16 MOVSxL x
-- We don't care about the upper bits for MO_XX_Conv, so MOV is enough. However, on 32-bit we
-- have 8-bit registers only for a few registers (as opposed to x86-64 where every register
-- has 8-bit version). So for 32-bit code, we'll just zero-extend.
MO_XX_Conv W8 W32
| is32Bit -> integerExtend W8 W32 MOVZxL x
| otherwise -> integerExtend W8 W32 MOV x
MO_XX_Conv W8 W16
| is32Bit -> integerExtend W8 W16 MOVZxL x
| otherwise -> integerExtend W8 W16 MOV x
MO_XX_Conv W16 W32 -> integerExtend W16 W32 MOV x
MO_UU_Conv W8 W64 | not is32Bit -> integerExtend W8 W64 MOVZxL x
MO_UU_Conv W16 W64 | not is32Bit -> integerExtend W16 W64 MOVZxL x
MO_UU_Conv W32 W64 | not is32Bit -> integerExtend W32 W64 MOVZxL x
MO_SS_Conv W8 W64 | not is32Bit -> integerExtend W8 W64 MOVSxL x
MO_SS_Conv W16 W64 | not is32Bit -> integerExtend W16 W64 MOVSxL x
MO_SS_Conv W32 W64 | not is32Bit -> integerExtend W32 W64 MOVSxL x
-- For 32-to-64 bit zero extension, amd64 uses an ordinary movl.
-- However, we don't want the register allocator to throw it
-- away as an unnecessary reg-to-reg move, so we keep it in
-- the form of a movzl and print it as a movl later.
-- This doesn't apply to MO_XX_Conv since in this case we don't care about
-- the upper bits. So we can just use MOV.
MO_XX_Conv W8 W64 | not is32Bit -> integerExtend W8 W64 MOV x
MO_XX_Conv W16 W64 | not is32Bit -> integerExtend W16 W64 MOV x
MO_XX_Conv W32 W64 | not is32Bit -> integerExtend W32 W64 MOV x
MO_FF_Conv W32 W64 -> coerceFP2FP W64 x
MO_FF_Conv W64 W32 -> coerceFP2FP W32 x
MO_FS_Conv from to -> coerceFP2Int from to x
MO_SF_Conv from to -> coerceInt2FP from to x
MO_V_Insert {} -> needLlvm
MO_V_Extract {} -> needLlvm
MO_V_Add {} -> needLlvm
MO_V_Sub {} -> needLlvm
MO_V_Mul {} -> needLlvm
MO_VS_Quot {} -> needLlvm
MO_VS_Rem {} -> needLlvm
MO_VS_Neg {} -> needLlvm
MO_VU_Quot {} -> needLlvm
MO_VU_Rem {} -> needLlvm
MO_VF_Insert {} -> needLlvm
MO_VF_Extract {} -> needLlvm
MO_VF_Add {} -> needLlvm
MO_VF_Sub {} -> needLlvm
MO_VF_Mul {} -> needLlvm
MO_VF_Quot {} -> needLlvm
MO_VF_Neg {} -> needLlvm
_other -> pprPanic "getRegister" (pprMachOp mop)
where
triv_ucode :: (Format -> Operand -> Instr) -> Format -> NatM Register
triv_ucode instr format = trivialUCode format (instr format) x
-- signed or unsigned extension.
integerExtend :: Width -> Width
-> (Format -> Operand -> Operand -> Instr)
-> CmmExpr -> NatM Register
integerExtend from to instr expr = do
(reg,e_code) <- if from == W8 then getByteReg expr
else getSomeReg expr
let
code dst =
e_code `snocOL`
instr (intFormat from) (OpReg reg) (OpReg dst)
return (Any (intFormat to) code)
toI8Reg :: Width -> CmmExpr -> NatM Register
toI8Reg new_rep expr
= do codefn <- getAnyReg expr
return (Any (intFormat new_rep) codefn)
-- HACK: use getAnyReg to get a byte-addressable register.
-- If the source was a Fixed register, this will add the
-- mov instruction to put it into the desired destination.
-- We're assuming that the destination won't be a fixed
-- non-byte-addressable register; it won't be, because all
-- fixed registers are word-sized.
toI16Reg = toI8Reg -- for now
conversionNop :: Format -> CmmExpr -> NatM Register
conversionNop new_format expr
= do e_code <- getRegister' dflags is32Bit expr
return (swizzleRegisterRep e_code new_format)
getRegister' _ is32Bit (CmmMachOp mop [x, y]) = do -- dyadic MachOps
case mop of
MO_F_Eq _ -> condFltReg is32Bit EQQ x y
MO_F_Ne _ -> condFltReg is32Bit NE x y
MO_F_Gt _ -> condFltReg is32Bit GTT x y
MO_F_Ge _ -> condFltReg is32Bit GE x y
-- Invert comparison condition and swap operands
-- See Note [SSE Parity Checks]
MO_F_Lt _ -> condFltReg is32Bit GTT y x
MO_F_Le _ -> condFltReg is32Bit GE y x
MO_Eq _ -> condIntReg EQQ x y
MO_Ne _ -> condIntReg NE x y
MO_S_Gt _ -> condIntReg GTT x y
MO_S_Ge _ -> condIntReg GE x y
MO_S_Lt _ -> condIntReg LTT x y
MO_S_Le _ -> condIntReg LE x y
MO_U_Gt _ -> condIntReg GU x y
MO_U_Ge _ -> condIntReg GEU x y
MO_U_Lt _ -> condIntReg LU x y
MO_U_Le _ -> condIntReg LEU x y
MO_F_Add w -> trivialFCode_sse2 w ADD x y
MO_F_Sub w -> trivialFCode_sse2 w SUB x y
MO_F_Quot w -> trivialFCode_sse2 w FDIV x y
MO_F_Mul w -> trivialFCode_sse2 w MUL x y
MO_Add rep -> add_code rep x y
MO_Sub rep -> sub_code rep x y
MO_S_Quot rep -> div_code rep True True x y
MO_S_Rem rep -> div_code rep True False x y
MO_U_Quot rep -> div_code rep False True x y
MO_U_Rem rep -> div_code rep False False x y
MO_S_MulMayOflo rep -> imulMayOflo rep x y
MO_Mul W8 -> imulW8 x y
MO_Mul rep -> triv_op rep IMUL
MO_And rep -> triv_op rep AND
MO_Or rep -> triv_op rep OR
MO_Xor rep -> triv_op rep XOR
{- Shift ops on x86s have constraints on their source, it
either has to be Imm, CL or 1
=> trivialCode is not restrictive enough (sigh.)
-}
MO_Shl rep -> shift_code rep SHL x y {-False-}
MO_U_Shr rep -> shift_code rep SHR x y {-False-}
MO_S_Shr rep -> shift_code rep SAR x y {-False-}
MO_V_Insert {} -> needLlvm
MO_V_Extract {} -> needLlvm
MO_V_Add {} -> needLlvm
MO_V_Sub {} -> needLlvm
MO_V_Mul {} -> needLlvm
MO_VS_Quot {} -> needLlvm
MO_VS_Rem {} -> needLlvm
MO_VS_Neg {} -> needLlvm
MO_VF_Insert {} -> needLlvm
MO_VF_Extract {} -> needLlvm
MO_VF_Add {} -> needLlvm
MO_VF_Sub {} -> needLlvm
MO_VF_Mul {} -> needLlvm
MO_VF_Quot {} -> needLlvm
MO_VF_Neg {} -> needLlvm
_other -> pprPanic "getRegister(x86) - binary CmmMachOp (1)" (pprMachOp mop)
where
--------------------
triv_op width instr = trivialCode width op (Just op) x y
where op = instr (intFormat width)
-- Special case for IMUL for bytes, since the result of IMULB will be in
-- %ax, the split to %dx/%edx/%rdx and %ax/%eax/%rax happens only for wider
-- values.
imulW8 :: CmmExpr -> CmmExpr -> NatM Register
imulW8 arg_a arg_b = do
(a_reg, a_code) <- getNonClobberedReg arg_a
b_code <- getAnyReg arg_b
let code = a_code `appOL` b_code eax `appOL`
toOL [ IMUL2 format (OpReg a_reg) ]
format = intFormat W8
return (Fixed format eax code)
imulMayOflo :: Width -> CmmExpr -> CmmExpr -> NatM Register
imulMayOflo rep a b = do
(a_reg, a_code) <- getNonClobberedReg a
b_code <- getAnyReg b
let
shift_amt = case rep of
W32 -> 31
W64 -> 63
_ -> panic "shift_amt"
format = intFormat rep
code = a_code `appOL` b_code eax `appOL`
toOL [
IMUL2 format (OpReg a_reg), -- result in %edx:%eax
SAR format (OpImm (ImmInt shift_amt)) (OpReg eax),
-- sign extend lower part
SUB format (OpReg edx) (OpReg eax)
-- compare against upper
-- eax==0 if high part == sign extended low part
]
return (Fixed format eax code)
--------------------
shift_code :: Width
-> (Format -> Operand -> Operand -> Instr)
-> CmmExpr
-> CmmExpr
-> NatM Register
{- Case1: shift length as immediate -}
shift_code width instr x (CmmLit lit) = do
x_code <- getAnyReg x
let
format = intFormat width
code dst
= x_code dst `snocOL`
instr format (OpImm (litToImm lit)) (OpReg dst)
return (Any format code)
{- Case2: shift length is complex (non-immediate)
* y must go in %ecx.
* we cannot do y first *and* put its result in %ecx, because
%ecx might be clobbered by x.
* if we do y second, then x cannot be
in a clobbered reg. Also, we cannot clobber x's reg
with the instruction itself.
* so we can either:
- do y first, put its result in a fresh tmp, then copy it to %ecx later
- do y second and put its result into %ecx. x gets placed in a fresh
tmp. This is likely to be better, because the reg alloc can
eliminate this reg->reg move here (it won't eliminate the other one,
because the move is into the fixed %ecx).
-}
shift_code width instr x y{-amount-} = do
x_code <- getAnyReg x
let format = intFormat width
tmp <- getNewRegNat format
y_code <- getAnyReg y
let
code = x_code tmp `appOL`
y_code ecx `snocOL`
instr format (OpReg ecx) (OpReg tmp)
return (Fixed format tmp code)
--------------------
add_code :: Width -> CmmExpr -> CmmExpr -> NatM Register
add_code rep x (CmmLit (CmmInt y _))
| is32BitInteger y = add_int rep x y
add_code rep x y = trivialCode rep (ADD format) (Just (ADD format)) x y
where format = intFormat rep
-- TODO: There are other interesting patterns we want to replace
-- with a LEA, e.g. `(x + offset) + (y << shift)`.
--------------------
sub_code :: Width -> CmmExpr -> CmmExpr -> NatM Register
sub_code rep x (CmmLit (CmmInt y _))
| is32BitInteger (-y) = add_int rep x (-y)
sub_code rep x y = trivialCode rep (SUB (intFormat rep)) Nothing x y
-- our three-operand add instruction:
add_int width x y = do
(x_reg, x_code) <- getSomeReg x
let
format = intFormat width
imm = ImmInt (fromInteger y)
code dst
= x_code `snocOL`
LEA format
(OpAddr (AddrBaseIndex (EABaseReg x_reg) EAIndexNone imm))
(OpReg dst)
--
return (Any format code)
----------------------
-- See Note [DIV/IDIV for bytes]
div_code W8 signed quotient x y = do
let widen | signed = MO_SS_Conv W8 W16
| otherwise = MO_UU_Conv W8 W16
div_code
W16
signed
quotient
(CmmMachOp widen [x])
(CmmMachOp widen [y])
div_code width signed quotient x y = do
(y_op, y_code) <- getRegOrMem y -- cannot be clobbered
x_code <- getAnyReg x
let
format = intFormat width
widen | signed = CLTD format
| otherwise = XOR format (OpReg edx) (OpReg edx)
instr | signed = IDIV
| otherwise = DIV
code = y_code `appOL`
x_code eax `appOL`
toOL [widen, instr format y_op]
result | quotient = eax
| otherwise = edx
return (Fixed format result code)
getRegister' _ _ (CmmLoad mem pk)
| isFloatType pk
= do
Amode addr mem_code <- getAmode mem
loadFloatAmode (typeWidth pk) addr mem_code
getRegister' _ is32Bit (CmmLoad mem pk)
| is32Bit && not (isWord64 pk)
= do
code <- intLoadCode instr mem
return (Any format code)
where
width = typeWidth pk
format = intFormat width
instr = case width of
W8 -> MOVZxL II8
_other -> MOV format
-- We always zero-extend 8-bit loads, if we
-- can't think of anything better. This is because
-- we can't guarantee access to an 8-bit variant of every register
-- (esi and edi don't have 8-bit variants), so to make things
-- simpler we do our 8-bit arithmetic with full 32-bit registers.
-- Simpler memory load code on x86_64
getRegister' _ is32Bit (CmmLoad mem pk)
| not is32Bit
= do
code <- intLoadCode (MOV format) mem
return (Any format code)
where format = intFormat $ typeWidth pk
getRegister' _ is32Bit (CmmLit (CmmInt 0 width))
= let
format = intFormat width
-- x86_64: 32-bit xor is one byte shorter, and zero-extends to 64 bits
format1 = if is32Bit then format
else case format of
II64 -> II32
_ -> format
code dst
= unitOL (XOR format1 (OpReg dst) (OpReg dst))
in
return (Any format code)
-- optimisation for loading small literals on x86_64: take advantage
-- of the automatic zero-extension from 32 to 64 bits, because the 32-bit
-- instruction forms are shorter.
getRegister' dflags is32Bit (CmmLit lit)
| not is32Bit, isWord64 (cmmLitType dflags lit), not (isBigLit lit)
= let
imm = litToImm lit
code dst = unitOL (MOV II32 (OpImm imm) (OpReg dst))
in
return (Any II64 code)
where
isBigLit (CmmInt i _) = i < 0 || i > 0xffffffff
isBigLit _ = False
-- note1: not the same as (not.is32BitLit), because that checks for
-- signed literals that fit in 32 bits, but we want unsigned
-- literals here.
-- note2: all labels are small, because we're assuming the
-- small memory model (see gcc docs, -mcmodel=small).
getRegister' dflags _ (CmmLit lit)
= do let format = cmmTypeFormat (cmmLitType dflags lit)
imm = litToImm lit
code dst = unitOL (MOV format (OpImm imm) (OpReg dst))
return (Any format code)
getRegister' _ _ other
| isVecExpr other = needLlvm
| otherwise = pprPanic "getRegister(x86)" (ppr other)
intLoadCode :: (Operand -> Operand -> Instr) -> CmmExpr
-> NatM (Reg -> InstrBlock)
intLoadCode instr mem = do
Amode src mem_code <- getAmode mem
return (\dst -> mem_code `snocOL` instr (OpAddr src) (OpReg dst))
-- Compute an expression into *any* register, adding the appropriate
-- move instruction if necessary.
getAnyReg :: CmmExpr -> NatM (Reg -> InstrBlock)
getAnyReg expr = do
r <- getRegister expr
anyReg r
anyReg :: Register -> NatM (Reg -> InstrBlock)
anyReg (Any _ code) = return code
anyReg (Fixed rep reg fcode) = return (\dst -> fcode `snocOL` reg2reg rep reg dst)
-- A bit like getSomeReg, but we want a reg that can be byte-addressed.
-- Fixed registers might not be byte-addressable, so we make sure we've
-- got a temporary, inserting an extra reg copy if necessary.
getByteReg :: CmmExpr -> NatM (Reg, InstrBlock)
getByteReg expr = do
is32Bit <- is32BitPlatform
if is32Bit
then do r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed rep reg code
| isVirtualReg reg -> return (reg,code)
| otherwise -> do
tmp <- getNewRegNat rep
return (tmp, code `snocOL` reg2reg rep reg tmp)
-- ToDo: could optimise slightly by checking for
-- byte-addressable real registers, but that will
-- happen very rarely if at all.
else getSomeReg expr -- all regs are byte-addressable on x86_64
-- Another variant: this time we want the result in a register that cannot
-- be modified by code to evaluate an arbitrary expression.
getNonClobberedReg :: CmmExpr -> NatM (Reg, InstrBlock)
getNonClobberedReg expr = do
dflags <- getDynFlags
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed rep reg code
-- only certain regs can be clobbered
| reg `elem` instrClobberedRegs (targetPlatform dflags)
-> do
tmp <- getNewRegNat rep
return (tmp, code `snocOL` reg2reg rep reg tmp)
| otherwise ->
return (reg, code)
reg2reg :: Format -> Reg -> Reg -> Instr
reg2reg format src dst = MOV format (OpReg src) (OpReg dst)
--------------------------------------------------------------------------------
getAmode :: CmmExpr -> NatM Amode
getAmode e = do is32Bit <- is32BitPlatform
getAmode' is32Bit e
getAmode' :: Bool -> CmmExpr -> NatM Amode
getAmode' _ (CmmRegOff r n) = do dflags <- getDynFlags
getAmode $ mangleIndexTree dflags r n
getAmode' is32Bit (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg),
CmmLit displacement])
| not is32Bit
= return $ Amode (ripRel (litToImm displacement)) nilOL
-- This is all just ridiculous, since it carefully undoes
-- what mangleIndexTree has just done.
getAmode' is32Bit (CmmMachOp (MO_Sub _rep) [x, CmmLit lit@(CmmInt i _)])
| is32BitLit is32Bit lit
-- ASSERT(rep == II32)???
= do (x_reg, x_code) <- getSomeReg x
let off = ImmInt (-(fromInteger i))
return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
getAmode' is32Bit (CmmMachOp (MO_Add _rep) [x, CmmLit lit])
| is32BitLit is32Bit lit
-- ASSERT(rep == II32)???
= do (x_reg, x_code) <- getSomeReg x
let off = litToImm lit
return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
-- Turn (lit1 << n + lit2) into (lit2 + lit1 << n) so it will be
-- recognised by the next rule.
getAmode' is32Bit (CmmMachOp (MO_Add rep) [a@(CmmMachOp (MO_Shl _) _),
b@(CmmLit _)])
= getAmode' is32Bit (CmmMachOp (MO_Add rep) [b,a])
-- Matches: (x + offset) + (y << shift)
getAmode' _ (CmmMachOp (MO_Add _) [CmmRegOff x offset,
CmmMachOp (MO_Shl _)
[y, CmmLit (CmmInt shift _)]])
| shift == 0 || shift == 1 || shift == 2 || shift == 3
= x86_complex_amode (CmmReg x) y shift (fromIntegral offset)
getAmode' _ (CmmMachOp (MO_Add _) [x, CmmMachOp (MO_Shl _)
[y, CmmLit (CmmInt shift _)]])
| shift == 0 || shift == 1 || shift == 2 || shift == 3
= x86_complex_amode x y shift 0
getAmode' _ (CmmMachOp (MO_Add _)
[x, CmmMachOp (MO_Add _)
[CmmMachOp (MO_Shl _) [y, CmmLit (CmmInt shift _)],
CmmLit (CmmInt offset _)]])
| shift == 0 || shift == 1 || shift == 2 || shift == 3
&& is32BitInteger offset
= x86_complex_amode x y shift offset
getAmode' _ (CmmMachOp (MO_Add _) [x,y])
= x86_complex_amode x y 0 0
getAmode' is32Bit (CmmLit lit) | is32BitLit is32Bit lit
= return (Amode (ImmAddr (litToImm lit) 0) nilOL)
getAmode' _ expr = do
(reg,code) <- getSomeReg expr
return (Amode (AddrBaseIndex (EABaseReg reg) EAIndexNone (ImmInt 0)) code)
-- | Like 'getAmode', but on 32-bit use simple register addressing
-- (i.e. no index register). This stops us from running out of
-- registers on x86 when using instructions such as cmpxchg, which can
-- use up to three virtual registers and one fixed register.
getSimpleAmode :: DynFlags -> Bool -> CmmExpr -> NatM Amode
getSimpleAmode dflags is32Bit addr
| is32Bit = do
addr_code <- getAnyReg addr
addr_r <- getNewRegNat (intFormat (wordWidth dflags))
let amode = AddrBaseIndex (EABaseReg addr_r) EAIndexNone (ImmInt 0)
return $! Amode amode (addr_code addr_r)
| otherwise = getAmode addr
x86_complex_amode :: CmmExpr -> CmmExpr -> Integer -> Integer -> NatM Amode
x86_complex_amode base index shift offset
= do (x_reg, x_code) <- getNonClobberedReg base
-- x must be in a temp, because it has to stay live over y_code
-- we could compare x_reg and y_reg and do something better here...
(y_reg, y_code) <- getSomeReg index
let
code = x_code `appOL` y_code
base = case shift of 0 -> 1; 1 -> 2; 2 -> 4; 3 -> 8;
n -> panic $ "x86_complex_amode: unhandled shift! (" ++ show n ++ ")"
return (Amode (AddrBaseIndex (EABaseReg x_reg) (EAIndex y_reg base) (ImmInt (fromIntegral offset)))
code)
-- -----------------------------------------------------------------------------
-- getOperand: sometimes any operand will do.
-- getNonClobberedOperand: the value of the operand will remain valid across
-- the computation of an arbitrary expression, unless the expression
-- is computed directly into a register which the operand refers to
-- (see trivialCode where this function is used for an example).
getNonClobberedOperand :: CmmExpr -> NatM (Operand, InstrBlock)
getNonClobberedOperand (CmmLit lit) = do
if isSuitableFloatingPointLit lit
then do
let CmmFloat _ w = lit
Amode addr code <- memConstant (mkAlignment $ widthInBytes w) lit
return (OpAddr addr, code)
else do
is32Bit <- is32BitPlatform
dflags <- getDynFlags
if is32BitLit is32Bit lit && not (isFloatType (cmmLitType dflags lit))
then return (OpImm (litToImm lit), nilOL)
else getNonClobberedOperand_generic (CmmLit lit)
getNonClobberedOperand (CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
-- this logic could be simplified
-- TODO FIXME
if (if is32Bit then not (isWord64 pk) else True)
-- if 32bit and pk is at float/double/simd value
-- or if 64bit
-- this could use some eyeballs or i'll need to stare at it more later
then do
dflags <- getDynFlags
let platform = targetPlatform dflags
Amode src mem_code <- getAmode mem
(src',save_code) <-
if (amodeCouldBeClobbered platform src)
then do
tmp <- getNewRegNat (archWordFormat is32Bit)
return (AddrBaseIndex (EABaseReg tmp) EAIndexNone (ImmInt 0),
unitOL (LEA (archWordFormat is32Bit)
(OpAddr src)
(OpReg tmp)))
else
return (src, nilOL)
return (OpAddr src', mem_code `appOL` save_code)
else do
-- if its a word or gcptr on 32bit?
getNonClobberedOperand_generic (CmmLoad mem pk)
getNonClobberedOperand e = getNonClobberedOperand_generic e
getNonClobberedOperand_generic :: CmmExpr -> NatM (Operand, InstrBlock)
getNonClobberedOperand_generic e = do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
amodeCouldBeClobbered :: Platform -> AddrMode -> Bool
amodeCouldBeClobbered platform amode = any (regClobbered platform) (addrModeRegs amode)
regClobbered :: Platform -> Reg -> Bool
regClobbered platform (RegReal (RealRegSingle rr)) = freeReg platform rr
regClobbered _ _ = False
-- getOperand: the operand is not required to remain valid across the
-- computation of an arbitrary expression.
getOperand :: CmmExpr -> NatM (Operand, InstrBlock)
getOperand (CmmLit lit) = do
use_sse2 <- sse2Enabled
if (use_sse2 && isSuitableFloatingPointLit lit)
then do
let CmmFloat _ w = lit
Amode addr code <- memConstant (mkAlignment $ widthInBytes w) lit
return (OpAddr addr, code)
else do
is32Bit <- is32BitPlatform
dflags <- getDynFlags
if is32BitLit is32Bit lit && not (isFloatType (cmmLitType dflags lit))
then return (OpImm (litToImm lit), nilOL)
else getOperand_generic (CmmLit lit)
getOperand (CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
use_sse2 <- sse2Enabled
if (not (isFloatType pk) || use_sse2) && (if is32Bit then not (isWord64 pk) else True)
then do
Amode src mem_code <- getAmode mem
return (OpAddr src, mem_code)
else
getOperand_generic (CmmLoad mem pk)
getOperand e = getOperand_generic e
getOperand_generic :: CmmExpr -> NatM (Operand, InstrBlock)
getOperand_generic e = do
(reg, code) <- getSomeReg e
return (OpReg reg, code)
isOperand :: Bool -> CmmExpr -> Bool
isOperand _ (CmmLoad _ _) = True
isOperand is32Bit (CmmLit lit) = is32BitLit is32Bit lit
|| isSuitableFloatingPointLit lit
isOperand _ _ = False
-- | Given a 'Register', produce a new 'Register' with an instruction block
-- which will check the value for alignment. Used for @-falignment-sanitisation@.
addAlignmentCheck :: Int -> Register -> Register
addAlignmentCheck align reg =
case reg of
Fixed fmt reg code -> Fixed fmt reg (code `appOL` check fmt reg)
Any fmt f -> Any fmt (\reg -> f reg `appOL` check fmt reg)
where
check :: Format -> Reg -> InstrBlock
check fmt reg =
ASSERT(not $ isFloatFormat fmt)
toOL [ TEST fmt (OpImm $ ImmInt $ align-1) (OpReg reg)
, JXX_GBL NE $ ImmCLbl mkBadAlignmentLabel
]
memConstant :: Alignment -> CmmLit -> NatM Amode
memConstant align lit = do
lbl <- getNewLabelNat
let rosection = Section ReadOnlyData lbl
dflags <- getDynFlags
(addr, addr_code) <- if target32Bit (targetPlatform dflags)
then do dynRef <- cmmMakeDynamicReference
dflags
DataReference
lbl
Amode addr addr_code <- getAmode dynRef
return (addr, addr_code)
else return (ripRel (ImmCLbl lbl), nilOL)
let code =
LDATA rosection (align, RawCmmStatics lbl [CmmStaticLit lit])
`consOL` addr_code
return (Amode addr code)
loadFloatAmode :: Width -> AddrMode -> InstrBlock -> NatM Register
loadFloatAmode w addr addr_code = do
let format = floatFormat w
code dst = addr_code `snocOL`
MOV format (OpAddr addr) (OpReg dst)
return (Any format code)
-- if we want a floating-point literal as an operand, we can
-- use it directly from memory. However, if the literal is
-- zero, we're better off generating it into a register using
-- xor.
isSuitableFloatingPointLit :: CmmLit -> Bool
isSuitableFloatingPointLit (CmmFloat f _) = f /= 0.0
isSuitableFloatingPointLit _ = False
getRegOrMem :: CmmExpr -> NatM (Operand, InstrBlock)
getRegOrMem e@(CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
use_sse2 <- sse2Enabled
if (not (isFloatType pk) || use_sse2) && (if is32Bit then not (isWord64 pk) else True)
then do
Amode src mem_code <- getAmode mem
return (OpAddr src, mem_code)
else do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
getRegOrMem e = do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
is32BitLit :: Bool -> CmmLit -> Bool
is32BitLit is32Bit (CmmInt i W64)
| not is32Bit
= -- assume that labels are in the range 0-2^31-1: this assumes the
-- small memory model (see gcc docs, -mcmodel=small).
is32BitInteger i
is32BitLit _ _ = True
-- Set up a condition code for a conditional branch.
getCondCode :: CmmExpr -> NatM CondCode
-- yes, they really do seem to want exactly the same!
getCondCode (CmmMachOp mop [x, y])
=
case mop of
MO_F_Eq W32 -> condFltCode EQQ x y
MO_F_Ne W32 -> condFltCode NE x y
MO_F_Gt W32 -> condFltCode GTT x y
MO_F_Ge W32 -> condFltCode GE x y
-- Invert comparison condition and swap operands
-- See Note [SSE Parity Checks]
MO_F_Lt W32 -> condFltCode GTT y x
MO_F_Le W32 -> condFltCode GE y x
MO_F_Eq W64 -> condFltCode EQQ x y
MO_F_Ne W64 -> condFltCode NE x y
MO_F_Gt W64 -> condFltCode GTT x y
MO_F_Ge W64 -> condFltCode GE x y
MO_F_Lt W64 -> condFltCode GTT y x
MO_F_Le W64 -> condFltCode GE y x
_ -> condIntCode (machOpToCond mop) x y
getCondCode other = pprPanic "getCondCode(2)(x86,x86_64)" (ppr other)
machOpToCond :: MachOp -> Cond
machOpToCond mo = case mo of
MO_Eq _ -> EQQ
MO_Ne _ -> NE
MO_S_Gt _ -> GTT
MO_S_Ge _ -> GE
MO_S_Lt _ -> LTT
MO_S_Le _ -> LE
MO_U_Gt _ -> GU
MO_U_Ge _ -> GEU
MO_U_Lt _ -> LU
MO_U_Le _ -> LEU
_other -> pprPanic "machOpToCond" (pprMachOp mo)
-- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
-- passed back up the tree.
condIntCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condIntCode cond x y = do is32Bit <- is32BitPlatform
condIntCode' is32Bit cond x y
condIntCode' :: Bool -> Cond -> CmmExpr -> CmmExpr -> NatM CondCode
-- memory vs immediate
condIntCode' is32Bit cond (CmmLoad x pk) (CmmLit lit)
| is32BitLit is32Bit lit = do
Amode x_addr x_code <- getAmode x
let
imm = litToImm lit
code = x_code `snocOL`
CMP (cmmTypeFormat pk) (OpImm imm) (OpAddr x_addr)
--
return (CondCode False cond code)
-- anything vs zero, using a mask
-- TODO: Add some sanity checking!!!!
condIntCode' is32Bit cond (CmmMachOp (MO_And _) [x,o2]) (CmmLit (CmmInt 0 pk))
| (CmmLit lit@(CmmInt mask _)) <- o2, is32BitLit is32Bit lit
= do
(x_reg, x_code) <- getSomeReg x
let
code = x_code `snocOL`
TEST (intFormat pk) (OpImm (ImmInteger mask)) (OpReg x_reg)
--
return (CondCode False cond code)
-- anything vs zero
condIntCode' _ cond x (CmmLit (CmmInt 0 pk)) = do
(x_reg, x_code) <- getSomeReg x
let
code = x_code `snocOL`
TEST (intFormat pk) (OpReg x_reg) (OpReg x_reg)
--
return (CondCode False cond code)
-- anything vs operand
condIntCode' is32Bit cond x y
| isOperand is32Bit y = do
dflags <- getDynFlags
(x_reg, x_code) <- getNonClobberedReg x
(y_op, y_code) <- getOperand y
let
code = x_code `appOL` y_code `snocOL`
CMP (cmmTypeFormat (cmmExprType dflags x)) y_op (OpReg x_reg)
return (CondCode False cond code)
-- operand vs. anything: invert the comparison so that we can use a
-- single comparison instruction.
| isOperand is32Bit x
, Just revcond <- maybeFlipCond cond = do
dflags <- getDynFlags
(y_reg, y_code) <- getNonClobberedReg y
(x_op, x_code) <- getOperand x
let
code = y_code `appOL` x_code `snocOL`
CMP (cmmTypeFormat (cmmExprType dflags x)) x_op (OpReg y_reg)
return (CondCode False revcond code)
-- anything vs anything
condIntCode' _ cond x y = do
dflags <- getDynFlags
(y_reg, y_code) <- getNonClobberedReg y
(x_op, x_code) <- getRegOrMem x
let
code = y_code `appOL`
x_code `snocOL`
CMP (cmmTypeFormat (cmmExprType dflags x)) (OpReg y_reg) x_op
return (CondCode False cond code)
--------------------------------------------------------------------------------
condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condFltCode cond x y
= condFltCode_sse2
where
-- in the SSE2 comparison ops (ucomiss, ucomisd) the left arg may be
-- an operand, but the right must be a reg. We can probably do better
-- than this general case...
condFltCode_sse2 = do
dflags <- getDynFlags
(x_reg, x_code) <- getNonClobberedReg x
(y_op, y_code) <- getOperand y
let
code = x_code `appOL`
y_code `snocOL`
CMP (floatFormat $ cmmExprWidth dflags x) y_op (OpReg x_reg)
-- NB(1): we need to use the unsigned comparison operators on the
-- result of this comparison.
return (CondCode True (condToUnsigned cond) code)
-- -----------------------------------------------------------------------------
-- Generating assignments
-- Assignments are really at the heart of the whole code generation
-- business. Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers. If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side. This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).
assignMem_IntCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_IntCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_FltCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_FltCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
-- integer assignment to memory
-- specific case of adding/subtracting an integer to a particular address.
-- ToDo: catch other cases where we can use an operation directly on a memory
-- address.
assignMem_IntCode pk addr (CmmMachOp op [CmmLoad addr2 _,
CmmLit (CmmInt i _)])
| addr == addr2, pk /= II64 || is32BitInteger i,
Just instr <- check op
= do Amode amode code_addr <- getAmode addr
let code = code_addr `snocOL`
instr pk (OpImm (ImmInt (fromIntegral i))) (OpAddr amode)
return code
where
check (MO_Add _) = Just ADD
check (MO_Sub _) = Just SUB
check _ = Nothing
-- ToDo: more?
-- general case
assignMem_IntCode pk addr src = do
is32Bit <- is32BitPlatform
Amode addr code_addr <- getAmode addr
(code_src, op_src) <- get_op_RI is32Bit src
let
code = code_src `appOL`
code_addr `snocOL`
MOV pk op_src (OpAddr addr)
-- NOTE: op_src is stable, so it will still be valid
-- after code_addr. This may involve the introduction
-- of an extra MOV to a temporary register, but we hope
-- the register allocator will get rid of it.
--
return code
where
get_op_RI :: Bool -> CmmExpr -> NatM (InstrBlock,Operand) -- code, operator
get_op_RI is32Bit (CmmLit lit) | is32BitLit is32Bit lit
= return (nilOL, OpImm (litToImm lit))
get_op_RI _ op
= do (reg,code) <- getNonClobberedReg op
return (code, OpReg reg)
-- Assign; dst is a reg, rhs is mem
assignReg_IntCode pk reg (CmmLoad src _) = do
load_code <- intLoadCode (MOV pk) src
dflags <- getDynFlags
let platform = targetPlatform dflags
return (load_code (getRegisterReg platform reg))
-- dst is a reg, but src could be anything
assignReg_IntCode _ reg src = do
dflags <- getDynFlags
let platform = targetPlatform dflags
code <- getAnyReg src
return (code (getRegisterReg platform reg))
-- Floating point assignment to memory
assignMem_FltCode pk addr src = do
(src_reg, src_code) <- getNonClobberedReg src
Amode addr addr_code <- getAmode addr
let
code = src_code `appOL`
addr_code `snocOL`
MOV pk (OpReg src_reg) (OpAddr addr)
return code
-- Floating point assignment to a register/temporary
assignReg_FltCode _ reg src = do
src_code <- getAnyReg src
dflags <- getDynFlags
let platform = targetPlatform dflags
return (src_code (getRegisterReg platform reg))
genJump :: CmmExpr{-the branch target-} -> [Reg] -> NatM InstrBlock
genJump (CmmLoad mem _) regs = do
Amode target code <- getAmode mem
return (code `snocOL` JMP (OpAddr target) regs)
genJump (CmmLit lit) regs = do
return (unitOL (JMP (OpImm (litToImm lit)) regs))
genJump expr regs = do
(reg,code) <- getSomeReg expr
return (code `snocOL` JMP (OpReg reg) regs)
-- -----------------------------------------------------------------------------
-- Unconditional branches
genBranch :: BlockId -> InstrBlock
genBranch = toOL . mkJumpInstr
-- -----------------------------------------------------------------------------
-- Conditional jumps/branches
{-
Conditional jumps are always to local labels, so we can use branch
instructions. We peek at the arguments to decide what kind of
comparison to do.
I386: First, we have to ensure that the condition
codes are set according to the supplied comparison operation.
-}
genCondBranch
:: BlockId -- the source of the jump
-> BlockId -- the true branch target
-> BlockId -- the false branch target
-> CmmExpr -- the condition on which to branch
-> NatM InstrBlock -- Instructions
genCondBranch bid id false expr = do
is32Bit <- is32BitPlatform
genCondBranch' is32Bit bid id false expr
-- | We return the instructions generated.
genCondBranch' :: Bool -> BlockId -> BlockId -> BlockId -> CmmExpr
-> NatM InstrBlock
-- 64-bit integer comparisons on 32-bit
genCondBranch' is32Bit _bid true false (CmmMachOp mop [e1,e2])
| is32Bit, Just W64 <- maybeIntComparison mop = do
ChildCode64 code1 r1_lo <- iselExpr64 e1
ChildCode64 code2 r2_lo <- iselExpr64 e2
let r1_hi = getHiVRegFromLo r1_lo
r2_hi = getHiVRegFromLo r2_lo
cond = machOpToCond mop
Just cond' = maybeFlipCond cond
--TODO: Update CFG for x86
let code = code1 `appOL` code2 `appOL` toOL [
CMP II32 (OpReg r2_hi) (OpReg r1_hi),
JXX cond true,
JXX cond' false,
CMP II32 (OpReg r2_lo) (OpReg r1_lo),
JXX cond true] `appOL` genBranch false
return code
genCondBranch' _ bid id false bool = do
CondCode is_float cond cond_code <- getCondCode bool
use_sse2 <- sse2Enabled
if not is_float || not use_sse2
then
return (cond_code `snocOL` JXX cond id `appOL` genBranch false)
else do
-- See Note [SSE Parity Checks]
let jmpFalse = genBranch false
code
= case cond of
NE -> or_unordered
GU -> plain_test
GEU -> plain_test
-- Use ASSERT so we don't break releases if
-- LTT/LE creep in somehow.
LTT ->
ASSERT2(False, ppr "Should have been turned into >")
and_ordered
LE ->
ASSERT2(False, ppr "Should have been turned into >=")
and_ordered
_ -> and_ordered
plain_test = unitOL (
JXX cond id
) `appOL` jmpFalse
or_unordered = toOL [
JXX cond id,
JXX PARITY id
] `appOL` jmpFalse
and_ordered = toOL [
JXX PARITY false,
JXX cond id,
JXX ALWAYS false
]
updateCfgNat (\cfg -> adjustEdgeWeight cfg (+3) bid false)
return (cond_code `appOL` code)
{- Note [Introducing cfg edges inside basic blocks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
During instruction selection a statement `s`
in a block B with control of the sort: B -> C
will sometimes result in control
flow of the sort:
┌ < ┐
v ^
B -> B1 ┴ -> C
as is the case for some atomic operations.
Now to keep the CFG in sync when introducing B1 we clearly
want to insert it between B and C. However there is
a catch when we have to deal with self loops.
We might start with code and a CFG of these forms:
loop:
stmt1 ┌ < ┐
.... v ^
stmtX loop ┘
stmtY
....
goto loop:
Now we introduce B1:
┌ ─ ─ ─ ─ ─┐
loop: │ ┌ < ┐ │
instrs v │ │ ^
.... loop ┴ B1 ┴ ┘
instrsFromX
stmtY
goto loop:
This is simple, all outgoing edges from loop now simply
start from B1 instead and the code generator knows which
new edges it introduced for the self loop of B1.
Disaster strikes if the statement Y follows the same pattern.
If we apply the same rule that all outgoing edges change then
we end up with:
loop ─> B1 ─> B2 ┬─┐
│ │ └─<┤ │
│ └───<───┘ │
└───────<────────┘
This is problematic. The edge B1->B1 is modified as expected.
However the modification is wrong!
The assembly in this case looked like this:
_loop:
<instrs>
_B1:
...
cmpxchgq ...
jne _B1
<instrs>
<end _B1>
_B2:
...
cmpxchgq ...
jne _B2
<instrs>
jmp loop
There is no edge _B2 -> _B1 here. It's still a self loop onto _B1.
The problem here is that really B1 should be two basic blocks.
Otherwise we have control flow in the *middle* of a basic block.
A contradiction!
So to account for this we add yet another basic block marker:
_B:
<instrs>
_B1:
...
cmpxchgq ...
jne _B1
jmp _B1'
_B1':
<instrs>
<end _B1>
_B2:
...
Now when inserting B2 we will only look at the outgoing edges of B1' and
everything will work out nicely.
You might also wonder why we don't insert jumps at the end of _B1'. There is
no way another block ends up jumping to the labels _B1 or _B2 since they are
essentially invisible to other blocks. View them as control flow labels local
to the basic block if you'd like.
Not doing this ultimately caused (part 2 of) #17334.
-}
-- -----------------------------------------------------------------------------
-- Generating C calls
-- Now the biggest nightmare---calls. Most of the nastiness is buried in
-- @get_arg@, which moves the arguments to the correct registers/stack
-- locations. Apart from that, the code is easy.
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
--
-- See Note [Keeping track of the current block] for information why we need
-- to take/return a block id.
genCCall
:: DynFlags
-> Bool -- 32 bit platform?
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> BlockId -- The block we are in
-> NatM (InstrBlock, Maybe BlockId)
-- First we deal with cases which might introduce new blocks in the stream.
genCCall dflags is32Bit (PrimTarget (MO_AtomicRMW width amop))
[dst] [addr, n] bid = do
Amode amode addr_code <-
if amop `elem` [AMO_Add, AMO_Sub]
then getAmode addr
else getSimpleAmode dflags is32Bit addr -- See genCCall for MO_Cmpxchg
arg <- getNewRegNat format
arg_code <- getAnyReg n
let platform = targetPlatform dflags
dst_r = getRegisterReg platform (CmmLocal dst)
(code, lbl) <- op_code dst_r arg amode
return (addr_code `appOL` arg_code arg `appOL` code, Just lbl)
where
-- Code for the operation
op_code :: Reg -- Destination reg
-> Reg -- Register containing argument
-> AddrMode -- Address of location to mutate
-> NatM (OrdList Instr,BlockId) -- TODO: Return Maybe BlockId
op_code dst_r arg amode = case amop of
-- In the common case where dst_r is a virtual register the
-- final move should go away, because it's the last use of arg
-- and the first use of dst_r.
AMO_Add -> return $ (toOL [ LOCK (XADD format (OpReg arg) (OpAddr amode))
, MOV format (OpReg arg) (OpReg dst_r)
], bid)
AMO_Sub -> return $ (toOL [ NEGI format (OpReg arg)
, LOCK (XADD format (OpReg arg) (OpAddr amode))
, MOV format (OpReg arg) (OpReg dst_r)
], bid)
-- In these cases we need a new block id, and have to return it so
-- that later instruction selection can reference it.
AMO_And -> cmpxchg_code (\ src dst -> unitOL $ AND format src dst)
AMO_Nand -> cmpxchg_code (\ src dst -> toOL [ AND format src dst
, NOT format dst
])
AMO_Or -> cmpxchg_code (\ src dst -> unitOL $ OR format src dst)
AMO_Xor -> cmpxchg_code (\ src dst -> unitOL $ XOR format src dst)
where
-- Simulate operation that lacks a dedicated instruction using
-- cmpxchg.
cmpxchg_code :: (Operand -> Operand -> OrdList Instr)
-> NatM (OrdList Instr, BlockId)
cmpxchg_code instrs = do
lbl1 <- getBlockIdNat
lbl2 <- getBlockIdNat
tmp <- getNewRegNat format
--Record inserted blocks
-- We turn A -> B into A -> A' -> A'' -> B
-- with a self loop on A'.
addImmediateSuccessorNat bid lbl1
addImmediateSuccessorNat lbl1 lbl2
updateCfgNat (addWeightEdge lbl1 lbl1 0)
return $ (toOL
[ MOV format (OpAddr amode) (OpReg eax)
, JXX ALWAYS lbl1
, NEWBLOCK lbl1
-- Keep old value so we can return it:
, MOV format (OpReg eax) (OpReg dst_r)
, MOV format (OpReg eax) (OpReg tmp)
]
`appOL` instrs (OpReg arg) (OpReg tmp) `appOL` toOL
[ LOCK (CMPXCHG format (OpReg tmp) (OpAddr amode))
, JXX NE lbl1
-- See Note [Introducing cfg edges inside basic blocks]
-- why this basic block is required.
, JXX ALWAYS lbl2
, NEWBLOCK lbl2
],
lbl2)
format = intFormat width
genCCall dflags is32Bit (PrimTarget (MO_Ctz width)) [dst] [src] bid
| is32Bit, width == W64 = do
ChildCode64 vcode rlo <- iselExpr64 src
let rhi = getHiVRegFromLo rlo
dst_r = getRegisterReg platform (CmmLocal dst)
lbl1 <- getBlockIdNat
lbl2 <- getBlockIdNat
let format = if width == W8 then II16 else intFormat width
tmp_r <- getNewRegNat format
-- New CFG Edges:
-- bid -> lbl2
-- bid -> lbl1 -> lbl2
-- We also changes edges originating at bid to start at lbl2 instead.
updateCfgNat (addWeightEdge bid lbl1 110 .
addWeightEdge lbl1 lbl2 110 .
addImmediateSuccessor bid lbl2)
-- The following instruction sequence corresponds to the pseudo-code
--
-- if (src) {
-- dst = src.lo32 ? BSF(src.lo32) : (BSF(src.hi32) + 32);
-- } else {
-- dst = 64;
-- }
let !instrs = vcode `appOL` toOL
([ MOV II32 (OpReg rhi) (OpReg tmp_r)
, OR II32 (OpReg rlo) (OpReg tmp_r)
, MOV II32 (OpImm (ImmInt 64)) (OpReg dst_r)
, JXX EQQ lbl2
, JXX ALWAYS lbl1
, NEWBLOCK lbl1
, BSF II32 (OpReg rhi) dst_r
, ADD II32 (OpImm (ImmInt 32)) (OpReg dst_r)
, BSF II32 (OpReg rlo) tmp_r
, CMOV NE II32 (OpReg tmp_r) dst_r
, JXX ALWAYS lbl2
, NEWBLOCK lbl2
])
return (instrs, Just lbl2)
| otherwise = do
code_src <- getAnyReg src
let dst_r = getRegisterReg platform (CmmLocal dst)
if isBmi2Enabled dflags
then do
src_r <- getNewRegNat (intFormat width)
let instrs = appOL (code_src src_r) $ case width of
W8 -> toOL
[ OR II32 (OpImm (ImmInteger 0xFFFFFF00)) (OpReg src_r)
, TZCNT II32 (OpReg src_r) dst_r
]
W16 -> toOL
[ TZCNT II16 (OpReg src_r) dst_r
, MOVZxL II16 (OpReg dst_r) (OpReg dst_r)
]
_ -> unitOL $ TZCNT (intFormat width) (OpReg src_r) dst_r
return (instrs, Nothing)
else do
-- The following insn sequence makes sure 'ctz 0' has a defined value.
-- starting with Haswell, one could use the TZCNT insn instead.
let format = if width == W8 then II16 else intFormat width
src_r <- getNewRegNat format
tmp_r <- getNewRegNat format
let !instrs = code_src src_r `appOL` toOL
([ MOVZxL II8 (OpReg src_r) (OpReg src_r) | width == W8 ] ++
[ BSF format (OpReg src_r) tmp_r
, MOV II32 (OpImm (ImmInt bw)) (OpReg dst_r)
, CMOV NE format (OpReg tmp_r) dst_r
]) -- NB: We don't need to zero-extend the result for the
-- W8/W16 cases because the 'MOV' insn already
-- took care of implicitly clearing the upper bits
return (instrs, Nothing)
where
bw = widthInBits width
platform = targetPlatform dflags
genCCall dflags bits mop dst args bid = do
instr <- genCCall' dflags bits mop dst args bid
return (instr, Nothing)
-- genCCall' handles cases not introducing new code blocks.
genCCall'
:: DynFlags
-> Bool -- 32 bit platform?
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> BlockId -- The block we are in
-> NatM InstrBlock
-- Unroll memcpy calls if the number of bytes to copy isn't too
-- large. Otherwise, call C's memcpy.
genCCall' dflags _ (PrimTarget (MO_Memcpy align)) _
[dst, src, CmmLit (CmmInt n _)] _
| fromInteger insns <= maxInlineMemcpyInsns dflags = do
code_dst <- getAnyReg dst
dst_r <- getNewRegNat format
code_src <- getAnyReg src
src_r <- getNewRegNat format
tmp_r <- getNewRegNat format
return $ code_dst dst_r `appOL` code_src src_r `appOL`
go dst_r src_r tmp_r (fromInteger n)
where
-- The number of instructions we will generate (approx). We need 2
-- instructions per move.
insns = 2 * ((n + sizeBytes - 1) `div` sizeBytes)
maxAlignment = wordAlignment dflags -- only machine word wide MOVs are supported
effectiveAlignment = min (alignmentOf align) maxAlignment
format = intFormat . widthFromBytes $ alignmentBytes effectiveAlignment
-- The size of each move, in bytes.
sizeBytes :: Integer
sizeBytes = fromIntegral (formatInBytes format)
go :: Reg -> Reg -> Reg -> Integer -> OrdList Instr
go dst src tmp i
| i >= sizeBytes =
unitOL (MOV format (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV format (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - sizeBytes)
-- Deal with remaining bytes.
| i >= 4 = -- Will never happen on 32-bit
unitOL (MOV II32 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II32 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 4)
| i >= 2 =
unitOL (MOVZxL II16 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II16 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 2)
| i >= 1 =
unitOL (MOVZxL II8 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II8 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 1)
| otherwise = nilOL
where
src_addr = AddrBaseIndex (EABaseReg src) EAIndexNone
(ImmInteger (n - i))
dst_addr = AddrBaseIndex (EABaseReg dst) EAIndexNone
(ImmInteger (n - i))
genCCall' dflags _ (PrimTarget (MO_Memset align)) _
[dst,
CmmLit (CmmInt c _),
CmmLit (CmmInt n _)]
_
| fromInteger insns <= maxInlineMemsetInsns dflags = do
code_dst <- getAnyReg dst
dst_r <- getNewRegNat format
if format == II64 && n >= 8 then do
code_imm8byte <- getAnyReg (CmmLit (CmmInt c8 W64))
imm8byte_r <- getNewRegNat II64
return $ code_dst dst_r `appOL`
code_imm8byte imm8byte_r `appOL`
go8 dst_r imm8byte_r (fromInteger n)
else
return $ code_dst dst_r `appOL`
go4 dst_r (fromInteger n)
where
maxAlignment = wordAlignment dflags -- only machine word wide MOVs are supported
effectiveAlignment = min (alignmentOf align) maxAlignment
format = intFormat . widthFromBytes $ alignmentBytes effectiveAlignment
c2 = c `shiftL` 8 .|. c
c4 = c2 `shiftL` 16 .|. c2
c8 = c4 `shiftL` 32 .|. c4
-- The number of instructions we will generate (approx). We need 1
-- instructions per move.
insns = (n + sizeBytes - 1) `div` sizeBytes
-- The size of each move, in bytes.
sizeBytes :: Integer
sizeBytes = fromIntegral (formatInBytes format)
-- Depending on size returns the widest MOV instruction and its
-- width.
gen4 :: AddrMode -> Integer -> (InstrBlock, Integer)
gen4 addr size
| size >= 4 =
(unitOL (MOV II32 (OpImm (ImmInteger c4)) (OpAddr addr)), 4)
| size >= 2 =
(unitOL (MOV II16 (OpImm (ImmInteger c2)) (OpAddr addr)), 2)
| size >= 1 =
(unitOL (MOV II8 (OpImm (ImmInteger c)) (OpAddr addr)), 1)
| otherwise = (nilOL, 0)
-- Generates a 64-bit wide MOV instruction from REG to MEM.
gen8 :: AddrMode -> Reg -> InstrBlock
gen8 addr reg8byte =
unitOL (MOV format (OpReg reg8byte) (OpAddr addr))
-- Unrolls memset when the widest MOV is <= 4 bytes.
go4 :: Reg -> Integer -> InstrBlock
go4 dst left =
if left <= 0 then nilOL
else curMov `appOL` go4 dst (left - curWidth)
where
possibleWidth = minimum [left, sizeBytes]
dst_addr = AddrBaseIndex (EABaseReg dst) EAIndexNone (ImmInteger (n - left))
(curMov, curWidth) = gen4 dst_addr possibleWidth
-- Unrolls memset when the widest MOV is 8 bytes (thus another Reg
-- argument). Falls back to go4 when all 8 byte moves are
-- exhausted.
go8 :: Reg -> Reg -> Integer -> InstrBlock
go8 dst reg8byte left =
if possibleWidth >= 8 then
let curMov = gen8 dst_addr reg8byte
in curMov `appOL` go8 dst reg8byte (left - 8)
else go4 dst left
where
possibleWidth = minimum [left, sizeBytes]
dst_addr = AddrBaseIndex (EABaseReg dst) EAIndexNone (ImmInteger (n - left))
genCCall' _ _ (PrimTarget MO_ReadBarrier) _ _ _ = return nilOL
genCCall' _ _ (PrimTarget MO_WriteBarrier) _ _ _ = return nilOL
-- barriers compile to no code on x86/x86-64;
-- we keep it this long in order to prevent earlier optimisations.
genCCall' _ _ (PrimTarget MO_Touch) _ _ _ = return nilOL
genCCall' _ is32bit (PrimTarget (MO_Prefetch_Data n )) _ [src] _ =
case n of
0 -> genPrefetch src $ PREFETCH NTA format
1 -> genPrefetch src $ PREFETCH Lvl2 format
2 -> genPrefetch src $ PREFETCH Lvl1 format
3 -> genPrefetch src $ PREFETCH Lvl0 format
l -> panic $ "unexpected prefetch level in genCCall MO_Prefetch_Data: " ++ (show l)
-- the c / llvm prefetch convention is 0, 1, 2, and 3
-- the x86 corresponding names are : NTA, 2 , 1, and 0
where
format = archWordFormat is32bit
-- need to know what register width for pointers!
genPrefetch inRegSrc prefetchCTor =
do
code_src <- getAnyReg inRegSrc
src_r <- getNewRegNat format
return $ code_src src_r `appOL`
(unitOL (prefetchCTor (OpAddr
((AddrBaseIndex (EABaseReg src_r ) EAIndexNone (ImmInt 0)))) ))
-- prefetch always takes an address
genCCall' dflags is32Bit (PrimTarget (MO_BSwap width)) [dst] [src] _ = do
let platform = targetPlatform dflags
let dst_r = getRegisterReg platform (CmmLocal dst)
case width of
W64 | is32Bit -> do
ChildCode64 vcode rlo <- iselExpr64 src
let dst_rhi = getHiVRegFromLo dst_r
rhi = getHiVRegFromLo rlo
return $ vcode `appOL`
toOL [ MOV II32 (OpReg rlo) (OpReg dst_rhi),
MOV II32 (OpReg rhi) (OpReg dst_r),
BSWAP II32 dst_rhi,
BSWAP II32 dst_r ]
W16 -> do code_src <- getAnyReg src
return $ code_src dst_r `appOL`
unitOL (BSWAP II32 dst_r) `appOL`
unitOL (SHR II32 (OpImm $ ImmInt 16) (OpReg dst_r))
_ -> do code_src <- getAnyReg src
return $ code_src dst_r `appOL` unitOL (BSWAP format dst_r)
where
format = intFormat width
genCCall' dflags is32Bit (PrimTarget (MO_PopCnt width)) dest_regs@[dst]
args@[src] bid = do
sse4_2 <- sse4_2Enabled
let platform = targetPlatform dflags
if sse4_2
then do code_src <- getAnyReg src
src_r <- getNewRegNat format
let dst_r = getRegisterReg platform (CmmLocal dst)
return $ code_src src_r `appOL`
(if width == W8 then
-- The POPCNT instruction doesn't take a r/m8
unitOL (MOVZxL II8 (OpReg src_r) (OpReg src_r)) `appOL`
unitOL (POPCNT II16 (OpReg src_r) dst_r)
else
unitOL (POPCNT format (OpReg src_r) dst_r)) `appOL`
(if width == W8 || width == W16 then
-- We used a 16-bit destination register above,
-- so zero-extend
unitOL (MOVZxL II16 (OpReg dst_r) (OpReg dst_r))
else nilOL)
else do
targetExpr <- cmmMakeDynamicReference dflags
CallReference lbl
let target = ForeignTarget targetExpr (ForeignConvention CCallConv
[NoHint] [NoHint]
CmmMayReturn)
genCCall' dflags is32Bit target dest_regs args bid
where
format = intFormat width
lbl = mkCmmCodeLabel primUnitId (fsLit (popCntLabel width))
genCCall' dflags is32Bit (PrimTarget (MO_Pdep width)) dest_regs@[dst]
args@[src, mask] bid = do
let platform = targetPlatform dflags
if isBmi2Enabled dflags
then do code_src <- getAnyReg src
code_mask <- getAnyReg mask
src_r <- getNewRegNat format
mask_r <- getNewRegNat format
let dst_r = getRegisterReg platform (CmmLocal dst)
return $ code_src src_r `appOL` code_mask mask_r `appOL`
(if width == W8 then
-- The PDEP instruction doesn't take a r/m8
unitOL (MOVZxL II8 (OpReg src_r ) (OpReg src_r )) `appOL`
unitOL (MOVZxL II8 (OpReg mask_r) (OpReg mask_r)) `appOL`
unitOL (PDEP II16 (OpReg mask_r) (OpReg src_r ) dst_r)
else
unitOL (PDEP format (OpReg mask_r) (OpReg src_r) dst_r)) `appOL`
(if width == W8 || width == W16 then
-- We used a 16-bit destination register above,
-- so zero-extend
unitOL (MOVZxL II16 (OpReg dst_r) (OpReg dst_r))
else nilOL)
else do
targetExpr <- cmmMakeDynamicReference dflags
CallReference lbl
let target = ForeignTarget targetExpr (ForeignConvention CCallConv
[NoHint] [NoHint]
CmmMayReturn)
genCCall' dflags is32Bit target dest_regs args bid
where
format = intFormat width
lbl = mkCmmCodeLabel primUnitId (fsLit (pdepLabel width))
genCCall' dflags is32Bit (PrimTarget (MO_Pext width)) dest_regs@[dst]
args@[src, mask] bid = do
let platform = targetPlatform dflags
if isBmi2Enabled dflags
then do code_src <- getAnyReg src
code_mask <- getAnyReg mask
src_r <- getNewRegNat format
mask_r <- getNewRegNat format
let dst_r = getRegisterReg platform (CmmLocal dst)
return $ code_src src_r `appOL` code_mask mask_r `appOL`
(if width == W8 then
-- The PEXT instruction doesn't take a r/m8
unitOL (MOVZxL II8 (OpReg src_r ) (OpReg src_r )) `appOL`
unitOL (MOVZxL II8 (OpReg mask_r) (OpReg mask_r)) `appOL`
unitOL (PEXT II16 (OpReg mask_r) (OpReg src_r) dst_r)
else
unitOL (PEXT format (OpReg mask_r) (OpReg src_r) dst_r)) `appOL`
(if width == W8 || width == W16 then
-- We used a 16-bit destination register above,
-- so zero-extend
unitOL (MOVZxL II16 (OpReg dst_r) (OpReg dst_r))
else nilOL)
else do
targetExpr <- cmmMakeDynamicReference dflags
CallReference lbl
let target = ForeignTarget targetExpr (ForeignConvention CCallConv
[NoHint] [NoHint]
CmmMayReturn)
genCCall' dflags is32Bit target dest_regs args bid
where
format = intFormat width
lbl = mkCmmCodeLabel primUnitId (fsLit (pextLabel width))
genCCall' dflags is32Bit (PrimTarget (MO_Clz width)) dest_regs@[dst] args@[src] bid
| is32Bit && width == W64 = do
-- Fallback to `hs_clz64` on i386
targetExpr <- cmmMakeDynamicReference dflags CallReference lbl
let target = ForeignTarget targetExpr (ForeignConvention CCallConv
[NoHint] [NoHint]
CmmMayReturn)
genCCall' dflags is32Bit target dest_regs args bid
| otherwise = do
code_src <- getAnyReg src
let dst_r = getRegisterReg platform (CmmLocal dst)
if isBmi2Enabled dflags
then do
src_r <- getNewRegNat (intFormat width)
return $ appOL (code_src src_r) $ case width of
W8 -> toOL
[ MOVZxL II8 (OpReg src_r) (OpReg src_r) -- zero-extend to 32 bit
, LZCNT II32 (OpReg src_r) dst_r -- lzcnt with extra 24 zeros
, SUB II32 (OpImm (ImmInt 24)) (OpReg dst_r) -- compensate for extra zeros
]
W16 -> toOL
[ LZCNT II16 (OpReg src_r) dst_r
, MOVZxL II16 (OpReg dst_r) (OpReg dst_r) -- zero-extend from 16 bit
]
_ -> unitOL (LZCNT (intFormat width) (OpReg src_r) dst_r)
else do
let format = if width == W8 then II16 else intFormat width
src_r <- getNewRegNat format
tmp_r <- getNewRegNat format
return $ code_src src_r `appOL` toOL
([ MOVZxL II8 (OpReg src_r) (OpReg src_r) | width == W8 ] ++
[ BSR format (OpReg src_r) tmp_r
, MOV II32 (OpImm (ImmInt (2*bw-1))) (OpReg dst_r)
, CMOV NE format (OpReg tmp_r) dst_r
, XOR format (OpImm (ImmInt (bw-1))) (OpReg dst_r)
]) -- NB: We don't need to zero-extend the result for the
-- W8/W16 cases because the 'MOV' insn already
-- took care of implicitly clearing the upper bits
where
bw = widthInBits width
platform = targetPlatform dflags
lbl = mkCmmCodeLabel primUnitId (fsLit (clzLabel width))
genCCall' dflags is32Bit (PrimTarget (MO_UF_Conv width)) dest_regs args bid = do
targetExpr <- cmmMakeDynamicReference dflags
CallReference lbl
let target = ForeignTarget targetExpr (ForeignConvention CCallConv
[NoHint] [NoHint]
CmmMayReturn)
genCCall' dflags is32Bit target dest_regs args bid
where
lbl = mkCmmCodeLabel primUnitId (fsLit (word2FloatLabel width))
genCCall' dflags _ (PrimTarget (MO_AtomicRead width)) [dst] [addr] _ = do
load_code <- intLoadCode (MOV (intFormat width)) addr
let platform = targetPlatform dflags
return (load_code (getRegisterReg platform (CmmLocal dst)))
genCCall' _ _ (PrimTarget (MO_AtomicWrite width)) [] [addr, val] _ = do
code <- assignMem_IntCode (intFormat width) addr val
return $ code `snocOL` MFENCE
genCCall' dflags is32Bit (PrimTarget (MO_Cmpxchg width)) [dst] [addr, old, new] _ = do
-- On x86 we don't have enough registers to use cmpxchg with a
-- complicated addressing mode, so on that architecture we
-- pre-compute the address first.
Amode amode addr_code <- getSimpleAmode dflags is32Bit addr
newval <- getNewRegNat format
newval_code <- getAnyReg new
oldval <- getNewRegNat format
oldval_code <- getAnyReg old
let platform = targetPlatform dflags
dst_r = getRegisterReg platform (CmmLocal dst)
code = toOL
[ MOV format (OpReg oldval) (OpReg eax)
, LOCK (CMPXCHG format (OpReg newval) (OpAddr amode))
, MOV format (OpReg eax) (OpReg dst_r)
]
return $ addr_code `appOL` newval_code newval `appOL` oldval_code oldval
`appOL` code
where
format = intFormat width
genCCall' _ is32Bit target dest_regs args bid = do
dflags <- getDynFlags
let platform = targetPlatform dflags
case (target, dest_regs) of
-- void return type prim op
(PrimTarget op, []) ->
outOfLineCmmOp bid op Nothing args
-- we only cope with a single result for foreign calls
(PrimTarget op, [r]) -> case op of
MO_F32_Fabs -> case args of
[x] -> sse2FabsCode W32 x
_ -> panic "genCCall: Wrong number of arguments for fabs"
MO_F64_Fabs -> case args of
[x] -> sse2FabsCode W64 x
_ -> panic "genCCall: Wrong number of arguments for fabs"
MO_F32_Sqrt -> actuallyInlineSSE2Op (\fmt r -> SQRT fmt (OpReg r)) FF32 args
MO_F64_Sqrt -> actuallyInlineSSE2Op (\fmt r -> SQRT fmt (OpReg r)) FF64 args
_other_op -> outOfLineCmmOp bid op (Just r) args
where
actuallyInlineSSE2Op = actuallyInlineFloatOp'
actuallyInlineFloatOp' instr format [x]
= do res <- trivialUFCode format (instr format) x
any <- anyReg res
return (any (getRegisterReg platform (CmmLocal r)))
actuallyInlineFloatOp' _ _ args
= panic $ "genCCall.actuallyInlineFloatOp': bad number of arguments! ("
++ show (length args) ++ ")"
sse2FabsCode :: Width -> CmmExpr -> NatM InstrBlock
sse2FabsCode w x = do
let fmt = floatFormat w
x_code <- getAnyReg x
let
const | FF32 <- fmt = CmmInt 0x7fffffff W32
| otherwise = CmmInt 0x7fffffffffffffff W64
Amode amode amode_code <- memConstant (mkAlignment $ widthInBytes w) const
tmp <- getNewRegNat fmt
let
code dst = x_code dst `appOL` amode_code `appOL` toOL [
MOV fmt (OpAddr amode) (OpReg tmp),
AND fmt (OpReg tmp) (OpReg dst)
]
return $ code (getRegisterReg platform (CmmLocal r))
(PrimTarget (MO_S_QuotRem width), _) -> divOp1 platform True width dest_regs args
(PrimTarget (MO_U_QuotRem width), _) -> divOp1 platform False width dest_regs args
(PrimTarget (MO_U_QuotRem2 width), _) -> divOp2 platform False width dest_regs args
(PrimTarget (MO_Add2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do hCode <- getAnyReg (CmmLit (CmmInt 0 width))
let format = intFormat width
lCode <- anyReg =<< trivialCode width (ADD_CC format)
(Just (ADD_CC format)) arg_x arg_y
let reg_l = getRegisterReg platform (CmmLocal res_l)
reg_h = getRegisterReg platform (CmmLocal res_h)
code = hCode reg_h `appOL`
lCode reg_l `snocOL`
ADC format (OpImm (ImmInteger 0)) (OpReg reg_h)
return code
_ -> panic "genCCall: Wrong number of arguments/results for add2"
(PrimTarget (MO_AddWordC width), [res_r, res_c]) ->
addSubIntC platform ADD_CC (const Nothing) CARRY width res_r res_c args
(PrimTarget (MO_SubWordC width), [res_r, res_c]) ->
addSubIntC platform SUB_CC (const Nothing) CARRY width res_r res_c args
(PrimTarget (MO_AddIntC width), [res_r, res_c]) ->
addSubIntC platform ADD_CC (Just . ADD_CC) OFLO width res_r res_c args
(PrimTarget (MO_SubIntC width), [res_r, res_c]) ->
addSubIntC platform SUB_CC (const Nothing) OFLO width res_r res_c args
(PrimTarget (MO_U_Mul2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do (y_reg, y_code) <- getRegOrMem arg_y
x_code <- getAnyReg arg_x
let format = intFormat width
reg_h = getRegisterReg platform (CmmLocal res_h)
reg_l = getRegisterReg platform (CmmLocal res_l)
code = y_code `appOL`
x_code rax `appOL`
toOL [MUL2 format y_reg,
MOV format (OpReg rdx) (OpReg reg_h),
MOV format (OpReg rax) (OpReg reg_l)]
return code
_ -> panic "genCCall: Wrong number of arguments/results for mul2"
(PrimTarget (MO_S_Mul2 width), [res_c, res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do (y_reg, y_code) <- getRegOrMem arg_y
x_code <- getAnyReg arg_x
reg_tmp <- getNewRegNat II8
let format = intFormat width
reg_h = getRegisterReg platform (CmmLocal res_h)
reg_l = getRegisterReg platform (CmmLocal res_l)
reg_c = getRegisterReg platform (CmmLocal res_c)
code = y_code `appOL`
x_code rax `appOL`
toOL [ IMUL2 format y_reg
, MOV format (OpReg rdx) (OpReg reg_h)
, MOV format (OpReg rax) (OpReg reg_l)
, SETCC CARRY (OpReg reg_tmp)
, MOVZxL II8 (OpReg reg_tmp) (OpReg reg_c)
]
return code
_ -> panic "genCCall: Wrong number of arguments/results for imul2"
_ -> if is32Bit
then genCCall32' dflags target dest_regs args
else genCCall64' dflags target dest_regs args
where divOp1 platform signed width results [arg_x, arg_y]
= divOp platform signed width results Nothing arg_x arg_y
divOp1 _ _ _ _ _
= panic "genCCall: Wrong number of arguments for divOp1"
divOp2 platform signed width results [arg_x_high, arg_x_low, arg_y]
= divOp platform signed width results (Just arg_x_high) arg_x_low arg_y
divOp2 _ _ _ _ _
= panic "genCCall: Wrong number of arguments for divOp2"
-- See Note [DIV/IDIV for bytes]
divOp platform signed W8 [res_q, res_r] m_arg_x_high arg_x_low arg_y =
let widen | signed = MO_SS_Conv W8 W16
| otherwise = MO_UU_Conv W8 W16
arg_x_low_16 = CmmMachOp widen [arg_x_low]
arg_y_16 = CmmMachOp widen [arg_y]
m_arg_x_high_16 = (\p -> CmmMachOp widen [p]) <$> m_arg_x_high
in divOp
platform signed W16 [res_q, res_r]
m_arg_x_high_16 arg_x_low_16 arg_y_16
divOp platform signed width [res_q, res_r]
m_arg_x_high arg_x_low arg_y
= do let format = intFormat width
reg_q = getRegisterReg platform (CmmLocal res_q)
reg_r = getRegisterReg platform (CmmLocal res_r)
widen | signed = CLTD format
| otherwise = XOR format (OpReg rdx) (OpReg rdx)
instr | signed = IDIV
| otherwise = DIV
(y_reg, y_code) <- getRegOrMem arg_y
x_low_code <- getAnyReg arg_x_low
x_high_code <- case m_arg_x_high of
Just arg_x_high ->
getAnyReg arg_x_high
Nothing ->
return $ const $ unitOL widen
return $ y_code `appOL`
x_low_code rax `appOL`
x_high_code rdx `appOL`
toOL [instr format y_reg,
MOV format (OpReg rax) (OpReg reg_q),
MOV format (OpReg rdx) (OpReg reg_r)]
divOp _ _ _ _ _ _ _
= panic "genCCall: Wrong number of results for divOp"
addSubIntC platform instr mrevinstr cond width
res_r res_c [arg_x, arg_y]
= do let format = intFormat width
rCode <- anyReg =<< trivialCode width (instr format)
(mrevinstr format) arg_x arg_y
reg_tmp <- getNewRegNat II8
let reg_c = getRegisterReg platform (CmmLocal res_c)
reg_r = getRegisterReg platform (CmmLocal res_r)
code = rCode reg_r `snocOL`
SETCC cond (OpReg reg_tmp) `snocOL`
MOVZxL II8 (OpReg reg_tmp) (OpReg reg_c)
return code
addSubIntC _ _ _ _ _ _ _ _
= panic "genCCall: Wrong number of arguments/results for addSubIntC"
-- Note [DIV/IDIV for bytes]
--
-- IDIV reminder:
-- Size Dividend Divisor Quotient Remainder
-- byte %ax r/m8 %al %ah
-- word %dx:%ax r/m16 %ax %dx
-- dword %edx:%eax r/m32 %eax %edx
-- qword %rdx:%rax r/m64 %rax %rdx
--
-- We do a special case for the byte division because the current
-- codegen doesn't deal well with accessing %ah register (also,
-- accessing %ah in 64-bit mode is complicated because it cannot be an
-- operand of many instructions). So we just widen operands to 16 bits
-- and get the results from %al, %dl. This is not optimal, but a few
-- register moves are probably not a huge deal when doing division.
genCCall32' :: DynFlags
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall32' dflags target dest_regs args = do
let
prom_args = map (maybePromoteCArg dflags W32) args
-- Align stack to 16n for calls, assuming a starting stack
-- alignment of 16n - word_size on procedure entry. Which we
-- maintiain. See Note [rts/StgCRun.c : Stack Alignment on X86]
sizes = map (arg_size_bytes . cmmExprType dflags) (reverse args)
raw_arg_size = sum sizes + wORD_SIZE dflags
arg_pad_size = (roundTo 16 $ raw_arg_size) - raw_arg_size
tot_arg_size = raw_arg_size + arg_pad_size - wORD_SIZE dflags
delta0 <- getDeltaNat
setDeltaNat (delta0 - arg_pad_size)
push_codes <- mapM push_arg (reverse prom_args)
delta <- getDeltaNat
MASSERT(delta == delta0 - tot_arg_size)
-- deal with static vs dynamic call targets
(callinsns,cconv) <-
case target of
ForeignTarget (CmmLit (CmmLabel lbl)) conv
-> -- ToDo: stdcall arg sizes
return (unitOL (CALL (Left fn_imm) []), conv)
where fn_imm = ImmCLbl lbl
ForeignTarget expr conv
-> do { (dyn_r, dyn_c) <- getSomeReg expr
; ASSERT( isWord32 (cmmExprType dflags expr) )
return (dyn_c `snocOL` CALL (Right dyn_r) [], conv) }
PrimTarget _
-> panic $ "genCCall: Can't handle PrimTarget call type here, error "
++ "probably because too many return values."
let push_code
| arg_pad_size /= 0
= toOL [SUB II32 (OpImm (ImmInt arg_pad_size)) (OpReg esp),
DELTA (delta0 - arg_pad_size)]
`appOL` concatOL push_codes
| otherwise
= concatOL push_codes
-- Deallocate parameters after call for ccall;
-- but not for stdcall (callee does it)
--
-- We have to pop any stack padding we added
-- even if we are doing stdcall, though (#5052)
pop_size
| ForeignConvention StdCallConv _ _ _ <- cconv = arg_pad_size
| otherwise = tot_arg_size
call = callinsns `appOL`
toOL (
(if pop_size==0 then [] else
[ADD II32 (OpImm (ImmInt pop_size)) (OpReg esp)])
++
[DELTA delta0]
)
setDeltaNat delta0
dflags <- getDynFlags
let platform = targetPlatform dflags
let
-- assign the results, if necessary
assign_code [] = nilOL
assign_code [dest]
| isFloatType ty =
-- we assume SSE2
let tmp_amode = AddrBaseIndex (EABaseReg esp)
EAIndexNone
(ImmInt 0)
fmt = floatFormat w
in toOL [ SUB II32 (OpImm (ImmInt b)) (OpReg esp),
DELTA (delta0 - b),
X87Store fmt tmp_amode,
-- X87Store only supported for the CDECL ABI
-- NB: This code will need to be
-- revisted once GHC does more work around
-- SIGFPE f
MOV fmt (OpAddr tmp_amode) (OpReg r_dest),
ADD II32 (OpImm (ImmInt b)) (OpReg esp),
DELTA delta0]
| isWord64 ty = toOL [MOV II32 (OpReg eax) (OpReg r_dest),
MOV II32 (OpReg edx) (OpReg r_dest_hi)]
| otherwise = unitOL (MOV (intFormat w)
(OpReg eax)
(OpReg r_dest))
where
ty = localRegType dest
w = typeWidth ty
b = widthInBytes w
r_dest_hi = getHiVRegFromLo r_dest
r_dest = getRegisterReg platform (CmmLocal dest)
assign_code many = pprPanic "genCCall.assign_code - too many return values:" (ppr many)
return (push_code `appOL`
call `appOL`
assign_code dest_regs)
where
-- If the size is smaller than the word, we widen things (see maybePromoteCArg)
arg_size_bytes :: CmmType -> Int
arg_size_bytes ty = max (widthInBytes (typeWidth ty)) (widthInBytes (wordWidth dflags))
roundTo a x | x `mod` a == 0 = x
| otherwise = x + a - (x `mod` a)
push_arg :: CmmActual {-current argument-}
-> NatM InstrBlock -- code
push_arg arg -- we don't need the hints on x86
| isWord64 arg_ty = do
ChildCode64 code r_lo <- iselExpr64 arg
delta <- getDeltaNat
setDeltaNat (delta - 8)
let r_hi = getHiVRegFromLo r_lo
return ( code `appOL`
toOL [PUSH II32 (OpReg r_hi), DELTA (delta - 4),
PUSH II32 (OpReg r_lo), DELTA (delta - 8),
DELTA (delta-8)]
)
| isFloatType arg_ty = do
(reg, code) <- getSomeReg arg
delta <- getDeltaNat
setDeltaNat (delta-size)
return (code `appOL`
toOL [SUB II32 (OpImm (ImmInt size)) (OpReg esp),
DELTA (delta-size),
let addr = AddrBaseIndex (EABaseReg esp)
EAIndexNone
(ImmInt 0)
format = floatFormat (typeWidth arg_ty)
in
-- assume SSE2
MOV format (OpReg reg) (OpAddr addr)
]
)
| otherwise = do
-- Arguments can be smaller than 32-bit, but we still use @PUSH
-- II32@ - the usual calling conventions expect integers to be
-- 4-byte aligned.
ASSERT((typeWidth arg_ty) <= W32) return ()
(operand, code) <- getOperand arg
delta <- getDeltaNat
setDeltaNat (delta-size)
return (code `snocOL`
PUSH II32 operand `snocOL`
DELTA (delta-size))
where
arg_ty = cmmExprType dflags arg
size = arg_size_bytes arg_ty -- Byte size
genCCall64' :: DynFlags
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall64' dflags target dest_regs args = do
-- load up the register arguments
let prom_args = map (maybePromoteCArg dflags W32) args
(stack_args, int_regs_used, fp_regs_used, load_args_code, assign_args_code)
<-
if platformOS platform == OSMinGW32
then load_args_win prom_args [] [] (allArgRegs platform) nilOL
else do
(stack_args, aregs, fregs, load_args_code, assign_args_code)
<- load_args prom_args (allIntArgRegs platform)
(allFPArgRegs platform)
nilOL nilOL
let used_regs rs as = reverse (drop (length rs) (reverse as))
fregs_used = used_regs fregs (allFPArgRegs platform)
aregs_used = used_regs aregs (allIntArgRegs platform)
return (stack_args, aregs_used, fregs_used, load_args_code
, assign_args_code)
let
arg_regs_used = int_regs_used ++ fp_regs_used
arg_regs = [eax] ++ arg_regs_used
-- for annotating the call instruction with
sse_regs = length fp_regs_used
arg_stack_slots = if platformOS platform == OSMinGW32
then length stack_args + length (allArgRegs platform)
else length stack_args
tot_arg_size = arg_size * arg_stack_slots
-- Align stack to 16n for calls, assuming a starting stack
-- alignment of 16n - word_size on procedure entry. Which we
-- maintain. See Note [rts/StgCRun.c : Stack Alignment on X86]
(real_size, adjust_rsp) <-
if (tot_arg_size + wORD_SIZE dflags) `rem` 16 == 0
then return (tot_arg_size, nilOL)
else do -- we need to adjust...
delta <- getDeltaNat
setDeltaNat (delta - wORD_SIZE dflags)
return (tot_arg_size + wORD_SIZE dflags, toOL [
SUB II64 (OpImm (ImmInt (wORD_SIZE dflags))) (OpReg rsp),
DELTA (delta - wORD_SIZE dflags) ])
-- push the stack args, right to left
push_code <- push_args (reverse stack_args) nilOL
-- On Win64, we also have to leave stack space for the arguments
-- that we are passing in registers
lss_code <- if platformOS platform == OSMinGW32
then leaveStackSpace (length (allArgRegs platform))
else return nilOL
delta <- getDeltaNat
-- deal with static vs dynamic call targets
(callinsns,_cconv) <-
case target of
ForeignTarget (CmmLit (CmmLabel lbl)) conv
-> -- ToDo: stdcall arg sizes
return (unitOL (CALL (Left fn_imm) arg_regs), conv)
where fn_imm = ImmCLbl lbl
ForeignTarget expr conv
-> do (dyn_r, dyn_c) <- getSomeReg expr
return (dyn_c `snocOL` CALL (Right dyn_r) arg_regs, conv)
PrimTarget _
-> panic $ "genCCall: Can't handle PrimTarget call type here, error "
++ "probably because too many return values."
let
-- The x86_64 ABI requires us to set %al to the number of SSE2
-- registers that contain arguments, if the called routine
-- is a varargs function. We don't know whether it's a
-- varargs function or not, so we have to assume it is.
--
-- It's not safe to omit this assignment, even if the number
-- of SSE2 regs in use is zero. If %al is larger than 8
-- on entry to a varargs function, seg faults ensue.
assign_eax n = unitOL (MOV II32 (OpImm (ImmInt n)) (OpReg eax))
let call = callinsns `appOL`
toOL (
-- Deallocate parameters after call for ccall;
-- stdcall has callee do it, but is not supported on
-- x86_64 target (see #3336)
(if real_size==0 then [] else
[ADD (intFormat (wordWidth dflags)) (OpImm (ImmInt real_size)) (OpReg esp)])
++
[DELTA (delta + real_size)]
)
setDeltaNat (delta + real_size)
let
-- assign the results, if necessary
assign_code [] = nilOL
assign_code [dest] =
case typeWidth rep of
W32 | isFloatType rep -> unitOL (MOV (floatFormat W32)
(OpReg xmm0)
(OpReg r_dest))
W64 | isFloatType rep -> unitOL (MOV (floatFormat W64)
(OpReg xmm0)
(OpReg r_dest))
_ -> unitOL (MOV (cmmTypeFormat rep) (OpReg rax) (OpReg r_dest))
where
rep = localRegType dest
r_dest = getRegisterReg platform (CmmLocal dest)
assign_code _many = panic "genCCall.assign_code many"
return (adjust_rsp `appOL`
push_code `appOL`
load_args_code `appOL`
assign_args_code `appOL`
lss_code `appOL`
assign_eax sse_regs `appOL`
call `appOL`
assign_code dest_regs)
where platform = targetPlatform dflags
arg_size = 8 -- always, at the mo
load_args :: [CmmExpr]
-> [Reg] -- int regs avail for args
-> [Reg] -- FP regs avail for args
-> InstrBlock -- code computing args
-> InstrBlock -- code assigning args to ABI regs
-> NatM ([CmmExpr],[Reg],[Reg],InstrBlock,InstrBlock)
-- no more regs to use
load_args args [] [] code acode =
return (args, [], [], code, acode)
-- no more args to push
load_args [] aregs fregs code acode =
return ([], aregs, fregs, code, acode)
load_args (arg : rest) aregs fregs code acode
| isFloatType arg_rep = case fregs of
[] -> push_this_arg
(r:rs) -> do
(code',acode') <- reg_this_arg r
load_args rest aregs rs code' acode'
| otherwise = case aregs of
[] -> push_this_arg
(r:rs) -> do
(code',acode') <- reg_this_arg r
load_args rest rs fregs code' acode'
where
-- put arg into the list of stack pushed args
push_this_arg = do
(args',ars,frs,code',acode')
<- load_args rest aregs fregs code acode
return (arg:args', ars, frs, code', acode')
-- pass the arg into the given register
reg_this_arg r
-- "operand" args can be directly assigned into r
| isOperand False arg = do
arg_code <- getAnyReg arg
return (code, (acode `appOL` arg_code r))
-- The last non-operand arg can be directly assigned after its
-- computation without going into a temporary register
| all (isOperand False) rest = do
arg_code <- getAnyReg arg
return (code `appOL` arg_code r,acode)
-- other args need to be computed beforehand to avoid clobbering
-- previously assigned registers used to pass parameters (see
-- #11792, #12614). They are assigned into temporary registers
-- and get assigned to proper call ABI registers after they all
-- have been computed.
| otherwise = do
arg_code <- getAnyReg arg
tmp <- getNewRegNat arg_fmt
let
code' = code `appOL` arg_code tmp
acode' = acode `snocOL` reg2reg arg_fmt tmp r
return (code',acode')
arg_rep = cmmExprType dflags arg
arg_fmt = cmmTypeFormat arg_rep
load_args_win :: [CmmExpr]
-> [Reg] -- used int regs
-> [Reg] -- used FP regs
-> [(Reg, Reg)] -- (int, FP) regs avail for args
-> InstrBlock
-> NatM ([CmmExpr],[Reg],[Reg],InstrBlock,InstrBlock)
load_args_win args usedInt usedFP [] code
= return (args, usedInt, usedFP, code, nilOL)
-- no more regs to use
load_args_win [] usedInt usedFP _ code
= return ([], usedInt, usedFP, code, nilOL)
-- no more args to push
load_args_win (arg : rest) usedInt usedFP
((ireg, freg) : regs) code
| isFloatType arg_rep = do
arg_code <- getAnyReg arg
load_args_win rest (ireg : usedInt) (freg : usedFP) regs
(code `appOL`
arg_code freg `snocOL`
-- If we are calling a varargs function
-- then we need to define ireg as well
-- as freg
MOV II64 (OpReg freg) (OpReg ireg))
| otherwise = do
arg_code <- getAnyReg arg
load_args_win rest (ireg : usedInt) usedFP regs
(code `appOL` arg_code ireg)
where
arg_rep = cmmExprType dflags arg
push_args [] code = return code
push_args (arg:rest) code
| isFloatType arg_rep = do
(arg_reg, arg_code) <- getSomeReg arg
delta <- getDeltaNat
setDeltaNat (delta-arg_size)
let code' = code `appOL` arg_code `appOL` toOL [
SUB (intFormat (wordWidth dflags)) (OpImm (ImmInt arg_size)) (OpReg rsp),
DELTA (delta-arg_size),
MOV (floatFormat width) (OpReg arg_reg) (OpAddr (spRel dflags 0))]
push_args rest code'
| otherwise = do
-- Arguments can be smaller than 64-bit, but we still use @PUSH
-- II64@ - the usual calling conventions expect integers to be
-- 8-byte aligned.
ASSERT(width <= W64) return ()
(arg_op, arg_code) <- getOperand arg
delta <- getDeltaNat
setDeltaNat (delta-arg_size)
let code' = code `appOL` arg_code `appOL` toOL [
PUSH II64 arg_op,
DELTA (delta-arg_size)]
push_args rest code'
where
arg_rep = cmmExprType dflags arg
width = typeWidth arg_rep
leaveStackSpace n = do
delta <- getDeltaNat
setDeltaNat (delta - n * arg_size)
return $ toOL [
SUB II64 (OpImm (ImmInt (n * wORD_SIZE dflags))) (OpReg rsp),
DELTA (delta - n * arg_size)]
maybePromoteCArg :: DynFlags -> Width -> CmmExpr -> CmmExpr
maybePromoteCArg dflags wto arg
| wfrom < wto = CmmMachOp (MO_UU_Conv wfrom wto) [arg]
| otherwise = arg
where
wfrom = cmmExprWidth dflags arg
outOfLineCmmOp :: BlockId -> CallishMachOp -> Maybe CmmFormal -> [CmmActual]
-> NatM InstrBlock
outOfLineCmmOp bid mop res args
= do
dflags <- getDynFlags
targetExpr <- cmmMakeDynamicReference dflags CallReference lbl
let target = ForeignTarget targetExpr
(ForeignConvention CCallConv [] [] CmmMayReturn)
-- We know foreign calls results in no new basic blocks, so we can ignore
-- the returned block id.
(instrs, _) <- stmtToInstrs bid (CmmUnsafeForeignCall target (catMaybes [res]) args)
return instrs
where
-- Assume we can call these functions directly, and that they're not in a dynamic library.
-- TODO: Why is this ok? Under linux this code will be in libm.so
-- Is it because they're really implemented as a primitive instruction by the assembler?? -- BL 2009/12/31
lbl = mkForeignLabel fn Nothing ForeignLabelInThisPackage IsFunction
fn = case mop of
MO_F32_Sqrt -> fsLit "sqrtf"
MO_F32_Fabs -> fsLit "fabsf"
MO_F32_Sin -> fsLit "sinf"
MO_F32_Cos -> fsLit "cosf"
MO_F32_Tan -> fsLit "tanf"
MO_F32_Exp -> fsLit "expf"
MO_F32_ExpM1 -> fsLit "expm1f"
MO_F32_Log -> fsLit "logf"
MO_F32_Log1P -> fsLit "log1pf"
MO_F32_Asin -> fsLit "asinf"
MO_F32_Acos -> fsLit "acosf"
MO_F32_Atan -> fsLit "atanf"
MO_F32_Sinh -> fsLit "sinhf"
MO_F32_Cosh -> fsLit "coshf"
MO_F32_Tanh -> fsLit "tanhf"
MO_F32_Pwr -> fsLit "powf"
MO_F32_Asinh -> fsLit "asinhf"
MO_F32_Acosh -> fsLit "acoshf"
MO_F32_Atanh -> fsLit "atanhf"
MO_F64_Sqrt -> fsLit "sqrt"
MO_F64_Fabs -> fsLit "fabs"
MO_F64_Sin -> fsLit "sin"
MO_F64_Cos -> fsLit "cos"
MO_F64_Tan -> fsLit "tan"
MO_F64_Exp -> fsLit "exp"
MO_F64_ExpM1 -> fsLit "expm1"
MO_F64_Log -> fsLit "log"
MO_F64_Log1P -> fsLit "log1p"
MO_F64_Asin -> fsLit "asin"
MO_F64_Acos -> fsLit "acos"
MO_F64_Atan -> fsLit "atan"
MO_F64_Sinh -> fsLit "sinh"
MO_F64_Cosh -> fsLit "cosh"
MO_F64_Tanh -> fsLit "tanh"
MO_F64_Pwr -> fsLit "pow"
MO_F64_Asinh -> fsLit "asinh"
MO_F64_Acosh -> fsLit "acosh"
MO_F64_Atanh -> fsLit "atanh"
MO_Memcpy _ -> fsLit "memcpy"
MO_Memset _ -> fsLit "memset"
MO_Memmove _ -> fsLit "memmove"
MO_Memcmp _ -> fsLit "memcmp"
MO_PopCnt _ -> fsLit "popcnt"
MO_BSwap _ -> fsLit "bswap"
{- Here the C implementation is used as there is no x86
instruction to reverse a word's bit order.
-}
MO_BRev w -> fsLit $ bRevLabel w
MO_Clz w -> fsLit $ clzLabel w
MO_Ctz _ -> unsupported
MO_Pdep w -> fsLit $ pdepLabel w
MO_Pext w -> fsLit $ pextLabel w
MO_AtomicRMW _ _ -> fsLit "atomicrmw"
MO_AtomicRead _ -> fsLit "atomicread"
MO_AtomicWrite _ -> fsLit "atomicwrite"
MO_Cmpxchg _ -> fsLit "cmpxchg"
MO_UF_Conv _ -> unsupported
MO_S_Mul2 {} -> unsupported
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_AddIntC {} -> unsupported
MO_SubIntC {} -> unsupported
MO_AddWordC {} -> unsupported
MO_SubWordC {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_ReadBarrier -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _ ) -> unsupported
unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported here")
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> NatM InstrBlock
genSwitch dflags expr targets
| positionIndependent dflags
= do
(reg,e_code) <- getNonClobberedReg (cmmOffset dflags expr offset)
-- getNonClobberedReg because it needs to survive across t_code
lbl <- getNewLabelNat
dflags <- getDynFlags
let is32bit = target32Bit (targetPlatform dflags)
os = platformOS (targetPlatform dflags)
-- Might want to use .rodata.<function we're in> instead, but as
-- long as it's something unique it'll work out since the
-- references to the jump table are in the appropriate section.
rosection = case os of
-- on Mac OS X/x86_64, put the jump table in the text section to
-- work around a limitation of the linker.
-- ld64 is unable to handle the relocations for
-- .quad L1 - L0
-- if L0 is not preceded by a non-anonymous label in its section.
OSDarwin | not is32bit -> Section Text lbl
_ -> Section ReadOnlyData lbl
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
(tableReg,t_code) <- getSomeReg $ dynRef
let op = OpAddr (AddrBaseIndex (EABaseReg tableReg)
(EAIndex reg (wORD_SIZE dflags)) (ImmInt 0))
offsetReg <- getNewRegNat (intFormat (wordWidth dflags))
return $ if is32bit || os == OSDarwin
then e_code `appOL` t_code `appOL` toOL [
ADD (intFormat (wordWidth dflags)) op (OpReg tableReg),
JMP_TBL (OpReg tableReg) ids rosection lbl
]
else -- HACK: On x86_64 binutils<2.17 is only able to generate
-- PC32 relocations, hence we only get 32-bit offsets in
-- the jump table. As these offsets are always negative
-- we need to properly sign extend them to 64-bit. This
-- hack should be removed in conjunction with the hack in
-- PprMach.hs/pprDataItem once binutils 2.17 is standard.
e_code `appOL` t_code `appOL` toOL [
MOVSxL II32 op (OpReg offsetReg),
ADD (intFormat (wordWidth dflags))
(OpReg offsetReg)
(OpReg tableReg),
JMP_TBL (OpReg tableReg) ids rosection lbl
]
| otherwise
= do
(reg,e_code) <- getSomeReg (cmmOffset dflags expr offset)
lbl <- getNewLabelNat
let op = OpAddr (AddrBaseIndex EABaseNone (EAIndex reg (wORD_SIZE dflags)) (ImmCLbl lbl))
code = e_code `appOL` toOL [
JMP_TBL op ids (Section ReadOnlyData lbl) lbl
]
return code
where
(offset, blockIds) = switchTargetsToTable targets
ids = map (fmap DestBlockId) blockIds
generateJumpTableForInstr :: DynFlags -> Instr -> Maybe (NatCmmDecl (Alignment, RawCmmStatics) Instr)
generateJumpTableForInstr dflags (JMP_TBL _ ids section lbl)
= let getBlockId (DestBlockId id) = id
getBlockId _ = panic "Non-Label target in Jump Table"
blockIds = map (fmap getBlockId) ids
in Just (createJumpTable dflags blockIds section lbl)
generateJumpTableForInstr _ _ = Nothing
createJumpTable :: DynFlags -> [Maybe BlockId] -> Section -> CLabel
-> GenCmmDecl (Alignment, RawCmmStatics) h g
createJumpTable dflags ids section lbl
= let jumpTable
| positionIndependent dflags =
let ww = wordWidth dflags
jumpTableEntryRel Nothing
= CmmStaticLit (CmmInt 0 ww)
jumpTableEntryRel (Just blockid)
= CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0 ww)
where blockLabel = blockLbl blockid
in map jumpTableEntryRel ids
| otherwise = map (jumpTableEntry dflags) ids
in CmmData section (mkAlignment 1, RawCmmStatics lbl jumpTable)
extractUnwindPoints :: [Instr] -> [UnwindPoint]
extractUnwindPoints instrs =
[ UnwindPoint lbl unwinds | UNWIND lbl unwinds <- instrs]
-- -----------------------------------------------------------------------------
-- 'condIntReg' and 'condFltReg': condition codes into registers
-- Turn those condition codes into integers now (when they appear on
-- the right hand side of an assignment).
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
condIntReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register
condIntReg cond x y = do
CondCode _ cond cond_code <- condIntCode cond x y
tmp <- getNewRegNat II8
let
code dst = cond_code `appOL` toOL [
SETCC cond (OpReg tmp),
MOVZxL II8 (OpReg tmp) (OpReg dst)
]
return (Any II32 code)
-----------------------------------------------------------
--- Note [SSE Parity Checks] ---
-----------------------------------------------------------
-- We have to worry about unordered operands (eg. comparisons
-- against NaN). If the operands are unordered, the comparison
-- sets the parity flag, carry flag and zero flag.
-- All comparisons are supposed to return false for unordered
-- operands except for !=, which returns true.
--
-- Optimisation: we don't have to test the parity flag if we
-- know the test has already excluded the unordered case: eg >
-- and >= test for a zero carry flag, which can only occur for
-- ordered operands.
--
-- By reversing comparisons we can avoid testing the parity
-- for < and <= as well. If any of the arguments is an NaN we
-- return false either way. If both arguments are valid then
-- x <= y <-> y >= x holds. So it's safe to swap these.
--
-- We invert the condition inside getRegister'and getCondCode
-- which should cover all invertable cases.
-- All other functions translating FP comparisons to assembly
-- use these to two generate the comparison code.
--
-- As an example consider a simple check:
--
-- func :: Float -> Float -> Int
-- func x y = if x < y then 1 else 0
--
-- Which in Cmm gives the floating point comparison.
--
-- if (%MO_F_Lt_W32(F1, F2)) goto c2gg; else goto c2gf;
--
-- We used to compile this to an assembly code block like this:
-- _c2gh:
-- ucomiss %xmm2,%xmm1
-- jp _c2gf
-- jb _c2gg
-- jmp _c2gf
--
-- Where we have to introduce an explicit
-- check for unordered results (using jmp parity):
--
-- We can avoid this by exchanging the arguments and inverting the direction
-- of the comparison. This results in the sequence of:
--
-- ucomiss %xmm1,%xmm2
-- ja _c2g2
-- jmp _c2g1
--
-- Removing the jump reduces the pressure on the branch predidiction system
-- and plays better with the uOP cache.
condFltReg :: Bool -> Cond -> CmmExpr -> CmmExpr -> NatM Register
condFltReg is32Bit cond x y = condFltReg_sse2
where
condFltReg_sse2 = do
CondCode _ cond cond_code <- condFltCode cond x y
tmp1 <- getNewRegNat (archWordFormat is32Bit)
tmp2 <- getNewRegNat (archWordFormat is32Bit)
let -- See Note [SSE Parity Checks]
code dst =
cond_code `appOL`
(case cond of
NE -> or_unordered dst
GU -> plain_test dst
GEU -> plain_test dst
-- Use ASSERT so we don't break releases if these creep in.
LTT -> ASSERT2(False, ppr "Should have been turned into >")
and_ordered dst
LE -> ASSERT2(False, ppr "Should have been turned into >=")
and_ordered dst
_ -> and_ordered dst)
plain_test dst = toOL [
SETCC cond (OpReg tmp1),
MOVZxL II8 (OpReg tmp1) (OpReg dst)
]
or_unordered dst = toOL [
SETCC cond (OpReg tmp1),
SETCC PARITY (OpReg tmp2),
OR II8 (OpReg tmp1) (OpReg tmp2),
MOVZxL II8 (OpReg tmp2) (OpReg dst)
]
and_ordered dst = toOL [
SETCC cond (OpReg tmp1),
SETCC NOTPARITY (OpReg tmp2),
AND II8 (OpReg tmp1) (OpReg tmp2),
MOVZxL II8 (OpReg tmp2) (OpReg dst)
]
return (Any II32 code)
-- -----------------------------------------------------------------------------
-- 'trivial*Code': deal with trivial instructions
-- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode',
-- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions.
-- Only look for constants on the right hand side, because that's
-- where the generic optimizer will have put them.
-- Similarly, for unary instructions, we don't have to worry about
-- matching an StInt as the argument, because genericOpt will already
-- have handled the constant-folding.
{-
The Rules of the Game are:
* You cannot assume anything about the destination register dst;
it may be anything, including a fixed reg.
* You may compute an operand into a fixed reg, but you may not
subsequently change the contents of that fixed reg. If you
want to do so, first copy the value either to a temporary
or into dst. You are free to modify dst even if it happens
to be a fixed reg -- that's not your problem.
* You cannot assume that a fixed reg will stay live over an
arbitrary computation. The same applies to the dst reg.
* Temporary regs obtained from getNewRegNat are distinct from
each other and from all other regs, and stay live over
arbitrary computations.
--------------------
SDM's version of The Rules:
* If getRegister returns Any, that means it can generate correct
code which places the result in any register, period. Even if that
register happens to be read during the computation.
Corollary #1: this means that if you are generating code for an
operation with two arbitrary operands, you cannot assign the result
of the first operand into the destination register before computing
the second operand. The second operand might require the old value
of the destination register.
Corollary #2: A function might be able to generate more efficient
code if it knows the destination register is a new temporary (and
therefore not read by any of the sub-computations).
* If getRegister returns Any, then the code it generates may modify only:
(a) fresh temporaries
(b) the destination register
(c) known registers (eg. %ecx is used by shifts)
In particular, it may *not* modify global registers, unless the global
register happens to be the destination register.
-}
trivialCode :: Width -> (Operand -> Operand -> Instr)
-> Maybe (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCode width instr m a b
= do is32Bit <- is32BitPlatform
trivialCode' is32Bit width instr m a b
trivialCode' :: Bool -> Width -> (Operand -> Operand -> Instr)
-> Maybe (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCode' is32Bit width _ (Just revinstr) (CmmLit lit_a) b
| is32BitLit is32Bit lit_a = do
b_code <- getAnyReg b
let
code dst
= b_code dst `snocOL`
revinstr (OpImm (litToImm lit_a)) (OpReg dst)
return (Any (intFormat width) code)
trivialCode' _ width instr _ a b
= genTrivialCode (intFormat width) instr a b
-- This is re-used for floating pt instructions too.
genTrivialCode :: Format -> (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
genTrivialCode rep instr a b = do
(b_op, b_code) <- getNonClobberedOperand b
a_code <- getAnyReg a
tmp <- getNewRegNat rep
let
-- We want the value of b to stay alive across the computation of a.
-- But, we want to calculate a straight into the destination register,
-- because the instruction only has two operands (dst := dst `op` src).
-- The troublesome case is when the result of b is in the same register
-- as the destination reg. In this case, we have to save b in a
-- new temporary across the computation of a.
code dst
| dst `regClashesWithOp` b_op =
b_code `appOL`
unitOL (MOV rep b_op (OpReg tmp)) `appOL`
a_code dst `snocOL`
instr (OpReg tmp) (OpReg dst)
| otherwise =
b_code `appOL`
a_code dst `snocOL`
instr b_op (OpReg dst)
return (Any rep code)
regClashesWithOp :: Reg -> Operand -> Bool
reg `regClashesWithOp` OpReg reg2 = reg == reg2
reg `regClashesWithOp` OpAddr amode = any (==reg) (addrModeRegs amode)
_ `regClashesWithOp` _ = False
-----------
trivialUCode :: Format -> (Operand -> Instr)
-> CmmExpr -> NatM Register
trivialUCode rep instr x = do
x_code <- getAnyReg x
let
code dst =
x_code dst `snocOL`
instr (OpReg dst)
return (Any rep code)
-----------
trivialFCode_sse2 :: Width -> (Format -> Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialFCode_sse2 pk instr x y
= genTrivialCode format (instr format) x y
where format = floatFormat pk
trivialUFCode :: Format -> (Reg -> Reg -> Instr) -> CmmExpr -> NatM Register
trivialUFCode format instr x = do
(x_reg, x_code) <- getSomeReg x
let
code dst =
x_code `snocOL`
instr x_reg dst
return (Any format code)
--------------------------------------------------------------------------------
coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register
coerceInt2FP from to x = coerce_sse2
where
coerce_sse2 = do
(x_op, x_code) <- getOperand x -- ToDo: could be a safe operand
let
opc = case to of W32 -> CVTSI2SS; W64 -> CVTSI2SD
n -> panic $ "coerceInt2FP.sse: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc (intFormat from) x_op dst
return (Any (floatFormat to) code)
-- works even if the destination rep is <II32
--------------------------------------------------------------------------------
coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register
coerceFP2Int from to x = coerceFP2Int_sse2
where
coerceFP2Int_sse2 = do
(x_op, x_code) <- getOperand x -- ToDo: could be a safe operand
let
opc = case from of W32 -> CVTTSS2SIQ; W64 -> CVTTSD2SIQ;
n -> panic $ "coerceFP2Init.sse: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc (intFormat to) x_op dst
return (Any (intFormat to) code)
-- works even if the destination rep is <II32
--------------------------------------------------------------------------------
coerceFP2FP :: Width -> CmmExpr -> NatM Register
coerceFP2FP to x = do
(x_reg, x_code) <- getSomeReg x
let
opc = case to of W32 -> CVTSD2SS; W64 -> CVTSS2SD;
n -> panic $ "coerceFP2FP: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc x_reg dst
return (Any ( floatFormat to) code)
--------------------------------------------------------------------------------
sse2NegCode :: Width -> CmmExpr -> NatM Register
sse2NegCode w x = do
let fmt = floatFormat w
x_code <- getAnyReg x
-- This is how gcc does it, so it can't be that bad:
let
const = case fmt of
FF32 -> CmmInt 0x80000000 W32
FF64 -> CmmInt 0x8000000000000000 W64
x@II8 -> wrongFmt x
x@II16 -> wrongFmt x
x@II32 -> wrongFmt x
x@II64 -> wrongFmt x
where
wrongFmt x = panic $ "sse2NegCode: " ++ show x
Amode amode amode_code <- memConstant (mkAlignment $ widthInBytes w) const
tmp <- getNewRegNat fmt
let
code dst = x_code dst `appOL` amode_code `appOL` toOL [
MOV fmt (OpAddr amode) (OpReg tmp),
XOR fmt (OpReg tmp) (OpReg dst)
]
--
return (Any fmt code)
isVecExpr :: CmmExpr -> Bool
isVecExpr (CmmMachOp (MO_V_Insert {}) _) = True
isVecExpr (CmmMachOp (MO_V_Extract {}) _) = True
isVecExpr (CmmMachOp (MO_V_Add {}) _) = True
isVecExpr (CmmMachOp (MO_V_Sub {}) _) = True
isVecExpr (CmmMachOp (MO_V_Mul {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Quot {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Rem {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Neg {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Insert {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Extract {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Add {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Sub {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Mul {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Quot {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Neg {}) _) = True
isVecExpr (CmmMachOp _ [e]) = isVecExpr e
isVecExpr _ = False
needLlvm :: NatM a
needLlvm =
sorry $ unlines ["The native code generator does not support vector"
,"instructions. Please use -fllvm."]
-- | This works on the invariant that all jumps in the given blocks are required.
-- Starting from there we try to make a few more jumps redundant by reordering
-- them.
-- We depend on the information in the CFG to do so so without a given CFG
-- we do nothing.
invertCondBranches :: Maybe CFG -- ^ CFG if present
-> LabelMap a -- ^ Blocks with info tables
-> [NatBasicBlock Instr] -- ^ List of basic blocks
-> [NatBasicBlock Instr]
invertCondBranches Nothing _ bs = bs
invertCondBranches (Just cfg) keep bs =
invert bs
where
invert :: [NatBasicBlock Instr] -> [NatBasicBlock Instr]
invert ((BasicBlock lbl1 ins@(_:_:_xs)):b2@(BasicBlock lbl2 _):bs)
| --pprTrace "Block" (ppr lbl1) True,
(jmp1,jmp2) <- last2 ins
, JXX cond1 target1 <- jmp1
, target1 == lbl2
--, pprTrace "CutChance" (ppr b1) True
, JXX ALWAYS target2 <- jmp2
-- We have enough information to check if we can perform the inversion
-- TODO: We could also check for the last asm instruction which sets
-- status flags instead. Which I suspect is worse in terms of compiler
-- performance, but might be applicable to more cases
, Just edgeInfo1 <- getEdgeInfo lbl1 target1 cfg
, Just edgeInfo2 <- getEdgeInfo lbl1 target2 cfg
-- Both jumps come from the same cmm statement
, transitionSource edgeInfo1 == transitionSource edgeInfo2
, CmmSource {trans_cmmNode = cmmCondBranch} <- transitionSource edgeInfo1
--Int comparisons are invertable
, CmmCondBranch (CmmMachOp op _args) _ _ _ <- cmmCondBranch
, Just _ <- maybeIntComparison op
, Just invCond <- maybeInvertCond cond1
--Swap the last two jumps, invert the conditional jumps condition.
= let jumps =
case () of
-- We are free the eliminate the jmp. So we do so.
_ | not (mapMember target1 keep)
-> [JXX invCond target2]
-- If the conditional target is unlikely we put the other
-- target at the front.
| edgeWeight edgeInfo2 > edgeWeight edgeInfo1
-> [JXX invCond target2, JXX ALWAYS target1]
-- Keep things as-is otherwise
| otherwise
-> [jmp1, jmp2]
in --pprTrace "Cutable" (ppr [jmp1,jmp2] <+> text "=>" <+> ppr jumps) $
(BasicBlock lbl1
(dropTail 2 ins ++ jumps))
: invert (b2:bs)
invert (b:bs) = b : invert bs
invert [] = []
| sdiehl/ghc | compiler/nativeGen/X86/CodeGen.hs | bsd-3-clause | 148,774 | 0 | 24 | 49,676 | 35,273 | 17,485 | 17,788 | 2,387 | 126 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
import Shelly
( Sh, cmd, echo_err, errExit, escaping, exit, fromText, liftIO, rm_f
, runHandle, shelly, verbosely
)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO (hGetLine, hPutStrLn, putStrLn)
import Data.Sequence ((|>), ViewL((:<), EmptyL))
import qualified Data.Sequence as S (Seq, empty, viewl)
import System.Environment (getArgs, getProgName)
import System.IO (Handle, hClose, openTempFile)
import System.IO.Error (IOError)
import qualified System.Process as Proc (system)
import Control.Exception (try)
import BinSrc.GitUtils (truncate_colorized_line)
import BinSrc.TermSize (get_terminal_cols)
default (T.Text)
data GrepLine = BinaryLine T.Text
| TextLine T.Text Int
-- Returns the number of columns in the terminal
-- Defaults to using 80 columns if an exception is thrown by get_terminal_cols
nrTerminalColumns :: IO Int
nrTerminalColumns = do
eitherErrInt <- try get_terminal_cols :: IO (Either IOError Int)
case eitherErrInt of
-- default to using 80 columns
Left _ -> return 80
Right cols -> return cols
main :: IO ()
main = shelly $ verbosely $ do
progName <- liftIO getProgName
cmdArgs <- liftIO getArgs
nrColumns <- liftIO nrTerminalColumns
case cmdArgs of
(grepStr:filterList) -> do
(sysfpGitGrepOutFname, fh) <- liftIO $ openTempFile "/tmp" "ggfoutput"
-- close the file handles since we dont use them
let gitGrepOutFname = T.pack sysfpGitGrepOutFname
let gitGrepOpts = T.concat [ "grep -n --no-color '", T.pack grepStr, "'"]
let grepVCmds = construct_grep_inverse_cmd filterList
let gitGrepCmd = [gitGrepOpts, grepVCmds]
-- ignore non-zero exit code for git-grep, since a git-grep yielding no
-- matches will have a nonzero exit code
prefixes <- errExit False $ escaping False $
runHandle "git" gitGrepCmd (remove_fileinfo_from_lines fh)
liftIO $ hClose fh
-- Use grep to colorize the text and truncate lines to fit within terminal
(sysfpGrepColorFname, fh2) <- liftIO $ openTempFile "/tmp" "ggfoutput"
let grepColorOutFname = T.pack sysfpGrepColorFname
let grepColorOpts = [ "--color=always ", T.pack ("'" ++ grepStr ++ "'")
, gitGrepOutFname
]
errExit False $ escaping False $
runHandle "grep" grepColorOpts (grep_line_truncate fh2 nrColumns prefixes)
liftIO $ hClose fh2
_ <- liftIO $ Proc.system ("cat " ++ sysfpGrepColorFname ++ " | less -R")
rm_f $ fromText gitGrepOutFname
rm_f $ fromText grepColorOutFname
exit 0
[] -> do
echo_err $ T.pack (progName ++ ": please supply a pattern for git-grep")
exit 1
remove_fileinfo_from_lines :: Handle -> Handle -> Sh (S.Seq GrepLine)
remove_fileinfo_from_lines outFH stdoutHandle =
liftIO $ process_line S.empty
where
eqColon :: Char -> Bool
eqColon = (== ':')
process_line :: S.Seq GrepLine -> IO (S.Seq GrepLine)
process_line lst = do
eitherLine <- try (TIO.hGetLine stdoutHandle) :: IO (Either IOError T.Text)
case eitherLine of
Left _ -> return lst
Right s ->
let (before1stColon, s') = T.break eqColon s
in
if T.null s'
then
-- Binary file
process_line $ (|>) lst (BinaryLine s)
else
-- break again
let (before2ndColon, s'') = T.break eqColon (T.tail s')
grepLinePrefix = T.concat [ before1stColon, ":"
, before2ndColon, ":"
]
prefixLen = T.length grepLinePrefix
in
-- write line to file
TIO.hPutStrLn outFH (T.tail s'') >>
(process_line $ (|>) lst (TextLine grepLinePrefix prefixLen))
grep_line_truncate :: Handle -> Int -> S.Seq GrepLine -> Handle -> Sh ()
grep_line_truncate tmpfh nrColumns prefixes stdoutHandle =
liftIO $ process_line prefixes
where
process_line :: S.Seq GrepLine -> IO ()
process_line xs =
case S.viewl xs of
((BinaryLine l) :< remXs) -> do
TIO.hPutStrLn tmpfh l >> process_line remXs
((TextLine l len) :< remXs) -> do
eitherLine <- try (TIO.hGetLine stdoutHandle) :: IO (Either IOError T.Text)
case eitherLine of
Left _ -> return ()
Right s -> do
-- TODO: Get the actual column width
let toTruncate = max 0 (nrColumns - len)
let truncatedLine = truncate_colorized_line toTruncate s
TIO.hPutStrLn tmpfh $ T.append l truncatedLine
process_line remXs
EmptyL -> return ()
-- given a list of strings to filter off, construct the appropriate series of
-- inverse grep (grep -v) to filter them off.
--
-- Eg. given ["cat", "dog", "hamster"], returns
-- " | grep -v 'cat' | grep -v 'dog' | grep -v 'hamster'"
construct_grep_inverse_cmd :: [String] -> T.Text
construct_grep_inverse_cmd =
T.concat . map (\s -> T.pack $ " | grep -v '" ++ s ++ "'")
| yanhan/bin-src | hs-src/git-grep-filter.hs | bsd-3-clause | 5,253 | 0 | 22 | 1,488 | 1,368 | 701 | 667 | 95 | 4 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Constants.Math
-- Copyright : (C) 2014 Richard Eisenberg
-- License : BSD-style (see LICENSE)
-- Maintainer : Richard Eisenberg (rae@cs.brynmawr.edu)
-- Stability : experimental
-- Portability : non-portable
--
-- Approximates mathematical constants as 'Rational's
-----------------------------------------------------------------------------
module Data.Constants.Math where
piR :: Rational
piR = 3.1415926535897932384626433832795028841971693993751058209749445923078164
eR :: Rational
eR = 2.71828182845904523536028747135266249775724709369995957496696762772407663
| goldfirere/units | units-defs/Data/Constants/Math.hs | bsd-3-clause | 688 | 0 | 4 | 80 | 38 | 28 | 10 | 5 | 1 |
module Database.Aerospike.Policies
where
data Priority = Default | Low | Medium | High
data ConsistencyLevel = One | All
data Timeout = Timeout Int
data MaxRetries = MaxRetries Int
data SleepBetweenRetries = SleepBetweenRetries Int
data ReadPolicy = ReadPolicy {
priority :: Priority
, consistencyLevel :: ConsistencyLevel
, timeout :: Timeout
, maxRetries :: MaxRetries
, sleepBetweenRetries :: SleepBetweenRetries
, sendKey :: Boolean
}
defaultReadPolicy = ReadPolicy {
priority = Default
, consistencyLevel = One
, timeout = Timeout 0
, maxRetries = MaxRetries 1
, sleepBetweenRetries = SleepBetweenRetries 500
, sendKey = False
}
data RecordExistsAction = Update | UpdateOnly | Replace | ReplaceOnly | CreateOnly
data GenerationPolicy = None | ExpectGenEqual | ExpectGenGt
data CommitLevel = CommitAll | CommitMaster
data Generation = Generation Int
data Expiration = Expiration Int
data WritePolicy = WritePolicy {
priority :: Priority
, consistencyLevel :: consistencyLevel -- needed? we have commit level
, timeout :: Timeout
, maxRetries :: MaxRetries
, sleepBetweenRetries :: SleepBetweenRetries
, sendKey :: Boolean
, recordExistsAction :: RecordExistsAction
, generationPolicy :: GenerationPolicy
, commitLevel :: CommitLevel
, generation :: Generation
, expiration :: Expiration
} | vipo/aerospike-client-haskell | src/Database/Aerospike/Policies.hs | bsd-3-clause | 1,359 | 0 | 8 | 251 | 293 | 182 | 111 | 37 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE ExistentialQuantification #-}
-- Internal.hs: definition of core types and functions
-- as part of rawe - ReActive Web Framework
--
-- Copyright 2011 Roman Smrž <roman.smrz@seznam.cz>, see file LICENSE
-----------------------------------------------------------------------------
-- |
-- Maintainer : Roman Smrž <roman.smrz@seznam.cz>
-- Stability : experimental
--
-- In this module are provided all the core definitions of the library. This
-- interface, however, is considered internal and should not be relied upon.
--
-- Various functions defined here are re-exported from other modules: Rawe.hs
-- for basic types and rendering; Prelude.hs mainly for definitions of
-- equivalents of standard functions, but also contains various methods
-- handling events and some utility functions; Html.hs contains mainly
-- combinators for constructing pages.
--
-----------------------------------------------------------------------------
module FRP.Rawe.Internal where
import Prelude hiding (head,div,(.),id,fst,snd,span,curry,uncurry)
import Control.Applicative
import Control.Categorical.Bifunctor
import Control.Category
import Control.Category.Associative
import Control.Category.Braided
import Control.Category.Cartesian
import Control.Category.Cartesian.Closed
import Control.Category.Monoidal
import Control.Monad.Fix
import Control.Monad.State
import Control.Monad.Writer hiding (Product)
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
import Data.List
import Data.String
import Data.Void
import Text.JSON as J
-- * Basic definitions for HTML
-- | The type representing attributes of HTML elements
data Attribute = AttrVal String String -- ^ Key-value pair
| AttrBool String -- ^ Boolean attribute
instance BhvValue Attribute where
bhvValue (AttrVal name value) = do
(RawJS jn) <- bhvValue name; (RawJS jv) <- bhvValue value
return.RawJS $ "rawe.cthunk( { AttrVal: ["++jn++","++jv++"] } )"
bhvValue (AttrBool name) = do
(RawJS jn) <- bhvValue name
return.RawJS $ "rawe.cthunk( { AttrBool: ["++jn++"] } )"
-- | Type class used to enable adding attributes to values of both types
-- Html and Html -> Html.
class Attributable b where
(!) :: b -> Attribute -> b
instance Attributable (HtmlM a) where
(HtmlM f) ! a = HtmlM $ \s -> let (x, (cs, s')) = f s
in (x, (map (addAttr a) cs, s'))
instance Attributable (HtmlM a -> HtmlM a) where
f ! a = \html -> HtmlM $ \s -> let (HtmlM g) = f html
(x, (t, s')) = g s
in (x, (map (addAttr a) t, s'))
addAttr :: Attribute -> HtmlStructure -> HtmlStructure
addAttr a (Tag name as content) = Tag name (a:as) content
addAttr a (TagVoid name as) = TagVoid name (a:as)
addAttr _ t = t
instance Attributable (Bhv Html) where
(!) = primOp2 (!) "add_attr"
data AddAttr = AddAttr Attribute
instance BhvPrim AddAttr Html Html where
bhvPrim (AddAttr (AttrVal name val)) = do
jname <- bhvValue name; jval <- bhvValue val
return ("add_attr", [jname, jval])
bhvPrim (AddAttr (AttrBool name)) = do
jname <- bhvValue name; jval <- bhvValue True
return ("add_attr", [jname, jval])
unsafeBhvEval (AddAttr a) = (!a)
-- | The structure of HTML tree.
data HtmlStructure = Tag String [Attribute] [HtmlStructure] -- ^ Tag with content
| TagVoid String [Attribute] -- ^ Tag without content
| Doctype -- ^ Doctype declaration
| Text String -- ^ Text node
| Behaviour Int -- ^ Placeholder for HTML behaviour identified by the parameter
-- * The HtmlM monad
-- | The inner state kept in the HtmlM monad.
data HtmlState = HtmlState
{ hsUniq :: IntMap Int
-- ^ Counter for generating unique values
, hsBehaviours :: IntMap [(Int, String, [RawJS])]
-- ^ List of behaviours with their id, name of the JavaScript
-- constructor and list of parameters passed to it
, hsHtmlValues :: [(Int, String, Maybe String)]
-- ^ List of HTML values with ID of the snipped, the HTML code and
-- possibly assigned inner value
, hsHtmlCurrent :: Maybe Int
-- ^ Set, if we are currently rendering HTML for some other
-- behaviour
, hsHtmlBehaviours :: [(Int, Maybe Int)]
-- ^ Assignments of behaviours to parts of some HTML snippet or the
-- main page if none given
, hsHtmlGens :: [(Int, Maybe Int)]
-- ^ Assignments the generating behaviour to part of some HTML
-- snipped or the main page
, hsRecursion :: Int
-- ^ Level of recursion in executing HtmlM monads.
, hsRecNedded :: Int
-- ^ Recursion level needed for used behaviours
, hsInFix :: Bool
-- ^ Indicates whether we are inside an mfix call
}
emptyHtmlState = HtmlState (IM.singleton 0 0) (IM.singleton 0 []) [] Nothing [] [] 0 0 False
-- | The HtmlM monad.
data HtmlM a = HtmlM (HtmlState -> (a, ([HtmlStructure], HtmlState)))
-- | Type representing pure HTML snippet.
type Html = HtmlM ()
instance Functor HtmlM where
fmap f (HtmlM hf) = HtmlM $ \s -> (\(x, hs)->(f x, hs)) (hf s)
instance Applicative HtmlM where
pure = return
(<*>) = ap
instance Monad HtmlM where
return x = HtmlM $ \s -> (x, ([], s))
(HtmlM f) >>= g = HtmlM $ \s -> let (x, (cs, s')) = f s
(HtmlM g') = g x
(y, (ds, s'')) = g' s'
in (y, (cs++ds, s''))
instance MonadFix HtmlM where
mfix f = HtmlM $ \s -> let (HtmlM f') = f x
(x, (t, s')) = f' ( s { hsInFix = True } )
in (x, (t, s' { hsInFix = False } ))
instance MonadState HtmlState HtmlM where
get = HtmlM $ \s -> (s, ([], s))
put s = HtmlM $ \_ -> ((), ([], s))
instance IsString (Bhv String) where
fromString = cb
instance IsString Html where
fromString text = HtmlM $ \s -> ((), ([Text text], s))
-- | Function used to include text node into the HTML page. Forces the type
-- Html instead of arbitrary HtmlM a inferred when using overloaded strings
-- directly.
str :: String -> Html
str = fromString
-- ** Adding behaviours into HtmlM
-- | Adds a behaviour to the list of behaviours the state of HtmlM.
addBehaviour
:: Int -- ^ Level of recursion
-> Int -- ^ ID used for this behaviour
-> String -- ^ Name of the initialization function
-> [RawJS] -- ^ Parameters for the initialization function
-> HtmlM ()
addBehaviour r id name params =
modify $ \s -> s
{ hsBehaviours = IM.adjust ((id, name, params):) r (hsBehaviours s)
, hsRecNedded = max r (hsRecNedded s)
}
-- | Similar to 'addBehaviour', but generates a unique ID.
addBehaviourName :: String -> [RawJS] -> HtmlM (Int, Int)
addBehaviourName name params = do
bid <- htmlUniq
r <- gets hsRecursion
addBehaviour r bid name params
modify $ \s -> s { hsRecNedded = max r (hsRecNedded s) }
return (r,bid)
-- | Returns an ID of given behaviour in the current HtmlM monad. It may or may
-- not add a new one to the global list of behaviours.
assignBehaviour :: BhvFun a b -> HtmlM (Int,Int)
assignBehaviour b = do
-- We need to do this so b does not need to be evaluated for internal
-- unique counter and mfix may work for mutually recursive behaviours.
nids <- htmlUniqs
r <- gets hsRecursion
let checkExisting getCode = do
origNeed <- gets hsRecNedded
modify $ \s -> s { hsRecNedded = 0 }
(name, params) <- getCode
need <- gets hsRecNedded
modify $ \s -> s { hsRecNedded = max need origNeed }
let rneed = min r need
inFix <- gets hsInFix
let nid = nids rneed
if inFix
then do addBehaviour rneed nid name params
return (rneed,nid)
else do mbid <- return . find (\(_, n, p) -> (n,p)==(name,params)) . (IM.!rneed) =<< gets hsBehaviours
case mbid of
Just (id, _, _) -> return (rneed,id)
Nothing -> do addBehaviour rneed nid name params
return (rneed,nid)
case b of
Prim _ hf -> checkExisting hf
Composed _ _ -> checkExisting $ (,) "compose" <$> composedList b
Assigned _ (r,id) -> do
modify $ \s -> s { hsRecNedded = max r (hsRecNedded s) }
return (r,id)
BhvID -> return (0,0)
composedList :: BhvFun a b -> HtmlM [RawJS]
composedList (Composed x y) = (++) <$> composedList x <*> composedList y
composedList x = (:[]) <$> bhvValue x
-- ** Utility functions
-- | Generates a unique integer.
htmlUniq :: HtmlM Int
htmlUniq = do
r <- gets hsRecursion
us <- gets hsUniq
let x = us IM.! r
modify $ \s -> s { hsUniq = IM.insert r (x+1) us }
return x
-- | Generates unique integer for every recursion level
htmlUniqs :: HtmlM (Int -> Int)
htmlUniqs = do
us <- gets hsUniq
modify $ \s -> s { hsUniq = IM.map (+1) us }
return (us IM.!)
-- | Creates an environment for a "recursive" call used to list functions
-- between behaviours. Increments the recursion counter, and resets the unique
-- counter (for somewhat easier debugging is the counter initialized to 1000 *
-- <recursion level>), then executes given action and restores original state.
htmlLocal :: HtmlM a -> HtmlM a
htmlLocal action = do
state <- get
let newrec = hsRecursion state + 1
put $ emptyHtmlState
{ hsRecursion = newrec
, hsUniq = IM.insert newrec (1000*newrec) (hsUniq state)
, hsBehaviours = IM.insert newrec [] (hsBehaviours state)
, hsInFix = hsInFix state
}
result <- action
state' <- get
put $ state
{ hsBehaviours = IM.delete newrec (hsBehaviours state')
, hsUniq = IM.delete newrec (hsUniq state')
, hsRecNedded = max (hsRecNedded state) (hsRecNedded state')
}
return result
-- * Behaviours
-- | The representation of behaviour functions
data BhvFun a b = Prim (a -> b) (HtmlM (String, [RawJS]))
-- ^ Primitive function, keeps the function for evaluating and
-- an action generating name of parameters of the primitive
| Assigned (a -> b) (Int, Int)
-- ^ Behaviour function assigned in some instance of HtmlM monad,
-- keeps function for evaluating and the IDs.
| forall c. Composed (BhvFun a c) (BhvFun c b)
-- ^ Composition of two behaviour functions; multiple compositions
-- are flattened when generating JavaScript code.
| (a ~ b) => BhvID
-- ^ An identity function.
-- | The type representing behaviours.
type Bhv a = BhvFun Void a
-- | The type representing events.
type Event a = Bhv (Timed a)
-- Straightforward instances of various type classes from the package
-- categories.
instance Category BhvFun where
id = BhvID
BhvID . b = b
b . BhvID = b
g . f = Composed f g
instance PFunctor (,) BhvFun BhvFun where
first = firstDefault
instance QFunctor (,) BhvFun BhvFun where
second = secondDefault
instance Bifunctor (,) BhvFun BhvFun BhvFun where
bimap = bimapProduct
instance Braided BhvFun (,) where
braid = braidProduct
instance Symmetric BhvFun (,)
instance Associative BhvFun (,) where
associate = associateProduct
instance Disassociative BhvFun (,) where
disassociate = disassociateProduct
type instance Id BhvFun (,) = Void
instance Monoidal BhvFun (,) where
idl = snd
idr = fst
instance PreCartesian BhvFun where
type Product BhvFun = (,)
x &&& y = prim $ BhvModifier2 (&&&) "product" x y
fst = primOp fst "fst"
snd = primOp snd "snd"
instance CCC BhvFun where
type Exp BhvFun = (->)
apply = primOp apply "apply"
curry = prim . BhvModifier curry "curry"
uncurry = prim . BhvModifier uncurry "uncurry"
-- | 'BhvValue' is the type class representing the types which can be converted
-- to JavaScript and thus lifted into behaviours.
class BhvValue a where
bhvValue :: a -> HtmlM RawJS
-- ^ The expression is evaluated inside an HtmlM monad to allow
-- representing expressing, which depend on the inner state of HtmlM
-- Follow instances for basic types:
instance BhvValue (BhvFun a b) where
bhvValue f = do (r,i) <- assignBehaviour f
return $ RawJS $ "rawe.cthunk(r_bhv_fun_"++show r++"["++show i++"])"
instance BhvValue () where bhvValue () = return "rawe.cthunk([])"
instance BhvValue Int where bhvValue x = return.RawJS $ "rawe.cthunk("++show x++")"
instance BhvValue Float where bhvValue x = return.RawJS $ "rawe.cthunk("++show x++")"
instance BhvValue Bool where bhvValue x = return $ if x then "rawe.cthunk(true)" else "rawe.cthunk(false)"
instance BhvValue Char where
bhvValue x = return.RawJS $ "rawe.cthunk("++show x++")"
instance (BhvValue a, BhvValue b) => BhvValue (a, b) where
bhvValue (x,y) = do
(RawJS x') <- bhvValue x; (RawJS y') <- bhvValue y
return.RawJS $ "rawe.cthunk(["++x'++", "++y'++"])"
instance (BhvValue a) => BhvValue (Maybe a) where
bhvValue (Just x) = do (RawJS jx) <- bhvValue x
return.RawJS $ "rawe.cthunk({Just:"++jx++"})"
bhvValue Nothing = return.RawJS $ "rawe.cthunk({Nothing:null})"
instance BhvValue a => BhvValue [a] where
bhvValue [] = return.RawJS $ "rawe.cthunk({nil:[]})"
bhvValue (x:xs) = do RawJS jx <- bhvValue x
RawJS jxs <- bhvValue xs
return.RawJS $ "rawe.cthunk({cons:["++jx++","++jxs++"]})"
instance (BhvValue a, BhvValue b) => BhvValue (Either a b) where
bhvValue (Left x) = do RawJS jx <- bhvValue x
return.RawJS $ "rawe.cthunk({Left:"++jx++"})"
bhvValue (Right x) = do RawJS jx <- bhvValue x
return.RawJS $ "rawe.cthunk({Right:"++jx++"})"
-- | 'BhvPrim' was originally used in the definition of 'BhvFun' in the
-- constructor 'Prim' as a type class constraint for an existential type of the
-- function; for this reason, there are various data structures instantiating
-- this type class instead of calling the 'Prim' constructor directly.
class BhvPrim f a b | f -> a b where
bhvPrim :: f -> HtmlM (String, [RawJS])
unsafeBhvEval :: f -> a -> b
prim :: (BhvPrim f a b) => f -> BhvFun a b
prim f = Prim (unsafeBhvEval f) (bhvPrim f)
-- | Behaviour function without any parameter for the initialization function.
data BhvPrimFunc a b = BhvPrimFunc (a -> b) String
instance BhvPrim (BhvPrimFunc a b) a b where
bhvPrim (BhvPrimFunc _ name) = return (name, [])
unsafeBhvEval (BhvPrimFunc f _) = f
-- | Behaviour function that modifies another and that is passed to the
-- initializer as a parameter.
data BhvModifier a b c d = BhvModifier ((a -> b) -> (c -> d)) String (BhvFun a b)
instance BhvPrim (BhvModifier a b c d) c d where
bhvPrim (BhvModifier _ name x) = do jx <- bhvValue x
return (name, [jx])
unsafeBhvEval (BhvModifier f _ b) = f (unsafeBfEval b)
-- | Similar to BhvModifier, but has two parameter for the initialization function.
data BhvModifier2 a b c d e f = BhvModifier2 ((a -> b) -> (c -> d) -> (e -> f)) String (BhvFun a b) (BhvFun c d)
instance BhvPrim (BhvModifier2 a b c d e f) e f where
bhvPrim (BhvModifier2 _ name x y) = do jx <- bhvValue x; jy <- bhvValue y
return (name, [jx, jy])
unsafeBhvEval (BhvModifier2 f _ b1 b2) = f (unsafeBfEval b1) (unsafeBfEval b2)
-- | Constant behaviour function.
data BhvConst a b = (BhvValue b) => BhvConst b
instance BhvPrim (BhvConst a b) a b where
bhvPrim (BhvConst x) = do jx <- bhvValue x
return ("cb", [jx])
unsafeBhvEval (BhvConst x) = const x
cb :: (BhvValue a) => a -> BhvFun b a
cb = prim . BhvConst
-- Following are various utility function for constructing primitive operators,
-- which do not require parameter for their initialization function. Those are
-- provided for function of up to five parameters.
primOp :: (a -> b) -> String -> BhvFun a b
primOp f = prim . BhvPrimFunc f
primOp0 :: a -> String -> Bhv a
primOp0 x name = primOp (const x) name
primOp1 :: BhvValueFun a a' => (a' -> b) -> String -> a -> Bhv b
primOp1 f name a = primOp f name . (cbf a)
primOp2 :: (BhvValueFun a a', BhvValueFun b b') => (a' -> b' -> c) -> String -> a -> b -> Bhv c
primOp2 f name a b = primOp (uncurry f) name . (cbf a &&& cbf b)
primOp3 :: (BhvValueFun a a', BhvValueFun b b', BhvValueFun c c') => (a' -> b' -> c' -> d) -> String -> a -> b -> c -> Bhv d
primOp3 f name a b c = primOp (uncurry $ \x -> uncurry (f x)) name . (cbf a &&& cbf b &&& cbf c)
primOp4 :: (BhvValueFun a a', BhvValueFun b b', BhvValueFun c c', BhvValueFun d d') =>
(a' -> b' -> c' -> d' -> e) -> String -> a -> b -> c -> d -> Bhv e
primOp4 f name a b c d = primOp (uncurry $ \x -> uncurry $ \y -> uncurry (f x y))
name . (cbf a &&& cbf b &&& cbf c &&& cbf d)
primOp5 :: (BhvValueFun a a', BhvValueFun b b', BhvValueFun c c', BhvValueFun d d', BhvValueFun e e') =>
(a' -> b' -> c' -> d' -> e' -> f) -> String -> a -> b -> c -> d -> e -> Bhv f
primOp5 f name a b c d e = primOp (uncurry $ \x -> uncurry $ \y -> uncurry $ \z -> uncurry (f x y z))
name . (cbf a &&& cbf b &&& cbf c &&& cbf d &&& cbf e)
-- ** Lifting of functions
-- instance of BhvValue for function types
instance (BhvValue b) => BhvValue (Bhv a -> b) where
bhvValue = bhvValueCommon bhvValue $ \r iid ->
[ "var r_bhv_fun_"++show r++" = {};"
, "r_bhv_fun_"++show r++"["++show iid++"] = param.get();"
]
-- | This class is somewhat similar to the 'BhvValue'; it is used to lift
-- functions between behaviours to a behaviour of function on values (instead
-- of behaviour of functions between behaviours as the 'BhvValue' + 'cb'
-- combination would do) in order to avoid some of the wrapping and unwrapping.
class BhvValueFun a b | a -> b where
bhvValueFun :: a -> HtmlM RawJS
bhvValueFunEval :: a -> b
cbf :: a -> Bhv b
instance BhvValueFun (Bhv a) a where
bhvValueFun = bhvValue
bhvValueFunEval x = (unsafeBfEval x) novalue
cbf = id
instance BhvValueFun Attribute Attribute where
bhvValueFun = bhvValue
bhvValueFunEval = id
cbf = cb
instance BhvValueFun b b' => BhvValueFun (Bhv a -> b) (a -> b') where
bhvValueFun = bhvValueCommon bhvValueFun $ \r iid ->
[ "var r_bhv_fun_"++show r++" = {};"
, "r_bhv_fun_"++show r++"["++show iid++"] = param.get();"
]
bhvValueFunEval f = \x -> bhvValueFunEval (f (prim $ BhvConstEval x))
cbf = prim . BhvConstFun
data BhvConstFun a b b' = (BhvValueFun b b') => BhvConstFun b
instance BhvPrim (BhvConstFun a b b') a b' where
bhvPrim (BhvConstFun x) = do jx <- bhvValueFun x
return ("cbf", [jx])
unsafeBhvEval (BhvConstFun x) = const (bhvValueFunEval x)
-- | The actual implementation of lifting function between behaviours.
bhvValueCommon bv begin f = htmlLocal $ do
-- First we create a new behaviour
iid <- htmlUniq
r <- gets hsRecursion
-- Which is then passed to the function f, thus giving a value, which we
-- can then convert to JavaScript representation
RawJS result <- bv $ f (Assigned (error "eval: bhvValueCommon") (r,iid))
-- This forced to evaluate the result of f and added all the necessary
-- behaviour function to our local state, so now, we take them and make
-- proper JavaScript code from them:
bs <- gets $ reverse.(IM.!r).hsBehaviours
hs <- gets $ reverse.hsHtmlValues
hbs <- gets $ reverse.hsHtmlBehaviours
hgs <- gets $ reverse.hsHtmlGens
return $ RawJS $ init $ unlines $
("rawe.cthunk(function(param) {":) $ (++[replicate (r-1) '\t' ++ "})"]) $
-- the begin is implemented in the function, which called us, because
-- the code they need here differs a bit. However, in any case, they
-- has to initialize the behaviour we created in the beginning using
-- the JavaScript formal parameter in order to make the whole thing
-- work.
map (replicate r '\t' ++) $ (begin r iid ++) $
concat
-- First we create all the objects
[ flip map bs $ \(id, _, _) ->
"r_bhv_fun_"++show r++"["++show id++"] = new rawe.BhvFun("++show id++");"
-- Define HTML snippets, which are dynamically created
, flip map hs $ \(i, h, mi) ->
"var r_html_"++show i++" = $('"++escapeStringJS h++"')" ++
case mi of { Nothing -> ""; Just inner -> ".prop('rawe_html_inner', "++inner++")" }
++ ";"
-- Assign to behaviour those HTML snippets for which they are responsible
, flip map hbs $ \(i, mv) ->
let var = case mv of Nothing -> "$('body')"
Just v -> "r_html_"++show v
in "r_bhv_fun_"++show r++"["++show i++"].html = "++var++".find('*[bhv-id="++show i++"]');"
-- Assign to behaviurs HTML elements, which they use to generate values / events.
, flip map hgs $ \(i, mv) ->
let var = case mv of Nothing -> "$('body')"
Just v -> "r_html_"++show v
in "r_bhv_fun_"++show r++"["++show i++"].gen = "++var++".find2('*[bhv-gen="++show i++"]');"
-- And finally call all the initialization functions.
, flip map bs $ \(id, func, params) ->
let jid = show id
jfunc = "rawe.prim."++func
jparams = concatMap ((',':).unRawJS) params
in jfunc++".call(r_bhv_fun_"++show r++"["++jid++"]"++jparams++");"
, flip map hbs $ \(i, _) ->
"r_bhv_fun_"++show r++"["++show i++"].invalidate();"
]
++
[ "rawe.init(r_bhv_fun_"++show r++");"
, "return "++result++";"
]
--------------------------------------------------------------------------------
-- ** Evaluating to Haskell functions
-- | In some situation, it may be desirable to actually execute the code with
-- behaviours directly in the Haskell program itself. For this purpose, we have
-- this evaluation function. The behaviour function is executed as if in the
-- time at the beginning; no events occurred, no input was entered and so on.
-- The unsafe- prefix is used, because it loses the requirement that the value
-- of type 'a' is represented in JavaScript and thus, if we generate some
-- values of type 'Bhv', those may fail, if we try to pass them into the
-- JavaScript world; the simplest example is the function
--
-- > unsafeBfEval bhvWrap :: a -> Bhv a
--
-- without the type class constraint on the type 'a' seen in the function 'cb',
-- so it can not work correctly. Similar issue arises when evaluating
-- behaviours passed through 'HtmlM'.
unsafeBfEval :: BhvFun a b -> a -> b
unsafeBfEval (Prim f _) = f
unsafeBfEval (Assigned f _) = f
unsafeBfEval (Composed f g) = unsafeBfEval g . unsafeBfEval f
unsafeBfEval (BhvID) = id
instance BhvValue Void where
bhvValue _ = return "null"
novalue :: Void
novalue = error "novalue"
class BhvEval a b | a -> b where
-- | This is similar to the 'unsafeBfEval', but since we usually do not work
-- directly with behaviour functions, but rather with the more practical
-- functions between behaviours, this takes care of more general ''unwrapping''.
-- Given definition
--
-- > length :: Bhv [a] -> Bhv Int
-- > length = bfix $ \len -> list 0 (\_ xs -> 1 + len xs)
--
-- We may use
--
-- > unsafeEval length "abcd"
--
-- to get 4 directly in Haskell.
unsafeEval :: a -> b
unsafeUneval :: b -> a
instance BhvValue a => BhvEval (Bhv a) a where
unsafeEval = flip unsafeBfEval novalue
unsafeUneval = prim . BhvConstEval
instance (BhvEval a a', BhvEval b b') => BhvEval (a -> b) (a' -> b') where
unsafeEval f = unsafeEval . f . unsafeUneval
unsafeUneval f = unsafeUneval . f . unsafeEval
data BhvConstEval a b = BhvConstEval b
instance BhvPrim (BhvConstEval a b) a b where
bhvPrim _ = error "BhvConstEval: bhvPrim"
unsafeBhvEval (BhvConstEval x) = const x
--------------------------------------------------------------------------------
-- * Rendering page
-- | This function renders values of type 'Html' into a string representation.
-- The IO type is used, because that form may reveal differences between
-- otherwise semantically equivalent expressions (which are thus treated as
-- equal) and we do not want to break referential transparency.
render :: Html -> IO String
render html = let (HtmlM f) = renderH html
((result, ()), _) = f (emptyHtmlState { hsUniq = IM.singleton 0 1, hsBehaviours = IM.singleton 0 [(0, "id", [])] } )
in return result
-- | Variant of 'render', which evaluates itself in another instance of HtmlM monad.
renderH :: HtmlM a -> HtmlM (String, a)
renderH (HtmlM f) = do
(x, (xs, s')) <- gets f
put s'
return (execWriter (mapM_ render' xs), x)
where render' :: HtmlStructure -> Writer String ()
render' (Tag tag attrs xs) = do
tell $ "<" ++ tag
mapM_ renderAttrs attrs
tell ">\n"
mapM render' xs
tell $ "</" ++ tag ++ ">\n"
render' (TagVoid tag attrs) = do
tell $ "<" ++ tag
mapM_ renderAttrs attrs
tell ">\n"
-- we currently do not support other DTDs.
render' (Doctype) = tell "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
render' (Text text) = tell text
-- for behaviour just generate some placeholder.
render' (Behaviour id) = do
tell $ "<div bhv-id="++show id++"></div>\n"
renderAttrs (AttrBool name) = tell $ ' ':name
renderAttrs (AttrVal name val) = tell $ " "++name++"=\""++escapeStringHtml val++"\""
escapeStringHtml = (>>=helper)
where helper '"' = """
helper '&' = "&"
helper '<' = "<"
helper '>' = ">"
helper c = [c]
-- * Other definitions
-- ** Timed type, constructors, destructor and instances
-- | The type representing time; in Haskell, it is just an empty declaration.
data Time
-- | 'Timed' is used for the definition of events. It is similar to 'Maybe',
-- but carries additional time information.
data Timed a = NotYet | OnTime Time a
notYet :: Bhv (Timed a)
notYet = primOp0 NotYet "not_yet"
onTime :: Bhv Time -> Bhv a -> Bhv (Timed a)
onTime = primOp2 OnTime "on_time"
timed :: Bhv b -> (Bhv Time -> Bhv a -> Bhv b) -> Bhv (Timed a) -> Bhv b
timed = primOp3 (\ny ot x -> case x of NotYet -> ny; OnTime t y -> ot t y) "timed"
data TimedFold a b = TimedFold (Bhv Time -> Bhv a -> Bhv b -> Bhv a) (Bhv a) (Bhv (Timed b))
instance BhvPrim (TimedFold a b) Void a where
bhvPrim (TimedFold step def ev) = do
jstep <- bhvValue $ cbf step
jdef <- bhvValue def
jev <- bhvValue ev
return ("timed_fold", [jstep, jdef, jev])
unsafeBhvEval (TimedFold _ def _) = unsafeBfEval def
-- | timed-folding functions; it is the same as 'evfold'. (Or rather 'evfold'
-- is the same as this one.)
timedFold :: (Bhv Time -> Bhv a -> Bhv b -> Bhv a) -> Bhv a -> Bhv (Timed b) -> Bhv a
timedFold f x = prim . TimedFold f x
-- ** JSString constructor and destructor
toJSString :: Bhv String -> Bhv JSString
toJSString = primOp1 J.toJSString "to_js_string"
fromJSString :: Bhv JSString -> Bhv String
fromJSString = primOp1 J.fromJSString "from_js_string"
instance BhvValue JSString where
bhvValue str = return.RawJS $ "rawe.cthunk('"++escapeStringJS (J.fromJSString str)++"')"
-- ** Misc primitives
-- | Wraps a value in additional layer of 'Bhv'.
bhvWrap :: BhvFun a (Bhv a)
bhvWrap = primOp (prim . BhvConstEval) "bhv_wrap"
-- | Removes a layer of 'Bhv'.
bhvUnwrap :: BhvFun (Bhv a) a
bhvUnwrap = primOp (flip unsafeBfEval novalue) "bhv_unwrap"
-- | Turns behaviour function into a function between behaviours. Basically an
-- inverse of haskToBhv.
bhvToHask :: BhvFun a b -> (Bhv a -> Bhv b)
bhvToHask = (.)
-- | Turns function between behaviours into a behaviour function. Basically an
-- inverse of bhvToHask.
haskToBhv :: (Bhv a -> Bhv b) -> BhvFun a b
haskToBhv f = bhvUnwrap . apply . (cb f &&& bhvWrap)
-- | Type denoting raw JavaScript code
newtype RawJS = RawJS { unRawJS :: String }
deriving Eq
instance IsString RawJS where fromString = RawJS
escapeStringJS = (>>=helper)
where helper '\n' = "\\n"
helper c | c `elem` "'\"\\" = '\\':c:[]
| otherwise = [c]
| roman-smrz/rawe | src/FRP/Rawe/Internal.hs | bsd-3-clause | 29,596 | 14 | 24 | 7,870 | 8,171 | 4,287 | 3,884 | -1 | -1 |
{-# LANGUAGE TypeFamilies, RankNTypes, GADTs #-}
module QueryArrow.Binding.Binding where
import QueryArrow.Syntax.Term
import QueryArrow.Syntax.Type
import QueryArrow.Semantics.TypeChecker
import QueryArrow.Semantics.Value
import QueryArrow.Semantics.Compute
import QueryArrow.Utils
import QueryArrow.DB.ResultStream
import QueryArrow.DB.DB
import QueryArrow.DB.NoConnection
import Data.Set (Set, member)
import Data.Map.Strict (fromList)
import qualified Data.Map.Strict as Map
import Control.Monad.IO.Class (MonadIO(..))
import Data.List (find)
import Data.Maybe
import Data.Conduit
import qualified Data.Conduit.Combinators as C
import QueryArrow.Syntax.Utils
-- dbName :: a -> String
data ParamIO = I | O
class Binding a where
bindingPred :: a -> Pred
bindingSupport :: a -> [ParamIO] -> Bool
bindingSupportInsert :: a -> Bool
bindingSupportDelete :: a -> Bool
bindingExec :: a -> [ParamIO] -> [ResultValue] -> IO [[ResultValue]]
bindingInsert :: a -> [ResultValue] -> IO ()
bindingDelete :: a -> [ResultValue] -> IO ()
data AbstractBinding = forall a. (Binding a) => AbstractBinding a
instance Binding AbstractBinding where
bindingPred ab =
case ab of
AbstractBinding b -> bindingPred b
bindingSupport ab =
case ab of
AbstractBinding b -> bindingSupport b
bindingSupportInsert ab =
case ab of
AbstractBinding b -> bindingSupportInsert b
bindingSupportDelete ab =
case ab of
AbstractBinding b -> bindingSupportDelete b
bindingExec ab =
case ab of
AbstractBinding b -> bindingExec b
bindingInsert ab =
case ab of
AbstractBinding b -> bindingInsert b
bindingDelete ab =
case ab of
AbstractBinding b -> bindingDelete b
data BindingDatabase = BindingDatabase String [AbstractBinding]
getBindingByPredName :: PredName -> [AbstractBinding] -> AbstractBinding
getBindingByPredName predname = fromMaybe (error "cannot find predicate") . find (\ab -> predName (bindingPred ab) == predname)
argsToIO :: Set Var -> [Expr] -> [ParamIO]
argsToIO row =
map (\arg -> case arg of
VarExpr a | not (a `member` row) -> O
_ -> I)
argsToIOs :: MapResultRow -> [Expr] -> ([ParamIO], [ResultValue], [Var])
argsToIOs row =
mconcat . map (\arg -> case arg of
VarExpr a | not (a `Map.member` row) -> ([O], [], [a])
_ -> ([I], [evalExpr row arg], []))
instance IDatabase0 BindingDatabase where
type DBFormulaType BindingDatabase = FormulaT
getName (BindingDatabase n _) = n
getPreds (BindingDatabase _ bs) = map bindingPred bs
supported (BindingDatabase _ db) _ (FAtomicA _ (Atom predname args)) env = bindingSupport (getBindingByPredName predname db) (argsToIO env args)
supported (BindingDatabase _ db) _ (FInsertA _ (Lit Pos (Atom predname _))) _ = bindingSupportInsert (getBindingByPredName predname db)
supported (BindingDatabase _ db) _ (FInsertA _ (Lit Neg (Atom predname _))) _ = bindingSupportDelete (getBindingByPredName predname db)
supported _ _ _ _ = False
instance IDatabase1 BindingDatabase where
type DBQueryType BindingDatabase = ( Set Var, FormulaT, Set Var)
translateQuery _ vars qu vars2 = return (vars, qu, vars2)
instance INoConnectionDatabase2 BindingDatabase where
type NoConnectionQueryType BindingDatabase = (Set Var, FormulaT, Set Var)
type NoConnectionRowType BindingDatabase = MapResultRow
noConnectionDBStmtExec (BindingDatabase _ db) (_, FAtomicA _ (Atom predname args), _) stream =
stream .| awaitForever (\row -> do
let (ios, ivals, ovars) = argsToIOs row args
rs <- liftIO $ bindingExec (getBindingByPredName predname db) ios ivals
C.yieldMany (map (\ovals -> fromList (zip ovars ovals)) rs))
noConnectionDBStmtExec (BindingDatabase _ db) (_, FInsertA _ (Lit Pos (Atom predname as)), _) stream =
stream .| awaitForever (\row -> do
let avals = map (evalExpr row) as
liftIO $ bindingInsert (getBindingByPredName predname db) avals)
noConnectionDBStmtExec (BindingDatabase _ db) (_, FInsertA _ (Lit Neg (Atom predname as)), _) stream =
stream .| awaitForever (\row -> do
let avals = map (evalExpr row) as
liftIO $ bindingDelete (getBindingByPredName predname db) avals)
noConnectionDBStmtExec _ qu _ = error ("noConnectionDBStmtExec: unsupported Formula " ++ show qu)
data UnaryFunction = UnaryFunction String String CastType CastType (ResultValue -> ResultValue)
instance Binding UnaryFunction where
bindingPred (UnaryFunction ns n t1 t2 _) = Pred (PredName [ns] n) (PredType PropertyPred [PTKeyI t1, PTPropIO t2])
bindingSupport _ [I,_] = True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (UnaryFunction _ _ _ _ func) [I,I] [val1, val2] =
return (if func val1 == val2
then [[]]
else [])
bindingExec (UnaryFunction _ _ _ _ func) [I,O] [val1] =
return [ [func val1] ]
data BinaryFunction = BinaryFunction String String CastType CastType CastType (ResultValue -> ResultValue -> ResultValue)
instance Binding BinaryFunction where
bindingPred (BinaryFunction ns n t1 t2 t3 _) = Pred (PredName [ns] n) (PredType PropertyPred [PTKeyI t1, PTKeyI t2, PTPropIO t3])
bindingSupport _ [I,I,_] = True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (BinaryFunction _ _ _ _ _ func) [I,I,I] [val1, val2, val3] =
return (if func val1 val2 == val3
then [[]]
else [])
bindingExec (BinaryFunction _ _ _ _ _ func) [I,I,O] [val1, val2] =
return [ [func val1 val2] ]
data TernaryFunction = TernaryFunction String String CastType CastType CastType CastType (ResultValue -> ResultValue -> ResultValue -> ResultValue)
instance Binding TernaryFunction where
bindingPred (TernaryFunction ns n t1 t2 t3 t4 _) = Pred (PredName [ns] n) (PredType PropertyPred [PTKeyI t1, PTKeyI t2, PTKeyI t3, PTPropIO t4])
bindingSupport _ [I,I,I,_] = True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (TernaryFunction _ _ _ _ _ _ func) [I,I,I,I] [val1, val2, val3, val4] =
return (if func val1 val2 val3 == val4
then [[]]
else [])
bindingExec (TernaryFunction _ _ _ _ _ _ func) [I,I,I,O] [val1, val2, val3] =
return [ [func val1 val2 val3] ]
data UnaryIso = UnaryIso String String CastType CastType (ResultValue -> ResultValue) (ResultValue -> ResultValue)
instance Binding UnaryIso where
bindingPred (UnaryIso ns n t1 t2 _ _) = Pred (PredName [ns] n) (PredType PropertyPred [PTKeyIO t1, PTPropIO t2])
bindingSupport _ [I,I] = True
bindingSupport _ [I,O]= True
bindingSupport _ [O,I]= True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (UnaryIso _ _ _ _ func _) [I,I] [val1, val2] =
return (if func val1 == val2
then [[]]
else [])
bindingExec (UnaryIso _ _ _ _ func _) [I, O] [val1] =
return [ [func val1] ]
bindingExec (UnaryIso _ _ _ _ _ g) [O, I] [val2] =
return [ [g val2] ]
data BinaryIso = BinaryIso String String CastType CastType CastType (ResultValue -> ResultValue -> ResultValue) (ResultValue -> ResultValue -> ResultValue) (ResultValue -> ResultValue -> ResultValue)
instance Binding BinaryIso where
bindingPred (BinaryIso ns n t1 t2 t3 _ _ _) = Pred (PredName [ns] n) (PredType PropertyPred [PTKeyIO t1, PTKeyIO t2, PTPropIO t3])
bindingSupport _ [I,I,I] = True
bindingSupport _ [I,I,O] = True
bindingSupport _ [I,O,I] = True
bindingSupport _ [O,I,I] = True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (BinaryIso _ _ _ _ _ func _ _) [I,I,I] [a, b, c] =
return (if func a b == c
then [[]]
else [])
bindingExec (BinaryIso _ _ _ _ _ func _ _) [I,I,O] [a, b] =
return [[func a b]]
bindingExec (BinaryIso _ _ _ _ _ _ g _) [I,O,I] [a, c] =
return [[g a c]]
bindingExec (BinaryIso _ _ _ _ _ _ _ h) [O,I,I] [b, c] =
return [[h b c]]
data BinaryParamIso = BinaryParamIso String String CastType CastType CastType (ResultValue -> ResultValue -> ResultValue) (ResultValue -> ResultValue -> ResultValue)
instance Binding BinaryParamIso where
bindingPred (BinaryParamIso ns n t1 t2 t3 _ _) = Pred (PredName [ns] n) (PredType PropertyPred [PTKeyIO t1, PTKeyI t2, PTPropIO t3])
bindingSupport _ [I,I,I] = True
bindingSupport _ [I,I,O] = True
bindingSupport _ [O,I,I] = True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (BinaryParamIso _ _ _ _ _ func _) [I,I,I] [a, b, c] =
return (if func a b == c
then [[]]
else [])
bindingExec (BinaryParamIso _ _ _ _ _ func _) [I,I,O] [a, b] =
return [[func a b]]
bindingExec (BinaryParamIso _ _ _ _ _ _ g) [O,I,I] [b, c] =
return [[g c b]]
data UnaryMono = UnaryMono String String CastType CastType (ResultValue -> ResultValue) (ResultValue -> Maybe ResultValue)
instance Binding UnaryMono where
bindingPred (UnaryMono ns n t1 t2 _ _) = Pred (PredName [ns] n) (PredType PropertyPred [PTKeyIO t1, PTKeyIO t2])
bindingSupport _ [I,I] = True
bindingSupport _ [I,O] = True
bindingSupport _ [O,I] = True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (UnaryMono _ _ _ _ func _) [I,I] [a, b] =
return (if func a == b
then [[]]
else [])
bindingExec (UnaryMono _ _ _ _ func _) [I,O] [a] =
return [[func a]]
bindingExec (UnaryMono _ _ _ _ _ g) [O,I] [b] =
return (case g b of
Just a -> [[a]]
Nothing -> [])
data BinaryMono = BinaryMono String String CastType CastType CastType (ResultValue -> ResultValue -> ResultValue) (ResultValue -> ResultValue -> Maybe ResultValue) (ResultValue -> ResultValue -> Maybe ResultValue)
instance Binding BinaryMono where
bindingPred (BinaryMono ns n t1 t2 t3 _ _ _) = Pred (PredName [ns] n) (PredType PropertyPred [PTKeyIO t1, PTKeyIO t2, PTPropIO t3])
bindingSupport _ [I,I,I] = True
bindingSupport _ [I,I,O] = True
bindingSupport _ [I,O,I] = True
bindingSupport _ [O,I,I] = True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (BinaryMono _ _ _ _ _ func _ _) [I,I,I] [a, b, c] =
return (if func a b == c
then [[]]
else [])
bindingExec (BinaryMono _ _ _ _ _ func _ _) [I,I,O] [a, b] =
return [[func a b]]
bindingExec (BinaryMono _ _ _ _ _ _ g _) [I,O,I] [a, c] =
return (case g a c of
Just b -> [[b]]
Nothing -> [])
bindingExec (BinaryMono _ _ _ _ _ _ _ h) [O,I,I] [b, c] =
return (case h b c of
Just a -> [[a]]
Nothing -> [])
data UnaryBoolean = UnaryBoolean String String CastType (ResultValue -> Bool)
instance Binding UnaryBoolean where
bindingPred (UnaryBoolean ns n t1 _) = Pred (PredName [ns] n) (PredType ObjectPred [PTKeyI t1])
bindingSupport _ [I] = True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (UnaryBoolean _ _ _ func) _ [val1] =
return (if func val1
then [[]]
else [])
data BinaryBoolean = BinaryBoolean String String CastType CastType (ResultValue -> ResultValue -> Bool)
instance Binding BinaryBoolean where
bindingPred (BinaryBoolean ns n t1 t2 _) = Pred (PredName [ns] n) (PredType ObjectPred [PTKeyI t1, PTKeyI t2])
bindingSupport _ [I,I] = True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (BinaryBoolean _ _ _ _ func) _ [val1, val2] =
return (if func val1 val2
then [[]]
else [])
data TernaryBoolean = TernaryBoolean String String CastType CastType CastType (ResultValue -> ResultValue -> ResultValue -> Bool)
instance Binding TernaryBoolean where
bindingPred (TernaryBoolean ns n t1 t2 t3 _) = Pred (PredName [ns] n) (PredType ObjectPred [PTKeyI t1, PTKeyI t2, PTKeyI t3])
bindingSupport _ [I,I,I] = True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (TernaryBoolean _ _ _ _ _ func) _ [val1, val2, val3] =
return (if func val1 val2 val3
then [[]]
else [])
data UnaryProcedure = UnaryProcedure String String CastType (ResultValue -> IO ())
instance Binding UnaryProcedure where
bindingPred (UnaryProcedure ns n t1 _) = Pred (PredName [ns] n) (PredType ObjectPred [PTKeyI t1])
bindingSupport _ [I] = True
bindingSupport _ _ = False
bindingSupportInsert _ = False
bindingSupportDelete _ = False
bindingExec (UnaryProcedure _ _ _ func) [I] [val1] = do
func val1
return [[]]
| xu-hao/QueryArrow | QueryArrow-db-inmemory/src/QueryArrow/Binding/Binding.hs | bsd-3-clause | 13,132 | 0 | 19 | 3,070 | 5,244 | 2,772 | 2,472 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Applicative ((<|>))
import Control.Concurrent (threadDelay)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Machine.Concurrent
import Test.Tasty
import Test.Tasty.HUnit
worker :: String -> Double -> ProcessT IO () ()
worker _name dt = repeatedly $ do _ <- await
liftIO $ threadDelay dt'
yield ()
where dt' = floor $ dt * 10000
timed :: MonadIO m => m a -> m (a, Double)
timed m = do t1 <- liftIO getCurrentTime
r <- m
t2 <- liftIO getCurrentTime
return (r, realToFrac $ t2 `diffUTCTime` t1)
-- Based on GitHub Issue 7
-- https://github.com/acowley/concurrent-machines/issues/7
alternativeWorks :: TestTree
alternativeWorks = testCase "alternative" $ do
xs <- runT (replicated 5 "Step" ~> construct aux)
assertEqual "Results" (replicate 5 "Step" ++ ["Done"]) xs
where aux = do x <- await <|> yield "Done" *> stop
yield x
aux
alternativeWorksDelay :: TestTree
alternativeWorksDelay = testCase "alternative with delay" $ do
xs <- runT (construct (gen 5) ~> construct aux)
assertEqual "Results" (replicate 5 "Step" ++ ["Done"]) xs
where aux = do x <- await <|> yield "Done" *> stop
yield x
aux
gen :: MonadIO m => Int -> PlanT k String m a
gen 0 = stop
gen n = yield "Step" >> liftIO (threadDelay 100000) >> gen (n-1)
pipeline :: TestTree
pipeline = testCaseSteps "pipeline" $ \step -> do
(r,dt) <- timed . runT . supply (repeat ()) $
worker "A" 1 ~> worker "B" 1 ~> worker "C" 1 ~> taking 10
(r',dt') <- timed . runT . supply (repeat ()) $
worker "A" 1 >~> worker "B" 1 >~> worker "C" 1 >~> taking 10
step "Consistent results"
assertEqual "Results" r r'
step "Parallelism"
assertBool ("Pipeline faster than sequential" ++ show (dt',dt)) (dt' * 1.5 < dt)
workStealing :: TestTree
workStealing = testCaseSteps "work stealing" $ \step -> do
(r,dt) <- timed . runT $
source [1..32::Int] ~> scatter (replicate 4 slowDoubler)
(r',dt') <- timed. runT $ source [1..32] ~> slowDoubler
step "Consistent results"
assertBool "Predicted Parallel Length" (length r == 32)
assertBool "Predicted Serial Length" (length r' == 32)
assertBool "Predicted Results" (all (`elem` r) (map (*2) [1..32]))
assertBool "Results" (all (`elem` r) r')
step "Parallelism"
assertBool ("Work Stealing faster than sequential" ++ show (dt',dt))
(dt * 1.5 < dt')
where slowDoubler = repeatedly $ do x <- await
liftIO (threadDelay 100000)
yield (x * 2)
main :: IO ()
main = defaultMain $
testGroup "concurrent-machines"
[ pipeline, workStealing, alternativeWorks, alternativeWorksDelay ]
| acowley/concurrent-machines | tests/AllTests.hs | bsd-3-clause | 2,949 | 0 | 18 | 802 | 1,048 | 520 | 528 | 65 | 2 |
module Game.LambdaPad
( LambdaPadConfig
( gameConfigs
, padConfigs
, defaultPad
, defaultSpeed
)
, defaultLambdaPadConfig
, lambdaPad
) where
import Game.LambdaPad.Internal
| zearen-wover/lambda-pad | src/lib/Game/LambdaPad.hs | bsd-3-clause | 202 | 0 | 5 | 50 | 33 | 24 | 9 | 11 | 0 |
-- 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.
module Duckling.Quantity.RU.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Quantity.RU.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "RU Tests"
[ makeCorpusTest [Seal Quantity] corpus
]
| facebookincubator/duckling | tests/Duckling/Quantity/RU/Tests.hs | bsd-3-clause | 509 | 0 | 9 | 80 | 79 | 50 | 29 | 11 | 1 |
--------------------------------------------------------------------------------
-- | This module containing some specialized functions to deal with tags. It
-- assumes you follow some conventions.
--
-- We support two types of tags: tags and categories.
--
-- To use default tags, use 'buildTags'. Tags are placed in a comma-separated
-- metadata field like this:
--
-- > ---
-- > author: Philip K. Dick
-- > title: Do androids dream of electric sheep?
-- > tags: future, science fiction, humanoid
-- > ---
-- > The novel is set in a post-apocalyptic near future, where the Earth and
-- > its populations have been damaged greatly by Nuclear...
--
-- To use categories, use the 'buildCategories' function. Categories are
-- determined by the directory a page is in, for example, the post
--
-- > posts/coding/2010-01-28-hakyll-categories.markdown
--
-- will receive the @coding@ category.
--
-- Advanced users may implement custom systems using 'buildTagsWith' if desired.
--
-- In the above example, we would want to create a page which lists all pages in
-- the @coding@ category, for example, with the 'Identifier':
--
-- > tags/coding.html
--
-- This is where the first parameter of 'buildTags' and 'buildCategories' comes
-- in. In the above case, we used the function:
--
-- > fromCapture "tags/*.html" :: String -> Identifier
--
-- The 'tagsRules' function lets you generate such a page for each tag in the
-- 'Rules' monad.
{-# LANGUAGE Arrows #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Hakyll.Web.Tags
( Tags (..)
, getTags
, buildTagsWith
, buildTags
, buildCategories
, tagsRules
, renderTags
, renderTagCloud
, renderTagCloudWith
, tagCloudField
, tagCloudFieldWith
, renderTagList
, tagsField
, tagsFieldWith
, categoryField
, sortTagsBy
, caseInsensitiveTags
) where
--------------------------------------------------------------------------------
import Control.Arrow ((&&&))
import Control.Monad (foldM, forM, forM_)
import Data.Char (toLower)
import Data.List (intercalate, intersperse,
sortBy)
import qualified Data.Map as M
import Data.Maybe (catMaybes, fromMaybe)
import Data.Monoid (mconcat)
import Data.Ord (comparing)
import System.FilePath (takeBaseName, takeDirectory)
import Text.Blaze.Html (toHtml, toValue, (!))
import Text.Blaze.Html.Renderer.String (renderHtml)
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
--------------------------------------------------------------------------------
import Hakyll.Core.Compiler
import Hakyll.Core.Dependencies
import Hakyll.Core.Identifier
import Hakyll.Core.Identifier.Pattern
import Hakyll.Core.Item
import Hakyll.Core.Metadata
import Hakyll.Core.Rules
import Hakyll.Core.Util.String
import Hakyll.Web.Template.Context
import Hakyll.Web.Html
--------------------------------------------------------------------------------
-- | Data about tags
data Tags = Tags
{ tagsMap :: [(String, [Identifier])]
, tagsMakeId :: String -> Identifier
, tagsDependency :: Dependency
} deriving (Show)
--------------------------------------------------------------------------------
-- | Obtain tags from a page in the default way: parse them from the @tags@
-- metadata field.
getTags :: MonadMetadata m => Identifier -> m [String]
getTags identifier = do
metadata <- getMetadata identifier
return $ maybe [] (map trim . splitAll ",") $ M.lookup "tags" metadata
--------------------------------------------------------------------------------
-- | Obtain categories from a page.
getCategory :: MonadMetadata m => Identifier -> m [String]
getCategory = return . return . takeBaseName . takeDirectory . toFilePath
--------------------------------------------------------------------------------
-- | Higher-order function to read tags
buildTagsWith :: MonadMetadata m
=> (Identifier -> m [String])
-> Pattern
-> (String -> Identifier)
-> m Tags
buildTagsWith f pattern makeId = do
ids <- getMatches pattern
tagMap <- foldM addTags M.empty ids
return $ Tags (M.toList tagMap) makeId (PatternDependency pattern ids)
where
-- Create a tag map for one page
addTags tagMap id' = do
tags <- f id'
let tagMap' = M.fromList $ zip tags $ repeat [id']
return $ M.unionWith (++) tagMap tagMap'
--------------------------------------------------------------------------------
buildTags :: MonadMetadata m => Pattern -> (String -> Identifier) -> m Tags
buildTags = buildTagsWith getTags
--------------------------------------------------------------------------------
buildCategories :: MonadMetadata m => Pattern -> (String -> Identifier)
-> m Tags
buildCategories = buildTagsWith getCategory
--------------------------------------------------------------------------------
tagsRules :: Tags -> (String -> Pattern -> Rules ()) -> Rules ()
tagsRules tags rules =
forM_ (tagsMap tags) $ \(tag, identifiers) ->
create [tagsMakeId tags tag] $
rulesExtraDependencies [tagsDependency tags] $
rules tag $ fromList identifiers
--------------------------------------------------------------------------------
-- | Render tags in HTML (the flexible higher-order function)
renderTags :: (String -> String -> Int -> Int -> Int -> String)
-- ^ Produce a tag item: tag, url, count, min count, max count
-> ([String] -> String)
-- ^ Join items
-> Tags
-- ^ Tag cloud renderer
-> Compiler String
renderTags makeHtml concatHtml tags = do
-- In tags' we create a list: [((tag, route), count)]
tags' <- forM (tagsMap tags) $ \(tag, ids) -> do
route' <- getRoute $ tagsMakeId tags tag
return ((tag, route'), length ids)
-- TODO: We actually need to tell a dependency here!
let -- Absolute frequencies of the pages
freqs = map snd tags'
-- The minimum and maximum count found
(min', max')
| null freqs = (0, 1)
| otherwise = (minimum &&& maximum) freqs
-- Create a link for one item
makeHtml' ((tag, url), count) =
makeHtml tag (toUrl $ fromMaybe "/" url) count min' max'
-- Render and return the HTML
return $ concatHtml $ map makeHtml' tags'
--------------------------------------------------------------------------------
-- | Render a tag cloud in HTML
renderTagCloud :: Double
-- ^ Smallest font size, in percent
-> Double
-- ^ Biggest font size, in percent
-> Tags
-- ^ Input tags
-> Compiler String
-- ^ Rendered cloud
renderTagCloud = renderTagCloudWith makeLink (intercalate " ")
where
makeLink minSize maxSize tag url count min' max' =
-- Show the relative size of one 'count' in percent
let diff = 1 + fromIntegral max' - fromIntegral min'
relative = (fromIntegral count - fromIntegral min') / diff
size = floor $ minSize + relative * (maxSize - minSize) :: Int
in renderHtml $
H.a ! A.style (toValue $ "font-size: " ++ show size ++ "%")
! A.href (toValue url)
$ toHtml tag
--------------------------------------------------------------------------------
-- | Render a tag cloud in HTML
renderTagCloudWith :: (Double -> Double ->
String -> String -> Int -> Int -> Int -> String)
-- ^ Render a single tag link
-> ([String] -> String)
-- ^ Concatenate links
-> Double
-- ^ Smallest font size, in percent
-> Double
-- ^ Biggest font size, in percent
-> Tags
-- ^ Input tags
-> Compiler String
-- ^ Rendered cloud
renderTagCloudWith makeLink cat minSize maxSize =
renderTags (makeLink minSize maxSize) cat
--------------------------------------------------------------------------------
-- | Render a tag cloud in HTML as a context
tagCloudField :: String
-- ^ Destination key
-> Double
-- ^ Smallest font size, in percent
-> Double
-- ^ Biggest font size, in percent
-> Tags
-- ^ Input tags
-> Context a
-- ^ Context
tagCloudField key minSize maxSize tags =
field key $ \_ -> renderTagCloud minSize maxSize tags
--------------------------------------------------------------------------------
-- | Render a tag cloud in HTML as a context
tagCloudFieldWith :: String
-- ^ Destination key
-> (Double -> Double ->
String -> String -> Int -> Int -> Int -> String)
-- ^ Render a single tag link
-> ([String] -> String)
-- ^ Concatenate links
-> Double
-- ^ Smallest font size, in percent
-> Double
-- ^ Biggest font size, in percent
-> Tags
-- ^ Input tags
-> Context a
-- ^ Context
tagCloudFieldWith key makeLink cat minSize maxSize tags =
field key $ \_ -> renderTagCloudWith makeLink cat minSize maxSize tags
--------------------------------------------------------------------------------
-- | Render a simple tag list in HTML, with the tag count next to the item
-- TODO: Maybe produce a Context here
renderTagList :: Tags -> Compiler (String)
renderTagList = renderTags makeLink (intercalate ", ")
where
makeLink tag url count _ _ = renderHtml $
H.a ! A.href (toValue url) $ toHtml (tag ++ " (" ++ show count ++ ")")
--------------------------------------------------------------------------------
-- | Render tags with links with custom functions to get tags and to
-- render links
tagsFieldWith :: (Identifier -> Compiler [String])
-- ^ Get the tags
-> (String -> (Maybe FilePath) -> Maybe H.Html)
-- ^ Render link for one tag
-> ([H.Html] -> H.Html)
-- ^ Concatenate tag links
-> String
-- ^ Destination field
-> Tags
-- ^ Tags structure
-> Context a
-- ^ Resulting context
tagsFieldWith getTags' renderLink cat key tags = field key $ \item -> do
tags' <- getTags' $ itemIdentifier item
links <- forM tags' $ \tag -> do
route' <- getRoute $ tagsMakeId tags tag
return $ renderLink tag route'
return $ renderHtml $ cat $ catMaybes $ links
--------------------------------------------------------------------------------
-- | Render tags with links
tagsField :: String -- ^ Destination key
-> Tags -- ^ Tags
-> Context a -- ^ Context
tagsField =
tagsFieldWith getTags simpleRenderLink (mconcat . intersperse ", ")
--------------------------------------------------------------------------------
-- | Render the category in a link
categoryField :: String -- ^ Destination key
-> Tags -- ^ Tags
-> Context a -- ^ Context
categoryField =
tagsFieldWith getCategory simpleRenderLink (mconcat . intersperse ", ")
--------------------------------------------------------------------------------
-- | Render one tag link
simpleRenderLink :: String -> (Maybe FilePath) -> Maybe H.Html
simpleRenderLink _ Nothing = Nothing
simpleRenderLink tag (Just filePath) =
Just $ H.a ! A.href (toValue $ toUrl filePath) $ toHtml tag
--------------------------------------------------------------------------------
-- | Sort tags using supplied function. First element of the tuple passed to
-- the comparing function is the actual tag name.
sortTagsBy :: ((String, [Identifier]) -> (String, [Identifier]) -> Ordering)
-> Tags -> Tags
sortTagsBy f t = t {tagsMap = sortBy f (tagsMap t)}
--------------------------------------------------------------------------------
-- | Sample sorting function that compares tags case insensitively.
caseInsensitiveTags :: (String, [Identifier]) -> (String, [Identifier])
-> Ordering
caseInsensitiveTags = comparing $ map toLower . fst
| freizl/freizl.github.com-old | src/Hakyll/Web/Tags.hs | bsd-3-clause | 13,063 | 0 | 16 | 3,695 | 2,212 | 1,221 | 991 | 172 | 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.
module Duckling.Ordinal.UK.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Ordinal.UK.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "UK Tests"
[ makeCorpusTest [Seal Ordinal] corpus
]
| facebookincubator/duckling | tests/Duckling/Ordinal/UK/Tests.hs | bsd-3-clause | 504 | 0 | 9 | 78 | 79 | 50 | 29 | 11 | 1 |
module Quoter.Substitute where
| mgsloan/haskell-quoter | src/Quoter/Substitute.hs | bsd-3-clause | 32 | 0 | 3 | 4 | 6 | 4 | 2 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Test.Mafia.Tripping where
import Control.Applicative
import Data.Monoid
import Data.Function
import Test.QuickCheck
import Prelude
-- | Generalized round-trip property function
tripping :: (Applicative f, Show (f a), Eq (f a)) => (a -> b) -> (b -> f a) -> a -> Property
tripping = trippingOn id
trippingOn :: (Applicative f, Show (f a), Show (f c), Eq (f c)) => (a -> c) -> (a -> b) -> (b -> f a) -> a -> Property
trippingOn f = trippingWith ((===) `on` fmap f)
trippingWith :: (Applicative f, Show (f a)) => (f a -> f a -> Property) -> (a -> b) -> (b -> f a) -> a -> Property
trippingWith prop to fro a =
let tripped = (fro . to) a
purea = pure a
in counterexample (show tripped <> " /= " <> show purea)
(prop tripped purea)
| ambiata/mafia | test/Test/Mafia/Tripping.hs | bsd-3-clause | 877 | 0 | 11 | 223 | 372 | 196 | 176 | 18 | 1 |
-- | Sunroof provides a way to express Javascript computations in
-- Haskell. The computations can be expressed using the 'JS' monad.
--
-- There are ready to use API bindings for frequently used
-- Javascript:
--
-- * 'Language.Sunroof.JS.Browser' - Bindings of the standard browser APIs.
--
-- * 'Language.Sunroof.JS.Canvas' - Bindings of the HTML5 canvas element API.
--
-- * 'Language.Sunroof.JS.JQuery' - Bindings of some JQuery methods.
--
-- * 'Language.Sunroof.JS.Date' - Bindings of the standard data API.
--
-- It also provides an abstraction over Javascripts (not existing) threading
-- model. Cooperative multithreading can be emulated using the Sunroof
-- abstractions ('forkJS', 'yield', 'loop'). Equivalents of well-known
-- Haskell concurrency abstractions like 'Control.Concurrent.MVar'
-- or 'Control.Concurrent.Chan' are also provided on Javascript level
-- through 'JSMVar' and 'JSChan'.
--
-- Due to the threading abstraction there are two kinds of computations.
-- They are indicated by the first type parameter of 'JS' (a 'T' value).
-- Normal Javascript computations that can be assumed to terminate and
-- that may deliver a result value are written in the 'JSA' monad. While
-- possibly blocking computations (those that involve threading operations)
-- are written in the 'JSB' monad.
--
-- As the computations are expressed in Haskell, they have a functional
-- nature. It is possible to change the attribute values of objects using
-- ':=' and 'Language.Sunroof.Types.#':
--
-- > o # att := val
--
-- If a top-level mutable variable is needed, use the 'JSRef' abstraction.
-- It is comparable to 'Data.IORef.IORef'.
module Language.Sunroof
(
-- * Notes
-- | It is advised to use Sunroof with the following language extensions:
--
-- * @OverloadedStrings@ - Enables using literal strings for attribute
-- names and Javascript strings.
--
-- * @DataKinds@ - Enables using @JS A@ or @JS B@ instead of @JSA@ and @JSB@.
-- This extension is not essential.
--
-- * Sunroof Compiler
sunroofCompileJSA
, sunroofCompileJSB
, CompilerOpts(..)
-- * Classes
, Sunroof(..), SunroofValue(..), SunroofArgument(..)
, JSTuple(..)
, SunroofKey(..)
, SunroofFunctor(..)
-- * Types
, Type(..)
, T(..), ThreadProxy(..)
, SunroofThread(..)
, JS(..), JSA, JSB
, JSFunction
, JSContinuation
, JSSelector
-- * DSL Primitives and Utilties
, done, liftJS
, function, continuation
, apply, ($$), goto
, cast
, (#)
, attr
, fun, invoke, new
, evaluate, value
, switch
, nullJS
, label, index
, (!)
, callcc
, comment
, delete
-- * Concurrency Primitives
, forkJS
, threadDelay
, yield
-- * Basic JS types
-- ** JavaScript Object
, JSObject, this, object
-- ** Boolean
, JSBool
-- ** Numbers
, JSNumber, int
-- ** Strings
, JSString, string
-- ** Array
, JSArray
, array, newArray
, length'
, lookup'
, insert'
, shift, unshift
, pop, push
, empty
-- ** References
, JSRef
, newJSRef
, readJSRef
, writeJSRef
, modifyJSRef
-- ** Channnels
, JSChan
, newChan
, writeChan, readChan
-- ** Thread-safe Mutable Variables
, JSMVar
, newMVar
, newEmptyMVar
, takeMVar, putMVar
-- * DSL Utilties
, loop
, fixJS
-- * String Utilities
, substr, substr2
) where
import Language.Sunroof.JavaScript ( Type(..) )
import Language.Sunroof.Classes
( Sunroof(..), SunroofValue(..), SunroofArgument(..) )
import Language.Sunroof.Types
( T(..), ThreadProxy(..)
, SunroofThread(..)
, JS(..), JSA, JSB
, done, liftJS
, JSFunction
, JSContinuation
, function, continuation
, callcc
, apply, ($$), goto
, cast
, (#)
, attr
, fun, invoke, new
, evaluate, value
, switch
, nullJS
, delete
, JSTuple(..)
, SunroofKey(..)
, SunroofFunctor(..)
)
import Language.Sunroof.Compiler
( sunroofCompileJSA
, sunroofCompileJSB
, CompilerOpts(..) )
import Language.Sunroof.Selector
( JSSelector
, label, index
, (!) )
import Language.Sunroof.Concurrent
( loop
, forkJS
, threadDelay
, yield )
import Language.Sunroof.JS.Ref
( JSRef
, newJSRef
, readJSRef
, writeJSRef
, modifyJSRef )
import Language.Sunroof.JS.Bool ( JSBool )
import Language.Sunroof.JS.Object ( JSObject, object, this )
import Language.Sunroof.JS.Number ( JSNumber, int )
import Language.Sunroof.JS.String ( JSString, string )
import Language.Sunroof.JS.Array
( JSArray
, array, newArray
, length'
, lookup'
, insert'
, shift, unshift
, pop, push
, empty )
import Language.Sunroof.JS.Chan
( JSChan
, newChan
, writeChan, readChan )
import Language.Sunroof.JS.MVar
( JSMVar
, newMVar, newEmptyMVar
, takeMVar, putMVar )
import Language.Sunroof.Utils
( comment, fixJS, substr, substr2 )
| ku-fpg/sunroof-compiler | Language/Sunroof.hs | bsd-3-clause | 5,076 | 0 | 6 | 1,259 | 797 | 561 | 236 | 127 | 0 |
module Ling.Skel where
-- Haskell module generated by the BNF converter
import Ling.Abs
import Ling.ErrM
type Result = Err String
failure :: Show a => a -> Result
failure x = Bad $ "Undefined case: " ++ show x
transName :: Name -> Result
transName x = case x of
Name string -> failure x
transProgram :: Program -> Result
transProgram x = case x of
Prg decs -> failure x
transDec :: Dec -> Result
transDec x = case x of
DDef name optchandecs proc -> failure x
DSig name term optdef -> failure x
DDat name connames -> failure x
transConName :: ConName -> Result
transConName x = case x of
CN name -> failure x
transOptDef :: OptDef -> Result
transOptDef x = case x of
NoDef -> failure x
SoDef term -> failure x
transVarDec :: VarDec -> Result
transVarDec x = case x of
VD name term -> failure x
transOptChanDecs :: OptChanDecs -> Result
transOptChanDecs x = case x of
NoChanDecs -> failure x
SoChanDecs chandecs -> failure x
transChanDec :: ChanDec -> Result
transChanDec x = case x of
CD name optsession -> failure x
transBranch :: Branch -> Result
transBranch x = case x of
Br conname term -> failure x
transATerm :: ATerm -> Result
transATerm x = case x of
Var name -> failure x
Lit integer -> failure x
Con conname -> failure x
TTyp -> failure x
TProto rsessions -> failure x
Paren term -> failure x
transDTerm :: DTerm -> Result
transDTerm x = case x of
DTTyp name aterms -> failure x
DTBnd name term -> failure x
transTerm :: Term -> Result
transTerm x = case x of
RawApp aterm aterms -> failure x
Case term branchs -> failure x
TFun vardec vardecs term -> failure x
TSig vardec vardecs term -> failure x
Lam vardec vardecs term -> failure x
TProc chandecs proc -> failure x
transProc :: Proc -> Result
transProc x = case x of
Act prefs procs -> failure x
transProcs :: Procs -> Result
transProcs x = case x of
ZeroP -> failure x
Ax session names -> failure x
At aterm names -> failure x
NewSlice names aterm name proc -> failure x
Prll procs -> failure x
transPref :: Pref -> Result
transPref x = case x of
Nu chandec1 chandec2 -> failure x
ParSplit name chandecs -> failure x
TenSplit name chandecs -> failure x
SeqSplit name chandecs -> failure x
Send name aterm -> failure x
Recv name vardec -> failure x
transOptSession :: OptSession -> Result
transOptSession x = case x of
NoSession -> failure x
SoSession rsession -> failure x
transSession :: Session -> Result
transSession x = case x of
Atm name -> failure x
End -> failure x
Par rsessions -> failure x
Ten rsessions -> failure x
Seq rsessions -> failure x
Sort aterm1 aterm2 -> failure x
Log session -> failure x
Fwd integer session -> failure x
Snd dterm csession -> failure x
Rcv dterm csession -> failure x
Dual session -> failure x
Loli session1 session2 -> failure x
transRSession :: RSession -> Result
transRSession x = case x of
Repl session optrepl -> failure x
transOptRepl :: OptRepl -> Result
transOptRepl x = case x of
One -> failure x
Some aterm -> failure x
transCSession :: CSession -> Result
transCSession x = case x of
Cont session -> failure x
Done -> failure x
| jyp/ling | Ling/Skel.hs | bsd-3-clause | 3,164 | 0 | 8 | 699 | 1,227 | 572 | 655 | 104 | 12 |
{-# Language OverloadedStrings #-}
{-|
Module : Client.Hook.Matterbridge
Description : Hook for intergrating Matterbridge bridged messages
Copyright : (c) Felix Friedlander 2021
License : ISC
Maintainer : felix@ffetc.net
Matterbridge is a simple multi-protocol chat bridge, supporting
dozens of different protocols. This hook makes Matterbridged messages
appear native in the client.
message-hooks configuration takes one of two forms;
to operate on all channels:
> ["matterbridge", "nick"]
or, to operate only on selected channels:
> ["matterbridge", "nick", "#chan1", "#chan2", ..., "#chann"]
This hook assumes the Matterbridge RemoteNickFormat is simply
"<{NICK}> ".
-}
module Client.Hook.Matterbridge (matterbridgeHook) where
import Data.Text (Text)
import Control.Lens (set, view)
import Text.Regex.TDFA ((=~))
import Client.Hook (MessageHook(..), MessageResult(..))
import Irc.Message
import Irc.Identifier (mkId, Identifier)
import Irc.UserInfo (UserInfo(..), uiNick)
data MbMsg = Msg | Act
matterbridgeHook :: [Text] -> Maybe MessageHook
matterbridgeHook [] = Nothing
matterbridgeHook (nick:chans) = Just (MessageHook "matterbridge" False (remap (mkId nick) chanfilter))
where
chanfilter
| null chans = const True
| otherwise = (`elem` map mkId chans)
remap :: Identifier -> (Identifier -> Bool) -> IrcMsg -> MessageResult
remap nick chanfilter ircmsg =
case ircmsg of
Privmsg (Source ui _) chan msg
| view uiNick ui == nick, chanfilter chan -> remap' Msg ui chan msg
Ctcp (Source ui _) chan "ACTION" msg
| view uiNick ui == nick, chanfilter chan -> remap' Act ui chan msg
_ -> PassMessage
remap' :: MbMsg -> UserInfo -> Identifier -> Text -> MessageResult
remap' mbmsg ui chan msg =
case msg =~ ("^<([^>]+)> (.*)$"::Text) of
[_,nick,msg']:_ -> RemapMessage (newmsg mbmsg (fakeUser nick ui) chan msg')
_ -> PassMessage
newmsg :: MbMsg -> Source -> Identifier -> Text -> IrcMsg
newmsg Msg src chan msg = Privmsg src chan msg
newmsg Act src chan msg = Ctcp src chan "ACTION" msg
fakeUser :: Text -> UserInfo -> Source
fakeUser nick ui = Source (set uiNick (mkId nick) ui) ""
| dolio/irc-core | src/Client/Hook/Matterbridge.hs | isc | 2,172 | 0 | 12 | 400 | 580 | 304 | 276 | 34 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module MigrationTest where
import Database.Persist.TH
import qualified Data.Text as T
import Init
#ifdef WITH_NOSQL
mkPersist persistSettings [persistUpperCase|
#else
share [mkPersist sqlSettings, mkMigrate "migrationMigrate", mkDeleteCascade sqlSettings] [persistLowerCase|
#endif
Target
field1 Int
field2 T.Text
UniqueTarget field1 field2
deriving Eq Show
Source
field3 Int
field4 TargetId
|]
#ifdef WITH_NOSQL
mkPersist persistSettings [persistUpperCase|
#else
share [mkPersist sqlSettings, mkMigrate "migrationAddCol", mkDeleteCascade sqlSettings] [persistLowerCase|
#endif
Target1 sql=target
field1 Int
field2 T.Text
UniqueTarget1 field1 field2
deriving Eq Show
Source1 sql=source
field3 Int
extra Int
field4 Target1Id
|]
#ifndef WITH_NOSQL
specs :: Spec
specs = describe "Migration" $ do
it "is idempotent" $ db $ do
again <- getMigration migrationMigrate
liftIO $ again @?= []
it "really is idempotent" $ db $ do
runMigration migrationMigrate
again <- getMigration migrationMigrate
liftIO $ again @?= []
it "can add an extra column" $ db $ do
-- Failing test case for #735. Foreign-key checking, switched on in
-- version 2.6.1, caused persistent-sqlite to generate a `references`
-- constraint in a *temporary* table during migration, which fails.
_ <- runMigration migrationAddCol
again <- getMigration migrationAddCol
liftIO $ again @?= []
#endif
| plow-technologies/persistent | persistent-test/src/MigrationTest.hs | mit | 1,851 | 0 | 12 | 363 | 207 | 110 | 97 | 30 | 1 |
{- |
Module : ./COL/Print_AS.hs
Description : Pretty printing for COL
Copyright : (c) Wiebke Herding, C. Maeder, Uni Bremen 2004-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : till@informatik.uni-bremen.de
Stability : provisional
Portability : portable
pretty printing
-}
module COL.Print_AS where
import qualified Data.Set as Set
import qualified Data.Map as Map
import Common.Doc
import Common.DocUtils
import CASL.ToDoc
import COL.AS_COL
import COL.COLSign
instance Pretty COL_SIG_ITEM where
pretty = printCOL_SIG_ITEM
printCOL_SIG_ITEM :: COL_SIG_ITEM -> Doc
printCOL_SIG_ITEM csi = case csi of
Constructor_items ls _ -> keyword (constructorS ++ pluralS ls) <+>
semiAnnos idDoc ls
Observer_items ls _ -> keyword observerS <+>
semiAnnos (printPair idDoc (printMaybe pretty)) ls
instance Pretty COLSign where
pretty = printCOLSign
printCOLSign :: COLSign -> Doc
printCOLSign s = keyword constructorS <+>
fsep (punctuate semi $ map idDoc (Set.toList $ constructors s))
$+$ keyword observerS <+>
fsep (punctuate semi $
map (printPair idDoc pretty) (Map.toList $ observers s))
| spechub/Hets | COL/Print_AS.hs | gpl-2.0 | 1,169 | 0 | 14 | 230 | 268 | 138 | 130 | 24 | 2 |
{-# LANGUAGE CPP, TemplateHaskell #-}
{-
Version number-related utilities. See also the Makefile.
-}
module Hledger.Cli.Version (
progname,
version,
prognameandversion,
prognameanddetailedversion,
binaryfilename
)
where
import System.Info (os, arch)
import Text.Printf
import Hledger.Utils
-- package name and version from the cabal file
progname, version, prognameandversion, prognameanddetailedversion :: String
progname = "hledger"
#ifdef VERSION
version = VERSION
#else
version = "dev build"
#endif
prognameandversion = progname ++ " " ++ version
prognameanddetailedversion = printf "%s %s" progname version
-- developer build version strings include PATCHLEVEL (number of
-- patches since the last tag). If defined, it must be a number.
patchlevel :: String
#ifdef PATCHLEVEL
patchlevel = "." ++ show (PATCHLEVEL :: Int)
#else
patchlevel = ""
#endif
-- the package version plus patchlevel if specified
buildversion :: String
buildversion = version ++ patchlevel
-- | Given a program name, return a precise platform-specific executable
-- name suitable for naming downloadable binaries. Can raise an error if
-- the version and patch level was not defined correctly at build time.
binaryfilename :: String -> String
binaryfilename progname = prettify $ splitAtElement '.' buildversion
where
prettify (major:minor:bugfix:patches:[]) =
printf "%s-%s.%s%s%s-%s-%s%s" progname major minor bugfix' patches' os' arch suffix
where
bugfix'
| bugfix `elem` ["0"{-,"98","99"-}] = ""
| otherwise = '.' : bugfix
patches'
| patches/="0" = '+' : patches
| otherwise = ""
(os',suffix)
| os == "darwin" = ("mac","" :: String)
| os == "mingw32" = ("windows",".exe")
| otherwise = (os,"")
prettify (major:minor:bugfix:[]) = prettify [major,minor,bugfix,"0"]
prettify (major:minor:[]) = prettify [major,minor,"0","0"]
prettify (major:[]) = prettify [major,"0","0","0"]
prettify [] = error' "VERSION is empty, please fix"
prettify _ = error' "VERSION has too many components, please fix"
| ony/hledger | hledger/Hledger/Cli/Version.hs | gpl-3.0 | 2,541 | 0 | 13 | 843 | 482 | 270 | 212 | 38 | 6 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module TestHelper.Output where
import Control.Monad.Writer
import State.Output
-- Created with help from:
-- https://lexi-lambda.github.io/blog/2016/10/03/using-types-to-unit-test-in-haskell/
newtype TestM a = TestM (Writer [String] a)
deriving (Functor, Applicative, Monad, MonadWriter [String])
logTestM :: TestM a -> [String]
logTestM (TestM w) = execWriter w
instance MonadOutput TestM where
-- output :: String -> TestM ()
output str = tell [str]
| BakerSmithA/Turing | test/TestHelper/Output.hs | bsd-3-clause | 512 | 0 | 8 | 76 | 119 | 67 | 52 | 10 | 1 |
-- | Server and client game state types and operations.
module Game.LambdaHack.Server.State
( StateServer(..), emptyStateServer
, DebugModeSer(..), defDebugModeSer
, RNGs(..), FovCache3(..), emptyFovCache3
) where
import Data.Binary
import qualified Data.EnumMap.Strict as EM
import qualified Data.EnumSet as ES
import qualified Data.HashMap.Strict as HM
import Data.Text (Text)
import qualified System.Random as R
import System.Time
import Game.LambdaHack.Atomic
import Game.LambdaHack.Common.Actor
import Game.LambdaHack.Common.ClientOptions
import Game.LambdaHack.Common.Faction
import Game.LambdaHack.Common.Item
import Game.LambdaHack.Common.Level
import Game.LambdaHack.Common.Misc
import Game.LambdaHack.Common.Perception
import Game.LambdaHack.Common.Time
import Game.LambdaHack.Content.ModeKind
import Game.LambdaHack.Content.RuleKind
import Game.LambdaHack.Server.ItemRev
-- | Global, server state.
data StateServer = StateServer
{ sdiscoKind :: !DiscoveryKind -- ^ full item kind discoveries data
, sdiscoKindRev :: !DiscoveryKindRev -- ^ reverse map, used for item creation
, suniqueSet :: !UniqueSet -- ^ already generated unique items
, sdiscoEffect :: !DiscoveryEffect -- ^ full item effect&Co data
, sitemSeedD :: !ItemSeedDict -- ^ map from item ids to item seeds
, sitemRev :: !ItemRev -- ^ reverse id map, used for item creation
, sItemFovCache :: !(EM.EnumMap ItemId FovCache3)
-- ^ (sight, smell, light) aspect bonus
-- of the item; zeroes if not in the map
, sflavour :: !FlavourMap -- ^ association of flavour to items
, sacounter :: !ActorId -- ^ stores next actor index
, sicounter :: !ItemId -- ^ stores next item index
, snumSpawned :: !(EM.EnumMap LevelId Int)
, sprocessed :: !(EM.EnumMap LevelId Time)
-- ^ actors are processed up to this time
, sundo :: ![CmdAtomic] -- ^ atomic commands performed to date
, sper :: !Pers -- ^ perception of all factions
, srandom :: !R.StdGen -- ^ current random generator
, srngs :: !RNGs -- ^ initial random generators
, squit :: !Bool -- ^ exit the game loop
, swriteSave :: !Bool -- ^ write savegame to a file now
, sstart :: !ClockTime -- ^ this session start time
, sgstart :: !ClockTime -- ^ this game start time
, sallTime :: !Time -- ^ clips since the start of the session
, sheroNames :: !(EM.EnumMap FactionId [(Int, (Text, Text))])
-- ^ hero names sent by clients
, sdebugSer :: !DebugModeSer -- ^ current debugging mode
, sdebugNxt :: !DebugModeSer -- ^ debugging mode for the next game
}
deriving (Show)
data FovCache3 = FovCache3
{ fovSight :: !Int
, fovSmell :: !Int
, fovLight :: !Int
}
deriving (Show, Eq)
emptyFovCache3 :: FovCache3
emptyFovCache3 = FovCache3 0 0 0
-- | Debug commands. See 'Server.debugArgs' for the descriptions.
data DebugModeSer = DebugModeSer
{ sknowMap :: !Bool
, sknowEvents :: !Bool
, sniffIn :: !Bool
, sniffOut :: !Bool
, sallClear :: !Bool
, sgameMode :: !(Maybe (GroupName ModeKind))
, sautomateAll :: !Bool
, skeepAutomated :: !Bool
, sstopAfter :: !(Maybe Int)
, sdungeonRng :: !(Maybe R.StdGen)
, smainRng :: !(Maybe R.StdGen)
, sfovMode :: !(Maybe FovMode)
, snewGameSer :: !Bool
, scurDiffSer :: !Int
, sdumpInitRngs :: !Bool
, ssavePrefixSer :: !(Maybe String)
, sdbgMsgSer :: !Bool
, sdebugCli :: !DebugModeCli -- ^ client debug parameters
}
deriving Show
data RNGs = RNGs
{ dungeonRandomGenerator :: !(Maybe R.StdGen)
, startingRandomGenerator :: !(Maybe R.StdGen)
}
instance Show RNGs where
show RNGs{..} =
let args = [ maybe "" (\gen -> "--setDungeonRng \"" ++ show gen ++ "\"")
dungeonRandomGenerator
, maybe "" (\gen -> "--setMainRng \"" ++ show gen ++ "\"")
startingRandomGenerator ]
in unwords args
-- | Initial, empty game server state.
emptyStateServer :: StateServer
emptyStateServer =
StateServer
{ sdiscoKind = EM.empty
, sdiscoKindRev = EM.empty
, suniqueSet = ES.empty
, sdiscoEffect = EM.empty
, sitemSeedD = EM.empty
, sitemRev = HM.empty
, sItemFovCache = EM.empty
, sflavour = emptyFlavourMap
, sacounter = toEnum 0
, sicounter = toEnum 0
, snumSpawned = EM.empty
, sprocessed = EM.empty
, sundo = []
, sper = EM.empty
, srandom = R.mkStdGen 42
, srngs = RNGs { dungeonRandomGenerator = Nothing
, startingRandomGenerator = Nothing }
, squit = False
, swriteSave = False
, sstart = TOD 0 0
, sgstart = TOD 0 0
, sallTime = timeZero
, sheroNames = EM.empty
, sdebugSer = defDebugModeSer
, sdebugNxt = defDebugModeSer
}
defDebugModeSer :: DebugModeSer
defDebugModeSer = DebugModeSer { sknowMap = False
, sknowEvents = False
, sniffIn = False
, sniffOut = False
, sallClear = False
, sgameMode = Nothing
, sautomateAll = False
, skeepAutomated = False
, sstopAfter = Nothing
, sdungeonRng = Nothing
, smainRng = Nothing
, sfovMode = Nothing
, snewGameSer = False
, scurDiffSer = difficultyDefault
, sdumpInitRngs = False
, ssavePrefixSer = Nothing
, sdbgMsgSer = False
, sdebugCli = defDebugModeCli
}
instance Binary StateServer where
put StateServer{..} = do
put sdiscoKind
put sdiscoKindRev
put suniqueSet
put sdiscoEffect
put sitemSeedD
put sitemRev
put sItemFovCache -- out of laziness, but it's small
put sflavour
put sacounter
put sicounter
put snumSpawned
put sprocessed
put sundo
put (show srandom)
put srngs
put sheroNames
put sdebugSer
get = do
sdiscoKind <- get
sdiscoKindRev <- get
suniqueSet <- get
sdiscoEffect <- get
sitemSeedD <- get
sitemRev <- get
sItemFovCache <- get
sflavour <- get
sacounter <- get
sicounter <- get
snumSpawned <- get
sprocessed <- get
sundo <- get
g <- get
srngs <- get
sheroNames <- get
sdebugSer <- get
let srandom = read g
sper = EM.empty
squit = False
swriteSave = False
sstart = TOD 0 0
sgstart = TOD 0 0
sallTime = timeZero
sdebugNxt = defDebugModeSer -- TODO: here difficulty level, etc. from the last session is wiped out
return $! StateServer{..}
instance Binary FovCache3 where
put FovCache3{..} = do
put fovSight
put fovSmell
put fovLight
get = do
fovSight <- get
fovSmell <- get
fovLight <- get
return $! FovCache3{..}
instance Binary DebugModeSer where
put DebugModeSer{..} = do
put sknowMap
put sknowEvents
put sniffIn
put sniffOut
put sallClear
put sgameMode
put sautomateAll
put skeepAutomated
put scurDiffSer
put sfovMode
put ssavePrefixSer
put sdbgMsgSer
put sdebugCli
get = do
sknowMap <- get
sknowEvents <- get
sniffIn <- get
sniffOut <- get
sallClear <- get
sgameMode <- get
sautomateAll <- get
skeepAutomated <- get
scurDiffSer <- get
sfovMode <- get
ssavePrefixSer <- get
sdbgMsgSer <- get
sdebugCli <- get
let sstopAfter = Nothing
sdungeonRng = Nothing
smainRng = Nothing
snewGameSer = False
sdumpInitRngs = False
return $! DebugModeSer{..}
instance Binary RNGs where
put RNGs{..} = do
put (show dungeonRandomGenerator)
put (show startingRandomGenerator)
get = do
dg <- get
sg <- get
let dungeonRandomGenerator = read dg
startingRandomGenerator = read sg
return $! RNGs{..}
| Concomitant/LambdaHack | Game/LambdaHack/Server/State.hs | bsd-3-clause | 8,494 | 0 | 16 | 2,782 | 1,906 | 1,032 | 874 | -1 | -1 |
{-# Language StandaloneDeriving #-}
{-# OPTIONS -Wall #-}
-- | name identifier.
module Language.Paraiso.Name
(
Nameable(..),
Name, mkName, isNameOf,
Named(..), namee,
) where
import Control.Monad
import Data.Text (Text, unpack)
-- | a name.
newtype Name = Name Text deriving (Eq, Ord, Show, Read)
-- | create a name from a 'Text'.
-- We do not export the constructor 'Name' for future extensibility.
mkName :: Text -> Name
mkName x = Name x
-- | something that has name.
class Nameable a where
-- | get its name.
name :: a -> Name
-- | get its name as a 'Text'.
nameText :: a -> Text
nameText = (\(Name str) -> str) . name
-- | get its name as a 'String'.
nameStr :: a -> String
nameStr = unpack . (\(Name str) -> str) . name
-- | 'Name' has 'Name'. 'Name' of 'Name' is 'Name' itself.
instance Nameable Name where
name = id
-- | Convert some type to a named type.
data Named a = Named Name a
-- | create Named object in an instance.
isNameOf :: Text -> a -> Named a
isNameOf n a = Named (mkName n) a
instance Nameable (Named a) where
name (Named n _) = n
instance Functor Named where
fmap f (Named n a) = Named n $ f a
-- | The thing the name points to.
namee :: Named a -> a
namee (Named _ x) = x
deriving instance (Eq a) => Eq (Named a)
instance (Ord a) => Ord (Named a) where
(Named n a) `compare` (Named m b) = (a,n) `compare` (b,m)
deriving instance (Show a) => Show (Named a)
deriving instance (Read a) => Read (Named a)
| drmaruyama/Paraiso | Language/Paraiso/Name.hs | bsd-3-clause | 1,488 | 0 | 12 | 344 | 496 | 275 | 221 | 34 | 1 |
{-
(c) The University of Glasgow, 1992-2006
Here we collect a variety of helper functions that construct or
analyse HsSyn. All these functions deal with generic HsSyn; functions
which deal with the instantiated versions are located elsewhere:
Parameterised by Module
---------------- -------------
RdrName parser/RdrHsSyn
Name rename/RnHsSyn
Id typecheck/TcHsSyn
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
module HsUtils(
-- Terms
mkHsPar, mkHsApp, mkHsConApp, mkSimpleHsAlt,
mkSimpleMatch, unguardedGRHSs, unguardedRHS,
mkMatchGroup, mkMatchGroupName, mkMatch, mkHsLam, mkHsIf,
mkHsWrap, mkLHsWrap, mkHsWrapCo, mkHsWrapCoR, mkLHsWrapCo,
coToHsWrapper, coToHsWrapperR, mkHsDictLet, mkHsLams,
mkHsOpApp, mkHsDo, mkHsComp, mkHsWrapPat, mkHsWrapPatCo,
mkLHsPar, mkHsCmdCast,
nlHsTyApp, nlHsTyApps, nlHsVar, nlHsLit, nlHsApp, nlHsApps, nlHsIntLit, nlHsVarApps,
nlHsDo, nlHsOpApp, nlHsLam, nlHsPar, nlHsIf, nlHsCase, nlList,
mkLHsTupleExpr, mkLHsVarTuple, missingTupArg,
toHsType, toHsKind,
-- * Constructing general big tuples
-- $big_tuples
mkChunkified, chunkify,
-- Bindings
mkFunBind, mkVarBind, mkHsVarBind, mk_easy_FunBind, mkTopFunBind,
mkPatSynBind,
isInfixFunBind,
-- Literals
mkHsIntegral, mkHsFractional, mkHsIsString, mkHsString, mkHsStringPrimLit,
-- Patterns
mkNPat, mkNPlusKPat, nlVarPat, nlLitPat, nlConVarPat, nlConVarPatName, nlConPat,
nlConPatName, nlInfixConPat, nlNullaryConPat, nlWildConPat, nlWildPat,
nlWildPatName, nlWildPatId, nlTuplePat, mkParPat,
mkBigLHsVarTup, mkBigLHsTup, mkBigLHsVarPatTup, mkBigLHsPatTup,
-- Types
mkHsAppTy, userHsTyVarBndrs,
nlHsAppTy, nlHsTyVar, nlHsFunTy, nlHsTyConApp,
-- Stmts
mkTransformStmt, mkTransformByStmt, mkBodyStmt, mkBindStmt, mkLastStmt,
emptyTransStmt, mkGroupUsingStmt, mkGroupByUsingStmt,
emptyRecStmt, emptyRecStmtName, emptyRecStmtId, mkRecStmt,
-- Template Haskell
mkHsSpliceTy, mkHsSpliceE, mkHsSpliceTE, mkUntypedSplice,
mkHsQuasiQuote, unqualQuasiQuote,
-- Flags
noRebindableInfo,
-- Collecting binders
collectLocalBinders, collectHsValBinders, collectHsBindListBinders,
collectHsIdBinders,
collectHsBindsBinders, collectHsBindBinders, collectMethodBinders,
collectPatBinders, collectPatsBinders,
collectLStmtsBinders, collectStmtsBinders,
collectLStmtBinders, collectStmtBinders,
hsLTyClDeclBinders, hsTyClForeignBinders, hsPatSynBinders,
hsForeignDeclsBinders, hsGroupBinders, hsDataFamInstBinders,
-- Collecting implicit binders
lStmtsImplicits, hsValBindsImplicits, lPatImplicits
) where
#include "HsVersions.h"
import HsDecls
import HsBinds
import HsExpr
import HsPat
import HsTypes
import HsLit
import PlaceHolder
import TcEvidence
import RdrName
import Var
import TypeRep
import TcType
import Kind
import DataCon
import Name
import NameSet
import BasicTypes
import SrcLoc
import FastString
import Util
import Bag
import Outputable
import Constants
import Data.Either
import Data.Function
import Data.List
#if __GLASGOW_HASKELL__ < 709
import Data.Foldable ( foldMap )
import Data.Monoid ( mempty, mappend )
#endif
{-
************************************************************************
* *
Some useful helpers for constructing syntax
* *
************************************************************************
These functions attempt to construct a not-completely-useless SrcSpan
from their components, compared with the nl* functions below which
just attach noSrcSpan to everything.
-}
mkHsPar :: LHsExpr id -> LHsExpr id
mkHsPar e = L (getLoc e) (HsPar e)
mkSimpleMatch :: [LPat id] -> Located (body id) -> LMatch id (Located (body id))
mkSimpleMatch pats rhs
= L loc $
Match NonFunBindMatch pats Nothing (unguardedGRHSs rhs)
where
loc = case pats of
[] -> getLoc rhs
(pat:_) -> combineSrcSpans (getLoc pat) (getLoc rhs)
unguardedGRHSs :: Located (body id) -> GRHSs id (Located (body id))
unguardedGRHSs rhs@(L loc _)
= GRHSs (unguardedRHS loc rhs) (noLoc emptyLocalBinds)
unguardedRHS :: SrcSpan -> Located (body id) -> [LGRHS id (Located (body id))]
unguardedRHS loc rhs = [L loc (GRHS [] rhs)]
mkMatchGroup :: Origin -> [LMatch RdrName (Located (body RdrName))]
-> MatchGroup RdrName (Located (body RdrName))
mkMatchGroup origin matches = MG { mg_alts = mkLocatedList matches
, mg_arg_tys = []
, mg_res_ty = placeHolderType
, mg_origin = origin }
mkLocatedList :: [Located a] -> Located [Located a]
mkLocatedList [] = noLoc []
mkLocatedList ms = L (combineLocs (head ms) (last ms)) ms
mkMatchGroupName :: Origin -> [LMatch Name (Located (body Name))]
-> MatchGroup Name (Located (body Name))
mkMatchGroupName origin matches = MG { mg_alts = mkLocatedList matches
, mg_arg_tys = []
, mg_res_ty = placeHolderType
, mg_origin = origin }
mkHsAppTy :: LHsType name -> LHsType name -> LHsType name
mkHsAppTy t1 t2 = addCLoc t1 t2 (HsAppTy t1 t2)
mkHsApp :: LHsExpr name -> LHsExpr name -> LHsExpr name
mkHsApp e1 e2 = addCLoc e1 e2 (HsApp e1 e2)
mkHsLam :: [LPat RdrName] -> LHsExpr RdrName -> LHsExpr RdrName
mkHsLam pats body = mkHsPar (L (getLoc body) (HsLam matches))
where
matches = mkMatchGroup Generated [mkSimpleMatch pats body]
mkHsLams :: [TyVar] -> [EvVar] -> LHsExpr Id -> LHsExpr Id
mkHsLams tyvars dicts expr = mkLHsWrap (mkWpTyLams tyvars
<.> mkWpLams dicts) expr
mkHsConApp :: DataCon -> [Type] -> [HsExpr Id] -> LHsExpr Id
-- Used for constructing dictionary terms etc, so no locations
mkHsConApp data_con tys args
= foldl mk_app (nlHsTyApp (dataConWrapId data_con) tys) args
where
mk_app f a = noLoc (HsApp f (noLoc a))
mkSimpleHsAlt :: LPat id -> (Located (body id)) -> LMatch id (Located (body id))
-- A simple lambda with a single pattern, no binds, no guards; pre-typechecking
mkSimpleHsAlt pat expr
= mkSimpleMatch [pat] expr
nlHsTyApp :: name -> [Type] -> LHsExpr name
nlHsTyApp fun_id tys = noLoc (HsWrap (mkWpTyApps tys) (HsVar fun_id))
nlHsTyApps :: name -> [Type] -> [LHsExpr name] -> LHsExpr name
nlHsTyApps fun_id tys xs = foldl nlHsApp (nlHsTyApp fun_id tys) xs
--------- Adding parens ---------
mkLHsPar :: LHsExpr name -> LHsExpr name
-- Wrap in parens if hsExprNeedsParens says it needs them
-- So 'f x' becomes '(f x)', but '3' stays as '3'
mkLHsPar le@(L loc e) | hsExprNeedsParens e = L loc (HsPar le)
| otherwise = le
mkParPat :: LPat name -> LPat name
mkParPat lp@(L loc p) | hsPatNeedsParens p = L loc (ParPat lp)
| otherwise = lp
-------------------------------
-- These are the bits of syntax that contain rebindable names
-- See RnEnv.lookupSyntaxName
mkHsIntegral :: String -> Integer -> PostTc RdrName Type -> HsOverLit RdrName
mkHsFractional :: FractionalLit -> PostTc RdrName Type -> HsOverLit RdrName
mkHsIsString :: String -> FastString -> PostTc RdrName Type -> HsOverLit RdrName
mkHsDo :: HsStmtContext Name -> [ExprLStmt RdrName] -> HsExpr RdrName
mkHsComp :: HsStmtContext Name -> [ExprLStmt RdrName] -> LHsExpr RdrName
-> HsExpr RdrName
mkNPat :: Located (HsOverLit id) -> Maybe (SyntaxExpr id) -> Pat id
mkNPlusKPat :: Located id -> Located (HsOverLit id) -> Pat id
mkLastStmt :: Located (bodyR idR) -> StmtLR idL idR (Located (bodyR idR))
mkBodyStmt :: Located (bodyR RdrName)
-> StmtLR idL RdrName (Located (bodyR RdrName))
mkBindStmt :: LPat idL -> Located (bodyR idR) -> StmtLR idL idR (Located (bodyR idR))
emptyRecStmt :: StmtLR idL RdrName bodyR
emptyRecStmtName :: StmtLR Name Name bodyR
emptyRecStmtId :: StmtLR Id Id bodyR
mkRecStmt :: [LStmtLR idL RdrName bodyR] -> StmtLR idL RdrName bodyR
mkHsIntegral src i = OverLit (HsIntegral src i) noRebindableInfo noSyntaxExpr
mkHsFractional f = OverLit (HsFractional f) noRebindableInfo noSyntaxExpr
mkHsIsString src s = OverLit (HsIsString src s) noRebindableInfo noSyntaxExpr
noRebindableInfo :: PlaceHolder
noRebindableInfo = PlaceHolder -- Just another placeholder;
mkHsDo ctxt stmts = HsDo ctxt (mkLocatedList stmts) placeHolderType
mkHsComp ctxt stmts expr = mkHsDo ctxt (stmts ++ [last_stmt])
where
last_stmt = L (getLoc expr) $ mkLastStmt expr
mkHsIf :: LHsExpr id -> LHsExpr id -> LHsExpr id -> HsExpr id
mkHsIf c a b = HsIf (Just noSyntaxExpr) c a b
mkNPat lit neg = NPat lit neg noSyntaxExpr
mkNPlusKPat id lit = NPlusKPat id lit noSyntaxExpr noSyntaxExpr
mkTransformStmt :: [ExprLStmt idL] -> LHsExpr idR
-> StmtLR idL idR (LHsExpr idL)
mkTransformByStmt :: [ExprLStmt idL] -> LHsExpr idR -> LHsExpr idR
-> StmtLR idL idR (LHsExpr idL)
mkGroupUsingStmt :: [ExprLStmt idL] -> LHsExpr idR
-> StmtLR idL idR (LHsExpr idL)
mkGroupByUsingStmt :: [ExprLStmt idL] -> LHsExpr idR -> LHsExpr idR
-> StmtLR idL idR (LHsExpr idL)
emptyTransStmt :: StmtLR idL idR (LHsExpr idR)
emptyTransStmt = TransStmt { trS_form = panic "emptyTransStmt: form"
, trS_stmts = [], trS_bndrs = []
, trS_by = Nothing, trS_using = noLoc noSyntaxExpr
, trS_ret = noSyntaxExpr, trS_bind = noSyntaxExpr
, trS_fmap = noSyntaxExpr }
mkTransformStmt ss u = emptyTransStmt { trS_form = ThenForm, trS_stmts = ss, trS_using = u }
mkTransformByStmt ss u b = emptyTransStmt { trS_form = ThenForm, trS_stmts = ss, trS_using = u, trS_by = Just b }
mkGroupUsingStmt ss u = emptyTransStmt { trS_form = GroupForm, trS_stmts = ss, trS_using = u }
mkGroupByUsingStmt ss b u = emptyTransStmt { trS_form = GroupForm, trS_stmts = ss, trS_using = u, trS_by = Just b }
mkLastStmt body = LastStmt body False noSyntaxExpr
mkBodyStmt body = BodyStmt body noSyntaxExpr noSyntaxExpr placeHolderType
mkBindStmt pat body = BindStmt pat body noSyntaxExpr noSyntaxExpr
emptyRecStmt' :: forall idL idR body.
PostTc idR Type -> StmtLR idL idR body
emptyRecStmt' tyVal =
RecStmt
{ recS_stmts = [], recS_later_ids = []
, recS_rec_ids = []
, recS_ret_fn = noSyntaxExpr
, recS_mfix_fn = noSyntaxExpr
, recS_bind_fn = noSyntaxExpr, recS_later_rets = []
, recS_rec_rets = [], recS_ret_ty = tyVal }
emptyRecStmt = emptyRecStmt' placeHolderType
emptyRecStmtName = emptyRecStmt' placeHolderType
emptyRecStmtId = emptyRecStmt' placeHolderTypeTc
mkRecStmt stmts = emptyRecStmt { recS_stmts = stmts }
-------------------------------
--- A useful function for building @OpApps@. The operator is always a
-- variable, and we don't know the fixity yet.
mkHsOpApp :: LHsExpr id -> id -> LHsExpr id -> HsExpr id
mkHsOpApp e1 op e2 = OpApp e1 (noLoc (HsVar op)) (error "mkOpApp:fixity") e2
unqualSplice :: RdrName
unqualSplice = mkRdrUnqual (mkVarOccFS (fsLit "splice"))
mkUntypedSplice :: LHsExpr RdrName -> HsSplice RdrName
mkUntypedSplice e = HsUntypedSplice unqualSplice e
mkHsSpliceE :: LHsExpr RdrName -> HsExpr RdrName
mkHsSpliceE e = HsSpliceE (mkUntypedSplice e)
mkHsSpliceTE :: LHsExpr RdrName -> HsExpr RdrName
mkHsSpliceTE e = HsSpliceE (HsTypedSplice unqualSplice e)
mkHsSpliceTy :: LHsExpr RdrName -> HsType RdrName
mkHsSpliceTy e = HsSpliceTy (HsUntypedSplice unqualSplice e) placeHolderKind
mkHsQuasiQuote :: RdrName -> SrcSpan -> FastString -> HsSplice RdrName
mkHsQuasiQuote quoter span quote = HsQuasiQuote unqualSplice quoter span quote
unqualQuasiQuote :: RdrName
unqualQuasiQuote = mkRdrUnqual (mkVarOccFS (fsLit "quasiquote"))
-- A name (uniquified later) to
-- identify the quasi-quote
mkHsString :: String -> HsLit
mkHsString s = HsString s (mkFastString s)
mkHsStringPrimLit :: FastString -> HsLit
mkHsStringPrimLit fs
= HsStringPrim (unpackFS fs) (fastStringToByteString fs)
-------------
userHsTyVarBndrs :: SrcSpan -> [name] -> [Located (HsTyVarBndr name)]
-- Caller sets location
userHsTyVarBndrs loc bndrs = [ L loc (UserTyVar v) | v <- bndrs ]
{-
************************************************************************
* *
Constructing syntax with no location info
* *
************************************************************************
-}
nlHsVar :: id -> LHsExpr id
nlHsVar n = noLoc (HsVar n)
nlHsLit :: HsLit -> LHsExpr id
nlHsLit n = noLoc (HsLit n)
nlVarPat :: id -> LPat id
nlVarPat n = noLoc (VarPat n)
nlLitPat :: HsLit -> LPat id
nlLitPat l = noLoc (LitPat l)
nlHsApp :: LHsExpr id -> LHsExpr id -> LHsExpr id
nlHsApp f x = noLoc (HsApp f x)
nlHsIntLit :: Integer -> LHsExpr id
nlHsIntLit n = noLoc (HsLit (HsInt (show n) n))
nlHsApps :: id -> [LHsExpr id] -> LHsExpr id
nlHsApps f xs = foldl nlHsApp (nlHsVar f) xs
nlHsVarApps :: id -> [id] -> LHsExpr id
nlHsVarApps f xs = noLoc (foldl mk (HsVar f) (map HsVar xs))
where
mk f a = HsApp (noLoc f) (noLoc a)
nlConVarPat :: RdrName -> [RdrName] -> LPat RdrName
nlConVarPat con vars = nlConPat con (map nlVarPat vars)
nlConVarPatName :: Name -> [Name] -> LPat Name
nlConVarPatName con vars = nlConPatName con (map nlVarPat vars)
nlInfixConPat :: id -> LPat id -> LPat id -> LPat id
nlInfixConPat con l r = noLoc (ConPatIn (noLoc con) (InfixCon l r))
nlConPat :: RdrName -> [LPat RdrName] -> LPat RdrName
nlConPat con pats = noLoc (ConPatIn (noLoc con) (PrefixCon pats))
nlConPatName :: Name -> [LPat Name] -> LPat Name
nlConPatName con pats = noLoc (ConPatIn (noLoc con) (PrefixCon pats))
nlNullaryConPat :: id -> LPat id
nlNullaryConPat con = noLoc (ConPatIn (noLoc con) (PrefixCon []))
nlWildConPat :: DataCon -> LPat RdrName
nlWildConPat con = noLoc (ConPatIn (noLoc (getRdrName con))
(PrefixCon (nOfThem (dataConSourceArity con)
nlWildPat)))
nlWildPat :: LPat RdrName
nlWildPat = noLoc (WildPat placeHolderType ) -- Pre-typechecking
nlWildPatName :: LPat Name
nlWildPatName = noLoc (WildPat placeHolderType ) -- Pre-typechecking
nlWildPatId :: LPat Id
nlWildPatId = noLoc (WildPat placeHolderTypeTc ) -- Post-typechecking
nlHsDo :: HsStmtContext Name -> [LStmt RdrName (LHsExpr RdrName)]
-> LHsExpr RdrName
nlHsDo ctxt stmts = noLoc (mkHsDo ctxt stmts)
nlHsOpApp :: LHsExpr id -> id -> LHsExpr id -> LHsExpr id
nlHsOpApp e1 op e2 = noLoc (mkHsOpApp e1 op e2)
nlHsLam :: LMatch RdrName (LHsExpr RdrName) -> LHsExpr RdrName
nlHsPar :: LHsExpr id -> LHsExpr id
nlHsIf :: LHsExpr id -> LHsExpr id -> LHsExpr id -> LHsExpr id
nlHsCase :: LHsExpr RdrName -> [LMatch RdrName (LHsExpr RdrName)]
-> LHsExpr RdrName
nlList :: [LHsExpr RdrName] -> LHsExpr RdrName
nlHsLam match = noLoc (HsLam (mkMatchGroup Generated [match]))
nlHsPar e = noLoc (HsPar e)
nlHsIf cond true false = noLoc (mkHsIf cond true false)
nlHsCase expr matches = noLoc (HsCase expr (mkMatchGroup Generated matches))
nlList exprs = noLoc (ExplicitList placeHolderType Nothing exprs)
nlHsAppTy :: LHsType name -> LHsType name -> LHsType name
nlHsTyVar :: name -> LHsType name
nlHsFunTy :: LHsType name -> LHsType name -> LHsType name
nlHsAppTy f t = noLoc (HsAppTy f t)
nlHsTyVar x = noLoc (HsTyVar x)
nlHsFunTy a b = noLoc (HsFunTy a b)
nlHsTyConApp :: name -> [LHsType name] -> LHsType name
nlHsTyConApp tycon tys = foldl nlHsAppTy (nlHsTyVar tycon) tys
{-
Tuples. All these functions are *pre-typechecker* because they lack
types on the tuple.
-}
mkLHsTupleExpr :: [LHsExpr a] -> LHsExpr a
-- Makes a pre-typechecker boxed tuple, deals with 1 case
mkLHsTupleExpr [e] = e
mkLHsTupleExpr es = noLoc $ ExplicitTuple (map (noLoc . Present) es) Boxed
mkLHsVarTuple :: [a] -> LHsExpr a
mkLHsVarTuple ids = mkLHsTupleExpr (map nlHsVar ids)
nlTuplePat :: [LPat id] -> Boxity -> LPat id
nlTuplePat pats box = noLoc (TuplePat pats box [])
missingTupArg :: HsTupArg RdrName
missingTupArg = Missing placeHolderType
mkLHsPatTup :: [LPat id] -> LPat id
mkLHsPatTup [] = noLoc $ TuplePat [] Boxed []
mkLHsPatTup [lpat] = lpat
mkLHsPatTup lpats = L (getLoc (head lpats)) $ TuplePat lpats Boxed []
-- The Big equivalents for the source tuple expressions
mkBigLHsVarTup :: [id] -> LHsExpr id
mkBigLHsVarTup ids = mkBigLHsTup (map nlHsVar ids)
mkBigLHsTup :: [LHsExpr id] -> LHsExpr id
mkBigLHsTup = mkChunkified mkLHsTupleExpr
-- The Big equivalents for the source tuple patterns
mkBigLHsVarPatTup :: [id] -> LPat id
mkBigLHsVarPatTup bs = mkBigLHsPatTup (map nlVarPat bs)
mkBigLHsPatTup :: [LPat id] -> LPat id
mkBigLHsPatTup = mkChunkified mkLHsPatTup
-- $big_tuples
-- #big_tuples#
--
-- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but
-- we might concievably want to build such a massive tuple as part of the
-- output of a desugaring stage (notably that for list comprehensions).
--
-- We call tuples above this size \"big tuples\", and emulate them by
-- creating and pattern matching on >nested< tuples that are expressible
-- by GHC.
--
-- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects)
-- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any
-- construction to be big.
--
-- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector'
-- and 'mkTupleCase' functions to do all your work with tuples you should be
-- fine, and not have to worry about the arity limitation at all.
-- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decompositon
mkChunkified :: ([a] -> a) -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE'
-> [a] -- ^ Possible \"big\" list of things to construct from
-> a -- ^ Constructed thing made possible by recursive decomposition
mkChunkified small_tuple as = mk_big_tuple (chunkify as)
where
-- Each sub-list is short enough to fit in a tuple
mk_big_tuple [as] = small_tuple as
mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
chunkify :: [a] -> [[a]]
-- ^ Split a list into lists that are small enough to have a corresponding
-- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE'
-- But there may be more than 'mAX_TUPLE_SIZE' sub-lists
chunkify xs
| n_xs <= mAX_TUPLE_SIZE = [xs]
| otherwise = split xs
where
n_xs = length xs
split [] = []
split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
{-
************************************************************************
* *
Converting a Type to an HsType RdrName
* *
************************************************************************
This is needed to implement GeneralizedNewtypeDeriving.
-}
toHsType :: Type -> LHsType RdrName
toHsType ty
| [] <- tvs_only
, [] <- theta
= to_hs_type tau
| otherwise
= noLoc $
mkExplicitHsForAllTy (map mk_hs_tvb tvs_only)
(noLoc $ map toHsType theta)
(to_hs_type tau)
where
(tvs, theta, tau) = tcSplitSigmaTy ty
tvs_only = filter isTypeVar tvs
to_hs_type (TyVarTy tv) = nlHsTyVar (getRdrName tv)
to_hs_type (AppTy t1 t2) = nlHsAppTy (toHsType t1) (toHsType t2)
to_hs_type (TyConApp tc args) = nlHsTyConApp (getRdrName tc) (map toHsType args')
where
args' = filterOut isKind args
-- Source-language types have _implicit_ kind arguments,
-- so we must remove them here (Trac #8563)
to_hs_type (FunTy arg res) = ASSERT( not (isConstraintKind (typeKind arg)) )
nlHsFunTy (toHsType arg) (toHsType res)
to_hs_type t@(ForAllTy {}) = pprPanic "toHsType" (ppr t)
to_hs_type (LitTy (NumTyLit n)) = noLoc $ HsTyLit (HsNumTy "" n)
to_hs_type (LitTy (StrTyLit s)) = noLoc $ HsTyLit (HsStrTy "" s)
mk_hs_tvb tv = noLoc $ KindedTyVar (noLoc (getRdrName tv))
(toHsKind (tyVarKind tv))
toHsKind :: Kind -> LHsKind RdrName
toHsKind = toHsType
--------- HsWrappers: type args, dict args, casts ---------
mkLHsWrap :: HsWrapper -> LHsExpr id -> LHsExpr id
mkLHsWrap co_fn (L loc e) = L loc (mkHsWrap co_fn e)
mkHsWrap :: HsWrapper -> HsExpr id -> HsExpr id
mkHsWrap co_fn e | isIdHsWrapper co_fn = e
| otherwise = HsWrap co_fn e
mkHsWrapCo :: TcCoercionN -- A Nominal coercion a ~N b
-> HsExpr id -> HsExpr id
mkHsWrapCo co e = mkHsWrap (coToHsWrapper co) e
mkHsWrapCoR :: TcCoercionR -- A Representational coercion a ~R b
-> HsExpr id -> HsExpr id
mkHsWrapCoR co e = mkHsWrap (coToHsWrapperR co) e
mkLHsWrapCo :: TcCoercion -> LHsExpr id -> LHsExpr id
mkLHsWrapCo co (L loc e) = L loc (mkHsWrapCo co e)
mkHsCmdCast :: TcCoercion -> HsCmd id -> HsCmd id
mkHsCmdCast co cmd | isTcReflCo co = cmd
| otherwise = HsCmdCast co cmd
coToHsWrapper :: TcCoercion -> HsWrapper -- A Nominal coercion
coToHsWrapper co | isTcReflCo co = idHsWrapper
| otherwise = mkWpCast (mkTcSubCo co)
coToHsWrapperR :: TcCoercion -> HsWrapper -- A Representational coercion
coToHsWrapperR co | isTcReflCo co = idHsWrapper
| otherwise = mkWpCast co
mkHsWrapPat :: HsWrapper -> Pat id -> Type -> Pat id
mkHsWrapPat co_fn p ty | isIdHsWrapper co_fn = p
| otherwise = CoPat co_fn p ty
-- input coercion is Nominal
mkHsWrapPatCo :: TcCoercion -> Pat id -> Type -> Pat id
mkHsWrapPatCo co pat ty | isTcReflCo co = pat
| otherwise = CoPat (mkWpCast (mkTcSubCo co)) pat ty
mkHsDictLet :: TcEvBinds -> LHsExpr Id -> LHsExpr Id
mkHsDictLet ev_binds expr = mkLHsWrap (mkWpLet ev_binds) expr
{-
l
************************************************************************
* *
Bindings; with a location at the top
* *
************************************************************************
-}
mkFunBind :: Located RdrName -> [LMatch RdrName (LHsExpr RdrName)]
-> HsBind RdrName
-- Not infix, with place holders for coercion and free vars
mkFunBind fn ms = FunBind { fun_id = fn
, fun_matches = mkMatchGroup Generated ms
, fun_co_fn = idHsWrapper
, bind_fvs = placeHolderNames
, fun_tick = [] }
mkTopFunBind :: Origin -> Located Name -> [LMatch Name (LHsExpr Name)]
-> HsBind Name
-- In Name-land, with empty bind_fvs
mkTopFunBind origin fn ms = FunBind { fun_id = fn
, fun_matches = mkMatchGroupName origin ms
, fun_co_fn = idHsWrapper
, bind_fvs = emptyNameSet -- NB: closed
-- binding
, fun_tick = [] }
mkHsVarBind :: SrcSpan -> RdrName -> LHsExpr RdrName -> LHsBind RdrName
mkHsVarBind loc var rhs = mk_easy_FunBind loc var [] rhs
mkVarBind :: id -> LHsExpr id -> LHsBind id
mkVarBind var rhs = L (getLoc rhs) $
VarBind { var_id = var, var_rhs = rhs, var_inline = False }
mkPatSynBind :: Located RdrName -> HsPatSynDetails (Located RdrName)
-> LPat RdrName -> HsPatSynDir RdrName -> HsBind RdrName
mkPatSynBind name details lpat dir = PatSynBind psb
where
psb = PSB{ psb_id = name
, psb_args = details
, psb_def = lpat
, psb_dir = dir
, psb_fvs = placeHolderNames }
-- |If any of the matches in the 'FunBind' are infix, the 'FunBind' is
-- considered infix.
isInfixFunBind :: HsBindLR id1 id2 -> Bool
isInfixFunBind (FunBind _ (MG matches _ _ _) _ _ _)
= any (isInfixMatch . unLoc) (unLoc matches)
isInfixFunBind _ = False
------------
mk_easy_FunBind :: SrcSpan -> RdrName -> [LPat RdrName]
-> LHsExpr RdrName -> LHsBind RdrName
mk_easy_FunBind loc fun pats expr
= L loc $ mkFunBind (L loc fun) [mkMatch pats expr (noLoc emptyLocalBinds)]
------------
mkMatch :: [LPat id] -> LHsExpr id -> Located (HsLocalBinds id)
-> LMatch id (LHsExpr id)
mkMatch pats expr lbinds
= noLoc (Match NonFunBindMatch (map paren pats) Nothing
(GRHSs (unguardedRHS noSrcSpan expr) lbinds))
where
paren lp@(L l p) | hsPatNeedsParens p = L l (ParPat lp)
| otherwise = lp
{-
************************************************************************
* *
Collecting binders
* *
************************************************************************
Get all the binders in some HsBindGroups, IN THE ORDER OF APPEARANCE. eg.
...
where
(x, y) = ...
f i j = ...
[a, b] = ...
it should return [x, y, f, a, b] (remember, order important).
Note [Collect binders only after renaming]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
These functions should only be used on HsSyn *after* the renamer,
to return a [Name] or [Id]. Before renaming the record punning
and wild-card mechanism makes it hard to know what is bound.
So these functions should not be applied to (HsSyn RdrName)
-}
----------------- Bindings --------------------------
collectLocalBinders :: HsLocalBindsLR idL idR -> [idL]
collectLocalBinders (HsValBinds binds) = collectHsIdBinders binds
-- No pattern synonyms here
collectLocalBinders (HsIPBinds _) = []
collectLocalBinders EmptyLocalBinds = []
collectHsIdBinders, collectHsValBinders :: HsValBindsLR idL idR -> [idL]
-- Collect Id binders only, or Ids + pattern synonmys, respectively
collectHsIdBinders = collect_hs_val_binders True
collectHsValBinders = collect_hs_val_binders False
collectHsBindBinders :: HsBindLR idL idR -> [idL]
-- Collect both Ids and pattern-synonym binders
collectHsBindBinders b = collect_bind False b []
collectHsBindsBinders :: LHsBindsLR idL idR -> [idL]
collectHsBindsBinders binds = collect_binds False binds []
collectHsBindListBinders :: [LHsBindLR idL idR] -> [idL]
-- Same as collectHsBindsBinders, but works over a list of bindings
collectHsBindListBinders = foldr (collect_bind False . unLoc) []
collect_hs_val_binders :: Bool -> HsValBindsLR idL idR -> [idL]
collect_hs_val_binders ps (ValBindsIn binds _) = collect_binds ps binds []
collect_hs_val_binders ps (ValBindsOut binds _) = collect_out_binds ps binds
collect_out_binds :: Bool -> [(RecFlag, LHsBinds id)] -> [id]
collect_out_binds ps = foldr (collect_binds ps . snd) []
collect_binds :: Bool -> LHsBindsLR idL idR -> [idL] -> [idL]
-- Collect Ids, or Ids + patter synonyms, depending on boolean flag
collect_binds ps binds acc = foldrBag (collect_bind ps . unLoc) acc binds
collect_bind :: Bool -> HsBindLR idL idR -> [idL] -> [idL]
collect_bind _ (PatBind { pat_lhs = p }) acc = collect_lpat p acc
collect_bind _ (FunBind { fun_id = L _ f }) acc = f : acc
collect_bind _ (VarBind { var_id = f }) acc = f : acc
collect_bind _ (AbsBinds { abs_exports = dbinds }) acc = map abe_poly dbinds ++ acc
-- I don't think we want the binders from the abe_binds
-- The only time we collect binders from a typechecked
-- binding (hence see AbsBinds) is in zonking in TcHsSyn
collect_bind omitPatSyn (PatSynBind (PSB { psb_id = L _ ps })) acc =
if omitPatSyn then acc else ps : acc
collectMethodBinders :: LHsBindsLR RdrName idR -> [Located RdrName]
-- Used exclusively for the bindings of an instance decl which are all FunBinds
collectMethodBinders binds = foldrBag (get . unLoc) [] binds
where
get (FunBind { fun_id = f }) fs = f : fs
get _ fs = fs
-- Someone else complains about non-FunBinds
----------------- Statements --------------------------
collectLStmtsBinders :: [LStmtLR idL idR body] -> [idL]
collectLStmtsBinders = concatMap collectLStmtBinders
collectStmtsBinders :: [StmtLR idL idR body] -> [idL]
collectStmtsBinders = concatMap collectStmtBinders
collectLStmtBinders :: LStmtLR idL idR body -> [idL]
collectLStmtBinders = collectStmtBinders . unLoc
collectStmtBinders :: StmtLR idL idR body -> [idL]
-- Id Binders for a Stmt... [but what about pattern-sig type vars]?
collectStmtBinders (BindStmt pat _ _ _) = collectPatBinders pat
collectStmtBinders (LetStmt (L _ binds)) = collectLocalBinders binds
collectStmtBinders (BodyStmt {}) = []
collectStmtBinders (LastStmt {}) = []
collectStmtBinders (ParStmt xs _ _) = collectLStmtsBinders
$ [s | ParStmtBlock ss _ _ <- xs, s <- ss]
collectStmtBinders (TransStmt { trS_stmts = stmts }) = collectLStmtsBinders stmts
collectStmtBinders (RecStmt { recS_stmts = ss }) = collectLStmtsBinders ss
collectStmtBinders ApplicativeStmt{} = []
----------------- Patterns --------------------------
collectPatBinders :: LPat a -> [a]
collectPatBinders pat = collect_lpat pat []
collectPatsBinders :: [LPat a] -> [a]
collectPatsBinders pats = foldr collect_lpat [] pats
-------------
collect_lpat :: LPat name -> [name] -> [name]
collect_lpat (L _ pat) bndrs
= go pat
where
go (VarPat var) = var : bndrs
go (WildPat _) = bndrs
go (LazyPat pat) = collect_lpat pat bndrs
go (BangPat pat) = collect_lpat pat bndrs
go (AsPat (L _ a) pat) = a : collect_lpat pat bndrs
go (ViewPat _ pat _) = collect_lpat pat bndrs
go (ParPat pat) = collect_lpat pat bndrs
go (ListPat pats _ _) = foldr collect_lpat bndrs pats
go (PArrPat pats _) = foldr collect_lpat bndrs pats
go (TuplePat pats _ _) = foldr collect_lpat bndrs pats
go (ConPatIn _ ps) = foldr collect_lpat bndrs (hsConPatArgs ps)
go (ConPatOut {pat_args=ps}) = foldr collect_lpat bndrs (hsConPatArgs ps)
-- See Note [Dictionary binders in ConPatOut]
go (LitPat _) = bndrs
go (NPat _ _ _) = bndrs
go (NPlusKPat (L _ n) _ _ _) = n : bndrs
go (SigPatIn pat _) = collect_lpat pat bndrs
go (SigPatOut pat _) = collect_lpat pat bndrs
go (SplicePat _) = bndrs
go (CoPat _ pat _) = go pat
{-
Note [Dictionary binders in ConPatOut] See also same Note in DsArrows
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Do *not* gather (a) dictionary and (b) dictionary bindings as binders
of a ConPatOut pattern. For most calls it doesn't matter, because
it's pre-typechecker and there are no ConPatOuts. But it does matter
more in the desugarer; for example, DsUtils.mkSelectorBinds uses
collectPatBinders. In a lazy pattern, for example f ~(C x y) = ...,
we want to generate bindings for x,y but not for dictionaries bound by
C. (The type checker ensures they would not be used.)
Desugaring of arrow case expressions needs these bindings (see DsArrows
and arrowcase1), but SPJ (Jan 2007) says it's safer for it to use its
own pat-binder-collector:
Here's the problem. Consider
data T a where
C :: Num a => a -> Int -> T a
f ~(C (n+1) m) = (n,m)
Here, the pattern (C (n+1)) binds a hidden dictionary (d::Num a),
and *also* uses that dictionary to match the (n+1) pattern. Yet, the
variables bound by the lazy pattern are n,m, *not* the dictionary d.
So in mkSelectorBinds in DsUtils, we want just m,n as the variables bound.
-}
hsGroupBinders :: HsGroup Name -> [Name]
hsGroupBinders (HsGroup { hs_valds = val_decls, hs_tyclds = tycl_decls,
hs_instds = inst_decls, hs_fords = foreign_decls })
= collectHsValBinders val_decls
++ hsTyClForeignBinders tycl_decls inst_decls foreign_decls
hsTyClForeignBinders :: [TyClGroup Name] -> [LInstDecl Name]
-> [LForeignDecl Name] -> [Name]
-- We need to look at instance declarations too,
-- because their associated types may bind data constructors
hsTyClForeignBinders tycl_decls inst_decls foreign_decls
= map unLoc (hsForeignDeclsBinders foreign_decls)
++ getSelectorNames (foldMap (foldMap hsLTyClDeclBinders . group_tyclds) tycl_decls
`mappend` foldMap hsLInstDeclBinders inst_decls)
where
getSelectorNames :: ([Located Name], [LFieldOcc Name]) -> [Name]
getSelectorNames (ns, fs) = map unLoc ns ++ map (selectorFieldOcc.unLoc) fs
-------------------
hsLTyClDeclBinders :: Located (TyClDecl name) -> ([Located name], [LFieldOcc name])
-- ^ Returns all the /binding/ names of the decl. The first one is
-- guaranteed to be the name of the decl. The first component
-- represents all binding names except record fields; the second
-- represents field occurrences. For record fields mentioned in
-- multiple constructors, the SrcLoc will be from the first occurrence.
--
-- Each returned (Located name) has a SrcSpan for the /whole/ declaration.
-- See Note [SrcSpan for binders]
hsLTyClDeclBinders (L loc (FamDecl { tcdFam = FamilyDecl { fdLName = L _ name } }))
= ([L loc name], [])
hsLTyClDeclBinders (L loc (SynDecl { tcdLName = L _ name })) = ([L loc name], [])
hsLTyClDeclBinders (L loc (ClassDecl { tcdLName = L _ cls_name
, tcdSigs = sigs, tcdATs = ats }))
= (L loc cls_name :
[ L fam_loc fam_name | L fam_loc (FamilyDecl { fdLName = L _ fam_name }) <- ats ] ++
[ L mem_loc mem_name | L mem_loc (TypeSig ns _ _) <- sigs, L _ mem_name <- ns ]
, [])
hsLTyClDeclBinders (L loc (DataDecl { tcdLName = L _ name, tcdDataDefn = defn }))
= (\ (xs, ys) -> (L loc name : xs, ys)) $ hsDataDefnBinders defn
-------------------
hsForeignDeclsBinders :: [LForeignDecl name] -> [Located name]
-- See Note [SrcSpan for binders]
hsForeignDeclsBinders foreign_decls
= [ L decl_loc n
| L decl_loc (ForeignImport (L _ n) _ _ _) <- foreign_decls]
-------------------
hsPatSynBinders :: HsValBinds RdrName
-> ([Located RdrName], [Located RdrName])
-- Collect pattern-synonym binders only, not Ids
-- See Note [SrcSpan for binders]
hsPatSynBinders (ValBindsIn binds _) = foldrBag addPatSynBndr ([],[]) binds
hsPatSynBinders _ = panic "hsPatSynBinders"
addPatSynBndr :: LHsBindLR id id -> ([Located id], [Located id])
-> ([Located id], [Located id]) -- (selectors, other)
-- See Note [SrcSpan for binders]
addPatSynBndr bind (sels, pss)
| L bind_loc (PatSynBind (PSB { psb_id = L _ n
, psb_args = RecordPatSyn as })) <- bind
= (map recordPatSynSelectorId as ++ sels, L bind_loc n : pss)
| L bind_loc (PatSynBind (PSB { psb_id = L _ n})) <- bind
= (sels, L bind_loc n : pss)
| otherwise
= (sels, pss)
-------------------
hsLInstDeclBinders :: LInstDecl name -> ([Located name], [LFieldOcc name])
hsLInstDeclBinders (L _ (ClsInstD { cid_inst = ClsInstDecl { cid_datafam_insts = dfis } }))
= foldMap (hsDataFamInstBinders . unLoc) dfis
hsLInstDeclBinders (L _ (DataFamInstD { dfid_inst = fi }))
= hsDataFamInstBinders fi
hsLInstDeclBinders (L _ (TyFamInstD {})) = mempty
-------------------
-- the SrcLoc returned are for the whole declarations, not just the names
hsDataFamInstBinders :: DataFamInstDecl name -> ([Located name], [LFieldOcc name])
hsDataFamInstBinders (DataFamInstDecl { dfid_defn = defn })
= hsDataDefnBinders defn
-- There can't be repeated symbols because only data instances have binders
-------------------
-- the SrcLoc returned are for the whole declarations, not just the names
hsDataDefnBinders :: HsDataDefn name -> ([Located name], [LFieldOcc name])
hsDataDefnBinders (HsDataDefn { dd_cons = cons })
= hsConDeclsBinders cons
-- See Note [Binders in family instances]
-------------------
hsConDeclsBinders :: [LConDecl name] -> ([Located name], [LFieldOcc name])
-- See hsLTyClDeclBinders for what this does
-- The function is boringly complicated because of the records
-- And since we only have equality, we have to be a little careful
hsConDeclsBinders cons = go id cons
where go :: ([LFieldOcc name] -> [LFieldOcc name])
-> [LConDecl name] -> ([Located name], [LFieldOcc name])
go _ [] = ([], [])
go remSeen (r:rs) =
-- don't re-mangle the location of field names, because we don't
-- have a record of the full location of the field declaration anyway
case r of
-- remove only the first occurrence of any seen field in order to
-- avoid circumventing detection of duplicate fields (#9156)
L loc (ConDecl { con_names = names, con_details = RecCon flds }) ->
(map (L loc . unLoc) names ++ ns, r' ++ fs)
where r' = remSeen (concatMap (cd_fld_names . unLoc)
(unLoc flds))
remSeen' = foldr (.) remSeen [deleteBy ((==) `on` rdrNameFieldOcc . unLoc) v | v <- r']
(ns, fs) = go remSeen' rs
L loc (ConDecl { con_names = names }) ->
(map (L loc . unLoc) names ++ ns, fs)
where (ns, fs) = go remSeen rs
{-
Note [SrcSpan for binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~
When extracting the (Located RdrNme) for a binder, at least for the
main name (the TyCon of a type declaration etc), we want to give it
the @SrcSpan@ of the whole /declaration/, not just the name itself
(which is how it appears in the syntax tree). This SrcSpan (for the
entire declaration) is used as the SrcSpan for the Name that is
finally produced, and hence for error messages. (See Trac #8607.)
Note [Binders in family instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a type or data family instance declaration, the type
constructor is an *occurrence* not a binding site
type instance T Int = Int -> Int -- No binders
data instance S Bool = S1 | S2 -- Binders are S1,S2
************************************************************************
* *
Collecting binders the user did not write
* *
************************************************************************
The job of this family of functions is to run through binding sites and find the set of all Names
that were defined "implicitly", without being explicitly written by the user.
The main purpose is to find names introduced by record wildcards so that we can avoid
warning the user when they don't use those names (#4404)
-}
lStmtsImplicits :: [LStmtLR Name idR (Located (body idR))] -> NameSet
lStmtsImplicits = hs_lstmts
where
hs_lstmts :: [LStmtLR Name idR (Located (body idR))] -> NameSet
hs_lstmts = foldr (\stmt rest -> unionNameSet (hs_stmt (unLoc stmt)) rest) emptyNameSet
hs_stmt :: StmtLR Name idR (Located (body idR)) -> NameSet
hs_stmt (BindStmt pat _ _ _) = lPatImplicits pat
hs_stmt (ApplicativeStmt args _ _) = unionNameSets (map do_arg args)
where do_arg (_, ApplicativeArgOne pat _) = lPatImplicits pat
do_arg (_, ApplicativeArgMany stmts _ _) = hs_lstmts stmts
hs_stmt (LetStmt binds) = hs_local_binds (unLoc binds)
hs_stmt (BodyStmt {}) = emptyNameSet
hs_stmt (LastStmt {}) = emptyNameSet
hs_stmt (ParStmt xs _ _) = hs_lstmts [s | ParStmtBlock ss _ _ <- xs, s <- ss]
hs_stmt (TransStmt { trS_stmts = stmts }) = hs_lstmts stmts
hs_stmt (RecStmt { recS_stmts = ss }) = hs_lstmts ss
hs_local_binds (HsValBinds val_binds) = hsValBindsImplicits val_binds
hs_local_binds (HsIPBinds _) = emptyNameSet
hs_local_binds EmptyLocalBinds = emptyNameSet
hsValBindsImplicits :: HsValBindsLR Name idR -> NameSet
hsValBindsImplicits (ValBindsOut binds _)
= foldr (unionNameSet . lhsBindsImplicits . snd) emptyNameSet binds
hsValBindsImplicits (ValBindsIn binds _)
= lhsBindsImplicits binds
lhsBindsImplicits :: LHsBindsLR Name idR -> NameSet
lhsBindsImplicits = foldBag unionNameSet (lhs_bind . unLoc) emptyNameSet
where
lhs_bind (PatBind { pat_lhs = lpat }) = lPatImplicits lpat
lhs_bind _ = emptyNameSet
lPatImplicits :: LPat Name -> NameSet
lPatImplicits = hs_lpat
where
hs_lpat (L _ pat) = hs_pat pat
hs_lpats = foldr (\pat rest -> hs_lpat pat `unionNameSet` rest) emptyNameSet
hs_pat (LazyPat pat) = hs_lpat pat
hs_pat (BangPat pat) = hs_lpat pat
hs_pat (AsPat _ pat) = hs_lpat pat
hs_pat (ViewPat _ pat _) = hs_lpat pat
hs_pat (ParPat pat) = hs_lpat pat
hs_pat (ListPat pats _ _) = hs_lpats pats
hs_pat (PArrPat pats _) = hs_lpats pats
hs_pat (TuplePat pats _ _) = hs_lpats pats
hs_pat (SigPatIn pat _) = hs_lpat pat
hs_pat (SigPatOut pat _) = hs_lpat pat
hs_pat (CoPat _ pat _) = hs_pat pat
hs_pat (ConPatIn _ ps) = details ps
hs_pat (ConPatOut {pat_args=ps}) = details ps
hs_pat _ = emptyNameSet
details (PrefixCon ps) = hs_lpats ps
details (RecCon fs) = hs_lpats explicit `unionNameSet` mkNameSet (collectPatsBinders implicit)
where (explicit, implicit) = partitionEithers [if pat_explicit then Left pat else Right pat
| (i, fld) <- [0..] `zip` rec_flds fs
, let pat = hsRecFieldArg
(unLoc fld)
pat_explicit = maybe True (i<) (rec_dotdot fs)]
details (InfixCon p1 p2) = hs_lpat p1 `unionNameSet` hs_lpat p2
| elieux/ghc | compiler/hsSyn/HsUtils.hs | bsd-3-clause | 42,713 | 0 | 17 | 10,655 | 11,006 | 5,670 | 5,336 | -1 | -1 |
module InnerEar.Widgets.UserList where
import Reflex
import Reflex.Dom
import Data.Maybe
import Data.Map
import InnerEar.Types.Request
import InnerEar.Types.Response
import InnerEar.Types.User
import InnerEar.Types.Handle
import InnerEar.Widgets.Utility
userListWidget :: MonadWidget t m
=> Event t [Response] -> Dynamic t (Maybe Role) -> m (Event t Request,Event t (Maybe Handle))
userListWidget responses currentRole = elClass "div" "excerciseWrapper" $ do
-- after the widget is built it requests info on all users from the server, but only if role is Administrator
postBuild <- getPostBuild
isAdministrator <- mapDyn (== (Just Administrator)) currentRole
let getUserList = GetUserList <$ gate (current isAdministrator) postBuild
-- select any and all server responses that are UserData to display a clickable map of all users
let userEvents = fmap (catMaybes . fmap responseToUser) responses
userMap <- foldDyn (\xs m -> Prelude.foldl (\m' (h,u) -> insert h u m') m xs) Data.Map.empty userEvents
userList <- mapDyn elems userMap
userNavs <- simpleList userList $ \u -> do
userHandle <- mapDyn handle u
userRole <- mapDyn (show . role) u
divClass "navButton" $ do
dynText userHandle
text " ("
dynText userRole
text ") "
(fmap Just . tagDyn userHandle) <$> button "UserPage"
userNavs' <- mapDyn leftmost userNavs
let userNavs'' = switchPromptlyDyn userNavs'
-- widget asks to be closed when back button is pressed, or anytime role is not Administrator
backButton <- (Nothing <$) <$> button "Back"
let notAdminPostBuild = (Nothing <$) $ ffilter (/= (Just Administrator)) $ tagDyn currentRole postBuild
let notAdminLater = (Nothing <$) $ ffilter (/= (Just Administrator)) $ updated currentRole
let nav = leftmost [userNavs'',backButton,notAdminPostBuild,notAdminLater]
return (getUserList,nav)
responseToUser :: Response -> Maybe (String,User)
responseToUser (UserData x@(User h _ _)) = Just (h,x)
responseToUser _ = Nothing
| luisnavarrodelangel/InnerEar | src/InnerEar/Widgets/UserList.hs | gpl-3.0 | 2,011 | 0 | 19 | 357 | 614 | 307 | 307 | 38 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.RDS.CopyOptionGroup
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- 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 <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Copies the specified option group.
--
-- <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CopyOptionGroup.html>
module Network.AWS.RDS.CopyOptionGroup
(
-- * Request
CopyOptionGroup
-- ** Request constructor
, copyOptionGroup
-- ** Request lenses
, cog1SourceOptionGroupIdentifier
, cog1Tags
, cog1TargetOptionGroupDescription
, cog1TargetOptionGroupIdentifier
-- * Response
, CopyOptionGroupResponse
-- ** Response constructor
, copyOptionGroupResponse
-- ** Response lenses
, cogrOptionGroup
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.RDS.Types
import qualified GHC.Exts
data CopyOptionGroup = CopyOptionGroup
{ _cog1SourceOptionGroupIdentifier :: Text
, _cog1Tags :: List "member" Tag
, _cog1TargetOptionGroupDescription :: Text
, _cog1TargetOptionGroupIdentifier :: Text
} deriving (Eq, Read, Show)
-- | 'CopyOptionGroup' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cog1SourceOptionGroupIdentifier' @::@ 'Text'
--
-- * 'cog1Tags' @::@ ['Tag']
--
-- * 'cog1TargetOptionGroupDescription' @::@ 'Text'
--
-- * 'cog1TargetOptionGroupIdentifier' @::@ 'Text'
--
copyOptionGroup :: Text -- ^ 'cog1SourceOptionGroupIdentifier'
-> Text -- ^ 'cog1TargetOptionGroupIdentifier'
-> Text -- ^ 'cog1TargetOptionGroupDescription'
-> CopyOptionGroup
copyOptionGroup p1 p2 p3 = CopyOptionGroup
{ _cog1SourceOptionGroupIdentifier = p1
, _cog1TargetOptionGroupIdentifier = p2
, _cog1TargetOptionGroupDescription = p3
, _cog1Tags = mempty
}
-- | The identifier or ARN for the source option group.
--
-- Constraints:
--
-- Must specify a valid option group. If the source option group is in the
-- same region as the copy, specify a valid option group identifier, for example 'my-option-group', or a valid ARN. If the source option group is in a different
-- region than the copy, specify a valid option group ARN, for example 'arn:aws:rds:us-west-2:123456789012:og:special-options'.
cog1SourceOptionGroupIdentifier :: Lens' CopyOptionGroup Text
cog1SourceOptionGroupIdentifier =
lens _cog1SourceOptionGroupIdentifier
(\s a -> s { _cog1SourceOptionGroupIdentifier = a })
cog1Tags :: Lens' CopyOptionGroup [Tag]
cog1Tags = lens _cog1Tags (\s a -> s { _cog1Tags = a }) . _List
-- | The description for the copied option group.
cog1TargetOptionGroupDescription :: Lens' CopyOptionGroup Text
cog1TargetOptionGroupDescription =
lens _cog1TargetOptionGroupDescription
(\s a -> s { _cog1TargetOptionGroupDescription = a })
-- | The identifier for the copied option group.
--
-- Constraints:
--
-- Cannot be null, empty, or blank Must contain from 1 to 255 alphanumeric
-- characters or hyphens First character must be a letter Cannot end with a
-- hyphen or contain two consecutive hyphens Example: 'my-option-group'
cog1TargetOptionGroupIdentifier :: Lens' CopyOptionGroup Text
cog1TargetOptionGroupIdentifier =
lens _cog1TargetOptionGroupIdentifier
(\s a -> s { _cog1TargetOptionGroupIdentifier = a })
newtype CopyOptionGroupResponse = CopyOptionGroupResponse
{ _cogrOptionGroup :: Maybe OptionGroup
} deriving (Eq, Read, Show)
-- | 'CopyOptionGroupResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cogrOptionGroup' @::@ 'Maybe' 'OptionGroup'
--
copyOptionGroupResponse :: CopyOptionGroupResponse
copyOptionGroupResponse = CopyOptionGroupResponse
{ _cogrOptionGroup = Nothing
}
cogrOptionGroup :: Lens' CopyOptionGroupResponse (Maybe OptionGroup)
cogrOptionGroup = lens _cogrOptionGroup (\s a -> s { _cogrOptionGroup = a })
instance ToPath CopyOptionGroup where
toPath = const "/"
instance ToQuery CopyOptionGroup where
toQuery CopyOptionGroup{..} = mconcat
[ "SourceOptionGroupIdentifier" =? _cog1SourceOptionGroupIdentifier
, "Tags" =? _cog1Tags
, "TargetOptionGroupDescription" =? _cog1TargetOptionGroupDescription
, "TargetOptionGroupIdentifier" =? _cog1TargetOptionGroupIdentifier
]
instance ToHeaders CopyOptionGroup
instance AWSRequest CopyOptionGroup where
type Sv CopyOptionGroup = RDS
type Rs CopyOptionGroup = CopyOptionGroupResponse
request = post "CopyOptionGroup"
response = xmlResponse
instance FromXML CopyOptionGroupResponse where
parseXML = withElement "CopyOptionGroupResult" $ \x -> CopyOptionGroupResponse
<$> x .@? "OptionGroup"
| romanb/amazonka | amazonka-rds/gen/Network/AWS/RDS/CopyOptionGroup.hs | mpl-2.0 | 5,688 | 0 | 10 | 1,181 | 637 | 390 | 247 | 79 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.IAM.DeleteGroupPolicy
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- 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 <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes the specified inline policy that is embedded in the specified group.
--
-- A group can also have managed policies attached to it. To detach a managed
-- policy from a group, use 'DetachGroupPolicy'. For more information about
-- policies, refer to <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies> in the /Using IAM/
-- guide.
--
-- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteGroupPolicy.html>
module Network.AWS.IAM.DeleteGroupPolicy
(
-- * Request
DeleteGroupPolicy
-- ** Request constructor
, deleteGroupPolicy
-- ** Request lenses
, dgp1GroupName
, dgp1PolicyName
-- * Response
, DeleteGroupPolicyResponse
-- ** Response constructor
, deleteGroupPolicyResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.IAM.Types
import qualified GHC.Exts
data DeleteGroupPolicy = DeleteGroupPolicy
{ _dgp1GroupName :: Text
, _dgp1PolicyName :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'DeleteGroupPolicy' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dgp1GroupName' @::@ 'Text'
--
-- * 'dgp1PolicyName' @::@ 'Text'
--
deleteGroupPolicy :: Text -- ^ 'dgp1GroupName'
-> Text -- ^ 'dgp1PolicyName'
-> DeleteGroupPolicy
deleteGroupPolicy p1 p2 = DeleteGroupPolicy
{ _dgp1GroupName = p1
, _dgp1PolicyName = p2
}
-- | The name (friendly name, not ARN) identifying the group that the policy is
-- embedded in.
dgp1GroupName :: Lens' DeleteGroupPolicy Text
dgp1GroupName = lens _dgp1GroupName (\s a -> s { _dgp1GroupName = a })
-- | The name identifying the policy document to delete.
dgp1PolicyName :: Lens' DeleteGroupPolicy Text
dgp1PolicyName = lens _dgp1PolicyName (\s a -> s { _dgp1PolicyName = a })
data DeleteGroupPolicyResponse = DeleteGroupPolicyResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeleteGroupPolicyResponse' constructor.
deleteGroupPolicyResponse :: DeleteGroupPolicyResponse
deleteGroupPolicyResponse = DeleteGroupPolicyResponse
instance ToPath DeleteGroupPolicy where
toPath = const "/"
instance ToQuery DeleteGroupPolicy where
toQuery DeleteGroupPolicy{..} = mconcat
[ "GroupName" =? _dgp1GroupName
, "PolicyName" =? _dgp1PolicyName
]
instance ToHeaders DeleteGroupPolicy
instance AWSRequest DeleteGroupPolicy where
type Sv DeleteGroupPolicy = IAM
type Rs DeleteGroupPolicy = DeleteGroupPolicyResponse
request = post "DeleteGroupPolicy"
response = nullResponse DeleteGroupPolicyResponse
| romanb/amazonka | amazonka-iam/gen/Network/AWS/IAM/DeleteGroupPolicy.hs | mpl-2.0 | 3,703 | 0 | 9 | 777 | 399 | 246 | 153 | 52 | 1 |
listPrinters =
[(''[]
,\(typeVariable:_) _automaticPrinter ->
(let presentVar = varE (presentVarName typeVariable)
in lamE [varP (presentVarName typeVariable)]
[|(let typeString = "[" ++ fst $(presentVar) ++ "]"
in (typeString
,\xs ->
case fst $(presentVar) of
"GHC.Types.Char" ->
ChoicePresentation
"String"
[("String",undefined)
,("List of characters",undefined)]
_ ->
ListPresentation typeString
(map (snd $(presentVar)) xs)))|]))]
| lunaris/hindent | benchmarks/BigDeclarations.hs | bsd-3-clause | 774 | 0 | 15 | 389 | 76 | 41 | 35 | -1 | -1 |
{-# language DeriveDataTypeable #-}
module Base.Language where
import Data.Data
-- | Versioned language identifiers
data Language
= English | German
deriving (Show, Read, Typeable, Data)
| nikki-and-the-robots/nikki | src/Base/Language.hs | lgpl-3.0 | 198 | 0 | 6 | 36 | 42 | 25 | 17 | 6 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Database.Persist.Sql.Orphan.PersistUnique () where
import Control.Exception (throwIO)
import Control.Monad.IO.Class (liftIO)
import Database.Persist
import Database.Persist.Sql.Types
import Database.Persist.Sql.Raw
import Database.Persist.Sql.Orphan.PersistStore (withRawQuery)
import Database.Persist.Sql.Util (dbColumns, parseEntityValues)
import qualified Data.Text as T
import Data.Monoid (mappend)
import qualified Data.Conduit.List as CL
import Control.Monad.Trans.Reader (ask)
instance PersistUnique SqlBackend where
deleteBy uniq = do
conn <- ask
let sql' = sql conn
vals = persistUniqueToValues uniq
rawExecute sql' vals
where
t = entityDef $ dummyFromUnique uniq
go = map snd . persistUniqueToFieldNames
go' conn x = connEscapeName conn x `mappend` "=?"
sql conn = T.concat
[ "DELETE FROM "
, connEscapeName conn $ entityDB t
, " WHERE "
, T.intercalate " AND " $ map (go' conn) $ go uniq
]
getBy uniq = do
conn <- ask
let sql = T.concat
[ "SELECT "
, T.intercalate "," $ dbColumns conn t
, " FROM "
, connEscapeName conn $ entityDB t
, " WHERE "
, sqlClause conn
]
uvals = persistUniqueToValues uniq
withRawQuery sql uvals $ do
row <- CL.head
case row of
Nothing -> return Nothing
Just [] -> error "getBy: empty row"
Just vals -> case parseEntityValues t vals of
Left err -> liftIO $ throwIO $ PersistMarshalError err
Right r -> return $ Just r
where
sqlClause conn =
T.intercalate " AND " $ map (go conn) $ toFieldNames' uniq
go conn x = connEscapeName conn x `mappend` "=?"
t = entityDef $ dummyFromUnique uniq
toFieldNames' = map snd . persistUniqueToFieldNames
dummyFromUnique :: Unique v -> Maybe v
dummyFromUnique _ = Nothing
| jasonzoladz/persistent | persistent/Database/Persist/Sql/Orphan/PersistUnique.hs | mit | 2,179 | 0 | 18 | 715 | 570 | 296 | 274 | 53 | 1 |
{-# LANGUAGE CPP #-}
#ifndef MIN_VERSION_binary
#define MIN_VERSION_binary(x, y, z) 0
#endif
module Distribution.Compat.Binary
( decodeOrFailIO
#if __GLASGOW_HASKELL__ >= 708 || MIN_VERSION_binary(0,7,0)
, module Data.Binary
#else
, Binary(..)
, decode, encode
#endif
) where
import Control.Exception (ErrorCall(..), catch, evaluate)
import Data.ByteString.Lazy (ByteString)
#if __GLASGOW_HASKELL__ < 706
import Prelude hiding (catch)
#endif
#if __GLASGOW_HASKELL__ >= 708 || MIN_VERSION_binary(0,7,0)
import Data.Binary
#else
import Data.Binary.Get
import Data.Binary.Put
import Distribution.Compat.Binary.Class
import Distribution.Compat.Binary.Generic ()
-- | Decode a value from a lazy ByteString, reconstructing the original structure.
--
decode :: Binary a => ByteString -> a
decode = runGet get
-- | Encode a value using binary serialisation to a lazy ByteString.
--
encode :: Binary a => a -> ByteString
encode = runPut . put
{-# INLINE encode #-}
#endif
decodeOrFailIO :: Binary a => ByteString -> IO (Either String a)
decodeOrFailIO bs =
catch (evaluate (decode bs) >>= return . Right)
$ \(ErrorCall str) -> return $ Left str
| DavidAlphaFox/ghc | libraries/Cabal/Cabal/Distribution/Compat/Binary.hs | bsd-3-clause | 1,188 | 0 | 12 | 208 | 155 | 92 | 63 | 21 | 1 |
module Thread (threadTesting1) where
import Control.Concurrent
import Control.Concurrent.MVar
import Stream
import Converter
threadTesting1 :: Gray -> Gray -> IO Int
threadTesting1 xs ys = do
m <- newEmptyMVar
c1 <- forkIO (t1 m xs ys)
c2 <- forkIO (t2 m xs ys)
c3 <- forkIO (t3 m xs ys)
c4 <- forkIO (t4 m xs ys)
c5 <- forkIO (t5 m xs ys)
c6 <- forkIO (t6 m xs ys)
c7 <- forkIO (t7 m xs ys)
c8 <- forkIO (t8 m xs ys)
c9 <- forkIO (t9 m xs ys)
c <- takeMVar m
killThread c1
killThread c2
killThread c3
killThread c4
killThread c5
killThread c6
killThread c7
killThread c8
killThread c9
return c
t1 :: MVar Int -> Stream -> Stream -> IO()
t1 m (0:0:x) (0:0:y) = putMVar m 101
t1 m (0:0:x) (0:1:y) = putMVar m 102
t1 m (0:0:x) (1:0:y) = putMVar m 103
t1 m (0:0:x) (1:1:y) = putMVar m 104
t1 m (0:1:x) (0:0:y) = putMVar m 201
t1 m (0:1:x) (0:1:y) = putMVar m 202
t1 m (0:1:x) (1:0:y) = putMVar m 203
t1 m (0:1:x) (1:1:y) = putMVar m 204
t1 m (1:0:x) (0:0:y) = putMVar m 103
t1 m (1:0:x) (0:1:y) = putMVar m 104
t1 m (1:0:x) (1:0:y) = putMVar m 101
t1 m (1:0:x) (1:1:y) = putMVar m 102
t1 m (1:1:x) (0:0:y) = putMVar m 203
t1 m (1:1:x) (0:1:y) = putMVar m 204
t1 m (1:1:x) (1:0:y) = putMVar m 201
t1 m (1:1:x) (1:1:y) = putMVar m 202
t2 :: MVar Int -> Stream -> Stream -> IO()
t2 m (0:0:x) (b:1:0:y) = putMVar m 30
t2 m (1:0:x) (b:1:0:y) = putMVar m 31
t2 m (0:1:x) (b:1:0:y) = putMVar m 60
t2 m (1:1:x) (b:1:0:y) = putMVar m 61
t2 m x y = yield
t3 m (0:0:x) (0:b:1:y) = putMVar m 40
t3 m (1:0:x) (1:b:1:y) = putMVar m 40
t3 m (0:0:x) (1:b:1:y) = putMVar m 41
t3 m (1:0:x) (0:b:1:y) = putMVar m 41
t3 m (0:1:x) (0:b:1:y) = putMVar m 50
t3 m (1:1:x) (1:b:1:y) = putMVar m 50
t3 m (0:1:x) (1:b:1:y) = putMVar m 51
t3 m (1:1:x) (0:b:1:y) = putMVar m 51
t3 m x y = yield
t4 m (0:a:1:y) (0:0:x) = putMVar m 70
t4 m (1:a:1:y) (1:0:x) = putMVar m 70
t4 m (1:a:1:y) (0:0:x) = putMVar m 70
t4 m (0:a:1:y) (1:0:x) = putMVar m 70
t4 m (0:a:1:y) (0:1:x) = putMVar m 70
t4 m (1:a:1:y) (1:1:x) = putMVar m 70
t4 m (1:a:1:y) (0:1:x) = putMVar m 70
t4 m (0:a:1:y) (1:1:x) = putMVar m 70
t4 m x y = yield
t5 m (a:1:0:y) (0:0:x) = putMVar m 70
t5 m (a:1:0:y) (1:0:x) = putMVar m 70
t5 m (a:1:0:y) (0:1:x) = putMVar m 70
t5 m (a:1:0:y) (1:1:x) = putMVar m 70
t5 m x y = yield
t6 m (0:a:1:x) (0:b:1:y) = putMVar m 80
t6 m (1:a:1:x) (1:b:1:y) = putMVar m 80
t6 m (0:a:1:x) (1:b:1:y) = putMVar m 81
t6 m (1:a:1:x) (0:b:1:y) = putMVar m 81
t6 m x y = yield
t7 m (0:a:1:x) (b:1:0:y) = putMVar m 90
t7 m (1:a:1:x) (b:1:0:y) = putMVar m 91
t7 m x y = yield
t8 m (a:1:0:x) (b:1:0:y) = putMVar m 100
t8 m x y = yield
t9 m (a:1:0:x) (0:b:1:y) = putMVar m 70
t9 m (a:1:0:x) (1:b:1:y) = putMVar m 70
t9 m x y = yield
| snoyberg/ghc | testsuite/tests/concurrent/prog001/Thread.hs | bsd-3-clause | 3,129 | 0 | 10 | 1,022 | 2,534 | 1,274 | 1,260 | 87 | 1 |
{-# LANGUAGE PatternGuards #-}
module Idris.Erasure (performUsageAnalysis, mkFieldName) where
import Idris.AbsSyntax
import Idris.ASTUtils
import Idris.Core.CaseTree
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Primitives
import Idris.Error
import Debug.Trace
import System.IO.Unsafe
import Control.Category
import Prelude hiding (id, (.))
import Control.Arrow
import Control.Applicative
import Control.Monad.State
import Data.Maybe
import Data.List
import qualified Data.Set as S
import qualified Data.IntSet as IS
import qualified Data.Map as M
import qualified Data.IntMap as IM
import Data.Set (Set)
import Data.IntSet (IntSet)
import Data.Map (Map)
import Data.IntMap (IntMap)
import Data.Text (pack)
import qualified Data.Text as T
-- UseMap maps names to the set of used (reachable) argument positions.
type UseMap = Map Name (IntMap (Set Reason))
data Arg = Arg Int | Result deriving (Eq, Ord)
instance Show Arg where
show (Arg i) = show i
show Result = "*"
type Node = (Name, Arg)
type Deps = Map Cond DepSet
type Reason = (Name, Int) -- function name, argument index
-- Nodes along with sets of reasons for every one.
type DepSet = Map Node (Set Reason)
-- "Condition" is the conjunction
-- of elementary assumptions along the path from the root.
-- Elementary assumption (f, i) means that "function f uses the argument i".
type Cond = Set Node
-- Variables carry certain information with them.
data VarInfo = VI
{ viDeps :: DepSet -- dependencies drawn in by the variable
, viFunArg :: Maybe Int -- which function argument this variable came from (defined only for patvars)
, viMethod :: Maybe Name -- name of the metamethod represented by the var, if any
}
deriving Show
type Vars = Map Name VarInfo
-- Perform usage analysis, write the relevant information in the internal
-- structures, returning the list of reachable names.
performUsageAnalysis :: [Name] -> Idris [Name]
performUsageAnalysis startNames = do
ctx <- tt_ctxt <$> getIState
case startNames of
[] -> return [] -- no main -> not compiling -> reachability irrelevant
main -> do
ci <- idris_classes <$> getIState
cg <- idris_callgraph <$> getIState
opt <- idris_optimisation <$> getIState
used <- idris_erasureUsed <$> getIState
externs <- idris_externs <$> getIState
-- Build the dependency graph.
let depMap = buildDepMap ci used (S.toList externs) ctx main
-- Search for reachable nodes in the graph.
let (residDeps, (reachableNames, minUse)) = minimalUsage depMap
usage = M.toList minUse
-- Print some debug info.
logLvl 5 $ "Original deps:\n" ++ unlines (map fmtItem . M.toList $ depMap)
logLvl 3 $ "Reachable names:\n" ++ unlines (map (indent . show) . S.toList $ reachableNames)
logLvl 4 $ "Minimal usage:\n" ++ fmtUseMap usage
logLvl 5 $ "Residual deps:\n" ++ unlines (map fmtItem . M.toList $ residDeps)
-- Check that everything reachable is accessible.
checkEnabled <- (WarnReach `elem`) . opt_cmdline . idris_options <$> getIState
when checkEnabled $
mapM_ (checkAccessibility opt) usage
-- Check that no postulates are reachable.
reachablePostulates <- S.intersection reachableNames . idris_postulates <$> getIState
when (not . S.null $ reachablePostulates)
$ ifail ("reachable postulates:\n" ++ intercalate "\n" [" " ++ show n | n <- S.toList reachablePostulates])
-- Store the usage info in the internal state.
mapM_ storeUsage usage
return $ S.toList reachableNames
where
indent = (" " ++)
fmtItem :: (Cond, DepSet) -> String
fmtItem (cond, deps) = indent $ show (S.toList cond) ++ " -> " ++ show (M.toList deps)
fmtUseMap :: [(Name, IntMap (Set Reason))] -> String
fmtUseMap = unlines . map (\(n,is) -> indent $ show n ++ " -> " ++ fmtIxs is)
fmtIxs :: IntMap (Set Reason) -> String
fmtIxs = intercalate ", " . map fmtArg . IM.toList
where
fmtArg (i, rs)
| S.null rs = show i
| otherwise = show i ++ " from " ++ intercalate ", " (map show $ S.toList rs)
storeUsage :: (Name, IntMap (Set Reason)) -> Idris ()
storeUsage (n, args) = fputState (cg_usedpos . ist_callgraph n) flat
where
flat = [(i, S.toList rs) | (i,rs) <- IM.toList args]
checkAccessibility :: Ctxt OptInfo -> (Name, IntMap (Set Reason)) -> Idris ()
checkAccessibility opt (n, reachable)
| Just (Optimise inaccessible dt) <- lookupCtxtExact n opt
, eargs@(_:_) <- [fmt n (S.toList rs) | (i,n) <- inaccessible, rs <- maybeToList $ IM.lookup i reachable]
= warn $ show n ++ ": inaccessible arguments reachable:\n " ++ intercalate "\n " eargs
| otherwise = return ()
where
fmt n [] = show n ++ " (no more information available)"
fmt n rs = show n ++ " from " ++ intercalate ", " [show rn ++ " arg# " ++ show ri | (rn,ri) <- rs]
warn = logLvl 0
-- Find the minimal consistent usage by forward chaining.
minimalUsage :: Deps -> (Deps, (Set Name, UseMap))
minimalUsage = second gather . forwardChain
where
gather :: DepSet -> (Set Name, UseMap)
gather = foldr ins (S.empty, M.empty) . M.toList
where
ins :: (Node, Set Reason) -> (Set Name, UseMap) -> (Set Name, UseMap)
ins ((n, Result), rs) (ns, umap) = (S.insert n ns, umap)
ins ((n, Arg i ), rs) (ns, umap) = (ns, M.insertWith (IM.unionWith S.union) n (IM.singleton i rs) umap)
forwardChain :: Deps -> (Deps, DepSet)
forwardChain deps
| Just trivials <- M.lookup S.empty deps
= (M.unionWith S.union trivials)
`second` forwardChain (remove trivials . M.delete S.empty $ deps)
| otherwise = (deps, M.empty)
where
-- Remove the given nodes from the Deps entirely,
-- possibly creating new empty Conds.
remove :: DepSet -> Deps -> Deps
remove ds = M.mapKeysWith (M.unionWith S.union) (S.\\ M.keysSet ds)
-- Build the dependency graph,
-- starting the depth-first search from a list of Names.
buildDepMap :: Ctxt ClassInfo -> [(Name, Int)] -> [(Name, Int)] ->
Context -> [Name] -> Deps
buildDepMap ci used externs ctx startNames
= addPostulates used $ dfs S.empty M.empty startNames
where
-- mark the result of Main.main as used with the empty assumption
addPostulates :: [(Name, Int)] -> Deps -> Deps
addPostulates used deps = foldr (\(ds, rs) -> M.insertWith (M.unionWith S.union) ds rs) deps (postulates used)
where
-- mini-DSL for postulates
(==>) ds rs = (S.fromList ds, M.fromList [(r, S.empty) | r <- rs])
it n is = [(sUN n, Arg i) | i <- is]
mn n is = [(MN 0 $ pack n, Arg i) | i <- is]
-- believe_me is special because it does not use all its arguments
specialPrims = S.fromList [sUN "prim__believe_me"]
usedNames = allNames deps S.\\ specialPrims
usedPrims = [(p_name p, p_arity p) | p <- primitives, p_name p `S.member` usedNames]
postulates used =
[ [] ==> concat
-- Main.main ( + export lists) and run__IO, are always evaluated
-- but they elude analysis since they come from the seed term.
[(map (\n -> (n, Result)) startNames)
,[(sUN "run__IO", Result), (sUN "run__IO", Arg 1)]
,[(sUN "call__IO", Result), (sUN "call__IO", Arg 2)]
-- Explicit usage declarations from a %used pragma
, map (\(n, i) -> (n, Arg i)) used
-- MkIO is read by run__IO,
-- but this cannot be observed in the source code of programs.
, it "MkIO" [2]
, it "prim__IO" [1]
-- Foreign calls are built with pairs, but mkForeign doesn't
-- have an implementation so analysis won't see them
, [(pairCon, Arg 2),
(pairCon, Arg 3)] -- Used in foreign calls
-- these have been discovered as builtins but are not listed
-- among Idris.Primitives.primitives
--, mn "__MkPair" [2,3]
, it "prim_fork" [0]
, it "unsafePerformPrimIO" [1]
-- believe_me is a primitive but it only uses its third argument
-- it is special-cased in usedNames above
, it "prim__believe_me" [2]
-- in general, all other primitives use all their arguments
, [(n, Arg i) | (n,arity) <- usedPrims, i <- [0..arity-1]]
-- %externs are assumed to use all their arguments
, [(n, Arg i) | (n,arity) <- externs, i <- [0..arity-1]]
-- mkForeign* functions are special-cased below
]
]
-- perform depth-first search
-- to discover all the names used in the program
-- and call getDeps for every name
dfs :: Set Name -> Deps -> [Name] -> Deps
dfs visited deps [] = deps
dfs visited deps (n : ns)
| n `S.member` visited = dfs visited deps ns
| otherwise = dfs (S.insert n visited) (M.unionWith (M.unionWith S.union) deps' deps) (next ++ ns)
where
next = [n | n <- S.toList depn, n `S.notMember` visited]
depn = S.delete n $ allNames deps'
deps' = getDeps n
-- extract all names that a function depends on
-- from the Deps of the function
allNames :: Deps -> Set Name
allNames = S.unions . map names . M.toList
where
names (cs, ns) = S.map fst cs `S.union` S.map fst (M.keysSet ns)
-- get Deps for a Name
getDeps :: Name -> Deps
getDeps (SN (WhereN i (SN (InstanceCtorN classN)) (MN i' field)))
= M.empty -- these deps are created when applying instance ctors
getDeps n = case lookupDefExact n ctx of
Just def -> getDepsDef n def
Nothing -> error $ "erasure checker: unknown reference: " ++ show n
getDepsDef :: Name -> Def -> Deps
getDepsDef fn (Function ty t) = error "a function encountered" -- TODO
getDepsDef fn (TyDecl ty t) = M.empty
getDepsDef fn (Operator ty n' f) = M.empty -- TODO: what's this?
getDepsDef fn (CaseOp ci ty tys def tot cdefs)
= getDepsSC fn etaVars (etaMap `M.union` varMap) sc
where
-- we must eta-expand the definition with fresh variables
-- to capture these dependencies as well
etaIdx = [length vars .. length tys - 1]
etaVars = [eta i | i <- etaIdx]
etaMap = M.fromList [varPair (eta i) i | i <- etaIdx]
eta i = MN i (pack "eta")
-- the variables that arose as function arguments only depend on (n, i)
varMap = M.fromList [varPair v i | (v,i) <- zip vars [0..]]
varPair n argNo = (n, VI
{ viDeps = M.singleton (fn, Arg argNo) S.empty
, viFunArg = Just argNo
, viMethod = Nothing
})
(vars, sc) = cases_runtime cdefs
-- we use cases_runtime in order to have case-blocks
-- resolved to top-level functions before our analysis
etaExpand :: [Name] -> Term -> Term
etaExpand [] t = t
etaExpand (n : ns) t = etaExpand ns (App Complete t (P Ref n Erased))
getDepsSC :: Name -> [Name] -> Vars -> SC -> Deps
getDepsSC fn es vs ImpossibleCase = M.empty
getDepsSC fn es vs (UnmatchedCase msg) = M.empty
-- for the purposes of erasure, we can disregard the projection
getDepsSC fn es vs (ProjCase (Proj t i) alts) = getDepsSC fn es vs (ProjCase t alts) -- step
getDepsSC fn es vs (ProjCase (P _ n _) alts) = getDepsSC fn es vs (Case Shared n alts) -- base
-- other ProjCase's are not supported
getDepsSC fn es vs (ProjCase t alts) = error $ "ProjCase not supported:\n" ++ show (ProjCase t alts)
getDepsSC fn es vs (STerm t) = getDepsTerm vs [] (S.singleton (fn, Result)) (etaExpand es t)
getDepsSC fn es vs (Case sh n alts)
-- we case-split on this variable, which marks it as used
-- (unless there is exactly one case branch)
-- hence we add a new dependency, whose only precondition is
-- that the result of this function is used at all
= addTagDep $ unionMap (getDepsAlt fn es vs casedVar) alts -- coming from the whole subtree
where
addTagDep = case alts of
[_] -> id -- single branch, tag not used
_ -> M.insertWith (M.unionWith S.union) (S.singleton (fn, Result)) (viDeps casedVar)
casedVar = fromMaybe (error $ "nonpatvar in case: " ++ show n) (M.lookup n vs)
getDepsAlt :: Name -> [Name] -> Vars -> VarInfo -> CaseAlt -> Deps
getDepsAlt fn es vs var (FnCase n ns sc) = M.empty -- can't use FnCase at runtime
getDepsAlt fn es vs var (ConstCase c sc) = getDepsSC fn es vs sc
getDepsAlt fn es vs var (DefaultCase sc) = getDepsSC fn es vs sc
getDepsAlt fn es vs var (SucCase n sc)
= getDepsSC fn es (M.insert n var vs) sc -- we're not inserting the S-dependency here because it's special-cased
-- data constructors
getDepsAlt fn es vs var (ConCase n cnt ns sc)
= getDepsSC fn es (vs' `M.union` vs) sc -- left-biased union
where
-- Here we insert dependencies that arose from pattern matching on a constructor.
-- n = ctor name, j = ctor arg#, i = fun arg# of the cased var, cs = ctors of the cased var
vs' = M.fromList [(v, VI
{ viDeps = M.insertWith S.union (n, Arg j) (S.singleton (fn, varIdx)) (viDeps var)
, viFunArg = viFunArg var
, viMethod = meth j
})
| (v, j) <- zip ns [0..]]
-- this is safe because it's certainly a patvar
varIdx = fromJust (viFunArg var)
-- generate metamethod names, "n" is the instance ctor
meth :: Int -> Maybe Name
meth | SN (InstanceCtorN className) <- n = \j -> Just (mkFieldName n j)
| otherwise = \j -> Nothing
-- Named variables -> DeBruijn variables -> Conds/guards -> Term -> Deps
getDepsTerm :: Vars -> [(Name, Cond -> Deps)] -> Cond -> Term -> Deps
-- named variables introduce dependencies as described in `vs'
getDepsTerm vs bs cd (P _ n _)
-- de bruijns (lambda-bound, let-bound vars)
| Just deps <- lookup n bs
= deps cd
-- ctor-bound/arg-bound variables
| Just var <- M.lookup n vs
= M.singleton cd (viDeps var)
-- sanity check: machine-generated names shouldn't occur at top-level
| MN _ _ <- n
= error $ "erasure analysis: variable " ++ show n ++ " unbound in " ++ show (S.toList cd)
-- assumed to be a global reference
| otherwise = M.singleton cd (M.singleton (n, Result) S.empty)
-- dependencies of de bruijn variables are described in `bs'
getDepsTerm vs bs cd (V i) = snd (bs !! i) cd
getDepsTerm vs bs cd (Bind n bdr body)
-- here we just push IM.empty on the de bruijn stack
-- the args will be marked as used at the usage site
| Lam ty <- bdr = getDepsTerm vs ((n, const M.empty) : bs) cd body
| Pi _ ty _ <- bdr = getDepsTerm vs ((n, const M.empty) : bs) cd body
-- let-bound variables can get partially evaluated
-- it is sufficient just to plug the Cond in when the bound names are used
| Let ty t <- bdr = var t cd `union` getDepsTerm vs ((n, const M.empty) : bs) cd body
| NLet ty t <- bdr = var t cd `union` getDepsTerm vs ((n, const M.empty) : bs) cd body
where
var t cd = getDepsTerm vs bs cd t
-- applications may add items to Cond
getDepsTerm vs bs cd app@(App _ _ _)
| (fun, args) <- unApply app = case fun of
-- instance constructors -> create metamethod deps
P (DCon _ _ _) ctorName@(SN (InstanceCtorN className)) _
-> conditionalDeps ctorName args -- regular data ctor stuff
`union` unionMap (methodDeps ctorName) (zip [0..] args) -- method-specific stuff
-- ordinary constructors
P (TCon _ _) n _ -> unconditionalDeps args -- does not depend on anything
P (DCon _ _ _) n _ -> conditionalDeps n args -- depends on whether (n,#) is used
-- mkForeign* calls must be special-cased because they are variadic
-- All arguments must be marked as used, except for the first four,
-- which define the call type and are not needed at runtime.
P _ (UN n) _
| n == T.pack "mkForeignPrim"
-> unconditionalDeps $ drop 4 args
-- a bound variable might draw in additional dependencies,
-- think: f x = x 0 <-- here, `x' _is_ used
P _ n _
-- debruijn-bound name
| Just deps <- lookup n bs
-> deps cd `union` unconditionalDeps args
-- local name that refers to a method
| Just var <- M.lookup n vs
, Just meth <- viMethod var
-> viDeps var `ins` conditionalDeps meth args -- use the method instead
-- local name
| Just var <- M.lookup n vs
-- unconditional use
-> viDeps var `ins` unconditionalDeps args
-- global name
| otherwise
-- depends on whether the referred thing uses its argument
-> conditionalDeps n args
-- TODO: could we somehow infer how bound variables use their arguments?
V i -> snd (bs !! i) cd `union` unconditionalDeps args
-- we interpret applied lambdas as lets in order to reuse code here
Bind n (Lam ty) t -> getDepsTerm vs bs cd (lamToLet [] app)
-- and we interpret applied lets as lambdas
Bind n ( Let ty t') t -> getDepsTerm vs bs cd (App Complete (Bind n (Lam ty) t) t')
Bind n (NLet ty t') t -> getDepsTerm vs bs cd (App Complete (Bind n (Lam ty) t) t')
Proj t i
-> error $ "cannot[0] analyse projection !" ++ show i ++ " of " ++ show t
Erased -> M.empty
_ -> error $ "cannot analyse application of " ++ show fun ++ " to " ++ show args
where
union = M.unionWith $ M.unionWith S.union
ins = M.insertWith (M.unionWith S.union) cd
unconditionalDeps :: [Term] -> Deps
unconditionalDeps = unionMap (getDepsTerm vs bs cd)
conditionalDeps :: Name -> [Term] -> Deps
conditionalDeps n
= ins (M.singleton (n, Result) S.empty) . unionMap (getDepsArgs n) . zip indices
where
indices = map Just [0 .. getArity n - 1] ++ repeat Nothing
getDepsArgs n (Just i, t) = getDepsTerm vs bs (S.insert (n, Arg i) cd) t -- conditional
getDepsArgs n (Nothing, t) = getDepsTerm vs bs cd t -- unconditional
methodDeps :: Name -> (Int, Term) -> Deps
methodDeps ctorName (methNo, t)
= getDepsTerm (vars `M.union` vs) (bruijns ++ bs) cond body
where
vars = M.fromList [(v, VI
{ viDeps = deps i
, viFunArg = Just i
, viMethod = Nothing
}) | (v, i) <- zip args [0..]]
deps i = M.singleton (metameth, Arg i) S.empty
bruijns = reverse [(n, \cd -> M.singleton cd (deps i)) | (i, n) <- zip [0..] args]
cond = S.singleton (metameth, Result)
metameth = mkFieldName ctorName methNo
(args, body) = unfoldLams t
-- projections
getDepsTerm vs bs cd (Proj t (-1)) = getDepsTerm vs bs cd t -- naturals, (S n) -> n
getDepsTerm vs bs cd (Proj t i) = error $ "cannot[1] analyse projection !" ++ show i ++ " of " ++ show t
-- the easy cases
getDepsTerm vs bs cd (Constant _) = M.empty
getDepsTerm vs bs cd (TType _) = M.empty
getDepsTerm vs bs cd (UType _) = M.empty
getDepsTerm vs bs cd Erased = M.empty
getDepsTerm vs bs cd Impossible = M.empty
getDepsTerm vs bs cd t = error $ "cannot get deps of: " ++ show t
-- Get the number of arguments that might be considered for erasure.
getArity :: Name -> Int
getArity (SN (WhereN i' ctorName (MN i field)))
| Just (TyDecl (DCon _ _ _) ty) <- lookupDefExact ctorName ctx
= let argTys = map snd $ getArgTys ty
in if i <= length argTys
then length $ getArgTys (argTys !! i)
else error $ "invalid field number " ++ show i ++ " for " ++ show ctorName
| otherwise = error $ "unknown instance constructor: " ++ show ctorName
getArity n = case lookupDefExact n ctx of
Just (CaseOp ci ty tys def tot cdefs) -> length tys
Just (TyDecl (DCon tag arity _) _) -> arity
Just (TyDecl (Ref) ty) -> length $ getArgTys ty
Just (Operator ty arity op) -> arity
Just df -> error $ "Erasure/getArity: unrecognised entity '"
++ show n ++ "' with definition: " ++ show df
Nothing -> error $ "Erasure/getArity: definition not found for " ++ show n
-- convert applications of lambdas to lets
-- Note that this transformation preserves de bruijn numbering
lamToLet :: [Term] -> Term -> Term
lamToLet xs (App _ f x) = lamToLet (x:xs) f
lamToLet (x:xs) (Bind n (Lam ty) t) = Bind n (Let ty x) (lamToLet xs t)
lamToLet (x:xs) t = App Complete (lamToLet xs t) x
lamToLet [] t = t
-- split "\x_i -> T(x_i)" into [x_i] and T
unfoldLams :: Term -> ([Name], Term)
unfoldLams (Bind n (Lam ty) t) = let (ns,t') = unfoldLams t in (n:ns, t')
unfoldLams t = ([], t)
union :: Deps -> Deps -> Deps
union = M.unionWith (M.unionWith S.union)
unions :: [Deps] -> Deps
unions = M.unionsWith (M.unionWith S.union)
unionMap :: (a -> Deps) -> [a] -> Deps
unionMap f = M.unionsWith (M.unionWith S.union) . map f
-- Make a field name out of a data constructor name and field number.
mkFieldName :: Name -> Int -> Name
mkFieldName ctorName fieldNo = SN (WhereN fieldNo ctorName $ sMN fieldNo "field")
| raichoo/Idris-dev | src/Idris/Erasure.hs | bsd-3-clause | 22,478 | 0 | 21 | 6,902 | 6,713 | 3,489 | 3,224 | 307 | 53 |
module F11 where
fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
f11f = \z -> let x = fib 1000
in \y -> x+y
f11 = (f11f 5 6, f11f 7 8)
| olsner/ghc | testsuite/tests/arityanal/f11.hs | bsd-3-clause | 153 | 0 | 10 | 56 | 106 | 55 | 51 | 7 | 1 |
------------------------------------------------------------
-- Документация и материалы:
-- http://www.haskell.org/onlinereport/haskell2010/
-- http://www.haskell.org/tutorial/
------------------------------------------------------------
-- Явная инициализация основного файла программы с экспортированием
-- значения 'main'
module Main(main) where
import Chapter5.Main()
main = print $ "OK"
| mrLSD/HaskellTutorials | Main.hs | mit | 482 | 0 | 5 | 32 | 33 | 23 | 10 | 3 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.