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
-- | An umbrella module reexporting most types from the codebase (excluding -- specialized ones, like ones from "Guide.Markdown"). module Guide.Types ( module Guide.Types.Hue, module Guide.Types.Core, module Guide.Types.Edit, module Guide.Types.Analytics, module Guide.Types.User, module Guide.Types.Session, ) where import Guide.Types.Analytics import Guide.Types.Core import Guide.Types.Edit import Guide.Types.Hue import Guide.Types.Session import Guide.Types.User
aelve/guide
back/src/Guide/Types.hs
bsd-3-clause
481
0
5
61
89
62
27
14
0
module Scheme.Types where import Control.Monad.Except import Data.IORef import qualified Data.Vector as V import GHC.IO.Handle import Text.Parsec data LispValue = Atom String | List [LispValue] | DottedList [LispValue] LispValue | Vector (V.Vector LispValue) | RealNumber LispReal | ComplexNumber LispComplex | Character Char | String String | Bool Bool | PrimitiveFunc ([LispValue] -> ThrowsError LispValue) | Func { params :: [String], vararg :: (Maybe String), body :: [LispValue], closure :: Env } | IOFunc ([LispValue] -> IOThrowsError LispValue) | Port Handle instance Eq LispValue where Atom x == Atom y = x == y List x == List y = x == y DottedList xs x == DottedList ys y = xs == ys && x == y Vector x == Vector y = x == y RealNumber x == RealNumber y = x == y ComplexNumber x == ComplexNumber y = x == y Character x == Character y = x == y String x == String y = x == y Bool x == Bool y = x == y (==) Func { params = p1, vararg = v1, body = b1, closure = c1 } Func { params = p2, vararg = v2, body = b2, closure = c2 } = p1 == p2 && v1 == v2 && b1 == b2 && c1 == c2 _ == _ = False instance Show LispValue where show = showVal data LispComplex = LispComplex LispReal Sign LispReal deriving (Eq, Show) data LispReal = LispDouble Double | LispRational Integer Integer | LispInteger Integer deriving (Eq, Show) data Sign = Positive | Negative deriving (Eq, Show) showVal :: LispValue -> String showVal (String contents) = show contents showVal (Atom name) = name showVal (RealNumber (LispInteger number)) = show number showVal (RealNumber (LispDouble number)) = show number showVal (RealNumber (LispRational num denom)) = show num ++ "\\" ++ show denom showVal (ComplexNumber (LispComplex x Positive y)) = show x ++ "+" ++ show y ++ "i" showVal (Bool True) = "#t" showVal (Bool False) = "#f" showVal (List contents) = "(" ++ unwordsList contents ++ ")" showVal (DottedList first rest) = "(" ++ unwordsList first ++ " . " ++ showVal rest ++ ")" showVal (PrimitiveFunc _) = "<primitive>" showVal (Func { params = args, vararg = varargs, body = body, closure = env }) = "(lambda (" ++ unwords (map show args) ++ (case varargs of Nothing -> "" Just arg -> "." ++ arg) ++ ") ...)" showVal (Port _) = "<IO port>" showVal (IOFunc _) = "<IO primitive>" data LispError = NumArgs Integer [LispValue] | TypeMismatch String LispValue | Parser ParseError | BadSpecialForm String LispValue | NotFunction String String | UnboundVar String String | Default String type ThrowsError = Either LispError instance Show LispError where show = showError showError :: LispError -> String showError (UnboundVar message varname) = message ++ ": " ++ varname showError (BadSpecialForm message form) = message ++ ": " ++ show form showError (NotFunction message func) = message ++ ": " ++ show func showError (NumArgs expected found) = "Expected " ++ show expected ++ " args; found values " ++ unwordsList found showError (TypeMismatch expected found) = "Invalid type: expected " ++ show expected ++ ", found " ++ show found showError (Parser parseErr) = "Parser error at " ++ show parseErr showError (Default msg) = "Default " ++ show msg unwordsList :: [LispValue] -> String unwordsList = unwords . map showVal type Env = IORef [(String, IORef LispValue)] type IOThrowsError = ExceptT LispError IO
drets/scheme-haskell-48h
src/Scheme/Types.hs
bsd-3-clause
4,002
0
12
1,303
1,298
671
627
88
2
{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.Resource import System.Environment import System.Exit import System.Directory import System.IO import Data.Conduit import qualified Data.Conduit.List as CL import qualified Data.IntMap.Strict as IM import Data.Semigroup import qualified Data.Text.Lazy as L import qualified Data.Text.Lazy.IO as L import Numeric import Data.Arib data Count = Count { total :: {-#UNPACK#-}!Int , drops :: {-#UNPACK#-}!Int , errors :: {-#UNPACK#-}!Int , scrambles :: {-#UNPACK#-}!Int , offset :: {-#UNPACK#-}!Int , rawTs :: {-#UNPACK#-}!TS } deriving Show instance Semigroup Count where Count at ad ae as _ ar <> Count bt bd be bs bo br = let d = if ar `isNextOf` continuityCounter br then 0 else 1 in Count (at + bt) (ad + bd + d) (ae + be) (as + bs) bo ar tsToCount :: TS -> Int -> Count tsToCount ts o = Count { total = 1 , drops = 0 , errors = if transportErrorIndicator ts then 1 else 0 , scrambles = if tsTransportScramblingControl ts /= 0 then 1 else 0 , offset = o , rawTs = ts } abstruct :: (IM.IntMap Count, Int) -> TS -> (IM.IntMap Count, Int) abstruct (!m,!c) ts = {-# SCC "abstruct" #-}(IM.insertWith (<>) (tsProgramId ts) (tsToCount ts c) m, succ c) {-# INLINE abstruct #-} showResult :: [(Int, Count)] -> [L.Text] showResult l = map (\(pid,c) -> "pid=0x" `L.append` L.justifyRight 4 '0' (L.pack $ showHex pid []) `L.append` ", total=" `L.append` showElem c total `L.append` ", d=" `L.append` showElem c drops `L.append` ", e=" `L.append` showElem c errors `L.append` ", scrambling=" `L.append` showElem c scrambles `L.append` ", offset=" `L.append` showElem c offset ) l where maxDigit f = (+1) . floor . logBase 10 $ (fromIntegral . maximum $ map (f . snd) l :: Double) showElem c f = L.justifyRight (maxDigit f) ' ' (L.pack . show $ f c) select :: Monad m => Bool -> [Int] -> Conduit TS m TS select include pids = CL.filter (elm pids . tsProgramId) where elm = flip $ if include then elem else notElem main :: IO () main = getArgs >>= \case [file] -> runResourceT $ do r <- fmap fst $ sourceTs file $$ CL.fold abstruct (IM.empty, 0) liftIO $ mapM_ L.putStrLn . showResult $ IM.toAscList r src:dst:pidss_ -> do let (include, pidss) = span (== "-x") pidss_ ex <- doesFileExist dst when ex $ hPutStrLn stderr "dst file already exists." >> exitFailure pids <- mapM readIO pidss :: IO [Int] runResourceT $ sourceTs src $$ select (null include) pids =$ sinkTs dst _ -> do p <- getProgName putStrLn $ "USAGE: " ++ p ++ " SRC [DST [-x] pid1 [pid2 ...]]"
philopon/arib
examples/tsselect.hs
bsd-3-clause
3,038
0
23
835
1,056
573
483
70
3
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE PolyKinds #-} {-| This module is an internal GHC module. It declares the constants used in the implementation of type-level natural numbers. The programmer interface for working with type-level naturals should be defined in a separate library. @since 4.10.0.0 -} module GHC.TypeNats ( -- * Nat Kind Nat -- declared in GHC.Types in package ghc-prim -- * Linking type and value level , KnownNat, natVal, natVal' , SomeNat(..) , someNatVal , sameNat -- * Functions on type literals , type (<=), type (<=?), type (+), type (*), type (^), type (-) , CmpNat , Div, Mod, Log2 ) where import GHC.Base(Eq(..), Ord(..), Bool(True), Ordering(..), otherwise) import GHC.Types( Nat ) import GHC.Natural(Natural) import GHC.Show(Show(..)) import GHC.Read(Read(..)) import GHC.Prim(magicDict, Proxy#) import Data.Maybe(Maybe(..)) import Data.Proxy (Proxy(..)) import Data.Type.Equality((:~:)(Refl)) import Unsafe.Coerce(unsafeCoerce) -------------------------------------------------------------------------------- -- | This class gives the integer associated with a type-level natural. -- There are instances of the class for every concrete literal: 0, 1, 2, etc. -- -- @since 4.7.0.0 class KnownNat (n :: Nat) where natSing :: SNat n -- | @since 4.10.0.0 natVal :: forall n proxy. KnownNat n => proxy n -> Natural natVal _ = case natSing :: SNat n of SNat x -> x -- | @since 4.10.0.0 natVal' :: forall n. KnownNat n => Proxy# n -> Natural natVal' _ = case natSing :: SNat n of SNat x -> x -- | This type represents unknown type-level natural numbers. -- -- @since 4.10.0.0 data SomeNat = forall n. KnownNat n => SomeNat (Proxy n) -- | Convert an integer into an unknown type-level natural. -- -- @since 4.10.0.0 someNatVal :: Natural -> SomeNat someNatVal n = withSNat SomeNat (SNat n) Proxy -- | @since 4.7.0.0 instance Eq SomeNat where SomeNat x == SomeNat y = natVal x == natVal y -- | @since 4.7.0.0 instance Ord SomeNat where compare (SomeNat x) (SomeNat y) = compare (natVal x) (natVal y) -- | @since 4.7.0.0 instance Show SomeNat where showsPrec p (SomeNat x) = showsPrec p (natVal x) -- | @since 4.7.0.0 instance Read SomeNat where readsPrec p xs = do (a,ys) <- readsPrec p xs [(someNatVal a, ys)] -------------------------------------------------------------------------------- infix 4 <=?, <= infixl 6 +, - infixl 7 * infixr 8 ^ -- | Comparison of type-level naturals, as a constraint. -- -- @since 4.7.0.0 type x <= y = (x <=? y) ~ 'True -- | Comparison of type-level naturals, as a function. -- -- @since 4.7.0.0 type family CmpNat (m :: Nat) (n :: Nat) :: Ordering {- | Comparison of type-level naturals, as a function. NOTE: The functionality for this function should be subsumed by 'CmpNat', so this might go away in the future. Please let us know, if you encounter discrepancies between the two. -} type family (m :: Nat) <=? (n :: Nat) :: Bool -- | Addition of type-level naturals. -- -- @since 4.7.0.0 type family (m :: Nat) + (n :: Nat) :: Nat -- | Multiplication of type-level naturals. -- -- @since 4.7.0.0 type family (m :: Nat) * (n :: Nat) :: Nat -- | Exponentiation of type-level naturals. -- -- @since 4.7.0.0 type family (m :: Nat) ^ (n :: Nat) :: Nat -- | Subtraction of type-level naturals. -- -- @since 4.7.0.0 type family (m :: Nat) - (n :: Nat) :: Nat -- | Division (round down) of natural numbers. -- @Div x 0@ is undefined (i.e., it cannot be reduced). -- -- @since 4.11.0.0 type family Div (m :: Nat) (n :: Nat) :: Nat -- | Modulus of natural numbers. -- @Mod x 0@ is undefined (i.e., it cannot be reduced). -- -- @since 4.11.0.0 type family Mod (m :: Nat) (n :: Nat) :: Nat -- | Log base 2 (round down) of natural numbers. -- @Log 0@ is undefined (i.e., it cannot be reduced). -- -- @since 4.11.0.0 type family Log2 (m :: Nat) :: Nat -------------------------------------------------------------------------------- -- | We either get evidence that this function was instantiated with the -- same type-level numbers, or 'Nothing'. -- -- @since 4.7.0.0 sameNat :: (KnownNat a, KnownNat b) => Proxy a -> Proxy b -> Maybe (a :~: b) sameNat x y | natVal x == natVal y = Just (unsafeCoerce Refl) | otherwise = Nothing -------------------------------------------------------------------------------- -- PRIVATE: newtype SNat (n :: Nat) = SNat Natural data WrapN a b = WrapN (KnownNat a => Proxy a -> b) -- See Note [magicDictId magic] in "basicType/MkId.hs" withSNat :: (KnownNat a => Proxy a -> b) -> SNat a -> Proxy a -> b withSNat f x y = magicDict (WrapN f) x y
ezyang/ghc
libraries/base/GHC/TypeNats.hs
bsd-3-clause
5,112
3
10
1,014
1,107
665
442
-1
-1
{-# OPTIONS_GHC -Wno-redundant-constraints #-} {-# OPTIONS_GHC -Wno-incomplete-patterns #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE EmptyCase #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Data.Diverse.Which.Internal ( -- * 'Which' type Which(..) -- exporting constructor unsafely! -- * Single type -- ** Construction , impossible , impossible' -- , totally , pick , pick0 , pickOnly , pickL , pickTag , pickN -- ** Destruction , obvious , trial , trial' , trial0 , trial0' , trialL , trialL' , trialTag , trialTag' , trialN , trialN' -- * Multiple types -- ** Injection , Diversify , diversify , diversify' , diversify0 , DiversifyL , diversifyL , DiversifyN , diversifyN -- ** Inverse Injection , Reinterpret -- , Reinterpreted , reinterpret , Reinterpret' , reinterpret' , ReinterpretL -- , ReinterpretedL , reinterpretL , ReinterpretL' , reinterpretL' , ReinterpretN' , reinterpretN' -- * Catamorphism , Switch , switch , which , Switcher(..) , SwitchN , switchN , whichN , SwitcherN(..) ) where import Control.Applicative import Control.DeepSeq import Control.Monad import Data.Diverse.AFunctor import Data.Diverse.ATraversable import Data.Diverse.Case import Data.Diverse.CaseFunc import Data.Diverse.Reduce import Data.Diverse.Reiterate import Data.Diverse.TypeLevel import Data.Kind import Data.Semigroup (Semigroup(..)) import Data.Tagged import Data.Void import GHC.Exts (Any) import qualified GHC.Generics as G import GHC.TypeLits import Text.ParserCombinators.ReadPrec import Text.Read import qualified Text.Read.Lex as L import Unsafe.Coerce -- | A 'Which' is an anonymous sum type (also known as a polymorphic variant, or co-record) -- which can only contain one of the types in the typelist. -- This is essentially a typed version of 'Data.Dynamic'. -- -- The following functions are available can be used to manipulate unique types in the typelist -- -- * constructor: 'pick' -- * destructor: 'trial' -- * injection: 'diversify' and 'reinterpret' -- * catamorphism: 'which' or 'switch' -- -- These functions are type specified. This means labels are not required because the types themselves can be used to access the 'Which'. -- It is a compile error to use those functions for duplicate fields. -- -- For duplicate types in the list of possible types, Nat-indexed version of the functions are available: -- -- * constructor: 'pickN' -- * destructor: 'trialN' -- * inejction: 'diversifyN' and 'reinterpretN' -- * catamorphism: 'whichN' or 'switchN' -- -- Encoding: The variant contains a value whose type is at the given position in the type list. -- This is the same encoding as <https://github.com/haskus/haskus-utils/blob/master/src/lib/Haskus/Utils/Variant.hs Haskus.Util.Variant> and <https://hackage.haskell.org/package/HList-0.4.1.0/docs/src/Data-HList-Variant.html Data.Hlist.Variant>. -- -- The constructor is only exported in the "Data.Diverse.Which.Internal" module data Which (xs :: [Type]) = Which {-# UNPACK #-} !Int Any -- Just like Haskus and HList versions, inferred type is phantom which is wrong -- representational means: -- @ -- Coercible '[Int] '[IntLike] => Coercible (Which '[Int]) (Which '[IntLike]) -- @ type role Which representational ---------------------------------------------- -- | A terminating 'G.Generic' instance for no types encoded as a 'Which '[]'. -- The 'G.C1' and 'G.S1' metadata are not encoded. instance G.Generic (Which '[]) where type Rep (Which '[]) = G.V1 from _ = {- G.V1 -} error "No generic representation for Which '[]" to _ = error "No values for Which '[]" -- | A terminating 'G.Generic' instance for one type encoded with 'pick''. -- The 'G.C1' and 'G.S1' metadata are not encoded. instance G.Generic (Which '[x]) where type Rep (Which '[x]) = G.Rec0 x from v = {- G.Rec0 -} G.K1 (obvious v) to ({- G.Rec0 -} G.K1 a) = pickOnly a -- | A 'G.Generic' instance encoded as either the 'x' value ('G.:+:') or the 'diversify0'ed remaining 'Which xs'. -- The 'G.C1' and 'G.S1' metadata are not encoded. instance G.Generic (Which (x ': x' ': xs)) where type Rep (Which (x ': x' ': xs)) = (G.Rec0 x) G.:+: (G.Rec0 (Which (x' ': xs))) from v = case trial0 v of Right x -> G.L1 ({- G.Rec0 -} G.K1 x) Left v' -> G.R1 ({- G.Rec0 -} G.K1 v') to {- G.Rec0 -} x = case x of G.L1 ({- G.Rec0 -} G.K1 a) -> pick0 a G.R1 ({- G.Rec0 -} G.K1 v) -> diversify0 v ----------------------------------------------------------------------- instance Semigroup (Which '[]) where a <> _ = a -- | Analogous to 'Data.Void.absurd'. Renamed 'impossible' to avoid conflicts. -- -- Since 'Which \'[]' values logically don't exist, this witnesses the -- logical reasoning tool of \"ex falso quodlibet\", -- ie "from falsehood, anything follows". -- -- A 'Which \'[]' is a 'Which' with no alternatives, which may occur as a 'Left'-over from 'trial'ing a @Which '[x]@ with one type. -- It is an uninhabited type, just like 'Data.Void.Void' impossible :: Which '[] -> a impossible a = case a of {} -- Copied from http://hackage.haskell.org/package/base/docs/src/Data.Void.html -- | A @Which '[Void]@ is equivalent to @Which '[]@ -- A @Which '[Void]@ might occur if you lift a 'Void' into a @Which@ with 'pick'. -- This allows you to convert it back to 'Void' or @Which '[]@ impossible' :: Which '[Void] -> a impossible' a = case a of {} -- -- | This function is useful to type restrict something that returns a polymorphic type -- -- to return (Which '[]). Eg. use this that to prove at compile time that a -- -- finished continuation monad has no more unhandled holes. -- totally :: f (Which '[]) -> f (Which '[]) -- totally = id -- | Lift a value into a 'Which' of possibly other types @xs@. -- @xs@ can be inferred or specified with TypeApplications. -- NB. forall is used to specify @xs@ first, so TypeApplications can be used to specify @xs@ first -- -- @ -- 'pick' \'A' \@_ \@'[Int, Bool, Char, Maybe String] :: Which '[Int, Bool, Char, Maybe String] -- @ pick :: forall x xs. UniqueMember x xs => x -> Which xs pick = pick_ pick_ :: forall x xs n. (NatToInt n, n ~ IndexOf x xs) => x -> Which xs pick_ = Which (natToInt @n) . unsafeCoerce -- | A variation of 'pick' where @x@ is specified via a label -- -- @ -- let y = 'pickL' \@Foo (Tagged (5 :: Int)) :: Which '[Bool, Tagged Foo Int, Tagged Bar Char] -- x = 'trialL' \@Foo y -- x `shouldBe` (Right (Tagged 5)) -- @ pickL :: forall l x xs. (UniqueLabelMember l xs, x ~ KindAtLabel l xs) => x -> Which xs pickL = pick_ @x -- | Variation of 'pick' specialized to 'Tagged' that automatically tags the value. pickTag :: forall l x xs . (UniqueMember (Tagged l x) xs) => x -> Which xs pickTag a = pick @(Tagged l x) (Tagged @l a) -- | A variation of 'pick' into a 'Which' of a single type. -- -- @ -- 'pickOnly' \'A' :: Which '[Char] -- @ pickOnly :: x -> Which '[x] pickOnly = pick0 -- | A variation of 'pick' into a 'Which' where @x@ is the first type. -- -- @ -- 'pick0' \'A' :: Which '[Char, Int, Bool] -- @ pick0 :: x -> Which (x ': xs) pick0 = Which 0 . unsafeCoerce -- | Lift a value into a 'Which' of possibly other (possibley indistinct) types, where the value is the @n@-th type. -- -- @ -- 'pickN' \@4 (5 :: Int) :: Which '[Bool, Int, Char, Bool, Int, Char] -- @ pickN :: forall n x xs. MemberAt n x xs => x -> Which xs pickN = Which (natToInt @n) . unsafeCoerce -- | It is 'obvious' what value is inside a 'Which' of one type. -- -- @ -- let x = 'pick'' \'A' :: Which '[Char] -- 'obvious' x \`shouldBe` \'A' -- @ obvious :: Which '[a] -> a obvious (Which _ v) = unsafeCoerce v trial_ :: forall n x xs. (NatToInt n, n ~ IndexOf x xs) => Which xs -> Either (Which (Remove x xs)) x trial_ (Which n v) = let i = natToInt @n in if n == i then Right (unsafeCoerce v) else if n > i then Left (Which (n - 1) v) else Left (Which n v) -- | 'trialN' the n-th type of a 'Which', and get 'Either' the 'Right' value or the 'Left'-over possibilities. -- -- @ -- let x = 'pick' \'A' \@_ \@'[Int, Bool, Char, Maybe String] :: 'Which' '[Int, Bool, Char, Maybe String] -- 'trialN' \@1 x \`shouldBe` Left ('pick' \'A') :: 'Which' '[Int, Char, Maybe String] -- @ trialN :: forall n x xs. (MemberAt n x xs) => Which xs -> Either (Which (RemoveIndex n xs)) x trialN (Which n v) = let i = natToInt @n in if n == i then Right (unsafeCoerce v) else if n > i then Left (Which (n - 1) v) else Left (Which n v) -- | 'trial' a type in a 'Which' and 'Either' get the 'Right' value or the 'Left'-over possibilities. -- -- @ -- let x = 'pick' \'A' \@'[Int, Bool, Char, Maybe String] :: 'Which' '[Int, Bool, Char, Maybe String] -- 'trial' \@Char x \`shouldBe` Right \'A' -- 'trial' \@Int x \`shouldBe` Left ('pick' \'A') :: 'Which' '[Bool, Char, Maybe String] -- @ trial :: forall x xs. (UniqueMember x xs) => Which xs -> Either (Which (Remove x xs)) x trial = trial_ -- | A variation of 'trial' where x is specified via a label -- -- @ -- let y = 'pickL' \@Foo (Tagged (5 :: Int)) :: Which '[Bool, Tagged Foo Int, Tagged Bar Char] -- x = 'trialL' \@Foo Proxy y -- x `shouldBe` (Right (Tagged 5)) -- @ trialL :: forall l x xs. (UniqueLabelMember l xs, x ~ KindAtLabel l xs) => Which xs -> Either (Which (Remove x xs)) x trialL = trial_ @_ @x trial_' :: forall n x xs. (NatToInt n, n ~ IndexOf x xs) => Which xs -> Maybe x trial_' (Which n v) = let i = natToInt @n in if n == i then Just (unsafeCoerce v) else Nothing -- | Variation of 'trialL' specialized to 'Tagged' which untags the field. trialTag :: forall l x xs. (UniqueMember (Tagged l x) xs) => Which xs -> Either (Which (Remove (Tagged l x) xs)) x trialTag xs = unTagged <$> trial @(Tagged l x) xs -- | Variation of 'trialN' which returns a Maybe trialN' :: forall n x xs. (MemberAt n x xs) => Which xs -> Maybe x trialN' (Which n v) = let i = natToInt @n in if n == i then Just (unsafeCoerce v) else Nothing -- | Variation of 'trial' which returns a Maybe trial' :: forall x xs. (UniqueMember x xs) => Which xs -> Maybe x trial' = trial_' -- | Variation of 'trialL' which returns a Maybe trialL' :: forall l x xs. (UniqueLabelMember l xs, x ~ KindAtLabel l xs) => Which xs -> Maybe x trialL' = trial_' @_ @x -- | Variation of 'trialL'' specialized to 'Tagged' which untags the field. trialTag' :: forall l x xs. (UniqueMember (Tagged l x) xs) => Which xs -> Maybe x trialTag' xs = unTagged <$> trial' @(Tagged l x) xs -- | A variation of a 'Which' 'trial' which 'trial's the first type in the type list. -- -- @ -- let x = 'pick' \'A' \@'[Int, Bool, Char, Maybe String] :: 'Which' '[Int, Bool, Char, Maybe String] -- 'trial0' x \`shouldBe` Left ('pick' \'A') :: 'Which' '[Bool, Char, Maybe String] -- @ trial0 :: forall x xs. Which (x ': xs) -> Either (Which xs) x trial0 (Which n v) = if n == 0 then Right (unsafeCoerce v) else Left (Which (n - 1) v) -- | Variation of 'trial0' which returns a Maybe trial0' :: forall x xs. Which (x ': xs) -> Maybe x trial0' (Which n v) = if n == 0 then Just (unsafeCoerce v) else Nothing ----------------------------------------------------------------- -- | A friendlier constraint synonym for 'diversify'. type Diversify (branch :: [Type]) (tree :: [Type]) = Switch (CaseDiversify branch tree) (Which tree) branch -- | Convert a 'Which' to another 'Which' that may include other possibilities. -- That is, @branch@ is equal or is a subset of @tree@. -- -- This can also be used to rearrange the order of the types in the 'Which'. -- -- It is a compile error if @tree@ has duplicate types with @branch@. -- -- NB. Use TypeApplications with @_ to specify @tree@. -- -- @ -- let a = 'pick'' (5 :: Int) :: 'Which' '[Int] -- b = 'diversify' \@_ \@[Int, Bool] a :: 'Which' '[Int, Bool] -- c = 'diversify' \@_ \@[Bool, Int] b :: 'Which' '[Bool, Int] -- @ diversify :: forall branch tree. Diversify branch tree => Which branch -> Which tree diversify = which (CaseDiversify @branch @tree @_ @branch) data CaseDiversify (branch :: [Type]) (tree :: [Type]) r (branch' :: [Type]) = CaseDiversify type instance CaseResult (CaseDiversify branch tree r) x = r instance Reiterate (CaseDiversify r branch tree) branch' where reiterate CaseDiversify = CaseDiversify -- | The @Unique x branch@ is important to get a compile error if the from @branch@ doesn't have a unique x instance (UniqueMember x tree, Unique x branch) => Case (CaseDiversify branch tree (Which tree)) (x ': branch') where case' CaseDiversify = pick -- | A simple version of 'diversify' which add another type to the front of the typelist. diversify0 :: forall x xs. Which xs -> Which (x ': xs) diversify0 (Which n v) = Which (n + 1) v -- | A restricted version of 'diversify' which only rearranges the types diversify' :: forall branch tree. (Diversify branch tree, SameLength branch tree) => Which branch -> Which tree diversify' = diversify ------------------------------------------------------------------ -- | A friendlier constraint synonym for 'diversifyL'. type DiversifyL (ls :: [k]) (branch :: [Type]) (tree :: [Type]) = ( Diversify branch tree , branch ~ KindsAtLabels ls tree , UniqueLabels ls tree , IsDistinct ls ) -- | A variation of 'diversify' where @branch@is additionally specified by a labels list. -- -- @ -- let y = 'pickOnly' (5 :: Tagged Bar Int) -- y' = 'diversifyL' \@'[Bar] y :: 'Which' '[Tagged Bar Int, Tagged Foo Bool] -- y'' = 'diversifyL' \@'[Bar, Foo] y' :: 'Which' '[Tagged Foo Bool, Tagged Bar Int] -- 'switch' y'' ('Data.Diverse.CaseFunc.CaseFunc' \@'Data.Typeable.Typeable' (show . typeRep . (pure \@Proxy))) \`shouldBe` \"Tagged * Bar Int" -- @ diversifyL :: forall ls branch tree. (DiversifyL ls branch tree) => Which branch -> Which tree diversifyL = which (CaseDiversify @branch @tree @_ @branch) ------------------------------------------------------------------ -- | A friendlier constraint synonym for 'diversifyN'. type DiversifyN (ns :: [Nat]) (branch :: [Type]) (tree :: [Type]) = ( SwitchN Which (CaseDiversifyN ns) (Which tree) 0 branch , KindsAtIndices ns tree ~ branch ) -- | A variation of 'diversify' which uses a Nat list @indices@ to specify how to reorder the fields, where -- -- @ -- indices[branch_idx] = tree_idx -- @ -- -- This variation allows @tree@ to contain duplicate types with @branch@ since -- the mapping is specified by @indicies@. -- -- @ -- let y = 'pickOnly' (5 :: Int) -- y' = 'diversifyN' \@'[0] \@_ \@[Int, Bool] y -- y'' = 'diversifyN' \@[1,0] \@_ \@[Bool, Int] y' -- 'switch' y'' ('Data.Diverse.CaseFunc.CaseFunc' \@'Data.Typeable.Typeable' (show . typeRep . (pure \@Proxy))) \`shouldBe` \"Int" -- @ diversifyN :: forall ns branch tree. (DiversifyN ns branch tree) => Which branch -> Which tree diversifyN = whichN (CaseDiversifyN @ns @_ @0 @branch) data CaseDiversifyN (ns :: [Nat]) r (n :: Nat) (branch' :: [Type]) = CaseDiversifyN type instance CaseResult (CaseDiversifyN ns r n) x = r instance ReiterateN (CaseDiversifyN ns r) n branch' where reiterateN CaseDiversifyN = CaseDiversifyN instance MemberAt (KindAtIndex n ns) x tree => Case (CaseDiversifyN ns (Which tree) n) (x ': branch') where case' CaseDiversifyN v = pickN @(KindAtIndex n ns) v ------------------------------------------------------------------ -- | A friendlier constraint synonym for 'reinterpret'. type Reinterpret (branch :: [Type]) (tree :: [Type]) = Switch (CaseReinterpret branch tree) (Either (Which (Complement tree branch)) (Which branch)) tree -- -- | A variation of 'Reinterpret' that exposes @branchlessTree ~ Complement tree branch@ -- type Reinterpreted branch tree branchlessTree = (Reinterpret branch tree, branchlessTree ~ Complement tree branch) -- | Convert a 'Which' into possibly another 'Which' with a totally different typelist. -- Returns either a 'Which' with the 'Right' value, or a 'Which' with the 'Left'over @compliment@ types. -- -- It is a compile error if @branch@ or @compliment@ has duplicate types with @tree@. -- -- NB. forall used to specify @branch@ first, so TypeApplications can be used to specify @branch@ first. -- -- @ -- let a = 'pick' \@[Int, Char, Bool] (5 :: Int) :: 'Which' '[Int, Char, Bool] -- let b = 'reinterpret' @[String, Char] y -- b \`shouldBe` Left ('pick' (5 :: Int)) :: 'Which' '[Int, Bool] -- let c = 'reinterpret' @[String, Int] a -- c \`shouldBe` Right ('pick' (5 :: Int)) :: 'Which' '[String, Int] -- @ reinterpret :: forall branch tree. (Reinterpret branch tree) => Which tree -> Either (Which (Complement tree branch)) (Which branch) reinterpret = which (CaseReinterpret @branch @tree @_ @tree) data CaseReinterpret (branch :: [Type]) (tree :: [Type]) r (tree' :: [Type]) = CaseReinterpret type instance CaseResult (CaseReinterpret branch tree r) x = r instance Reiterate (CaseReinterpret branch tree r) tree' where reiterate CaseReinterpret = CaseReinterpret instance ( MaybeUniqueMember x branch , comp ~ Complement tree branch , MaybeUniqueMember x comp , Unique x tree -- Compile error to ensure reinterpret only works with unique fields ) => Case (CaseReinterpret branch tree (Either (Which comp) (Which branch))) (x ': tree') where case' CaseReinterpret a = case natToInt @(PositionOf x branch) of 0 -> let j = natToInt @(PositionOf x comp) -- safe use of partial! j will never be zero due to check above in Left $ Which (j - 1) (unsafeCoerce a) i -> Right $ Which (i - 1) (unsafeCoerce a) ------------------------------------------------------------------ -- | A friendlier constraint synonym for 'reinterpret''. type Reinterpret' (branch :: [Type]) (tree :: [Type]) = Switch (CaseReinterpret' branch tree) (Maybe (Which branch)) tree -- | Variation of 'reinterpret' which returns a Maybe. reinterpret' :: forall branch tree. (Reinterpret' branch tree) => Which tree -> Maybe (Which branch) reinterpret' = which (CaseReinterpret' @branch @tree @_ @tree) data CaseReinterpret' (branch :: [Type]) (tree :: [Type]) r (tree' :: [Type]) = CaseReinterpret' type instance CaseResult (CaseReinterpret' branch tree r) x = r instance Reiterate (CaseReinterpret' branch tree r) tree' where reiterate CaseReinterpret' = CaseReinterpret' instance ( MaybeUniqueMember x branch , comp ~ Complement tree branch , Unique x tree -- Compile error to ensure reinterpret only works with unique fields ) => Case (CaseReinterpret' branch tree (Maybe (Which branch))) (x ': tree') where case' CaseReinterpret' a = case natToInt @(PositionOf x branch) of 0 -> Nothing i -> Just $ Which (i - 1) (unsafeCoerce a) ------------------------------------------------------------------ -- | A friendlier constraint synonym for 'reinterpretL'. type ReinterpretL (ls :: [k]) (branch :: [Type]) (tree :: [Type]) = ( Reinterpret branch tree , branch ~ KindsAtLabels ls tree , UniqueLabels ls tree , IsDistinct ls ) -- -- | A variation of 'ReinterpretL' that exposes @branchlessTree ~ Complement tree branch@ -- type ReinterpretedL ls branch tree branchlessTree = (ReinterpretL ls branch tree, branchlessTree ~ Complement tree branch) -- | A variation of 'reinterpret' where the @branch@ is additionally specified with a labels list. -- -- @ -- let y = 'pick' \@[Tagged Bar Int, Tagged Foo Bool, Tagged Hi Char, Tagged Bye Bool] (5 :: Tagged Bar Int) -- y' = 'reinterpretL' \@[Foo, Bar] y -- x = 'pick' \@[Tagged Foo Bool, Tagged Bar Int] (5 :: Tagged Bar Int) -- y' \`shouldBe` Right x -- @ reinterpretL :: forall ls branch tree. (ReinterpretL ls branch tree) => Which tree -> Either (Which (Complement tree branch)) (Which branch) reinterpretL = which (CaseReinterpret @branch @tree @_ @tree) -- | A friendlier constraint synonym for 'reinterpretL'. type ReinterpretL' (ls :: [k]) (branch :: [Type]) (tree :: [Type]) = ( Reinterpret' branch tree , branch ~ KindsAtLabels ls tree , UniqueLabels ls tree , IsDistinct ls ) -- | Variation of 'reinterpretL' which returns a Maybe. reinterpretL' :: forall ls branch tree. (ReinterpretL' ls branch tree) => Which tree -> Maybe (Which branch) reinterpretL' = which (CaseReinterpret' @branch @tree @_ @tree) ------------------------------------------------------------------ -- | A friendlier constraint synonym for 'reinterpretN'. type ReinterpretN' (ns :: [Nat]) (branch :: [Type]) (tree :: [Type]) = ( SwitchN Which (CaseReinterpretN' ns) (Maybe (Which branch)) 0 tree , KindsAtIndices ns tree ~ branch) -- | A limited variation of 'reinterpret'' which uses a Nat list @n@ to specify how to reorder the fields, where -- -- @ -- indices[branch_idx] = tree_idx -- @ -- -- This variation allows @tree@ to contain duplicate types with @branch@ -- since the mapping is specified by @indicies@. -- -- However, unlike 'reinterpert', in this variation, -- @branch@ must be a subset of @tree@ instead of any arbitrary Which. -- Also it returns a Maybe instead of Either. -- -- This is so that the same @indices@ can be used in 'narrowN'. reinterpretN' :: forall ns branch tree. (ReinterpretN' ns branch tree) => Which tree -> Maybe (Which branch) reinterpretN' = whichN (CaseReinterpretN' @ns @_ @0 @tree) data CaseReinterpretN' (indices :: [Nat]) r (n :: Nat) (tree' :: [Type]) = CaseReinterpretN' type instance CaseResult (CaseReinterpretN' indices r n) x = r instance ReiterateN (CaseReinterpretN' indices r) n tree' where reiterateN CaseReinterpretN' = CaseReinterpretN' instance (MaybeMemberAt n' x branch, n' ~ PositionOf n indices) => Case (CaseReinterpretN' indices (Maybe (Which branch)) n) (x ': tree) where case' CaseReinterpretN' a = case natToInt @n' of 0 -> Nothing i -> Just $ Which (i - 1) (unsafeCoerce a) ------------------------------------------------------------------ -- | 'Switcher' is an instance of 'Reduce' for which __'reiterate'__s through the possibilities in a 'Which', -- delegating handling to 'Case', ensuring termination when 'Which' only contains one type. newtype Switcher c r (xs :: [Type]) = Switcher (c r xs) type instance Reduced (Switcher c r xs) = r -- | 'trial0' each type in a 'Which', and either handle the 'case'' with value discovered, or __'reiterate'__ -- trying the next type in the type list. instance ( Case (c r) (x ': x' ': xs) , Reduce (Which (x' ': xs)) (Switcher c r (x' ': xs)) , Reiterate (c r) (x : x' : xs) , r ~ CaseResult (c r) x -- This means all @r@ for all typelist must be the same @r@ ) => Reduce (Which (x ': x' ': xs)) (Switcher c r (x ': x' ': xs)) where reduce (Switcher c) v = case trial0 v of Right a -> case' c a Left v' -> reduce (Switcher (reiterate c)) v' -- GHC 8.2.1 can optimize to single case statement. See https://ghc.haskell.org/trac/ghc/ticket/12877 {-# INLINABLE reduce #-} -- This makes compiling tests a little faster than with no pragma -- | Terminating case of the loop, ensuring that a instance of @Case '[]@ -- with an empty typelist is not required. instance (Case (c r) '[x], r ~ CaseResult (c r) x) => Reduce (Which '[x]) (Switcher c r '[x]) where reduce (Switcher c) v = case obvious v of a -> case' c a -- | Allow 'Which \'[]' to be 'reinterpret''ed or 'diversify'ed into anything else -- This is safe because @Which '[]@ is uninhabited, and this is already something that -- can be done with 'impossible' instance Reduce (Which '[]) (Switcher c r '[]) where reduce _ = impossible -- | Allow 'Void' to be 'reinterpret''ed or 'diversify'ed into anything else -- This is safe because @Void@ is uninhabited, and this is already something that -- can be done with 'impossible' instance Reduce (Void) (Switcher c r '[]) where reduce _ = absurd -- | Allow 'Which \'[Void]' to be 'reinterpret''ed or 'diversify'ed into anything else -- This is safe because @Which '[Void]@ is uninhabited, and this is already something that -- can be done with 'impossible' instance Reduce (Which '[Void]) (Switcher c r '[]) where reduce _ = impossible' ------------------------------------------------------------------ -- | A friendlier constraint synonym for 'reinterpretN'. type Switch c r xs = Reduce (Which xs) (Switcher c r xs) -- | A switch/case statement for 'Which'. This is equivalent to @flip 'which'@ -- -- Use 'Case' instances like 'Data.Diverse.Cases.Cases' to apply a 'Which' of functions to a variant of values. -- -- @ -- let y = 'Data.Diverse.Which.pick' (5 :: Int) :: 'Data.Diverse.Which.Which' '[Int, Bool] -- 'Data.Diverse.Which.switch' y ( -- 'Data.Diverse.Cases.cases' (show \@Bool -- 'Data.Diverse.Many../' show \@Int -- 'Data.Diverse.Many../' 'Data.Diverse.Many.nil')) \`shouldBe` "5" -- @ -- -- Or 'Data.Diverse.CaseFunc.CaseFunc' \@'Data.Typeable.Typeable' to apply a polymorphic function that work on all 'Typeable's. -- -- @ -- let y = 'Data.Diverse.Which.pick' (5 :: Int) :: 'Data.Diverse.Which.Which' '[Int, Bool] -- 'Data.Diverse.Which.switch' y ('Data.Diverse.CaseFunc.CaseFunc' \@'Data.Typeable.Typeable' (show . typeRep . (pure \@Proxy))) \`shouldBe` "Int" -- @ -- -- Or you may use your own custom instance of 'Case'. switch :: Switch c r xs => Which xs -> c r xs -> r switch w c = reduce (Switcher c) w -- | Catamorphism for 'Which'. This is @flip 'switch'@. which :: Switch c r xs => c r xs -> Which xs -> r which = flip switch ------------------------------------------------------------------ -- | 'SwitcherN' is a variation of 'Switcher' which __'reiterateN'__s through the possibilities in a 'Which', -- delegating work to 'CaseN', ensuring termination when 'Which' only contains one type. newtype SwitcherN c r (n :: Nat) (xs :: [Type]) = SwitcherN (c r n xs) type instance Reduced (SwitcherN c r n xs) = r -- | 'trial0' each type in a 'Which', and either handle the 'case'' with value discovered, or __'reiterateN'__ -- trying the next type in the type list. instance ( Case (c r n) (x ': x' ': xs) , Reduce (Which (x' ': xs)) (SwitcherN c r (n + 1) (x' ': xs)) , ReiterateN (c r) n (x : x' : xs) , r ~ CaseResult (c r n) x -- This means all @r@ for all typelist must be the same @r@ ) => Reduce (Which (x ': x' ': xs)) (SwitcherN c r n (x ': x' ': xs)) where reduce (SwitcherN c) v = case trial0 v of Right a -> case' c a Left v' -> reduce (SwitcherN (reiterateN c)) v' -- Ghc 8.2.1 can optimize to single case statement. See https://ghc.haskell.org/trac/ghc/ticket/12877 {-# INLINABLE reduce #-} -- This makes compiling tests a little faster than with no pragma -- | Terminating case of the loop, ensuring that a instance of @Case '[]@ -- with an empty typelist is not required. -- You can't reduce 'zilch' instance (Case (c r n) '[x], r ~ CaseResult (c r n) x) => Reduce (Which '[x]) (SwitcherN c r n '[x]) where reduce (SwitcherN c) v = case obvious v of a -> case' c a -- | Catamorphism for 'Which'. This is equivalent to @flip 'switchN'@. whichN :: SwitchN w c r n xs => c r n xs -> w xs -> r whichN = flip switchN -- | A switch/case statement for 'Which'. This is equivalent to @flip 'whichN'@ -- -- Use 'Case' instances like 'Data.Diverse.Cases.CasesN' to apply a 'Which' of functions to a variant of values -- in index order. -- -- @ -- let y = 'pickN' \@0 (5 :: Int) :: 'Which' '[Int, Bool, Bool, Int] -- 'switchN' y ( -- 'Data.Diverse.Cases.casesN' (show \@Int -- 'Data.Diverse.Many../' show \@Bool -- 'Data.Diverse.Many../' show \@Bool -- 'Data.Diverse.Many../' show \@Int -- 'Data.Diverse.Many../' 'Data.Diverse.Many.nil')) \`shouldBe` "5" -- @ -- -- Or you may use your own custom instance of 'Case'. class SwitchN w c r (n :: Nat) xs where switchN :: w xs -> c r n xs -> r instance Reduce (Which xs) (SwitcherN c r n xs) => SwitchN Which c r n xs where switchN w c = reduce (SwitcherN c) w ----------------------------------------------------------------- -- | Two 'Which'es are only equal iff they both contain the equivalnet value at the same type index. instance (Switch CaseEqWhich Bool (x ': xs)) => Eq (Which (x ': xs)) where l@(Which i _) == (Which j u) = if i /= j then False else switch l (CaseEqWhich u) -- | @('zilch' == 'zilch') == True@ instance Eq (Which '[]) where _ == _ = True -- | Do not export constructor -- Stores the right Any to be compared when the correct type is discovered newtype CaseEqWhich r (xs :: [Type]) = CaseEqWhich Any type instance CaseResult (CaseEqWhich r) x = r instance Reiterate (CaseEqWhich r) (x ': xs) where reiterate (CaseEqWhich r) = CaseEqWhich r instance Eq x => Case (CaseEqWhich Bool) (x ': xs) where case' (CaseEqWhich r) l = l == unsafeCoerce r ----------------------------------------------------------------- -- | A 'Which' with a type at smaller type index is considered smaller. instance ( Switch CaseEqWhich Bool (x ': xs) , Switch CaseOrdWhich Ordering (x ': xs) ) => Ord (Which (x ': xs)) where compare l@(Which i _) (Which j u) = if i /= j then compare i j else switch l (CaseOrdWhich u) -- | @('compare' 'zilch' 'zilch') == EQ@ instance Ord (Which '[]) where compare _ _ = EQ -- | Do not export constructor -- Stores the right Any to be compared when the correct type is discovered newtype CaseOrdWhich r (xs :: [Type]) = CaseOrdWhich Any type instance CaseResult (CaseOrdWhich r) x = r instance Reiterate (CaseOrdWhich r) (x ': xs) where reiterate (CaseOrdWhich r) = CaseOrdWhich r instance Ord x => Case (CaseOrdWhich Ordering) (x ': xs) where case' (CaseOrdWhich r) l = compare l (unsafeCoerce r) ------------------------------------------------------------------ -- | @show ('pick'' \'A') == "pick \'A'"@ instance (Switch CaseShowWhich ShowS (x ': xs)) => Show (Which (x ': xs)) where showsPrec d v = showParen (d > app_prec) (which (CaseShowWhich 0) v) where app_prec = 10 instance Show (Which '[]) where showsPrec _ = impossible newtype CaseShowWhich r (xs :: [Type]) = CaseShowWhich Int type instance CaseResult (CaseShowWhich r) x = r instance Reiterate (CaseShowWhich r) (x ': xs) where reiterate (CaseShowWhich i) = CaseShowWhich (i + 1) instance Show x => Case (CaseShowWhich ShowS) (x ': xs) where case' (CaseShowWhich i) v = showString "pickN @" . showString (show i) . showChar ' ' . showsPrec (app_prec + 1) v where app_prec = 10 ------------------------------------------------------------------ class WhichRead v where whichReadPrec :: Int -> Int -> ReadPrec v -- | coerce Which to another type without incrementing Int. -- THis is because 'WhichRead' instance already increments the int coerceReadWhich :: forall x xs. Which xs -> Which (x ': xs) coerceReadWhich (Which i x) = Which i x -- | Succeed reading if the Int index match readWhich :: forall x xs. Read x => Int -> Int -> ReadPrec (Which (x ': xs)) readWhich i j = guard (i == j) >> parens (prec app_prec $ (Which i . unsafeCoerce) <$> readPrec @x) where app_prec = 10 instance Read x => WhichRead (Which '[x]) where whichReadPrec = readWhich instance (Read x, WhichRead (Which (x' ': xs))) => WhichRead (Which (x ': x' ': xs)) where whichReadPrec i j = readWhich i j <|> (coerceReadWhich <$> (whichReadPrec i (j + 1) :: ReadPrec (Which (x' ': xs)))) {-# INLINABLE whichReadPrec #-} -- This makes compiling tests a little faster than with no pragma -- | This 'Read' instance tries to read using the each type in the typelist, using the first successful type read. instance WhichRead (Which (x ': xs)) => Read (Which (x ': xs)) where readPrec = parens $ prec app_prec $ do lift $ L.expect (Ident "pickN") lift $ L.expect (Punc "@") i <- lift L.readDecP Which n v <- whichReadPrec i 0 :: ReadPrec (Which (x ': xs)) pure $ Which n v where app_prec = 10 ------------------------------------------------------------------ instance NFData (Which '[]) where rnf = impossible instance (Reduce (Which (x ': xs)) (Switcher (CaseFunc NFData) () (x ': xs))) => NFData (Which (x ': xs)) where rnf x = switch x (CaseFunc @NFData rnf) ------------------------------------------------------------------ -- class AFunctor f c xs where -- afmap :: c xs -> f xs -> f (CaseResults c xs) -- | Terminating AFunctor instance for empty type list instance AFunctor Which c '[] where afmap _ = impossible -- | Recursive AFunctor instance for non empty type list -- delegate afmap'ing the remainder to an instance of Collector' with one less type in the type list instance ( Reiterate c (a ': as) , AFunctor Which c as , Case c (a ': as) ) => AFunctor Which c (a ': as) where afmap c v = case trial0 v of Right a' -> Which 0 (unsafeCoerce (case' c a')) Left v' -> diversify0 (afmap (reiterate c) v') {-# INLINABLE afmap #-} -- This makes compiling tests a little faster than with no pragma ------------------------------------------------------------------ instance ATraversable Which c m '[] where atraverse _ = impossible instance ( Reiterate (c m) (a ': as) , ATraversable Which c m as , Case (c m) (a ': as) ) => ATraversable Which c m (a ': as) where atraverse c v = case trial0 v of Right a' -> Which 0 <$> unsafeCoerce (case' c a') Left v' -> unsafeCoerce . diversify0 <$> atraverse (reiterate c) v' {-# INLINABLE atraverse #-}
louispan/data-diverse
src/Data/Diverse/Which/Internal.hs
bsd-3-clause
35,112
0
16
7,779
7,777
4,273
3,504
434
3
module Language.Iso.AST where import Language.Iso.App import Language.Iso.Fls import Language.Iso.Ite import Language.Iso.Lam import Language.Iso.Tru import Language.Iso.Var import qualified Data.Set as S data AST = VAR String | LAM String AST | APP AST AST deriving (Eq, Show) ast2Repr :: (App repr, Lam repr, Var repr) => AST -> repr ast2Repr (VAR x) = var x ast2Repr (LAM x b) = lam x (ast2Repr b) ast2Repr (APP f x) = app (ast2Repr f) (ast2Repr x) boundVars :: AST -> S.Set String boundVars (VAR _) = S.empty boundVars (LAM x t) = S.singleton x `S.union` boundVars t boundVars (APP t t') = boundVars t `S.union` boundVars t' freeVars :: AST -> S.Set String freeVars (VAR x) = S.singleton x freeVars (LAM x t) = freeVars t S.\\ S.singleton x freeVars (APP t t') = freeVars t `S.union` freeVars t' instance Var AST where var = VAR instance Lam AST where lam = LAM instance App AST where app = APP instance Tru AST where tru = lam "t" $ lam "f" $ var "t" instance Fls AST where fls = lam "t" $ lam "f" $ var "f" instance Ite AST where ite b t = app (app b t) sub :: String -> AST -> AST -> AST sub x n v@(VAR y) | x == y = n | otherwise = v sub x n l@(LAM y b) | x /= y && y `S.notMember` freeVars n = lam y $ sub x n b | otherwise = l sub x n (APP f y) = app (sub x n f) (sub x n y) beta :: AST -> AST beta v@(VAR _) = v beta (LAM x b) = lam x (beta b) beta (APP (LAM x b) y) = sub x y b beta a@(APP (VAR _) _) = a beta a@(APP t t') = let redex = app (beta t) (beta t') in if redex == a then a else beta a
joneshf/iso
src/Language/Iso/AST.hs
bsd-3-clause
1,705
0
11
521
849
431
418
52
2
{-# LANGUAGE CPP, BangPatterns, DoAndIfThenElse, RecordWildCards #-} {-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-} ------------------------------------------------------------------------------ -- | -- Module: Database.PostgreSQL.Simple.Internal -- Copyright: (c) 2011-2012 Leon P Smith -- License: BSD3 -- Maintainer: Leon P Smith <leon@melding-monads.com> -- Stability: experimental -- -- Internal bits. This interface is less stable and can change at any time. -- In particular this means that while the rest of the postgresql-simple -- package endeavors to follow the package versioning policy, this module -- does not. Also, at the moment there are things in here that aren't -- particularly internal and are exported elsewhere; these will eventually -- disappear from this module. -- ------------------------------------------------------------------------------ module Database.PostgreSQL.Simple.Internal where import Control.Applicative import Control.Exception import Control.Concurrent.MVar import Control.Monad(MonadPlus(..)) import Data.ByteString(ByteString) import qualified Data.ByteString.Char8 as B8 import Data.Char (ord) import Data.Int (Int64) import qualified Data.IntMap as IntMap import Data.IORef import Data.Maybe(fromMaybe) import Data.String import Data.Typeable import Data.Word import Database.PostgreSQL.LibPQ(Oid(..)) import qualified Database.PostgreSQL.LibPQ as PQ import Database.PostgreSQL.LibPQ(ExecStatus(..)) import Database.PostgreSQL.Simple.Ok import Database.PostgreSQL.Simple.Types (Query(..)) import Database.PostgreSQL.Simple.TypeInfo.Types(TypeInfo) import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Reader import Control.Monad.Trans.Class import GHC.IO.Exception #if !defined(mingw32_HOST_OS) import Control.Concurrent(threadWaitRead, threadWaitWrite) #endif -- | A Field represents metadata about a particular field -- -- You don't particularly want to retain these structures for a long -- period of time, as they will retain the entire query result, not -- just the field metadata data Field = Field { result :: !PQ.Result , column :: {-# UNPACK #-} !PQ.Column , typeOid :: {-# UNPACK #-} !PQ.Oid -- ^ This returns the type oid associated with the column. Analogous -- to libpq's @PQftype@. } type TypeInfoCache = IntMap.IntMap TypeInfo data Connection = Connection { connectionHandle :: {-# UNPACK #-} !(MVar PQ.Connection) , connectionObjects :: {-# UNPACK #-} !(MVar TypeInfoCache) , connectionTempNameCounter :: {-# UNPACK #-} !(IORef Int64) } data SqlError = SqlError { sqlState :: ByteString , sqlExecStatus :: ExecStatus , sqlErrorMsg :: ByteString , sqlErrorDetail :: ByteString , sqlErrorHint :: ByteString } deriving (Show, Typeable) fatalError :: ByteString -> SqlError fatalError msg = SqlError "" FatalError msg "" "" instance Exception SqlError -- | Exception thrown if 'query' is used to perform an @INSERT@-like -- operation, or 'execute' is used to perform a @SELECT@-like operation. data QueryError = QueryError { qeMessage :: String , qeQuery :: Query } deriving (Eq, Show, Typeable) instance Exception QueryError data ConnectInfo = ConnectInfo { connectHost :: String , connectPort :: Word16 , connectUser :: String , connectPassword :: String , connectDatabase :: String } deriving (Eq,Read,Show,Typeable) -- | Default information for setting up a connection. -- -- Defaults are as follows: -- -- * Server on @localhost@ -- -- * Port on @5432@ -- -- * User @postgres@ -- -- * No password -- -- * Database @postgres@ -- -- Use as in the following example: -- -- > connect defaultConnectInfo { connectHost = "db.example.com" } defaultConnectInfo :: ConnectInfo defaultConnectInfo = ConnectInfo { connectHost = "127.0.0.1" , connectPort = 5432 , connectUser = "postgres" , connectPassword = "" , connectDatabase = "" } -- | Connect with the given username to the given database. Will throw -- an exception if it cannot connect. connect :: ConnectInfo -> IO Connection connect = connectPostgreSQL . postgreSQLConnectionString -- | Attempt to make a connection based on a libpq connection string. -- See <http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING> -- for more information. Here is an example with some -- of the most commonly used parameters: -- -- > host='db.somedomain.com' port=5432 ... -- -- This attempts to connect to @db.somedomain.com:5432@. Omitting the port -- will normally default to 5432. -- -- On systems that provide unix domain sockets, omitting the host parameter -- will cause libpq to attempt to connect via unix domain sockets. -- The default filesystem path to the socket is constructed from the -- port number and the @DEFAULT_PGSOCKET_DIR@ constant defined in the -- @pg_config_manual.h@ header file. Connecting via unix sockets tends -- to use the @peer@ authentication method, which is very secure and -- does not require a password. -- -- On Windows and other systems without unix domain sockets, omitting -- the host will default to @localhost@. -- -- > ... dbname='postgres' user='postgres' password='secret \' \\ pw' -- -- This attempts to connect to a database named @postgres@ with -- user @postgres@ and password @secret \' \\ pw@. Backslash -- characters will have to be double-quoted in literal Haskell strings, -- of course. Omitting @dbname@ and @user@ will both default to the -- system username that the client process is running as. -- -- Omitting @password@ will default to an appropriate password found -- in the @pgpass@ file, or no password at all if a matching line is -- not found. See -- <http://www.postgresql.org/docs/9.3/static/libpq-pgpass.html> for -- more information regarding this file. -- -- As all parameters are optional and the defaults are sensible, the -- empty connection string can be useful for development and -- exploratory use, assuming your system is set up appropriately. -- -- On Unix, such a setup would typically consist of a local -- postgresql server listening on port 5432, as well as a system user, -- database user, and database sharing a common name, with permissions -- granted to the user on the database. -- -- On Windows, in addition you will either need @pg_hba.conf@ -- to specify the use of the @trust@ authentication method for -- the connection, which may not be appropriate for multiuser -- or production machines, or you will need to use a @pgpass@ file -- with the @password@ or @md5@ authentication methods. -- -- See <http://www.postgresql.org/docs/9.3/static/client-authentication.html> -- for more information regarding the authentication process. -- -- SSL/TLS will typically "just work" if your postgresql server supports or -- requires it. However, note that libpq is trivially vulnerable to a MITM -- attack without setting additional SSL parameters in the connection string. -- In particular, @sslmode@ needs to set be @require@, @verify-ca@, or -- @verify-full@ to perform certificate validation. When @sslmode@ is -- @require@, then you will also need to have a @sslrootcert@ file, -- otherwise no validation of the server's identity will be performed. -- Client authentication via certificates is also possible via the -- @sslcert@ and @sslkey@ parameters. connectPostgreSQL :: ByteString -> IO Connection connectPostgreSQL connstr = do conn <- connectdb connstr stat <- PQ.status conn case stat of PQ.ConnectionOk -> do connectionHandle <- newMVar conn connectionObjects <- newMVar (IntMap.empty) connectionTempNameCounter <- newIORef 0 let wconn = Connection{..} version <- PQ.serverVersion conn let settings | version < 80200 = "SET datestyle TO ISO" | otherwise = "SET standard_conforming_strings TO on;SET datestyle TO ISO" _ <- execute_ wconn settings return wconn _ -> do msg <- maybe "connectPostgreSQL error" id <$> PQ.errorMessage conn throwIO $ fatalError msg connectdb :: ByteString -> IO PQ.Connection #if defined(mingw32_HOST_OS) connectdb = PQ.connectdb #else connectdb conninfo = do conn <- PQ.connectStart conninfo loop conn where funcName = "Database.PostgreSQL.Simple.connectPostgreSQL" loop conn = do status <- PQ.connectPoll conn case status of PQ.PollingFailed -> throwLibPQError conn "connection failed" PQ.PollingReading -> do mfd <- PQ.socket conn case mfd of Nothing -> throwIO $! fdError funcName Just fd -> do threadWaitRead fd loop conn PQ.PollingWriting -> do mfd <- PQ.socket conn case mfd of Nothing -> throwIO $! fdError funcName Just fd -> do threadWaitWrite fd loop conn PQ.PollingOk -> return conn #endif -- | Turns a 'ConnectInfo' data structure into a libpq connection string. postgreSQLConnectionString :: ConnectInfo -> ByteString postgreSQLConnectionString connectInfo = fromString connstr where connstr = str "host=" connectHost $ num "port=" connectPort $ str "user=" connectUser $ str "password=" connectPassword $ str "dbname=" connectDatabase $ [] str name field | null value = id | otherwise = showString name . quote value . space where value = field connectInfo num name field | value <= 0 = id | otherwise = showString name . shows value . space where value = field connectInfo quote str rest = '\'' : foldr delta ('\'' : rest) str where delta c cs = case c of '\\' -> '\\' : '\\' : cs '\'' -> '\\' : '\'' : cs _ -> c : cs space [] = [] space xs = ' ':xs oid2int :: Oid -> Int oid2int (Oid x) = fromIntegral x {-# INLINE oid2int #-} exec :: Connection -> ByteString -> IO PQ.Result #if defined(mingw32_HOST_OS) exec conn sql = withConnection conn $ \h -> do mres <- PQ.exec h sql case mres of Nothing -> throwLibPQError h "PQexec returned no results" Just res -> return res #else exec conn sql = withConnection conn $ \h -> do success <- PQ.sendQuery h sql if success then awaitResult h Nothing else throwLibPQError h "PQsendQuery failed" where awaitResult h mres = do mfd <- PQ.socket h case mfd of Nothing -> throwIO $! fdError "Database.PostgreSQL.Simple.Internal.exec" Just fd -> do threadWaitRead fd _ <- PQ.consumeInput h -- FIXME? getResult h mres getResult h mres = do isBusy <- PQ.isBusy h if isBusy then awaitResult h mres else do mres' <- PQ.getResult h case mres' of Nothing -> case mres of Nothing -> throwLibPQError h "PQgetResult returned no results" Just res -> return res Just res -> do status <- PQ.resultStatus res case status of PQ.EmptyQuery -> getResult h mres' PQ.CommandOk -> getResult h mres' PQ.TuplesOk -> getResult h mres' PQ.CopyOut -> return res PQ.CopyIn -> return res PQ.BadResponse -> getResult h mres' PQ.NonfatalError -> getResult h mres' PQ.FatalError -> getResult h mres' #endif -- | A version of 'execute' that does not perform query substitution. execute_ :: Connection -> Query -> IO Int64 execute_ conn q@(Query stmt) = do result <- exec conn stmt finishExecute conn q result finishExecute :: Connection -> Query -> PQ.Result -> IO Int64 finishExecute _conn q result = do status <- PQ.resultStatus result case status of PQ.EmptyQuery -> throwIO $ QueryError "execute: Empty query" q PQ.CommandOk -> do ncols <- PQ.nfields result if ncols /= 0 then throwIO $ QueryError ("execute resulted in " ++ show ncols ++ "-column result") q else do nstr <- PQ.cmdTuples result return $ case nstr of Nothing -> 0 -- is this appropriate? Just str -> toInteger str PQ.TuplesOk -> do ncols <- PQ.nfields result throwIO $ QueryError ("execute resulted in " ++ show ncols ++ "-column result") q PQ.CopyOut -> throwIO $ QueryError "execute: COPY TO is not supported" q PQ.CopyIn -> throwIO $ QueryError "execute: COPY FROM is not supported" q PQ.BadResponse -> throwResultError "execute" result status PQ.NonfatalError -> throwResultError "execute" result status PQ.FatalError -> throwResultError "execute" result status where toInteger str = B8.foldl' delta 0 str where delta acc c = if '0' <= c && c <= '9' then 10 * acc + fromIntegral (ord c - ord '0') else error ("finishExecute: not an int: " ++ B8.unpack str) throwResultError :: ByteString -> PQ.Result -> PQ.ExecStatus -> IO a throwResultError _ result status = do errormsg <- fromMaybe "" <$> PQ.resultErrorField result PQ.DiagMessagePrimary detail <- fromMaybe "" <$> PQ.resultErrorField result PQ.DiagMessageDetail hint <- fromMaybe "" <$> PQ.resultErrorField result PQ.DiagMessageHint state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate throwIO $ SqlError { sqlState = state , sqlExecStatus = status , sqlErrorMsg = errormsg , sqlErrorDetail = detail , sqlErrorHint = hint } disconnectedError :: SqlError disconnectedError = fatalError "connection disconnected" -- | Atomically perform an action with the database handle, if there is one. withConnection :: Connection -> (PQ.Connection -> IO a) -> IO a withConnection Connection{..} m = do withMVar connectionHandle $ \conn -> do if PQ.isNullConnection conn then throwIO disconnectedError else m conn close :: Connection -> IO () close Connection{..} = mask $ \restore -> (do conn <- takeMVar connectionHandle restore (PQ.finish conn) `finally` do putMVar connectionHandle =<< PQ.newNullConnection ) newNullConnection :: IO Connection newNullConnection = do connectionHandle <- newMVar =<< PQ.newNullConnection connectionObjects <- newMVar IntMap.empty connectionTempNameCounter <- newIORef 0 return Connection{..} data Row = Row { row :: {-# UNPACK #-} !PQ.Row , rowresult :: !PQ.Result } newtype RowParser a = RP { unRP :: ReaderT Row (StateT PQ.Column Conversion) a } deriving ( Functor, Applicative, Alternative, Monad ) liftRowParser :: IO a -> RowParser a liftRowParser = RP . lift . lift . liftConversion newtype Conversion a = Conversion { runConversion :: Connection -> IO (Ok a) } liftConversion :: IO a -> Conversion a liftConversion m = Conversion (\_ -> Ok <$> m) instance Functor Conversion where fmap f m = Conversion $ \conn -> (fmap . fmap) f (runConversion m conn) instance Applicative Conversion where pure a = Conversion $ \_conn -> pure (pure a) mf <*> ma = Conversion $ \conn -> do okf <- runConversion mf conn case okf of Ok f -> (fmap . fmap) f (runConversion ma conn) Errors errs -> return (Errors errs) instance Alternative Conversion where empty = Conversion $ \_conn -> pure empty ma <|> mb = Conversion $ \conn -> do oka <- runConversion ma conn case oka of Ok _ -> return oka Errors _ -> (oka <|>) <$> runConversion mb conn instance Monad Conversion where return a = Conversion $ \_conn -> return (return a) m >>= f = Conversion $ \conn -> do oka <- runConversion m conn case oka of Ok a -> runConversion (f a) conn Errors err -> return (Errors err) instance MonadPlus Conversion where mzero = empty mplus = (<|>) conversionMap :: (Ok a -> Ok b) -> Conversion a -> Conversion b conversionMap f m = Conversion $ \conn -> f <$> runConversion m conn conversionError :: Exception err => err -> Conversion a conversionError err = Conversion $ \_ -> return (Errors [SomeException err]) newTempName :: Connection -> IO Query newTempName Connection{..} = do !n <- atomicModifyIORef connectionTempNameCounter (\n -> let !n' = n+1 in (n', n')) return $! Query $ B8.pack $ "temp" ++ show n -- FIXME? What error should getNotification and getCopyData throw? fdError :: ByteString -> IOError fdError funcName = IOError { ioe_handle = Nothing, ioe_type = ResourceVanished, ioe_location = B8.unpack funcName, ioe_description = "failed to fetch file descriptor", ioe_errno = Nothing, ioe_filename = Nothing } libPQError :: ByteString -> IOError libPQError desc = IOError { ioe_handle = Nothing, ioe_type = OtherError, ioe_location = "libpq", ioe_description = B8.unpack desc, ioe_errno = Nothing, ioe_filename = Nothing } throwLibPQError :: PQ.Connection -> ByteString -> IO a throwLibPQError conn default_desc = do msg <- maybe default_desc id <$> PQ.errorMessage conn throwIO $! libPQError msg
avieth/postgresql-simple
src/Database/PostgreSQL/Simple/Internal.hs
bsd-3-clause
19,030
0
19
5,750
3,121
1,654
1,467
314
13
-- * Manipulation functions for cabal versions and version ranges {-# LANGUAGE TypeOperators , TemplateHaskell #-} module Version where import Data.Label import Distribution.Text import Distribution.Version $(mkLabels [''Version]) $(mkLabels [''VersionRange]) -- | Function to bump the nth position in a version to a higher number -- trailing version number will be discarded bumpPosition :: Int -> Version -> Version bumpPosition p = modify lVersionBranch (addPos p) where addPos 0 [] = [1] addPos 0 (v: _) = [v+1] addPos x [] = 0 : addPos (x - 1) [] addPos x (v: vs) = v : addPos (x - 1) vs previousVersion :: Version -> Version previousVersion = modify lVersionBranch mkPrevious where mkPrevious = reverse . prevHelp . reverse prevHelp [] = [] prevHelp (x:xs) = if x <= 1 then xs else (x - 1): xs -- No trailing zeros nextVersion :: Version -> Version nextVersion = modify lVersionBranch mkNext where mkNext = reverse . nextHelp . reverse nextHelp [] = [] nextHelp (x:xs) = (x + 1) : xs addVersionToRange :: Version -> VersionRange -> VersionRange addVersionToRange new r = if withinRange new r then r else let cVersion = const (thisVersion new) c2Version = const $ const (thisVersion new) in foldVersionRange' anyVersion -- any cVersion -- (==) cVersion -- > cVersion -- < cVersion -- >= cVersion -- <= (\v _ -> withinVersion $ v { versionBranch = take (length $ versionBranch v) $ versionBranch new }) -- .* c2Version -- (||) c2Version -- (&&) id -- (_) r printRange :: VersionRange -> String printRange = let sShow s = ((s ++ " ") ++) . display in foldVersionRange' "*" (sShow "==") (sShow ">") (sShow "<") (sShow ">=") (sShow "<=") (\v _ -> "== " ++ display v ++ ".*") (\v1 v2 -> v1 ++ " || " ++ v2) (\v1 v2 -> v1 ++ " && " ++ v2) (\v -> "(" ++ v ++ ")")
silkapp/bumper
src/Version.hs
bsd-3-clause
2,092
0
18
649
662
352
310
57
4
{-# OPTIONS -Wall #-} {-# LANGUAGE TypeSynonymInstances, FlexibleContexts #-} module PushdownAutomaton.Models.PDA1 ( mach, mach2 ) where import Basic.Types import Basic.Memory import Basic.MemoryImpl --(StackMem, ListMem, fillMem, Address(..)) import PushdownAutomaton.Operations import PushdownAutomaton.State import PushdownAutomaton.Machine import qualified PushdownAutomaton.Machine2 as M2 import qualified PushdownAutomaton.State2 as S2 -------------------------------------------------------------------------- --------------------------specilized model operations & models -------------------------------------------------------------------------- --------------------------------------------------------------------------- -- DPDA-I (1 push-down store) -- an exampel from Example 5.1 of Book Introduction to automata theory, languages, and computation -- Type 2: Pushdown Automaton data CState = P | Q | R deriving (Show, Eq) data InpAlp = Zero | One deriving (Show, Eq) data StackAlp = B | Z deriving (Show, Eq) trans :: [InpAlp] -> [StackAlp] -> CState -> (CState, [StackCommd StackAlp]) trans [Zero] [Z] P = (P, [Push B]) trans [Zero] [B] P = (P, [Push B]) trans [One] [Z] P = (Q, [None]) trans [One] [B] P = (Q, [None]) trans [One] [B] Q = (Q, [Pop]) trans _ [Z] Q = (R, [None]) trans a b c = error ("undefined tr: " ++ show a ++ ", " ++ show b ++ ", " ++ show c) finalState :: ListMem CState finalState = fillMem [R] input :: ListMem [InpAlp] input = fillMem [[Zero], [Zero], [One], [One], [One], [One]] instance Pointed StackAlp where pt = B initialState :: (Pointed StackAlp) => PDAStaten CState MapMem IOne StackMem StackAlp (Address Int) initialState = initialPDAStaten P B (A (0::Int)) mach :: PDAn CState MapMem IOne StackMem StackAlp (Address Int) ListMem ListMem [InpAlp] mach = PDA initialState finalState (gcompile $ translate trans) input initialState2 :: CState initialState2 = P initialMem2 :: MapMem IOne (StackMem StackAlp) initialMem2 = S2.initialStackn B emptyM' mach2 :: M2.PDAn CState MapMem IOne StackMem StackAlp ListMem ListMem [InpAlp] mach2 = M2.PDA initialState2 initialMem2 finalState (S2.gcompile $ S2.translate trans) input
davidzhulijun/TAM
PushdownAutomaton/Models/PDA1.hs
bsd-3-clause
2,202
0
12
330
682
386
296
40
1
module Provisioning where import TPM import Demo3Shared import System.IO import Data.Word import Data.Binary goldenFileName :: String goldenFileName= "goldenPcrComposite.txt" readComp :: IO TPM_PCR_COMPOSITE readComp = do handle <- openFile goldenFileName ReadMode compString <- hGetLine handle let comp :: TPM_PCR_COMPOSITE comp = read compString putStrLn $ show comp hClose handle return comp getCurrentComp :: IO TPM_PCR_COMPOSITE getCurrentComp = do let list = [0..23] :: [Word8] pcrSelect = tpm_pcr_selection 24 list compGolden <- tpm_pcr_composite tpm pcrSelect return compGolden --Helper for export doExport :: String -> TPM_PCR_COMPOSITE -> IO () doExport fileName comp = do handle <- openFile fileName WriteMode hPutStrLn handle $ show comp hClose handle --Helper for export genDoExport :: (Binary a) => String -> a -> IO () genDoExport fileName val = do encodeFile fileName val
armoredsoftware/protocol
tpm/mainline/provisioning/Provisioning.hs
bsd-3-clause
1,037
0
10
274
276
134
142
31
1
module Main where import System.IO import qualified Media.MpegTs.Packet as P import Options.Applicative import qualified Data.ByteString as BS {- Data type to hold the command line optio -} data Options = Options { input :: String , verbose :: Bool } deriving Show {- Option Parser -} parseOptions :: Parser Options parseOptions = Options <$> strArgument ( metavar "INPUT" <> help "The input file" ) <*> switch ( long "verbose" <> short 'v' <> help "Enable verbose mode" ) -- Actual program logic run :: Options -> IO () run opts = do putStrLn $ "Reading file " ++ (input opts) withBinaryFile (input opts) ReadMode (\handle -> do input <- BS.hGetContents handle let packets = P.tsPacketList input let pid_packets = filter (\p -> (P.ts_pid $ P.header p) == 256) packets putStrLn $ show pid_packets -- putStrLn $ show (tsPacketList input) -- P.printTsPacketList input 0 putStrLn "done.") main :: IO () main = execParser opts >>= run where opts = info (helper <*> parseOptions) ( fullDesc <> progDesc "Parse the specified MpegTS file" <> header "mpegts-hs - a parser for MpegTS streams" )
kevinkirkup/mpegts-hs
app/Main.hs
bsd-3-clause
1,236
0
22
331
323
167
156
32
1
{-# LANGUAGE PatternSynonyms #-} -- | Very simple and inefficient interpreter of Unison terms module Unison.Eval.Interpreter where import Data.Map (Map) import Debug.Trace import Unison.Eval import Unison.Term (Term) import Unison.Var (Var) import qualified Data.Map as M import qualified Unison.Reference as R import qualified Unison.Term as E -- | A Haskell function accepting 'arity' arguments data Primop f v = Primop { arity :: Int, call :: [Term v] -> f (Term v) } watch :: Show a => String -> a -> a watch msg a = trace (msg ++ ": " ++ show a) a -- | Produce an evaluator from a environment of 'Primop' values eval :: (Applicative f, Monad f, Var v) => Map R.Reference (Primop f v) -> Eval f v eval env = Eval whnf step where -- reduce x args | trace ("reduce:" ++ show (x:args)) False = undefined reduce (E.Lam' _ _) [] = return Nothing reduce e@(E.Lam' _ _) (arg1:args) = return $ let r = E.betaReduce (E.app e arg1) in Just (foldl E.app r args) reduce (E.Ref' h) args = case M.lookup h env of Nothing -> return Nothing Just op | length args >= arity op -> call op (take (arity op) args) >>= \e -> return . Just $ foldl E.app e (drop (arity op) args) Just _ | otherwise -> return Nothing reduce (E.App' f x) args = reduce f (x:args) reduce _ _ = return Nothing step resolveRef e = case e of E.App' f x -> do f' <- E.link resolveRef f e' <- reduce f' [x] maybe (return e) return e' E.Ref' h -> do f <- E.link resolveRef (E.ref h) e <- reduce f [] maybe (return f) return e _ -> return e whnf resolveRef e = case e of E.App' f x -> do f' <- E.link resolveRef f e' <- reduce f' [x] maybe (return e) (whnf resolveRef) e' _ -> return e
CGenie/platform
node/src/Unison/Eval/Interpreter.hs
mit
1,841
0
18
522
748
372
376
44
10
{-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# LANGUAGE CPP #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Recursive (specs, #ifndef WITH_NOSQL recursiveMigrate #endif ) where import Init #if WITH_NOSQL mkPersist persistSettings [persistUpperCase| #else share [mkPersist sqlSettings, mkMigrate "recursiveMigrate"] [persistLowerCase| #endif SubType object [MenuObject] deriving Show Eq MenuObject sub SubType Maybe deriving Show Eq |] #if WITH_NOSQL cleanDB :: ReaderT Context IO () cleanDB = do deleteWhere ([] :: [Filter MenuObject]) deleteWhere ([] :: [Filter SubType]) db :: Action IO () -> Assertion db = db' cleanDB #endif specs :: Spec specs = describe "recursive definitions" $ do it "mutually recursive" $ db $ do let m1 = MenuObject $ Just $ SubType [] let m2 = MenuObject $ Just $ SubType [m1] let m3 = MenuObject $ Just $ SubType [m2] k3 <- insert m3 m3' <- get k3 m3' @== Just m3
plow-technologies/persistent
persistent-test/src/Recursive.hs
mit
1,268
0
16
220
257
136
121
26
1
module Tiny ( resource, resource_dyn ) where import API import Data.Dynamic resource = tiny { field = "hello strange world" } resource_dyn :: Dynamic resource_dyn = toDyn resource
abuiles/turbinado-blog
tmp/dependencies/hs-plugins-1.3.1/testsuite/make/simple/Tiny.hs
bsd-3-clause
196
0
6
44
46
28
18
7
1
{-# LANGUAGE RecordWildCards #-} parseArgs = Args { equalProb = E `elem` opts , .. }
mpickering/ghc-exactprint
tests/examples/ghc710/RecordWildcard.hs
bsd-3-clause
113
0
7
44
24
15
9
5
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Halfs.Protection( UserID (..) , GroupID(..) , rootUser , rootGroup ) where import Data.Serialize import Data.Word newtype UserID = UID Word64 deriving (Show, Eq, Real, Enum, Integral, Num, Ord) instance Serialize UserID where put (UID x) = putWord64be x get = UID `fmap` getWord64be rootUser :: UserID rootUser = UID 0 -- newtype GroupID = GID Word64 deriving (Show, Eq, Real, Enum, Integral, Num, Ord) instance Serialize GroupID where put (GID x) = putWord64be x get = GID `fmap` getWord64be rootGroup :: GroupID rootGroup = GID 0
hackern/halfs
Halfs/Protection.hs
bsd-3-clause
659
0
8
167
216
121
95
22
1
-- Copyright (c) 2014-present, Facebook, Inc. -- All rights reserved. -- -- This source code is distributed under the terms of a BSD license, -- found in the LICENSE file. {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances #-} module SleepDataSource ( Sleep, sleep, ) where import Haxl.Prelude import Prelude () import Haxl.Core import Haxl.DataSource.ConcurrentIO import Control.Concurrent import Data.Hashable import Data.Typeable sleep :: Int -> GenHaxl u w Int sleep n = dataFetch (Sleep n) data Sleep deriving Typeable instance ConcurrentIO Sleep where data ConcurrentIOReq Sleep a where Sleep :: Int -> ConcurrentIOReq Sleep Int performIO (Sleep n) = threadDelay (n*1000) >> return n deriving instance Eq (ConcurrentIOReq Sleep a) deriving instance Show (ConcurrentIOReq Sleep a) instance ShowP (ConcurrentIOReq Sleep) where showp = show instance Hashable (ConcurrentIOReq Sleep a) where hashWithSalt s (Sleep n) = hashWithSalt s n
facebook/Haxl
tests/SleepDataSource.hs
bsd-3-clause
1,188
0
9
188
253
140
113
-1
-1
import qualified Data.List as L import qualified Data.Map.Strict as M solve :: String -> String -> String solve x y = if length before_last == 0 then "-1" else foldr (\a b -> a ++ " " ++ b) "" before_last where wx = map (\s -> read s :: Int) (L.words x) n = wx !! 0 k = wx !! 1 wy = L.words y m = foldr (\ele mm -> M.insertWith (+) ele 1 mm) M.empty wy before_last = L.nub $ filter filter_func wy where filter_func ele = case M.lookup ele m of Nothing -> False Just v -> if v >= k then True else False main :: IO() main = do st <- getLine sq <- getContents let t = read st :: Int q = lines sq putStr . unlines $ [solve (q !! (2 * i)) (q !! (2 * i + 1)) | i <- [0..t - 1]]
EdisonAlgorithms/HackerRank
practice/fp/recursion/filter-elements/filter-elements.hs
mit
892
0
14
376
364
192
172
22
4
{- | Module : Data.UUID.V3 Copyright : (c) 2010,2012 Antoine Latter License : BSD-style Maintainer : aslatter@gmail.com Stability : experimental Portability : portable NOTE: This module uses MD5 hashing. Unless you know you need to use this module, you should probably be using "Data.UUID.V5", which offers the same sort of functionality as this module except implemented with SHA-1 hashing. This module implements Version 3 UUIDs as specified in RFC 4122. These UUIDs identify an object within a namespace, and are deterministic. The namespace is identified by a UUID. Several sample namespaces are enclosed. -} module Data.UUID.V3 (generateNamed ,Shared.namespaceDNS ,Shared.namespaceURL ,Shared.namespaceOID ,Shared.namespaceX500 ) where import Data.Word import Data.UUID.Internal import qualified Data.UUID.Named as Shared import qualified Crypto.Hash.MD5 as MD5 -- |Generate a 'UUID' within the specified namespace out of the given -- object. -- -- Uses an MD5 hash. The UUID is built from first 128 bits of the hash of -- the namespace UUID and the name (as a series of Word8). generateNamed :: UUID -- ^Namespace -> [Word8] -- ^Object -> UUID generateNamed = Shared.generateNamed MD5.hash 3
alphaHeavy/uuid
Data/UUID/V3.hs
bsd-3-clause
1,279
0
7
258
99
65
34
14
1
module Codec.Base64 (encode, decode) where import Data.Array.Unboxed import Data.Bits import Data.Char import Data.Word -- | -- Base64 encoding. -- -- >>> encode "foo bar" -- "Zm9vIGJhcg==" -- -- prop> decode (encode xs) == xs encode :: String -> String encode = map (base64array !) . encode' . map (fromIntegral . ord) encode' :: [Word8] -> [Word8] encode' [] = [] encode' [a] = e1 a : e2 a 0 : pad : pad : [] encode' [a,b] = e1 a : e2 a b : e3 b 0 : pad : [] encode' (a:b:c:xs) = e1 a : e2 a b : e3 b c : e4 c : encode' xs e1,e4 :: Word8 -> Word8 e2,e3 :: Word8 -> Word8 -> Word8 e1 a = shiftR a 2 e2 a b = shiftL (a .&. 0x03) 4 .|. shiftR b 4 e3 b c = shiftL (b .&. 0x0f) 2 .|. shiftR c 6 e4 c = c .&. 0x3f base64 :: String base64 = ['A'..'Z']++['a'..'z']++['0'..'9']++"+/=" base64array :: UArray Word8 Char base64array = array (0,pad) $ zip [0..pad] base64 pad :: Word8 pad = 64 -- | -- Base64 decoding. -- -- >>> decode "Zm9vIGJhcg==" -- "foo bar" decode :: String -> String decode = map (chr . fromIntegral) . decode' . map ((base128array !) . fromIntegral . ord) decode' :: [Word8] -> [Word8] decode' [] = [] decode' (a:b:c:d:xs) | c == pad = d1 a b : [] | d == pad = d1 a b : d2 b c : [] | otherwise = d1 a b : d2 b c : d3 c d : decode' xs decode' _ = error "decode'" d1,d2,d3 :: Word8 -> Word8 -> Word8 d1 a b = shiftL a 2 .|. shiftR b 4 d2 b c = shiftL (b .&. 0x0f) 4 .|. shiftR c 2 d3 c d = shiftL (c .&. 0x03) 6 .|. d base128array :: UArray Word8 Word8 base128array = array (0,255) $ zip [0..255] base128 ng :: Word8 ng = 0 base128 :: [Word8] base128 = [ ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng , ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng , ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, ng, 62, ng, ng, ng, 63 , 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, ng, ng, ng, 64, ng, ng , ng, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 , 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, ng, ng, ng, ng, ng , ng, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 , 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, ng, ng, ng, ng, ng ]
arowM/unit-test-bin-example
src/Codec/Base64.hs
bsd-3-clause
2,210
0
10
613
1,202
684
518
53
1
----------------------------------------------------------------------------- -- | -- Module : Hadrian.Haskell.Cabal.Type -- Copyright : (c) Andrey Mokhov 2014-2018 -- License : MIT (see the file LICENSE) -- Maintainer : andrey.mokhov@gmail.com -- Stability : experimental -- -- Data types for storing basic Haskell package metadata, such as package name, -- version and dependencies, extracted from a Cabal file. ----------------------------------------------------------------------------- module Hadrian.Haskell.Cabal.Type where import Development.Shake.Classes import Distribution.PackageDescription import GHC.Generics import Hadrian.Package -- | Haskell package metadata extracted from a Cabal file without performing -- the resolution of package configuration flags and associated conditionals, -- which are build context specific. Note that 'packageDependencies' is an -- overappoximation of actual package dependencies; for example, both @unix@ and -- @win32@ packages may be included even if only one of them is required on the -- target OS. See 'ContextData' for metadata obtained after resolving package -- configuration flags and conditionals according to the current build context. data PackageData = PackageData { name :: PackageName , version :: String , synopsis :: String , description :: String , packageDependencies :: [Package] , genericPackageDescription :: GenericPackageDescription } deriving (Eq, Generic, Show, Typeable) -- | Haskell package metadata obtained after resolving package configuration -- flags and associated conditionals according to the current build context. -- See 'PackageData' for metadata that can be obtained without resolving package -- configuration flags and conditionals. data ContextData = ContextData { dependencies :: [PackageName] , componentId :: String , mainIs :: Maybe (String, FilePath) -- ("Main", filepath) , modules :: [String] , otherModules :: [String] , srcDirs :: [String] , depIds :: [String] , depNames :: [String] , includeDirs :: [String] , includes :: [String] , installIncludes :: [String] , extraLibs :: [String] , extraLibDirs :: [String] , asmSrcs :: [String] , cSrcs :: [String] , cmmSrcs :: [String] , hcOpts :: [String] , asmOpts :: [String] , ccOpts :: [String] , cmmOpts :: [String] , cppOpts :: [String] , ldOpts :: [String] , depIncludeDirs :: [String] , depCcOpts :: [String] , depLdOpts :: [String] , buildGhciLib :: Bool , frameworks :: [String] , packageDescription :: PackageDescription } deriving (Eq, Generic, Show, Typeable) instance Binary PackageData instance Hashable PackageData where hashWithSalt salt = hashWithSalt salt . show instance NFData PackageData instance Binary ContextData instance Hashable ContextData where hashWithSalt salt = hashWithSalt salt . show instance NFData ContextData
sdiehl/ghc
hadrian/src/Hadrian/Haskell/Cabal/Type.hs
bsd-3-clause
3,284
0
10
874
470
297
173
49
0
{-# LANGUAGE OverloadedStrings #-} {- Copyright (C) 2006-2015 John MacFarlane <jgm@berkeley.edu> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Writers.Native Copyright : Copyright (C) 2006-2015 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <jgm@berkeley.edu> Stability : alpha Portability : portable Conversion of a 'Pandoc' document to a string representation. Note: If @writerStandalone@ is @False@, only the document body is represented; otherwise, the full 'Pandoc' document, including the metadata. -} module Text.Pandoc.Writers.Native ( writeNative ) where import Text.Pandoc.Options ( WriterOptions(..) ) import Data.List ( intersperse ) import Text.Pandoc.Definition import Text.Pandoc.Pretty prettyList :: [Doc] -> Doc prettyList ds = "[" <> (cat $ intersperse (cr <> ",") $ map (nest 1) ds) <> "]" -- | Prettyprint Pandoc block element. prettyBlock :: Block -> Doc prettyBlock (BlockQuote blocks) = "BlockQuote" $$ prettyList (map prettyBlock blocks) prettyBlock (OrderedList attribs blockLists) = "OrderedList" <> space <> text (show attribs) $$ (prettyList $ map (prettyList . map prettyBlock) blockLists) prettyBlock (BulletList blockLists) = "BulletList" $$ (prettyList $ map (prettyList . map prettyBlock) blockLists) prettyBlock (DefinitionList items) = "DefinitionList" $$ (prettyList $ map deflistitem items) where deflistitem (term, defs) = "(" <> text (show term) <> "," <> cr <> nest 1 (prettyList $ map (prettyList . map prettyBlock) defs) <> ")" prettyBlock (Table caption aligns widths header rows) = "Table " <> text (show caption) <> " " <> text (show aligns) <> " " <> text (show widths) $$ prettyRow header $$ prettyList (map prettyRow rows) where prettyRow cols = prettyList (map (prettyList . map prettyBlock) cols) prettyBlock block = text $ show block -- | Prettyprint Pandoc document. writeNative :: WriterOptions -> Pandoc -> String writeNative opts (Pandoc meta blocks) = let colwidth = if writerWrapText opts then Just $ writerColumns opts else Nothing withHead = if writerStandalone opts then \bs -> text ("Pandoc (" ++ show meta ++ ")") $$ bs $$ cr else id in render colwidth $ withHead $ prettyList $ map prettyBlock blocks
gbataille/pandoc
src/Text/Pandoc/Writers/Native.hs
gpl-2.0
3,066
0
17
652
617
316
301
39
3
module Network.Wai.Session.TokyoCabinet (tokyocabinetStore, tokyocabinetStore_) where import Control.Monad import Data.ByteString (ByteString) import Control.Monad.IO.Class (liftIO, MonadIO) import Network.Wai.Session (Session, SessionStore, genSessionId) import Control.Error (hush) import qualified Data.ByteString as BS import Database.TokyoCabinet import Data.Serialize (encode, decode, Serialize) -- | Session store that keeps all content in TokyoCabinet -- -- WARNING: This session is vulnerable to sidejacking, -- use with TLS for security. tokyocabinetStore :: (TCDB a, Serialize k, Serialize v, MonadIO m) => IO ByteString -- ^ 'IO' action to generate unique session IDs -> a -- ^ TokyoCabinet handle -> SessionStore m k v tokyocabinetStore _ db (Just sk) = backend db sk tokyocabinetStore genNewKey db Nothing = genNewKey >>= backend db -- | Store using simple session ID generator based on time and 'Data.Unique' tokyocabinetStore_ :: (TCDB a, Serialize k, Serialize v, MonadIO m) => a -> SessionStore m k v tokyocabinetStore_ = tokyocabinetStore genSessionId backend :: (TCDB a, Serialize k, Serialize v, MonadIO m) => a -> ByteString -> IO (Session m k v, IO ByteString) backend db sk = return (( liftTCM . liftM (join . liftM (hush . decode)) . get db . fullKey, (\k v -> liftTCM $ put db (fullKey k) (encode v) >> return ()) ), return sk) where liftTCM = liftIO . runTCM fullKey k = sk `BS.append` encode k
singpolyma/wai-session-tokyocabinet
Network/Wai/Session/TokyoCabinet.hs
isc
1,444
19
16
238
458
251
207
25
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiWayIf #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} -- http://localhost:8001/ -- type 'q' in terminal to quit server module Web.Play.Server where import Web.Play.MVC import MVC.Extended import Control.Concurrent.Async import Control.Lens import Data.Aeson hiding ((.=)) import Data.Default import Web.Page.Html (Html) import Web.Page.Render import Web.Page.Server import MVC import qualified Pipes.Prelude as Pipes import Web.Play.Page import Web.Play.Types import Web.Socket runPlay :: (ToMessage a, FromJSON b, ToJSON b, Show b, Eq b) => Producer b IO () -> a -> PlayState -> IO PlayState runPlay prod page'' p = do aRun <- async $ runMVC p (asPipe $ mainPipe cat) (vcPlay p defaultSocketConfig prod (return ())) aServe <- async $ serve $ ok $ toResponse page'' res <- wait aRun cancel aServe return res runPlayWrapped :: (ToMessage a, FromJSON b, ToJSON b, Show b, Eq b) => Producer b IO () -> a -> PlayState -> IO (SWrap PlayState (Out b) (In b)) runPlayWrapped prod page'' p = do aRun <- async $ runMVCWrapped p (mainPipe cat) (vcPlay p defaultSocketConfig prod (return ())) aServe <- async $ serve $ ok $ toResponse page'' res <- wait aRun cancel aServe return res runPlayWrappedAuto :: (ToMessage a, FromJSON b, ToJSON b, Show b, Eq b) => Producer b IO () -> Producer (In b) IO () -> a -> PlayState -> IO (SWrap PlayState (Out b) (In b)) runPlayWrappedAuto prod auto page'' p = do aRun <- async $ runMVCWrapped p (mainPipe cat) (vcPlay p defaultSocketConfig prod auto) aServe <- async $ serve $ ok $ toResponse page'' res <- wait aRun cancel aServe return res responsePlay :: (FromJSON b,ToJSON b, Show b, Eq b) => Producer b IO () -> Html () -> PlayState -> ServerPartT IO Response responsePlay prod page'' p = do _ <- liftIO $ async $ runMVC p (asPipe $ mainPipe cat) (vcPlay defaultPlayState defaultSocketConfig prod (return ())) ok $ toResponse page'' -- tests tPlayAuto :: Int -> Producer (In [Int]) IO () -> IO (SWrap PlayState (Out [Int]) (In [Int])) tPlayAuto n auto = do let prod = MVC.each [1..n] >-> Pipes.map (:[]) p = pTotalFrames .~ Just n $ defaultPlayState runMVCWrapped p (mainPipe cat) (vcPlay p defaultSocketConfig prod auto) tGoStop :: IO (SWrap PlayState (Out [Int]) (In [Int])) tGoStop = tPlayAuto 10 $ do yield $ PlayCommand Go lift $ sleep 3.3 yield $ PlayCommand Stop lift $ sleep 1.2 yield ServerQuit testPlay' :: PlayState -> Int -> IO (SWrap PlayState (Out Int) (In Int)) testPlay' p n = runPlayWrappedAuto (MVC.each [1..n]) (return ()) (renderPage $ playWith (PlayConfig p jsEcho def def)) p testManual :: IO (SWrap PlayState (Out Int) (In Int)) testManual = testPlay' (pTotalFrames .~ Just 1000 $ defaultPlayState) 1000
tonyday567/web-play
src/Web/Play/Server.hs
mit
3,126
0
14
766
1,189
593
596
103
1
-------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings, TupleSections, LambdaCase #-} module CustomTags where import Data.Char import Data.Monoid import qualified Data.Set as S import Hakyll import Text.Pandoc.Options import System.FilePath (takeBaseName, takeFileName, takeDirectory, joinPath, splitPath, replaceExtension) import Control.Lens hiding (Context) import Control.Monad import Data.List import qualified Data.Map as M import qualified Data.MultiMap as MM import qualified Data.Text as T import Text.Printf import qualified Data.HashMap.Strict as H --import qualified Data.Tree as T import Debug.Trace import Utilities import HakyllUtils getTagsFrom :: MonadMetadata m => String -> Identifier -> m [String] getTagsFrom name identifier = do metadata <- getMetadata identifier return $ maybe [] (map trim . splitAll ",") $ lookupString name metadata -- metadata --M.lookup name metadata --H.lookup (T.pack name) buildTagsFrom :: MonadMetadata m => String -> Pattern -> (String -> Identifier) -> m Tags buildTagsFrom name = buildTagsWith (getTagsFrom name) makeTagsList :: Context String -> Tags -> Compiler String makeTagsList ctx t = do let tm = tagsMap t fmap mconcat $ mapM (buildOneTag ctx) tm buildOneTag :: Context String -> (String, [Identifier]) -> Compiler String buildOneTag ctx (s, li) = do comps <- loadAll ((foldl (.||.) "" $ map (fromGlob . toFilePath) li) .&&. hasNoVersion) compsSorted <- sortByField id "published" comps items <- applyTemplateList postItemTemplate ctx compsSorted return (printf "<p><b>%s</b></p>\n<ul>\n%s\n</ul>" s items)
holdenlee/philosophocle
src/CustomTags.hs
mit
1,783
0
15
366
458
247
211
35
1
module Parser where import Text.Parsec hiding (spaces) import Text.Parsec.String (Parser) import qualified Text.Parsec.Expr as Ex import Lexer import Expr spaces = skipMany space >> skipMany newline -- let x : int = 1 in x + 1 end -- let f (x : int, y : int) : int = x + y in f 1 1 end letin :: Parser Expr letin = do reserved "let" x <- identifier ps <- optionMaybe $ parens $ sepBy idenannotation (char ',' >> spaces) reservedOp ":" t <- ty reservedOp "=" e1 <- expr reserved "in" e2 <- expr return $ ELet x t ps e1 e2 letglob :: Parser Defi letglob = do reserved "let" x <- identifier ps <- optionMaybe $ parens $ sepBy idenannotation (char ',' >> spaces) reservedOp ":" t <- ty reservedOp "=" e <- expr return $ DGlobLet x t ps e {- case x : nat of Z -> Z ; S (n : nat) -> n case xs : natList of nil -> Z ; cons y ys -> y -} inductivecase :: Parser Expr inductivecase = do reserved "case" x <- exprannotation reserved "of" cs <- sepBy1 casematch (spaces >> char ';' >> spaces) return $ ECase (EApp (EUnfold (snd x)) [fst x]) cs casematch :: Parser (Sym, ([Sym], Expr)) casematch = do x <- many1 identifier reservedOp "->" e <- expr case x of x : xs -> return $ (x, (xs, e)) {- observe natStream as head -> Z ; tail -> tail ns -} observe :: Parser Expr observe = do reserved "observe" t <- ty reserved "as" os <- sepBy1 observation (spaces >> char ';' >> spaces) return $ EObserve t os observation :: Parser (Sym, Expr) observation = do x <- identifier reservedOp "->" e <- expr return (x, e) {- data nat = Z | S nat -} inductivedata :: Parser Defi inductivedata = do reserved "data" x <- identifier reservedOp "=" cs <- braces $ sepBy1 (dataconstructor x) (spaces >> char '|' >> spaces) return $ DData x (TRecInd x (TVari cs)) dataconstructor :: String -> Parser (Sym, [Type]) dataconstructor n = do x <- identifier ts <- sepBy ((try $ rectypevar n) <|> ty) spaces return (x, ts) {- codata natStream = head nat | tail natStream -} codata :: Parser Defi codata = do reserved "codata" x <- identifier reservedOp "=" ds <- braces $ sepBy1 (codatadestructor x) (spaces >> char '|' >> spaces) return $ DCodata x (TRecCoind x ds) codatadestructor :: String -> Parser (Sym, Type) codatadestructor n = do x <- identifier ts <- ((try $ rectypevar n) <|> ty) return (x, ts) exprannotation :: Parser (Expr, Type) exprannotation = do e <- expr reservedOp ":" t <- ty return (e, t) idenannotation :: Parser (Sym, Type) idenannotation = do x <- identifier reservedOp ":" t <- ty return (x, t) funapp :: Parser Expr funapp = do f <- exprtail spaces as <- parens $ sepBy1 expr (spaces >> char ',' >> spaces) return $ EApp f as var :: Parser Expr var = do x <- identifier return $ EVar x unittype :: Parser Type unittype = spaces >> string "Unit" >> spaces >> (return TUnit) unitexpr :: Parser Expr unitexpr = spaces >> string "()" >> spaces >> (return EUnit) globaltypevar :: Parser Type globaltypevar = do x <- identifier return $ TGlobTypeVar x ty :: Parser Type ty = (try unittype) <|> globaltypevar <|> arrowType rectypevar :: String -> Parser Type rectypevar s = string s >> (return $ TRecTypeVar s) arrowType :: Parser Type arrowType = do ts <- parens $ sepBy1 ty (reservedOp "->") case reverse ts of x : xs -> return $ TArr (reverse xs) x expr :: Parser Expr expr = try funapp <|> exprtail exprtail :: Parser Expr exprtail = (try letin) <|> inductivecase <|> observe <|> unitexpr <|> try var defi :: Parser Defi defi = inductivedata <|> codata <|> letglob prog :: Parser Expr prog = do es <- sepBy defi spaces eof return $ ERoot es readExpr :: String -> Either ParseError Expr readExpr input = parse prog "findus" input letExample = "let x : (nat -> Unit) = Z in S (Z)" letGlobExample1 = "let x : Unit = f (Z)" letGlobExample2 = "let y : Unit = x (S (Z))" letFunExample = "let f (x : int, y : int) : int = () in ()" caseExample = "case xs : natList of " ++ "nil -> Z ;" ++ "cons y ys -> S Z" observeExample = "observe natStream as " ++ "head -> Z;" ++ "tail -> fib" natEx = "data nat = {" ++ "Z " ++ "| S nat}" dataNatListExample = "data natList = " ++ "nil" ++ "cons nat natList" natStreamEx = "codata natStream = " ++ " {head nat" ++ "| tail natStream}" testEx = unlines [natEx, natStreamEx, letExample]
tdidriksen/copatterns
src/findus/parser.hs
mit
4,570
0
14
1,188
1,579
769
810
159
1
module HeatMapTest where import Test.Hspec import TestData import HeatMap.PIFM import Util.Utils heatmap_tests = heat_point_tests testHeatMap = blankHeatMap testState heat_point_tests = describe "make sure point heating works" $ do it "test 1 point heats correctly" $ (getCost $ findTile (2,1) $ heatPoint testState (1,1) 3 testHeatMap ) `shouldBe` 2 where findTile p heatmap = head $ filter (\(PointValue testpoint _) -> testpoint == p) heatmap
octopuscabbage/OctoVindiniumBots
test/HeatMapTest.hs
mit
458
0
14
76
139
75
64
10
1
--import Control.Parallel -- main = a `par` b `par` c `pseq` print (a + b + c) -- where -- a = ack 3 10 -- b = fac 42 -- c = fib 34 --fac 0 = 1 --fac n = n * fac (n-1) --ack 0 n = n+1 --ack m 0 = ack(m-1) 1 --ack m n = ack (m-1 ) (ack m (n-1)) --fib 0 = 1 --fib 1 = 1 --fib n = fib(n -1) + fib(n-2) import Control.Parallel main = a `par` b `par` c `pseq` print (a + b + c) where a = ack 3 10 b = fac 42 c = fib 34 fac 0 = 1 fac n = n * fac (n-1) ack 0 n = n+1 ack m 0 = ack (m-1) 1 ack m n = ack (m-1) (ack m (n-1)) fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2)
super1ha1/haskell
src/function.hs
mit
614
0
9
208
236
129
107
13
1
{-# LANGUAGE OverloadedStrings #-} module System.Process.BetterSpec (main, spec) where import Test.Hspec import System.IO import System.IO.Silently import System.Process.Better main :: IO () main = hspec spec spec :: Spec spec = do describe "readProcess" $ do it "can be used with RawCommand" $ do readProcess (RawCommand "echo" ["foo"]) "" `shouldReturn` "foo\n" it "can be used with ShellCommand" $ do readProcess (ShellCommand "echo foo") "" `shouldReturn` "foo\n" it "can be used with a String as command" $ do readProcess "echo foo" "" `shouldReturn` "foo\n" context "when specified command does not exist" $ do it "throws an exception" $ do hSilence [stderr] (readProcess "foo" "") `shouldThrow` anyIOException
sol/better-process
test/System/Process/BetterSpec.hs
mit
814
0
19
201
210
107
103
20
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Data.Functor ((<$>)) import Data.List (isPrefixOf) import Data.Monoid ((<>)) import Data.Text (pack, unpack, replace, empty) import qualified Data.Set as S import Text.Pandoc.Options import Skylighting.Styles import Hakyll main :: IO () main = hakyll $ do -- Build tags tags <- buildTags "posts/*" (fromCapture "tags/*.html") -- Compress CSS match "css/*" $ do route idRoute compile compressCssCompiler match "js/*" $ do route idRoute compile copyFileCompiler -- Copy Files match "files/**" $ do route idRoute compile copyFileCompiler -- Render posts match "posts/*" $ do route $ setExtension ".html" compile $ myPandocCompiler >>= loadAndApplyTemplate "templates/post.html" (tagsCtx tags) >>= (externalizeUrls $ feedRoot feedConfiguration) >>= saveSnapshot "content" >>= (unExternalizeUrls $ feedRoot feedConfiguration) >>= loadAndApplyTemplate "templates/base.html" (tagsCtx tags) >>= relativizeUrls -- Render posts list create ["posts.html"] $ do route idRoute compile $ do posts <- loadAll "posts/*" sorted <- recentFirst posts itemTpl <- loadBody "templates/postitem.html" list <- applyTemplateList itemTpl postCtx sorted makeItem list >>= loadAndApplyTemplate "templates/posts.html" allPostsCtx >>= loadAndApplyTemplate "templates/base.html" allPostsCtx >>= relativizeUrls -- Index create ["index.html"] $ do route idRoute compile $ do posts <- loadAll "posts/*" sorted <- take 10 <$> recentFirst posts itemTpl <- loadBody "templates/postitem.html" list <- applyTemplateList itemTpl postCtx sorted makeItem list >>= loadAndApplyTemplate "templates/index.html" (homeCtx tags list) >>= loadAndApplyTemplate "templates/base.html" (homeCtx tags list) >>= relativizeUrls -- Post tags tagsRules tags $ \tag pattern -> do let title = "Posts tagged " ++ tag route idRoute compile $ do list <- postList tags pattern recentFirst makeItem "" >>= loadAndApplyTemplate "templates/posts.html" (constField "title" title <> constField "body" list <> defaultContext) >>= loadAndApplyTemplate "templates/base.html" (constField "title" title <> defaultContext) >>= relativizeUrls -- Render RSS feed create ["rss.xml"] $ do route idRoute compile $ do posts <- loadAllSnapshots "posts/*" "content" sorted <- take 10 <$> recentFirst posts renderRss feedConfiguration feedCtx (take 10 sorted) create ["atom.xml"] $ do route idRoute compile $ do posts <- loadAllSnapshots "posts/*" "content" sorted <- take 10 <$> recentFirst posts renderAtom feedConfiguration feedCtx sorted -- Read templates match "templates/*" $ compile templateCompiler postCtx :: Context String postCtx = dateField "date" "%B %e, %Y" <> defaultContext allPostsCtx :: Context String allPostsCtx = constField "title" "All posts" <> postCtx homeCtx :: Tags -> String -> Context String homeCtx tags list = constField "posts" list <> constField "title" "Index" <> field "taglist" (\_ -> renderTagList tags) <> defaultContext feedCtx :: Context String feedCtx = bodyField "description" <> postCtx tagsCtx :: Tags -> Context String tagsCtx tags = tagsField "prettytags" tags <> postCtx feedConfiguration :: FeedConfiguration feedConfiguration = FeedConfiguration { feedTitle = "clrnd's - RSS feed" , feedDescription = "Soy un pibe de Lanús al que le gustan los cartogramas y Haskell.\n Estudio Cs. de la Computación en la UBA y el flan me gusta con crema." , feedAuthorName = "Ezequiel A. Alvarez" , feedAuthorEmail = "welcometothechango@gmail.com" , feedRoot = "http://clrnd.com.ar" } externalizeUrls :: String -> Item String -> Compiler (Item String) externalizeUrls root item = return $ fmap (externalizeUrlsWith root) item externalizeUrlsWith :: String -> String -> String externalizeUrlsWith root = withUrls ext where ext x = if isExternal x then x else root ++ x -- TODO: clean me unExternalizeUrls :: String -> Item String -> Compiler (Item String) unExternalizeUrls root item = return $ fmap (unExternalizeUrlsWith root) item unExternalizeUrlsWith :: String -> String -> String unExternalizeUrlsWith root = withUrls unExt where unExt x = if root `isPrefixOf` x then unpack $ replace (pack root) empty (pack x) else x postList :: Tags -> Pattern -> ([Item String] -> Compiler [Item String]) -> Compiler String postList tags pattern preprocess' = do postItemTpl <- loadBody "templates/postitem.html" posts <- loadAll pattern processed <- preprocess' posts applyTemplateList postItemTpl (tagsCtx tags) processed myPandocCompiler :: Compiler (Item String) myPandocCompiler = pandocCompilerWith defaultHakyllReaderOptions defaultHakyllWriterOptions { writerHighlightStyle = Just pygments , writerHTMLMathMethod = PlainMath , writerEmailObfuscation = NoObfuscation }
alvare/clrnds-blog
Main.hs
mit
5,739
0
22
1,687
1,343
644
699
136
2
module SemiGroup13 where import Data.Semigroup import Test.QuickCheck hiding (Failure, Success) import SemiGroupAssociativeLaw import Test.QuickCheck.Gen (oneof) import ArbitrarySum import SemiGroup11 newtype AccumulateBoth a b = AccumulateBoth (Validation a b) deriving (Eq, Show) instance (Semigroup a, Semigroup b) => Semigroup (AccumulateBoth a b) where AccumulateBoth(Success x) <> AccumulateBoth(Success y) = AccumulateBoth(Success (x <> y)) AccumulateBoth(Failure x) <> AccumulateBoth(Failure y) = AccumulateBoth(Failure (x <> y)) AccumulateBoth(Failure x) <> _ = AccumulateBoth(Failure x) _ <> v = v instance (Arbitrary a, Arbitrary b) => Arbitrary (AccumulateBoth a b) where arbitrary = do x <- arbitrary y <- arbitrary oneof [return $ AccumulateBoth(Failure x), return $ AccumulateBoth(Success y)] type AccumulateBothAssoc = AccumulateBoth (Sum Int) (Sum Int) -> AccumulateBoth (Sum Int) (Sum Int) -> AccumulateBoth (Sum Int) (Sum Int) -> Bool main :: IO () main = quickCheck (semigroupAssoc :: AccumulateBothAssoc)
NickAger/LearningHaskell
HaskellProgrammingFromFirstPrinciples/Chapter15.hsproj/SemiGroup13.hs
mit
1,083
0
13
192
414
211
203
23
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} module Static where import CMark import Data.FileEmbed import Data.Text (Text) import qualified Data.Text.Encoding as T introHtml :: Text introHtml = commonmarkToHtml [] $ T.decodeUtf8 $(embedFile "src/Static/markdown/intro.md") enDocHtml :: Text enDocHtml = commonmarkToHtml [] $ T.decodeUtf8 $(embedFile "src/Static/markdown/enDoc.md") cnDocHtml :: Text cnDocHtml = commonmarkToHtml [] $ T.decodeUtf8 $(embedFile "src/Static/markdown/cnDoc.md") indexScript :: Text indexScript = T.decodeUtf8 $(embedFile "src/Static/dist/index.js") docScript :: Text docScript = T.decodeUtf8 $(embedFile "src/Static/dist/doc.js") searchScript :: Text searchScript = T.decodeUtf8 $(embedFile "src/Static/dist/search.js") userPageScript :: Text userPageScript = T.decodeUtf8 $(embedFile "src/Static/dist/user.js") snippetScript :: Text snippetScript = T.decodeUtf8 $(embedFile "src/Static/dist/snippet.js") loginScript :: Text loginScript = T.decodeUtf8 $(embedFile "src/Static/dist/login.js") aceScriptCdnUrl :: Text aceScriptCdnUrl = "http://cs0.meituan.net/cf/ace/1.2.0/ace.js" coffeeScriptCdnUrl :: Text coffeeScriptCdnUrl = "//coffeescript.org/extras/coffee-script.js" liveScriptCdnUrl :: Text liveScriptCdnUrl = "http://cs0.meituan.net/cf/livescript/1.4.0/livescript-min.js" marxCssCDNUrl :: Text marxCssCDNUrl = "http://cs0.meituan.net/cf/marx/1.3.0/marx.min.css" baseCss :: Text baseCss = T.decodeUtf8 $(embedFile "src/Static/css/base.css")
winterland1989/jsmServer
src/Static.hs
mit
1,592
0
9
203
321
170
151
36
1
module GHCJS.DOM.SVGAnimatedNumberList ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SVGAnimatedNumberList.hs
mit
51
0
3
7
10
7
3
1
0
-- | Public Module -- module Network.AWS.Wolf ( module Exports ) where import Network.AWS.Wolf.Act as Exports import Network.AWS.Wolf.Decide as Exports import Network.AWS.Wolf.Prelude as Exports
mfine/wolf
src/Network/AWS/Wolf.hs
mit
205
0
4
34
42
32
10
5
0
{-# LANGUAGE NoImplicitPrelude #-} module Main ( main ) where import Graphics.Caramia import Graphics.Caramia.Prelude hiding ( init ) import Graphics.UI.SDL import Data.Bits import Foreign.C.String main :: IO () main = withCString "smoke-test" $ \cstr -> do _ <- init SDL_INIT_VIDEO _ <- glSetAttribute SDL_GL_CONTEXT_MAJOR_VERSION 3 _ <- glSetAttribute SDL_GL_CONTEXT_MINOR_VERSION 3 _ <- glSetAttribute SDL_GL_CONTEXT_PROFILE_MASK SDL_GL_CONTEXT_PROFILE_CORE _ <- glSetAttribute SDL_GL_CONTEXT_FLAGS SDL_GL_CONTEXT_DEBUG_FLAG window <- createWindow cstr SDL_WINDOWPOS_UNDEFINED SDL_WINDOWPOS_UNDEFINED 500 500 (SDL_WINDOW_OPENGL .|. SDL_WINDOW_SHOWN) _ <- glCreateContext window giveContext $ do putStrLn "Attempting to create all sorts of textures..." putStrLn "(check OpenGL debug log to see that everything works)" for_ [(topo, format) | topo <- topologies, format <- formats] $ \(topo, format) -> do print (topo, format) void $ newTexture textureSpecification { topology = topo , imageFormat = format , mipmapLevels = 4 } runPendingFinalizers topologies :: [Topology] topologies = [Tex1D { width1D = 256 } ,Tex2D { height2D = 512, width2D = 512 } ,Tex3D { width3D = 256, height3D = 256, depth3D = 4 } ,Tex1DArray { width1DArray = 64, layers1D = 100 } ,Tex2DArray { width2DArray = 32, height2DArray = 64, layers2D = 19 } ,Tex2DMultisample { width2DMS = 1024, height2DMS = 64 , samples2DMS = 4 , fixedSampleLocations2DMS = False } ,Tex2DMultisample { width2DMS = 1024, height2DMS = 64 , samples2DMS = 4 , fixedSampleLocations2DMS = True } ,Tex2DMultisampleArray { width2DMSArray = 1024, height2DMSArray = 64 , layers2DMS = 2 , samples2DMSArray = 4 , fixedSampleLocations2DMSArray = False } ,Tex2DMultisampleArray { width2DMSArray = 1024, height2DMSArray = 64 , layers2DMS = 2 , samples2DMSArray = 4 , fixedSampleLocations2DMSArray = True } ,TexCube { widthCube = 512 }] formats :: [ImageFormat] formats = [ R8 , R8I , R8UI , R16 , R16I , R16UI , R16F , R32F , R32I , R32UI , RG8 , RG8I , RG8UI , RG16 , RG16I , RG16UI , RG16F , RG32F , RG32I , RG32UI , R11F_G11F_B10F , RGBA32F , RGBA32I , RGBA32UI , RGBA16 , RGBA16F , RGBA16I , RGBA16UI , RGBA8 , RGBA8UI , SRGB8_ALPHA8 , RGB10_A2 , RGB32F , RGB32I , RGB32UI , RGB16F , RGB16I , RGB16UI , RGB16 , RGB8 , RGB8I , RGB8UI , SRGB8 , RGB9_E5 , COMPRESSED_RG_RGTC2 , COMPRESSED_SIGNED_RG_RGTC2 , COMPRESSED_RED_RGTC1 , COMPRESSED_SIGNED_RED_RGTC1 , COMPRESSED_RGB_S3TC_DXT1 , COMPRESSED_RGBA_S3TC_DXT1 , COMPRESSED_RGBA_S3TC_DXT3 , COMPRESSED_RGBA_S3TC_DXT5 , COMPRESSED_SRGB_S3TC_DXT1 , COMPRESSED_SRGB_ALPHA_S3TC_DXT1 , COMPRESSED_SRGB_ALPHA_S3TC_DXT3 , COMPRESSED_SRGB_ALPHA_S3TC_DXT5 , DEPTH_COMPONENT32 , DEPTH_COMPONENT32F , DEPTH_COMPONENT24 , DEPTH_COMPONENT16 , DEPTH32F_STENCIL8 , DEPTH24_STENCIL8]
Noeda/caramia
demos/textures/Main.hs
mit
3,576
0
19
1,213
718
430
288
117
1
{- Paranoid Pirate Pattern queue in Haskell. Uses heartbeating to detect crashed or blocked workers. -} module Main where import System.ZMQ4.Monadic import ZHelpers import Control.Monad (when, forM_) import Control.Applicative ((<$>)) import System.IO (hSetEncoding, stdout, utf8) import Data.ByteString.Char8 (pack, unpack, empty) import qualified Data.List.NonEmpty as N type SockID = String data Worker = Worker { sockID :: SockID , expiry :: Integer } deriving (Show) heartbeatLiveness = 3 heartbeatInterval_ms = 1000 pppReady = "\001" pppHeartbeat = "\002" main :: IO () main = runZMQ $ do frontend <- socket Router bind frontend "tcp://*:5555" backend <- socket Router bind backend "tcp://*:5556" liftIO $ hSetEncoding stdout utf8 heartbeat_at <- liftIO $ nextHeartbeatTime_ms heartbeatInterval_ms pollPeers frontend backend [] heartbeat_at createWorker :: SockID -> IO Worker createWorker id = do currTime <- currentTime_ms let expiry = currTime + heartbeatInterval_ms * heartbeatLiveness return (Worker id expiry) pollPeers :: Socket z Router -> Socket z Router -> [Worker] -> Integer -> ZMQ z () pollPeers frontend backend workers heartbeat_at = do let toPoll = getPollList workers evts <- poll (fromInteger heartbeatInterval_ms) toPoll workers' <- getBackend backend frontend evts workers workers'' <- getFrontend frontend backend evts workers' newHeartbeatAt <- heartbeat backend workers'' heartbeat_at workersPurged <- purge workers'' pollPeers frontend backend workersPurged newHeartbeatAt where getPollList [] = [Sock backend [In] Nothing] getPollList _ = [Sock backend [In] Nothing, Sock frontend [In] Nothing] getBackend :: Socket z Router -> Socket z Router -> [[Event]] -> [Worker] -> ZMQ z ([Worker]) getBackend backend frontend evts workers = if (In `elem` (evts !! 0)) then do frame <- receiveMulti backend let wkrID = frame !! 0 msg = frame !! 1 if ((length frame) == 2) -- PPP message then when (unpack msg `notElem` [pppReady, pppHeartbeat]) $ do liftIO $ putStrLn $ "E: Invalid message from worker " ++ (unpack msg) else do -- Route the message to the client liftIO $ putStrLn "I: Sending normal message to client" let id = frame !! 1 msg = frame !! 3 send frontend [SendMore] id send frontend [SendMore] empty send frontend [] msg newWorker <- liftIO $ createWorker $ unpack wkrID return $ workers ++ [newWorker] else return workers getFrontend :: Socket z Router -> Socket z Router -> [[Event]] -> [Worker] -> ZMQ z ([Worker]) getFrontend frontend backend evts workers = if (length evts > 1 && In `elem` (evts !! 1)) then do -- Route message to workers frame <- receiveMulti frontend let wkrID = sockID . head $ workers send backend [SendMore] (pack wkrID) send backend [SendMore] empty sendMulti backend (N.fromList frame) return $ tail workers else return workers heartbeat :: Socket z Router -> [Worker] -> Integer -> ZMQ z Integer heartbeat backend workers heartbeat_at = do currTime <- liftIO currentTime_ms if (currTime >= heartbeat_at) then do forM_ workers (\worker -> do send backend [SendMore] (pack $ sockID worker) send backend [SendMore] empty send backend [] (pack pppHeartbeat) liftIO $ putStrLn $ "I: sending heartbeat to '" ++ (sockID worker) ++ "'") liftIO $ nextHeartbeatTime_ms heartbeatInterval_ms else return heartbeat_at purge :: [Worker] -> ZMQ z ([Worker]) purge workers = do currTime <- liftIO currentTime_ms return $ filter (\wkr -> expiry wkr > currTime) workers
soscpd/bee
root/tests/zguide/examples/Haskell/ppqueue.hs
mit
4,505
0
20
1,612
1,233
619
614
92
6
{-# LANGUAGE NoMonomorphismRestriction #-} module Plugins.Gallery.Gallery.Manual56 where import Diagrams.Prelude -- c :: Diagram a R2 c = circle 5 # scaleX 2 # rotateBy (1/14) # lw 0.03 -- Generated by fair dice roll, guaranteed to be random points = map p2 $ [ (0.8936218079179525,6.501173563301563) , (0.33932828810065985,9.06458375044167) , (2.12546952534467,4.603130561299622) , (-8.036711369641125,6.741718165576458) , (-9.636495308950543,-8.960315063595772) , (-5.125008672475815,-4.196763141080737) , (-8.740284494124353,-1.748269759118557) , (-2.7303729625418782,-9.902752498164773) , (-1.6317121405154467,-6.026127282530069) , (-3.363167801871896,7.5571909081190825) , (5.109759075567126,-5.433154460042715) , (8.492015791125596,-9.813023637980223) , (7.762080919928849,8.340037921443582) , (-6.8589746952056885,3.9604472182691097) , (-0.6083773449063301,-3.7738202372565866) , (1.3444943726062775,1.1363744735717773) , (0.13720748480409384,8.718934659846127) , (-5.091010760515928,-8.887260649353266) , (-5.828490639105439,-9.392594425007701) , (0.7190148020163178,1.4832069771364331) ] mkPoint p = (p, circle 0.3 # lw 0 # fc (case sample (c :: D R2) p of Any True -> red Any False -> blue ) ) example = c <> position (map mkPoint points)
andrey013/pluginstest
Plugins/Gallery/Gallery/Manual56.hs
mit
1,541
0
12
413
376
220
156
31
2
module HTMLEntities.Prelude ( module Exports, ) where -- base ------------------------- import Control.Applicative as Exports hiding (WrappedArrow(..)) import Control.Arrow as Exports hiding (first, second) import Control.Category as Exports import Control.Concurrent as Exports import Control.Exception as Exports import Control.Monad as Exports hiding (fail, mapM_, sequence_, forM_, msum, mapM, sequence, forM) import Control.Monad.IO.Class as Exports import Control.Monad.Fail as Exports import Control.Monad.Fix as Exports hiding (fix) import Control.Monad.ST as Exports import Data.Bifunctor as Exports import Data.Bits as Exports import Data.Bool as Exports import Data.Char as Exports import Data.Coerce as Exports import Data.Complex as Exports import Data.Data as Exports import Data.Dynamic as Exports import Data.Either as Exports import Data.Fixed as Exports import Data.Foldable as Exports hiding (toList) import Data.Function as Exports hiding (id, (.)) import Data.Functor as Exports import Data.Functor.Compose as Exports import Data.Int as Exports import Data.IORef as Exports import Data.Ix as Exports import Data.List as Exports hiding (sortOn, isSubsequenceOf, uncons, concat, foldr, foldl1, maximum, minimum, product, sum, all, and, any, concatMap, elem, foldl, foldr1, notElem, or, find, maximumBy, minimumBy, mapAccumL, mapAccumR, foldl') import Data.List.NonEmpty as Exports (NonEmpty(..)) import Data.Maybe as Exports import Data.Monoid as Exports hiding (Alt, (<>)) import Data.Ord as Exports import Data.Proxy as Exports import Data.Ratio as Exports import Data.Semigroup as Exports hiding (First(..), Last(..)) import Data.STRef as Exports import Data.String as Exports import Data.Traversable as Exports import Data.Tuple as Exports import Data.Unique as Exports import Data.Version as Exports import Data.Void as Exports import Data.Word as Exports import Debug.Trace as Exports import Foreign.ForeignPtr as Exports import Foreign.Ptr as Exports import Foreign.StablePtr as Exports import Foreign.Storable as Exports import GHC.Conc as Exports hiding (orElse, withMVar, threadWaitWriteSTM, threadWaitWrite, threadWaitReadSTM, threadWaitRead) import GHC.Exts as Exports (IsList(..), lazy, inline, sortWith, groupWith) import GHC.Generics as Exports (Generic) import GHC.IO.Exception as Exports import GHC.OverloadedLabels as Exports import Numeric as Exports import Prelude as Exports hiding (Read, fail, concat, foldr, mapM_, sequence_, foldl1, maximum, minimum, product, sum, all, and, any, concatMap, elem, foldl, foldr1, notElem, or, mapM, sequence, id, (.)) import System.Environment as Exports import System.Exit as Exports import System.IO as Exports (Handle, hClose) import System.IO.Error as Exports import System.IO.Unsafe as Exports import System.Mem as Exports import System.Mem.StableName as Exports import System.Timeout as Exports import Text.ParserCombinators.ReadP as Exports (ReadP, readP_to_S, readS_to_P) import Text.ParserCombinators.ReadPrec as Exports (ReadPrec, readPrec_to_P, readP_to_Prec, readPrec_to_S, readS_to_Prec) import Text.Printf as Exports (printf, hPrintf) import Unsafe.Coerce as Exports -- text ------------------------- import Data.Text as Exports (Text)
nikita-volkov/html-entities
library/HTMLEntities/Prelude.hs
mit
3,229
0
6
394
859
603
256
71
0
{-# LANGUAGE OverloadedStrings #-} {-| Game CUI implemented using [brick](https://github.com/jtdaugherty/brick/). -} module Game.H2048.UI.Brick ( main ) where import Brick import Brick.Widgets.Border import Brick.Widgets.Center import Data.Functor import Data.List import Data.String import Graphics.Vty.Attributes import Graphics.Vty.Input.Events import System.Random.TF import qualified Data.Map.Strict as M import Game.H2048.Gameplay data RName = RBoard deriving (Eq, Ord) type AppState = Gameplay tierAttr :: Int -> AttrName tierAttr = ("tier" <>) . fromString . show boardWidget :: AppState -> Widget RName boardWidget s = joinBorders . border $ grid where bd = _gpBoard s grid = hLimit (hMax*4+3) $ vBox (intersperse hBorder (row <$> [0..3])) row :: Int -> Widget RName row r = vLimit 1 $ hBox (intersperse vBorder (cell r <$> [0..3])) contentSample = " 2048 " :: String hMax = length contentSample cell :: Int -> Int -> Widget RName cell r c = vLimit 1 . hLimit hMax $ cellW where mVal = bd M.!? (r,c) cellW = case mVal of Nothing -> fill ' ' Just ce | tier <- _cTier ce -> withAttr (tierAttr tier) . padLeft Max $ str (show (cellToInt ce) <> " ") ui :: AppState -> Widget RName ui s = center $ hCenter (boardWidget s) <=> hCenter (str $ "Current Score: " <> show score) <=> hCenter (str ctrlHelpMsg) where score = _gpScore s won = hasWon s alive = isAlive s moveHelp = "i / k / j / l / arrow keys to move, " commonHelp = "q to quit, r to restart." {- TODO: this starts getting awkward, perhaps time to split the widget. -} ctrlHelpMsg = if not alive then (if won then "You won, but no more moves. " else "No more moves, game over. ") <> commonHelp else (if won then "You've won! " else "") <> moveHelp <> commonHelp handleEvent :: AppState -> BrickEvent RName e -> EventM RName (Next AppState) handleEvent s e = case e of VtyEvent (EvKey (KChar 'q') []) -> halt s VtyEvent (EvKey (KChar 'r') []) -> let initState = mkGameplay (_gpGen s) (_gpRule s) in continue (newGame initState) VtyEvent (EvKey k []) | Just dir <- getMove k , Just gp' <- stepGame dir s -> continue gp' _ -> continue s getMove :: Key -> Maybe Dir getMove KUp = Just DUp getMove KDown = Just DDown getMove KLeft = Just DLeft getMove KRight = Just DRight getMove (KChar 'i') = Just DUp getMove (KChar 'k') = Just DDown getMove (KChar 'j') = Just DLeft getMove (KChar 'l') = Just DRight getMove _ = Nothing -- | The entry for the CUI, a fancier and more practical one. main :: IO () main = do g <- newTFGen let initState = mkGameplay g standardGameRule app = App { appDraw = \s -> [ui s] , appHandleEvent = handleEvent , appStartEvent = pure , appAttrMap = const $ attrMap defAttr $ zip (tierAttr <$> [1..]) [ fg (ISOColor 7) `withStyle` dim , fg (ISOColor 6) `withStyle` dim , fg (ISOColor 3) `withStyle` dim , fg (ISOColor 2) `withStyle` dim , fg (ISOColor 1) `withStyle` dim , fg (ISOColor 7) `withStyle` bold , fg (ISOColor 4) `withStyle` bold , fg (ISOColor 6) `withStyle` bold , fg (ISOColor 2) `withStyle` bold , fg (ISOColor 1) `withStyle` bold , fg (ISOColor 3) `withStyle` bold ] , appChooseCursor = neverShowCursor } void $ defaultMain app (newGame initState)
Javran/h2048
src/Game/H2048/UI/Brick.hs
mit
3,817
0
19
1,230
1,229
639
590
106
4
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html module Stratosphere.Resources.GlueCrawler where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.GlueCrawlerSchedule import Stratosphere.ResourceProperties.GlueCrawlerSchemaChangePolicy import Stratosphere.ResourceProperties.GlueCrawlerTargets -- | Full data type definition for GlueCrawler. See 'glueCrawler' for a more -- convenient constructor. data GlueCrawler = GlueCrawler { _glueCrawlerClassifiers :: Maybe (ValList Text) , _glueCrawlerConfiguration :: Maybe (Val Text) , _glueCrawlerDatabaseName :: Val Text , _glueCrawlerDescription :: Maybe (Val Text) , _glueCrawlerName :: Maybe (Val Text) , _glueCrawlerRole :: Val Text , _glueCrawlerSchedule :: Maybe GlueCrawlerSchedule , _glueCrawlerSchemaChangePolicy :: Maybe GlueCrawlerSchemaChangePolicy , _glueCrawlerTablePrefix :: Maybe (Val Text) , _glueCrawlerTargets :: GlueCrawlerTargets } deriving (Show, Eq) instance ToResourceProperties GlueCrawler where toResourceProperties GlueCrawler{..} = ResourceProperties { resourcePropertiesType = "AWS::Glue::Crawler" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ fmap (("Classifiers",) . toJSON) _glueCrawlerClassifiers , fmap (("Configuration",) . toJSON) _glueCrawlerConfiguration , (Just . ("DatabaseName",) . toJSON) _glueCrawlerDatabaseName , fmap (("Description",) . toJSON) _glueCrawlerDescription , fmap (("Name",) . toJSON) _glueCrawlerName , (Just . ("Role",) . toJSON) _glueCrawlerRole , fmap (("Schedule",) . toJSON) _glueCrawlerSchedule , fmap (("SchemaChangePolicy",) . toJSON) _glueCrawlerSchemaChangePolicy , fmap (("TablePrefix",) . toJSON) _glueCrawlerTablePrefix , (Just . ("Targets",) . toJSON) _glueCrawlerTargets ] } -- | Constructor for 'GlueCrawler' containing required fields as arguments. glueCrawler :: Val Text -- ^ 'gcDatabaseName' -> Val Text -- ^ 'gcRole' -> GlueCrawlerTargets -- ^ 'gcTargets' -> GlueCrawler glueCrawler databaseNamearg rolearg targetsarg = GlueCrawler { _glueCrawlerClassifiers = Nothing , _glueCrawlerConfiguration = Nothing , _glueCrawlerDatabaseName = databaseNamearg , _glueCrawlerDescription = Nothing , _glueCrawlerName = Nothing , _glueCrawlerRole = rolearg , _glueCrawlerSchedule = Nothing , _glueCrawlerSchemaChangePolicy = Nothing , _glueCrawlerTablePrefix = Nothing , _glueCrawlerTargets = targetsarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-classifiers gcClassifiers :: Lens' GlueCrawler (Maybe (ValList Text)) gcClassifiers = lens _glueCrawlerClassifiers (\s a -> s { _glueCrawlerClassifiers = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-configuration gcConfiguration :: Lens' GlueCrawler (Maybe (Val Text)) gcConfiguration = lens _glueCrawlerConfiguration (\s a -> s { _glueCrawlerConfiguration = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-databasename gcDatabaseName :: Lens' GlueCrawler (Val Text) gcDatabaseName = lens _glueCrawlerDatabaseName (\s a -> s { _glueCrawlerDatabaseName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-description gcDescription :: Lens' GlueCrawler (Maybe (Val Text)) gcDescription = lens _glueCrawlerDescription (\s a -> s { _glueCrawlerDescription = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-name gcName :: Lens' GlueCrawler (Maybe (Val Text)) gcName = lens _glueCrawlerName (\s a -> s { _glueCrawlerName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-role gcRole :: Lens' GlueCrawler (Val Text) gcRole = lens _glueCrawlerRole (\s a -> s { _glueCrawlerRole = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-schedule gcSchedule :: Lens' GlueCrawler (Maybe GlueCrawlerSchedule) gcSchedule = lens _glueCrawlerSchedule (\s a -> s { _glueCrawlerSchedule = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-schemachangepolicy gcSchemaChangePolicy :: Lens' GlueCrawler (Maybe GlueCrawlerSchemaChangePolicy) gcSchemaChangePolicy = lens _glueCrawlerSchemaChangePolicy (\s a -> s { _glueCrawlerSchemaChangePolicy = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-tableprefix gcTablePrefix :: Lens' GlueCrawler (Maybe (Val Text)) gcTablePrefix = lens _glueCrawlerTablePrefix (\s a -> s { _glueCrawlerTablePrefix = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-targets gcTargets :: Lens' GlueCrawler GlueCrawlerTargets gcTargets = lens _glueCrawlerTargets (\s a -> s { _glueCrawlerTargets = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/GlueCrawler.hs
mit
5,384
0
15
678
988
562
426
75
1
{-# LANGUAGE OverloadedStrings, RecordWildCards, FlexibleInstances, CPP #-} module DumpFormat ( DumpFormat(..) , readDumpFormat , dumpActivity , dumpSample , dumpSamples ) where import Data.MyText (unpack, null, pack, Text) import Data.Aeson import qualified Data.ByteString.Lazy as LBS import Data.Time #if MIN_VERSION_time(1,5,0) import Data.Time.Format(defaultTimeLocale) #else import System.Locale (defaultTimeLocale) #endif import Data.Char import Data.Foldable (toList) import Control.Applicative ((<$>), (<|>), (<*>), pure) import Data import Text.Printf import Data.List hiding (null) import Prelude hiding (null) data DumpFormat = DFShow | DFHuman | DFJSON deriving (Show, Eq) instance ToJSON Text where toJSON = toJSON . unpack instance FromJSON Text where parseJSON x = pack <$> parseJSON x instance ToJSON (TimeLogEntry CaptureData) where toJSON (TimeLogEntry {..}) = object [ "date" .= tlTime, "rate" .= tlRate, "inactive" .= cLastActivity tlData, "windows" .= cWindows tlData, "desktop" .= cDesktop tlData ] instance FromJSON (TimeLogEntry CaptureData) where parseJSON = withObject "TimeLogEntry" $ \v -> do tlTime <- v .: "date" tlRate <- v .: "rate" cLastActivity <- v .: "inactive" cWindows <- v .: "windows" cDesktop <- v .: "desktop" let tlData = CaptureData {..} let entry = TimeLogEntry {..} pure entry instance ToJSON WindowData where toJSON WindowData{..} = object [ "active" .= wActive , "hidden" .= wHidden , "title" .= wTitle , "program" .= wProgram , "desktop" .= wDesktop ] instance FromJSON WindowData where parseJSON = withObject "window" $ \v -> do wActive <- v .: "active" wHidden <- v .:! "hidden" .!= not wActive wTitle <- v .: "title" wProgram <- v .: "program" wDesktop <- v .:! "desktop" .!= "" pure WindowData{..} readDumpFormat :: String -> Maybe DumpFormat readDumpFormat arg = case map toLower arg of "human" -> return DFHuman "show" -> return DFShow "json" -> return DFJSON _ -> Nothing dumpActivity :: TimeLog (CaptureData, ActivityData) -> IO () dumpActivity = mapM_ go where go tle = do dumpHeader (tlTime tle) (cLastActivity cd) dumpDesktop (cDesktop cd) mapM_ dumpWindow (cWindows cd) dumpTags ad where (cd, ad) = tlData tle dumpTags :: ActivityData -> IO () dumpTags = mapM_ go where go act = printf " %s\n" (show act) dumpHeader :: UTCTime -> Integer -> IO () dumpHeader time lastActivity = do tz <- getCurrentTimeZone printf "%s (%dms inactive):\n" (formatTime defaultTimeLocale "%F %X" (utcToLocalTime tz time)) lastActivity dumpWindow :: WindowData -> IO () dumpWindow WindowData{..} = do printf " (%c)%-*s %-15s %s\n" a (dw :: Int) d p t where a | wActive = '*' | wHidden = ' ' | otherwise = '.' (dw, d) | wDesktop == "" = (0, "") | otherwise = (15, " [" ++ unpack wDesktop ++ "]") p = unpack wProgram ++ ":" t = unpack wTitle dumpDesktop :: Text -> IO () dumpDesktop d | null d = return () | otherwise = printf " Current Desktop: %s\n" (unpack d) dumpSample :: TimeLogEntry CaptureData -> IO () dumpSample tle = do dumpHeader (tlTime tle) (cLastActivity (tlData tle)) dumpDesktop (cDesktop (tlData tle)) mapM_ dumpWindow (cWindows (tlData tle)) dumpSamples :: DumpFormat -> TimeLog CaptureData -> IO () dumpSamples DFShow = mapM_ print dumpSamples DFHuman = mapM_ dumpSample dumpSamples DFJSON = enclose . sequence_ . intersperse (putStrLn ",") . map (LBS.putStr . encode) where enclose m = putStrLn "[" >> m >> putStrLn "]"
nomeata/darcs-mirror-arbtt
src/DumpFormat.hs
gpl-2.0
3,925
0
13
1,073
1,256
635
621
108
4
{-# OPTIONS_GHC -fglasgow-exts -fffi #-} module Fenfire.Irc2Notetaker where -- Copyright (c) 2006-2007, Benja Fallenstein, Tuukka Hastrup -- This file is part of Fenfire. -- -- Fenfire is free software; you can redistribute it and/or modify it under -- the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- Fenfire 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 Fenfire; if not, write to the Free -- Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, -- MA 02111-1307 USA import System.Time (getClockTime, toUTCTime, CalendarTime(..), ClockTime(..), toClockTime) import System.Environment (getArgs, getProgName) import System.IO (hFlush, stdout) import System.IO.Unsafe (unsafeInterleaveIO) import Network.URI (escapeURIString, isUnreserved) import System.Cmd (rawSystem) import Data.Char (ord, toUpper, toLower, isLetter, isSpace) import Data.Bits ((.&.)) import Data.List (isPrefixOf, intersperse) import qualified Data.Map as Map import Control.Monad (when) import qualified Control.Exception import System.Glib.UTFString (newUTFString, readCString, peekUTFString) import System.Glib.FFI (withCString, nullPtr, CString, CInt, Ptr) import System.IO.Unsafe (unsafePerformIO) foreign import ccall "g_utf8_validate" valid :: CString -> CInt -> Ptr (CString) -> Bool -- XXX real toUTF isn't exported from System.Glib.UTFString toUTF :: String -> String toUTF s = unsafePerformIO $ newUTFString s >>= readCString fromUTF :: String -> String fromUTF s = unsafePerformIO $ Control.Exception.catch (withCString s $ \cstr -> peekUTFString cstr >>= \s' -> if (valid cstr (-1) nullPtr && all isUnicode s') -- force any exceptions then return s' -- it really was utf-8 else return s ) -- it really wasn't utf-8 (\_e -> return s) -- if any, keep the local encoding -- from gutf8.c used in g_utf8_validate isUnicode c' = let c = ord c' in c < 0x110000 && c .&. 0xFFFFF800 /= 0xD800 && (c < 0xFDD0 || c > 0xFDEF) && c .&. 0xFFFE /= 0xFFFE -- command line parsing and event dispatching main = do (root,channels,parseTimeStamps) <- do args <- getArgs case args of [root,channels] -> return (root,channels,False) ["-t",root,channels] -> return (root,channels,True) _ -> error "[-t] root channels" when (not $ "http://" `isPrefixOf` root) $ error "The root doesn't start with http://" (irclines,timestamps) <- case parseTimeStamps of False -> do irc <- getContents timestamps <- getTimeStamps return (lines irc,timestamps) True -> do irc <- getContents >>= return . lines let (firsts, rests) = unzip $ map (span (/= ' ')) irc return (map (drop 1) rests, map parseTime firsts) mapM_ (uncurry $ handle (words channels) root) $ zip (map fromUTF irclines) (uniquify timestamps) -- a lazy stream of timestamps based on evaluation time getTimeStamps = do ~(TOD secs _picos) <- unsafeInterleaveIO getClockTime xs <- unsafeInterleaveIO getTimeStamps return (TOD secs 0:xs) -- parser for timestamp input format yyyy-mm-ddThh:mm:ss+zhzm parseTime :: String -> ClockTime parseTime str = toClockTime $ CalendarTime (read year) (toEnum $ read month-1) (read day) (read hour) (read minute) (read second) 0 (toEnum 0) 0 "" ((read tzh*60+read tzm)*60) False where (year, rest0) = span (/= '-') str (month, rest1) = span (/= '-') $ drop 1 rest0 (day, rest2) = span (/= 'T') $ drop 1 rest1 (hour, rest3) = span (/= ':') $ drop 1 rest2 (minute, rest4) = span (/= ':') $ drop 1 rest3 (second, rest5) = span (/= '+') $ drop 1 rest4 (tzh, tzm ) = splitAt 2 $ drop 1 rest5 -- differentiating consecutive equivalent elements by adding a sequence number uniquify [] = [] uniquify (x:xs) = (x,Nothing):uniquify' (x,Nothing) xs uniquify' _ [] = [] uniquify' prev (x:xs) | fst prev == x = next prev:uniquify' (next prev) xs | otherwise = first x:uniquify' (first x) xs where next (i,offset) = (i, Just $ maybe (2::Integer) (+1) offset) first i = (i, Nothing) -- event handling by posting queries handle :: [String] -> String -> String -> (ClockTime, Maybe Integer) -> IO () handle channels root line time = do let query = irc2notetaker channels time (parse line) maybe (return ()) (\xs -> rawSystem "curl" ["--data",build xs,root] >> return ()) query build = concat . intersperse "&" . map build' where build' (key,value) = key ++ "=" ++ escapeURIString isUnreserved (toUTF value) -- parsing of a line in irc protocol syntax parse (':':rest) = (Just $ takeWhile (/=' ') rest, parse' "" (tail $ dropWhile (/=' ') rest)) parse rest = (Nothing, parse' "" rest) parse' acc [] = [reverse acc] parse' acc ['\r'] = [reverse acc] parse' "" (':':xs) = [reverse . dropWhile (=='\r') $ reverse xs] parse' acc (' ':xs) = reverse acc : parse' "" xs parse' acc (x:xs) = parse' (x:acc) xs -- maybe query for a given irc event irc2notetaker :: [String] -> (ClockTime, Maybe Integer) -> (Maybe String,[String]) -> Maybe [(String, String)] irc2notetaker channels (time,_offset) ((Just prefix),[cmd,target,msg0]) | map toUpper cmd == "PRIVMSG", '#':channelName <- map toLower target, channelName `elem` channels = let msg = case msg0 of '+':cs -> cs; '-':cs -> cs; cs -> cs in Just [("nick",nick),("line",msg)] where nick = takeWhile (/='!') prefix (CalendarTime y moe d h m s _ps _wd _yd _tzn _tz _isDST) = toUTCTime time mo = (fromEnum moe+1) p n i = take (n-length (show i)) (repeat '0') ++ show i _day = p 4 y ++ '-':p 2 mo ++ '-':p 2 d _second = p 2 h ++ ':':p 2 m ++ ':':p 2 s irc2notetaker _ _ _ = Nothing
timthelion/fenfire
Fenfire/Irc2Notetaker.hs
gpl-2.0
6,824
0
20
2,005
2,119
1,127
992
109
4
{-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Numerical.PETSc.Apps.FEM -- Copyright : (c) Marco Zocca 2015 -- License : LGPL3 -- Maintainer : zocca . marco . gmail . com -- Stability : experimental -- -- | Application : Finite Element Method -- ----------------------------------------------------------------------------- module Numerical.PETSc.Apps.FEM where import qualified Data.Vector as V -- data Element a = Element { }
ocramz/petsc-hs
src/Numerical/PETSc/Apps/FEM.hs
gpl-3.0
531
0
4
87
29
25
4
3
0
module Torrent where import Files import Files.MMap import MetaInfo import Peer.Connection import Peer.Env import Tracker import Torrent.Env import HTorrentPrelude import Data.Array import qualified Data.ByteString as BS import Network.Socket import System.Random splitPieces :: ByteString -> [ByteString] splitPieces = unfoldr f where f bs = guard (not (BS.null bs)) >> Just (BS.splitAt 20 bs) pieceArray :: Int -> [ByteString] -> Array Int ByteString pieceArray n bs = listArray (0, n - 1) bs initTorrent :: MetaInfo -> PortNumber -> IO TorrentEnv initTorrent m p = do id <- replicateM 20 randomIO let fs = initFileMap (m ^. info) let torrentInfo = TorrentInfo { _torrentName = m ^. info . name, _torrentHash = m ^. info . hash, _tracker = m ^. announce, _numPieces = pn, _pieceLength = m ^. info . piece_length, _localId = BS.pack id, _portNumber = p, _uploaded = 0, _pieceHash = pa, _files = fs } initTorrentEnv torrentInfo where ps = splitPieces (m ^. info . pieceHashes) pn = length ps pa = pieceArray pn ps startTorrent :: MetaInfo -> PortNumber -> IO (Maybe TorrentEnv) startTorrent m p = do env <- initTorrent m p tr <- trackerRequest (env ^. torrentInfo) case tr of Just (_, as) -> do mapM (forkIO . peerThread env) as return (Just env) Nothing -> return Nothing
ian-mi/hTorrent
Torrent.hs
gpl-3.0
1,466
0
15
406
497
261
236
-1
-1
{- Copyright 2012 Dustin DeWeese This file is part of peg. peg 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. peg 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 peg. If not, see <http://www.gnu.org/licenses/>. -} module Peg.Parse where import Peg.Types import Control.Applicative import Debug.Trace import Text.Parsec hiding ((<|>), many, optional) import Text.Parsec.String import qualified Text.Parsec.Token as P import Text.Parsec.Language (haskellDef) import Control.Monad.State lexer = P.makeTokenParser haskellDef integer = P.integer lexer float = P.float lexer naturalOrFloat = P.naturalOrFloat lexer natural = P.natural lexer whiteSpace = P.whiteSpace lexer charLiteral = P.charLiteral lexer stringLiteral = P.stringLiteral lexer word :: Parser Value word = W <$> ((:) <$> (lower <|> char ':') <*> many (alphaNum <|> oneOf "?_'#")) atom :: Parser Value atom = A <$> (((:) <$> upper <*> many (alphaNum <|> oneOf "?_'#")) <|> ((:[]) <$> oneOf "[_")) var :: Parser Value var = V <$> (char '?' *> many1 (alphaNum <|> char '_')) svar :: Parser Value svar = S <$> (char '@' *> many1 (alphaNum <|> char '_')) symbol :: Parser Value symbol = W <$> (many1 (oneOf "!@#$%^&*()-+=<>.~/?\\|") <|> fmap (:[]) (oneOf "]{};")) quote :: Parser Value quote = L . (:[]) <$> (char '`' *> value) number :: Parser Value number = do m <- optionMaybe (char '-') let f = maybe (either I F) (const $ either (I . negate) (F . negate)) m f <$> naturalOrFloat value :: Parser Value value = try number <|> try var <|> try svar <|> try symbol <|> word <|> atom <|> C <$> charLiteral <|> L . map C <$> stringLiteral <|> quote comment = string "--" >> many (noneOf "\n") stackExpr :: Parser Stack stackExpr = concatMap f . reverse <$> (whiteSpace >> value `sepEndBy` whiteSpace <* optional comment) where f (W "{") = [A "[", A "["] f (W "}") = [W "]", W "]"] f (W ";") = [A "[", W "]"] f x = [x] showStack :: Stack -> String showStack s = drop 1 $ loop s [] where loop [] = id loop (I x : s) = loop s . (' ':) . shows x loop (C x : s) = loop s . (' ':) . shows x loop (F x : s) = loop s . (' ':) . shows x loop (W x : s) = loop s . ((' ':x) ++) loop (A x : s) = loop s . ((' ':x) ++) loop (V x : s) = loop s . ((' ':'?':x) ++) loop (S x : s) = loop s . ((' ':'@':x) ++) loop (Io : s) = loop s . (" IO" ++) loop (L [] : s) = loop s . (" [ ]" ++) loop (L x : s) = case toString (L x) of Just str -> loop s . (' ':) . shows str Nothing -> case toQuote (L x) of Just str -> loop s . (' ':) . (str ++) Nothing -> loop s . (" [" ++) . loop x . (" ]" ++) toQuote (L [x]) | isList x = ('`':) <$> toQuote x | otherwise = Just ('`' : showStack [x]) toQuote _ = Nothing parseStack = parse stackExpr "" -------------------- Debug -------------------- probe s x = trace (s ++ show x) x traceStack :: Peg () traceStack = do s <- psStack <$> get when (not $ null s) . trace (showStack s) $ return ()
HackerFoo/peg
Peg/Parse.hs
gpl-3.0
3,803
0
16
1,159
1,420
730
690
-1
-1
-- 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.Grid.Output.Fancy.ShadeSpace ( shadeSpace, shadeSpaceColor, shadeSpaceWrite, ) where import MyPrelude import Game import Game.Grid import Game.Data.Color import Game.Run.RunWorld.Scene import OpenGL import OpenGL.Helpers shadeSpace :: ShadeSpace -> Tweak -> Float -> Mat4 -> IO () shadeSpace sh tweak alpha modv = do glUseProgram (shadeSpacePrg sh) glBindVertexArrayOES (shadeSpaceVAO sh) -- modv matrix uniformMat4 (shadeSpaceUniModvInvMatrix sh) $ mat4Transpose modv -- alpha glUniform1f (shadeSpaceUniAlpha sh) $ rTF alpha -- Tweak -- glUniform4f (shadeSpaceUniDot sh) (1.0) (1.0) (1.0) (0.0) glUniform2f (shadeSpaceUniScalePlus sh) (1.0) (1.0) glUniform1f (shadeSpaceUniIntensity sh) (1.0) glUniform1f (shadeSpaceUniColorfy sh) (0.0) -- set textures glActiveTexture gl_TEXTURE0 glBindTexture gl_TEXTURE_CUBE_MAP $ shadeSpaceTex sh -- draw glDrawArrays gl_TRIANGLE_STRIP 0 4 shadeSpaceColor :: ShadeSpace -> Tweak -> Float -> Mat4 -> Color -> IO () shadeSpaceColor sh tweak alpha modv color = do glUseProgram (shadeSpacePrg sh) glBindVertexArrayOES (shadeSpaceVAO sh) -- modv matrix uniformMat4 (shadeSpaceUniModvInvMatrix sh) $ mat4Transpose modv -- alpha glUniform1f (shadeSpaceUniAlpha sh) $ rTF alpha -- color uniformColor (shadeSpaceUniColor sh) color -- Tweak -- glUniform4f (shadeSpaceUniDot sh) (1.0) (1.0) (1.0) (0.0) glUniform2f (shadeSpaceUniScalePlus sh) (1.0) (1.0) glUniform1f (shadeSpaceUniIntensity sh) (1.0) glUniform1f (shadeSpaceUniColorfy sh) (1.0) -- set textures glActiveTexture gl_TEXTURE0 glBindTexture gl_TEXTURE_CUBE_MAP $ shadeSpaceTex sh -- draw glDrawArrays gl_TRIANGLE_STRIP 0 4 shadeSpaceWrite :: ShadeSpace -> Shape -> IO () shadeSpaceWrite sh (Shape wth hth) = do glProgramUniform2fEXT (shadeSpacePrg sh) (shadeSpaceUniScale sh) (rTF wth) (rTF hth)
karamellpelle/grid
source/Game/Grid/Output/Fancy/ShadeSpace.hs
gpl-3.0
2,743
0
11
550
612
311
301
42
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.CloudTrace.Types -- 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) -- module Network.Google.CloudTrace.Types ( -- * Service Configuration cloudTraceService -- * OAuth Scopes , traceAppendScope , cloudPlatformScope -- * Span , Span , span , sSpanKind , sStatus , sStartTime , sChildSpanCount , sSameProcessAsParentSpan , sName , sStackTrace , sAttributes , sEndTime , sTimeEvents , sDisplayName , sParentSpanId , sLinks , sSpanId -- * TruncatableString , TruncatableString , truncatableString , tsValue , tsTruncatedByteCount -- * Status , Status , status , sDetails , sCode , sMessage -- * AttributesAttributeMap , AttributesAttributeMap , attributesAttributeMap , aamAddtional -- * Annotation , Annotation , annotation , aAttributes , aDescription -- * AttributeValue , AttributeValue , attributeValue , avBoolValue , avIntValue , avStringValue -- * MessageEvent , MessageEvent , messageEvent , meId , meUncompressedSizeBytes , meType , meCompressedSizeBytes -- * Empty , Empty , empty -- * SpanSpanKind , SpanSpanKind (..) -- * Link , Link , link , lTraceId , lAttributes , lType , lSpanId -- * StatusDetailsItem , StatusDetailsItem , statusDetailsItem , sdiAddtional -- * StackTrace , StackTrace , stackTrace , stStackTraceHashId , stStackFrames -- * BatchWriteSpansRequest , BatchWriteSpansRequest , batchWriteSpansRequest , bwsrSpans -- * MessageEventType , MessageEventType (..) -- * Attributes , Attributes , attributes , aDroppedAttributesCount , aAttributeMap -- * Module , Module , module' , mBuildId , mModule -- * TimeEvents , TimeEvents , timeEvents , teDroppedMessageEventsCount , teDroppedAnnotationsCount , teTimeEvent -- * Xgafv , Xgafv (..) -- * StackFrames , StackFrames , stackFrames , sfDroppedFramesCount , sfFrame -- * LinkType , LinkType (..) -- * StackFrame , StackFrame , stackFrame , sfLoadModule , sfOriginalFunctionName , sfLineNumber , sfSourceVersion , sfFunctionName , sfColumnNumber , sfFileName -- * Links , Links , links , lDroppedLinksCount , lLink -- * TimeEvent , TimeEvent , timeEvent , teMessageEvent , teAnnotation , teTime ) where import Network.Google.CloudTrace.Types.Product import Network.Google.CloudTrace.Types.Sum import Network.Google.Prelude -- | Default request referring to version 'v2' of the Cloud Trace API. This contains the host and root path used as a starting point for constructing service requests. cloudTraceService :: ServiceConfig cloudTraceService = defaultService (ServiceId "cloudtrace:v2") "cloudtrace.googleapis.com" -- | Write Trace data for a project or application traceAppendScope :: Proxy '["https://www.googleapis.com/auth/trace.append"] traceAppendScope = Proxy -- | See, edit, configure, and delete your Google Cloud Platform data cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"] cloudPlatformScope = Proxy
brendanhay/gogol
gogol-cloudtrace/gen/Network/Google/CloudTrace/Types.hs
mpl-2.0
3,814
0
7
1,023
456
314
142
122
1
{- Copyright (C) 2011, 2012 Jeroen Ketema This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} -- This module implements the drawing of the mouse square used for zooming module DrawMouseSquare ( zoomOk, zoomPosition, drawMouseSquare ) where import Environment import DrawReduction import Prelude import Graphics.Rendering.OpenGL -- Maximum allowed zoom. -- -- Limiting the zoom avoids drawing errors caused by rounding to be shown. maxZoom :: GLdouble maxZoom = 1.6e-5 -- Establish if we are allowed to zoom any further. zoomOk :: GLdouble -> GLdouble -> Bool zoomOk x x' = abs (x' - x) >= visualWidth * maxZoom -- If the zoom area is too small, enlarge to the minimal allowed area. limitPosition :: GLdouble -> GLdouble -> GLdouble -> GLdouble -> (GLdouble, GLdouble, GLdouble, GLdouble) limitPosition x y x' y' | zoomOk x x' = (x, y, x', y') | otherwise = (x, y, x_new', y_new') where x_new' = x + visualWidth * (if x' < x then -maxZoom else maxZoom) y_new' = y + visualHeight * (if y' < y then -maxZoom else maxZoom) -- Calculate the area to zoom to in terms of the drawing area of the reduction. -- -- The parameters are as follows: -- * phys_pos: physical screen coordinates of the mouse -- * vis: currently visible drawing area -- * size: current window size -- -- The additional zoom parameter of zoom_position' indicates if the calculated -- positions are either for an actual zoom or just to draw the mouse square. -- The behavior of the tow is different in case the mouse has not moved from -- its initial position. zoomPosition :: (Position, Position) -> (VisiblePos, VisiblePos) -> Size -> (GLdouble, GLdouble, GLdouble, GLdouble) zoomPosition phys_pos vis size = zoomPosition' phys_pos vis size True zoomPosition' :: (Position, Position) -> (VisiblePos, VisiblePos) -> Size -> Bool -> (GLdouble, GLdouble, GLdouble, GLdouble) zoomPosition' (Position x y, Position x' y') ((l, u), (r, d)) (Size p q) z | x == x' && y == y && z = (l, u, r, d) | x == x' && y == y = (x_new, y_new, x_new', y_new') | otherwise = limitPosition x_new y_new x_new' y_new' where x_new = l + fromIntegral x * x_scale :: GLdouble y_new = u + fromIntegral y * y_scale :: GLdouble x_new' = l + fromIntegral x' * x_scale :: GLdouble y_new' = u + fromIntegral y' * y_scale :: GLdouble x_scale = (r - l) / fromIntegral p y_scale = (d - u) / fromIntegral q -- drawMouseSquare -- -- The first parameter indicates if a mouse square needs to be drawn. The -- last parameter indicates the background color. The other parameters -- correspond to those of zoom_position. drawMouseSquare :: Bool -> (Position, Position) -> (VisiblePos, VisiblePos) -> Size -> Background -> IO () drawMouseSquare True phys_pos vis size back = unsafePreservingMatrix $ do color $ case back of -- Arbitrarily chosen colors for the square Black -> Color4 (255.0 * 0.45 :: GLdouble) (255.0 * 0.95) 0.0 1.0 White -> Color4 0.0 (255.0 * 0.45 :: GLdouble) (255.0 * 0.95) 1.0 let (x, y, x', y') = zoomPosition' phys_pos vis size False renderPrimitive LineLoop $ do vertex $ Vertex3 x y 0.5 vertex $ Vertex3 x y' 0.5 vertex $ Vertex3 x' y' 0.5 vertex $ Vertex3 x' y 0.5 drawMouseSquare False _ _ _ _ = return ()
jeroenk/iTRSsVisualised
DrawMouseSquare.hs
agpl-3.0
3,999
0
14
917
877
480
397
49
3
{-# LANGUAGE GADTs #-} import DNA.Actor import DNA.AST import DNA import DNA.Compiler.CH ---------------------------------------------------------------- -- Print actor ---------------------------------------------------------------- exprPrint :: Expr () (() -> Int -> ((),Out)) exprPrint = Lam $ Lam $ Tup ( Scalar () `Cons` Out [PrintInt $ Var ZeroIdx] `Cons` Nil) actorPrint :: Actor () actorPrint = actor $ do rule $ exprPrint startingState $ Scalar () return () ---------------------------------------------------------------- -- Source actor ---------------------------------------------------------------- exprSrcInt :: Conn Int -> Expr () (Int -> (Int,Out)) exprSrcInt i = Lam $ Tup ( Ap (Ap Add (Var ZeroIdx)) (Scalar (1 :: Int)) `Cons` Out [Outbound i (Var ZeroIdx)] `Cons` Nil) actorSrcInt :: Actor (Conn Int) actorSrcInt = actor $ do c <- simpleOut ConnOne producer $ exprSrcInt c startingState $ Scalar 0 return c program = do (aPr, ()) <- use actorPrint (_ , c ) <- use actorSrcInt connect c aPr main :: IO () main = compile compileToCH (saveProject "dir") 2 program
SKA-ScienceDataProcessor/RC
MS1/dna-examples/test.hs
apache-2.0
1,181
4
13
255
408
206
202
31
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Openshift.V1.OAuthAuthorizeTokenList where import GHC.Generics import Data.Text import Openshift.Unversioned.ListMeta import Openshift.V1.OAuthAuthorizeToken import qualified Data.Aeson -- | data OAuthAuthorizeTokenList = OAuthAuthorizeTokenList { kind :: Maybe Text -- ^ Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds , apiVersion :: Maybe Text -- ^ APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources , metadata :: Maybe ListMeta -- ^ , items :: [OAuthAuthorizeToken] -- ^ list of oauth authorization tokens } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON OAuthAuthorizeTokenList instance Data.Aeson.ToJSON OAuthAuthorizeTokenList
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/V1/OAuthAuthorizeTokenList.hs
apache-2.0
1,280
0
9
174
125
77
48
19
0
{-| Copyright : (C) 2012-2016, University of Twente License : BSD2 (see the file LICENSE) Maintainer : Christiaan Baaij <christiaan.baaij@gmail.com> Utilities for converting Core Type/Term to Netlist datatypes -} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} module CLaSH.Netlist.Util where import Control.Error (hush) import Control.Lens ((.=),(%=)) import qualified Control.Lens as Lens import qualified Control.Monad as Monad import Data.Either (partitionEithers) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.Maybe (catMaybes,fromMaybe) import Data.Text.Lazy (append,pack,unpack) import qualified Data.Text.Lazy as Text import Unbound.Generics.LocallyNameless (Embed, Fresh, bind, embed, makeName, name2Integer, name2String, unbind, unembed, unrec) import CLaSH.Core.DataCon (DataCon (..)) import CLaSH.Core.FreeVars (termFreeIds, typeFreeVars) import CLaSH.Core.Pretty (showDoc) import CLaSH.Core.Subst (substTys) import CLaSH.Core.Term (LetBinding, Term (..), TmName) import CLaSH.Core.TyCon (TyCon (..), TyConName, tyConDataCons) import CLaSH.Core.Type (Type (..), TypeView (..), LitTy (..), splitTyConAppM, tyView) import CLaSH.Core.Util (collectBndrs, termType) import CLaSH.Core.Var (Id, Var (..), modifyVarName) import CLaSH.Netlist.Types as HW import CLaSH.Util mkBasicId :: Identifier -> NetlistMonad Identifier mkBasicId n = do f <- Lens.use mkBasicIdFn let n' = f n if Text.null n' then return (pack "x") else return n' -- | Split a normalized term into: a list of arguments, a list of let-bindings, -- and a variable reference that is the body of the let-binding. Returns a -- String containing the error is the term was not in a normalized form. splitNormalized :: (Fresh m, Functor m) => HashMap TyConName TyCon -> Term -> m (Either String ([Id],[LetBinding],Id)) splitNormalized tcm expr = do (args,letExpr) <- fmap (first partitionEithers) $ collectBndrs expr case letExpr of Letrec b | (tmArgs,[]) <- args -> do (xes,e) <- unbind b case e of Var t v -> return $! Right (tmArgs,unrec xes,Id v (embed t)) _ -> return $! Left ($(curLoc) ++ "Not in normal form: res not simple var") | otherwise -> return $! Left ($(curLoc) ++ "Not in normal form: tyArgs") _ -> do ty <- termType tcm expr return $! Left ($(curLoc) ++ "Not in normal from: no Letrec:\n" ++ showDoc expr ++ "\nWhich has type:\n" ++ showDoc ty) -- | Converts a Core type to a HWType given a function that translates certain -- builtin types. Errors if the Core type is not translatable. unsafeCoreTypeToHWType :: String -> (HashMap TyConName TyCon -> Type -> Maybe (Either String HWType)) -> HashMap TyConName TyCon -> Type -> HWType unsafeCoreTypeToHWType loc builtInTranslation m = either (error . (loc ++)) id . coreTypeToHWType builtInTranslation m -- | Converts a Core type to a HWType within the NetlistMonad; errors on failure unsafeCoreTypeToHWTypeM :: String -> Type -> NetlistMonad HWType unsafeCoreTypeToHWTypeM loc ty = unsafeCoreTypeToHWType loc <$> Lens.use typeTranslator <*> Lens.use tcCache <*> pure ty -- | Converts a Core type to a HWType within the NetlistMonad; 'Nothing' on failure coreTypeToHWTypeM :: Type -> NetlistMonad (Maybe HWType) coreTypeToHWTypeM ty = hush <$> (coreTypeToHWType <$> Lens.use typeTranslator <*> Lens.use tcCache <*> pure ty) -- | Returns the name and period of the clock corresponding to a type synchronizedClk :: HashMap TyConName TyCon -- ^ TyCon cache -> Type -> Maybe (Identifier,Int) synchronizedClk tcm ty | not . null . Lens.toListOf typeFreeVars $ ty = Nothing | Just (tyCon,args) <- splitTyConAppM ty = case name2String tyCon of "CLaSH.Sized.Vector.Vec" -> synchronizedClk tcm (args!!1) "CLaSH.Signal.Internal.SClock" -> case splitTyConAppM (head args) of Just (_,[LitTy (SymTy s),LitTy (NumTy i)]) -> Just (pack s,i) _ -> error $ $(curLoc) ++ "Clock period not a simple literal: " ++ showDoc ty "CLaSH.Signal.Internal.Signal'" -> case splitTyConAppM (head args) of Just (_,[LitTy (SymTy s),LitTy (NumTy i)]) -> Just (pack s,i) _ -> error $ $(curLoc) ++ "Clock period not a simple literal: " ++ showDoc ty _ -> case tyConDataCons (tcm HashMap.! tyCon) of [dc] -> let argTys = dcArgTys dc argTVs = dcUnivTyVars dc argSubts = zip argTVs args args' = map (substTys argSubts) argTys in case args' of (arg:_) -> synchronizedClk tcm arg _ -> Nothing _ -> Nothing | otherwise = Nothing -- | Converts a Core type to a HWType given a function that translates certain -- builtin types. Returns a string containing the error message when the Core -- type is not translatable. coreTypeToHWType :: (HashMap TyConName TyCon -> Type -> Maybe (Either String HWType)) -> HashMap TyConName TyCon -> Type -> Either String HWType coreTypeToHWType builtInTranslation m ty = fromMaybe (case tyView ty of TyConApp tc args -> mkADT builtInTranslation m (showDoc ty) tc args _ -> Left $ "Can't translate non-tycon type: " ++ showDoc ty) (builtInTranslation m ty) -- | Converts an algebraic Core type (split into a TyCon and its argument) to a HWType. mkADT :: (HashMap TyConName TyCon -> Type -> Maybe (Either String HWType)) -- ^ Hardcoded Type -> HWType translator -> HashMap TyConName TyCon -- ^ TyCon cache -> String -- ^ String representation of the Core type for error messages -> TyConName -- ^ The TyCon -> [Type] -- ^ Its applied arguments -> Either String HWType mkADT _ m tyString tc _ | isRecursiveTy m tc = Left $ $(curLoc) ++ "Can't translate recursive type: " ++ tyString mkADT builtInTranslation m tyString tc args = case tyConDataCons (m HashMap.! tc) of [] -> Left $ $(curLoc) ++ "Can't translate empty type: " ++ tyString dcs -> do let tcName = pack $ name2String tc argTyss = map dcArgTys dcs argTVss = map dcUnivTyVars dcs argSubts = map (`zip` args) argTVss substArgTyss = zipWith (\s tys -> map (substTys s) tys) argSubts argTyss argHTyss <- mapM (mapM (coreTypeToHWType builtInTranslation m)) substArgTyss case (dcs,argHTyss) of (_:[],[[elemTy]]) -> return elemTy (_:[],[elemTys@(_:_)]) -> return $ Product tcName elemTys (_ ,concat -> []) -> return $ Sum tcName $ map (pack . name2String . dcName) dcs (_ ,elemHTys) -> return $ SP tcName $ zipWith (\dc tys -> ( pack . name2String $ dcName dc , tys ) ) dcs elemHTys -- | Simple check if a TyCon is recursively defined. isRecursiveTy :: HashMap TyConName TyCon -> TyConName -> Bool isRecursiveTy m tc = case tyConDataCons (m HashMap.! tc) of [] -> False dcs -> let argTyss = map dcArgTys dcs argTycons = (map fst . catMaybes) $ (concatMap . map) splitTyConAppM argTyss in tc `elem` argTycons -- | Determines if a Core type is translatable to a HWType given a function that -- translates certain builtin types. representableType :: (HashMap TyConName TyCon -> Type -> Maybe (Either String HWType)) -> HashMap TyConName TyCon -> Type -> Bool representableType builtInTranslation m = either (const False) ((> 0) . typeSize) . coreTypeToHWType builtInTranslation m -- | Determines the bitsize of a type typeSize :: HWType -> Int typeSize Void = 0 typeSize String = 1 typeSize Bool = 1 typeSize (Clock _ _) = 1 typeSize (Reset _ _) = 1 typeSize (BitVector i) = i typeSize (Index 0) = 0 typeSize (Index 1) = 1 typeSize (Index u) = clog2 u typeSize (Signed i) = i typeSize (Unsigned i) = i typeSize (Vector n el) = n * typeSize el typeSize t@(SP _ cons) = conSize t + maximum (map (sum . map typeSize . snd) cons) typeSize (Sum _ dcs) = max 1 (clog2 $ length dcs) typeSize (Product _ tys) = sum $ map typeSize tys -- | Determines the bitsize of the constructor of a type conSize :: HWType -> Int conSize (SP _ cons) = clog2 $ length cons conSize t = typeSize t -- | Gives the length of length-indexed types typeLength :: HWType -> Int typeLength (Vector n _) = n typeLength _ = 0 -- | Gives the HWType corresponding to a term. Returns an error if the term has -- a Core type that is not translatable to a HWType. termHWType :: String -> Term -> NetlistMonad HWType termHWType loc e = do m <- Lens.use tcCache ty <- termType m e unsafeCoreTypeToHWTypeM loc ty -- | Gives the HWType corresponding to a term. Returns 'Nothing' if the term has -- a Core type that is not translatable to a HWType. termHWTypeM :: Term -> NetlistMonad (Maybe HWType) termHWTypeM e = do m <- Lens.use tcCache ty <- termType m e coreTypeToHWTypeM ty -- | Uniquely rename all the variables and their references in a normalized -- term mkUniqueNormalized :: ([Id],[LetBinding],Id) -> NetlistMonad ([Id],[LetBinding],TmName) mkUniqueNormalized (args,binds,res) = do -- Make arguments unique (args',subst) <- mkUnique [] args -- Make result unique ([res1],subst') <- mkUnique subst [res] let bndrs = map fst binds exprs = map (unembed . snd) binds usesOutput = concatMap (filter (== varName res) . Lens.toListOf termFreeIds) exprs -- If the let-binder carrying the result is used in a feedback loop -- rename the let-binder to "<X>_rec", and assign the "<X>_rec" to -- "<X>". We do this because output ports in most HDLs cannot be read. (res2,subst'',extraBndr) <- case usesOutput of [] -> return (varName res1,(res,res1):subst',[] :: [(Id, Embed Term)]) _ -> do ([res3],_) <- mkUnique [] [modifyVarName (`appendToName` "_rec") res1] return (varName res3,(res,res3):subst' ,[(res1,embed $ Var (unembed $ varType res) (varName res3))]) -- Replace occurences of "<X>" by "<X>_rec" let resN = varName res bndrs' = map (\i -> if varName i == resN then modifyVarName (const res2) i else i) bndrs (bndrsL,r:bndrsR) = break ((== res2).varName) bndrs' -- Make let-binders unique (bndrsL',substL) <- mkUnique subst'' bndrsL (bndrsR',substR) <- mkUnique substL bndrsR -- Replace old IDs by update unique IDs in the RHSs of the let-binders exprs' <- fmap (map embed) $ Monad.foldM subsBndrs exprs substR -- Return the uniquely named arguments, let-binders, and result return (args',zip (bndrsL' ++ r:bndrsR') exprs' ++ extraBndr,varName res1) where subsBndrs :: [Term] -> (Id,Id) -> NetlistMonad [Term] subsBndrs es (f,r) = mapM (subsBndr f r) es subsBndr :: Id -> Id -> Term -> NetlistMonad Term subsBndr f r e = case e of Var t v | v == varName f -> return . Var t $ varName r App e1 e2 -> App <$> subsBndr f r e1 <*> subsBndr f r e2 Case scrut ty alts -> Case <$> subsBndr f r scrut <*> pure ty <*> mapM ( return . uncurry bind <=< secondM (subsBndr f r) <=< unbind ) alts _ -> return e -- | Make a set of IDs unique; also returns a substitution from old ID to new -- updated unique ID. mkUnique :: [(Id,Id)] -- ^ Existing substitution -> [Id] -- ^ IDs to make unique -> NetlistMonad ([Id],[(Id,Id)]) -- ^ (Unique IDs, update substitution) mkUnique = go [] where go :: [Id] -> [(Id,Id)] -> [Id] -> NetlistMonad ([Id],[(Id,Id)]) go processed subst [] = return (reverse processed,subst) go processed subst (i:is) = do iN <- mkUniqueIdentifier . pack . name2String $ varName i let iN_unpacked = unpack iN i' = modifyVarName (repName iN_unpacked) i go (i':processed) ((i,i'):subst) is repName s n = makeName s (name2Integer n) mkUniqueIdentifier :: Identifier -> NetlistMonad Identifier mkUniqueIdentifier nm = do seen <- Lens.use seenIds seenC <- Lens.use seenComps i <- mkBasicId nm let s = seenC ++ seen if i `elem` s then go 0 s i else do seenIds %= (i:) return i where go :: Integer -> [Identifier] -> Identifier -> NetlistMonad Identifier go n s i = do i' <- mkBasicId (i `append` pack ('_':show n)) if i' `elem` s then go (n+1) s i else do seenIds %= (i':) return i' -- | Append a string to a name appendToName :: TmName -> String -> TmName appendToName n s = makeName (name2String n ++ s) (name2Integer n) -- | Preserve the Netlist '_varEnv' and '_varCount' when executing a monadic action preserveVarEnv :: NetlistMonad a -> NetlistMonad a preserveVarEnv action = do -- store state vCnt <- Lens.use varCount vEnv <- Lens.use varEnv vComp <- Lens.use curCompNm vSeen <- Lens.use seenIds -- perform action val <- action -- restore state varCount .= vCnt varEnv .= vEnv curCompNm .= vComp seenIds .= vSeen return val dcToLiteral :: HWType -> Int -> Literal dcToLiteral Bool 1 = BoolLit False dcToLiteral Bool 2 = BoolLit True dcToLiteral _ i = NumLit (toInteger i-1)
ggreif/clash-compiler
clash-lib/src/CLaSH/Netlist/Util.hs
bsd-2-clause
15,044
242
21
4,946
3,993
2,144
1,849
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableSuperClasses #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeOperators #-} module Data.Memorable.Internal where import Control.Arrow (first) import Text.Printf import Control.Applicative import Control.Monad.Except import Data.Maybe import Data.List.Split import Control.Monad.State import Control.Monad.Writer import Data.Hashable import Data.Binary.Get import Data.Binary.Put import qualified Data.Binary import Data.Bits import Data.Bits.Coding hiding (putUnaligned) import Data.Bytes.Put import Data.Bytes.Get import Data.Type.Equality import Data.Type.Bool import Data.ByteString.Lazy (ByteString, pack, unpack) import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString as B import Data.List import Data.Proxy import Data.Word import Data.Int import GHC.TypeLits import GHC.Exts import Numeric import System.Random (randomIO) #ifdef DATA_DWORD import Data.DoubleWord #endif #ifdef NETWORK_IP import Network.IP.Addr #endif #ifdef CRYPTONITE import Data.ByteArray (convert) import Crypto.Hash hiding (hash) #endif #ifdef HASHABLE import Data.Hashable #endif -- | Choice between two sub patterns. It's not safe to use this directly. -- Use `.|` instead. -- -- Also, if you are parsing back rendered phrases, you must make sure that -- the selected word is enough to choose a side. That is, `a` and `b` must -- have unique first words. This is NOT checked, as it causes a HUGE -- compile-time performance hit. If we can make it performant it may be -- checked one day. data a :| b -- | Append two patterns together by doing the first, then the second. See -- also `.-` data a :- b -- | Proxy version of `:|`. It also constraints the two subpatterns to -- being the same depth. Use this to add an extra bit to the pattern depth, -- where the bit chooses to proceed down either the left or right side. -- -- >>> :set -XTypeApplications -- >>> :set -XDataKinds -- >>> import Data.Word -- >>> let myPattern = padHex (Proxy @"foo" .| Proxy @"bar") -- >>> renderMemorable myPattern (0x00 :: Word8) -- "bar-00" -- >>> renderMemorable myPattern (0xff :: Word8) -- "foo-7f" -- -- See also 'ToTree' -- -- WARNING: Each side of the split must be unique. See the warning about `:|`. (.|) :: (Depth a ~ Depth b) => Proxy a -> Proxy b -> Proxy (a :| b) _ .| _ = Proxy -- | Proxy version of `:-`. -- The new pattern depth is the sum of the two parts. -- >>> import Data.Word -- >>> import Data.Memorable.Theme.Words -- >>> let myPattern = words8 .- words8 -- >>> renderMemorable myPattern (0xabcd :: Word16) -- "ages-old" (.-) :: Proxy a -> Proxy b -> Proxy (a :- b) _ .- _ = Proxy -- | Captures `n` bits and converts them to a string via the `nt` ("number type") -- argument. See `Dec`, `Hex`. type Number nt n = NumberWithOffset nt n 0 -- | Captures `n` bits and convertes them to a string via the `nt` ("number type") -- argument after adding the offset. See `Dec`, `Hex`. data NumberWithOffset nt (n :: Nat) (o :: Nat) -- | Pad the `a` argument out to length `n` by taking the remaining bits -- and converting them via `nt` (see `Dec` and `Hex`). If padding is required, -- it is separated by a dash. -- -- See `padHex` and `padDec` for convinence functions. data PadTo nt (n :: Nat) a --------------------------------------------------------------------- -- Utility type functions --------------------------------------------------------------------- -- Helper for `ToTree` type family ToTreeH (a :: [k]) :: [*] where ToTreeH '[] = '[] ToTreeH (x1 ': x2 ': x3 ': x4 ': x5 ': x6 ': x7 ': x8 ': x9 ': x10 ': x11 ': x12 ': x13 ': x14 ': x15 ': x16 ': x17 ': x18 ': x19 ': x20 ': x21 ': x22 ': x23 ': x24 ': x25 ': x26 ': x27 ': x28 ': x29 ': x30 ': x31 ': x32 ': x33 ': x34 ': x35 ': x36 ': x37 ': x38 ': x39 ': x40 ': x41 ': x42 ': x43 ': x44 ': x45 ': x46 ': x47 ': x48 ': x49 ': x50 ': x51 ': x52 ': x53 ': x54 ': x55 ': x56 ': x57 ': x58 ': x59 ': x60 ': x61 ': x62 ': x63 ': x64 ': xs) = ToTree64 (x1 ': x2 ': x3 ': x4 ': x5 ': x6 ': x7 ': x8 ': x9 ': x10 ': x11 ': x12 ': x13 ': x14 ': x15 ': x16 ': x17 ': x18 ': x19 ': x20 ': x21 ': x22 ': x23 ': x24 ': x25 ': x26 ': x27 ': x28 ': x29 ': x30 ': x31 ': x32 ': x33 ': x34 ': x35 ': x36 ': x37 ': x38 ': x39 ': x40 ': x41 ': x42 ': x43 ': x44 ': x45 ': x46 ': x47 ': x48 ': x49 ': x50 ': x51 ': x52 ': x53 ': x54 ': x55 ': x56 ': x57 ': x58 ': x59 ': x60 ': x61 ': x62 ': x63 ': x64 ': xs) ToTreeH as = ToTree2 as type family ToTree2 (as :: [k]) :: [*] where ToTree2 '[] = '[] ToTree2 (a ': b ': bs) = (a :| b) ': ToTree2 bs type family ToTree64 (as :: [k]) :: [*] where ToTree64 '[] = '[] ToTree64 (x1 ': x2 ': x3 ': x4 ': x5 ': x6 ': x7 ': x8 ': x9 ': x10 ': x11 ': x12 ': x13 ': x14 ': x15 ': x16 ': x17 ': x18 ': x19 ': x20 ': x21 ': x22 ': x23 ': x24 ': x25 ': x26 ': x27 ': x28 ': x29 ': x30 ': x31 ': x32 ': x33 ': x34 ': x35 ': x36 ': x37 ': x38 ': x39 ': x40 ': x41 ': x42 ': x43 ': x44 ': x45 ': x46 ': x47 ': x48 ': x49 ': x50 ': x51 ': x52 ': x53 ': x54 ': x55 ': x56 ': x57 ': x58 ': x59 ': x60 ': x61 ': x62 ': x63 ': x64 ': xs) = ( ( ( ( ( (x1 :| x2) :| (x3 :| x4) ) :| ( (x5 :| x6) :| (x7 :| x8) ) ) :| ( ( (x9 :| x10) :| (x11 :| x12) ) :| ( (x13 :| x14) :| (x15 :| x16) ) ) ) :| ( ( ( (x17 :| x18) :| (x19 :| x20) ) :| ( (x21 :| x22) :| (x23 :| x24) ) ) :| ( ( (x25 :| x26) :| (x27 :| x28) ) :| ( (x29 :| x30) :| (x31 :| x32) ) ) ) ) :| ( ( ( ( (x33 :| x34) :| (x35 :| x36) ) :| ( (x37 :| x38) :| (x39 :| x40) ) ) :| ( ( (x41 :| x42) :| (x43 :| x44) ) :| ( (x45 :| x46) :| (x47 :| x48) ) ) ) :| ( ( ( (x49 :| x50) :| (x51 :| x52) ) :| ( (x53 :| x54) :| (x55 :| x56) ) ) :| ( ( (x57 :| x58) :| (x59 :| x60) ) :| ( (x61 :| x62) :| (x63 :| x64) ) ) ) ) ) ': ToTree64 xs type family Len (a :: [Symbol]) :: Nat where Len (a ': b ': c ': d ': e ': f ': g ': h ': i ': j ': k ': l ': m ': n ': o ': p ': q ': r ': s ': t ': u ': v ': w ': x ': y ': z ': as) = Len as + 26 Len (a ': as) = Len as + 1 Len '[] = 0 -- | Convert a @'[Symbol]@ to a balanced tree of `:|`. Each result has equal -- probability of occurring. Length of the list must be a power of two. This -- is very useful for converting long lists of words into a usable pattern. -- -- >>> :kind! ToTree '["a", "b", "c", "d"] -- ToTree '["a", "b", "c", "d"] :: * -- = ("a" :| "b") :| ("c" :| "d") type family ToTree (a :: [k]) :: * where ToTree (x ': y ': '[] ) = x :| y ToTree '[(x :| y)] = x :| y ToTree xs = ToTree (ToTreeH xs) type family Concat (a :: [k]) :: * where Concat (a ': b ': '[]) = a :- b Concat (a ': b ': cs) = a :- b :- Concat cs type family Intersperse (a :: k) (b :: [k]) :: [k] where Intersperse a '[] = '[] Intersperse a (b ': '[]) = b ': '[] Intersperse a (b ': cs) = b ': a ': Intersperse a cs -- | Useful to prevent haddock from expanding the type. type family LeftSide (a :: *) :: * where LeftSide (a :| b) = a -- | Useful to prevent haddock from expanding the type. type family RightSide (a :: *) :: * where RightSide (a :| b) = b -- | Shrink a branching pattern by discarding the right hand side. leftSide :: Proxy (a :| b) -> Proxy a leftSide _ = Proxy -- | Shrink a branching pattern by discarding the left hand side. rightSide :: Proxy (a :| b) -> Proxy b rightSide _ = Proxy type PowerOfTwo n = (IsPowerOfTwo n ~ True) type family IsPowerOfTwo (a :: Nat) :: Bool where IsPowerOfTwo 1 = True IsPowerOfTwo 2 = True IsPowerOfTwo 4 = True IsPowerOfTwo 8 = True IsPowerOfTwo 16 = True IsPowerOfTwo 32 = True IsPowerOfTwo 64 = True IsPowerOfTwo 128 = True IsPowerOfTwo 256 = True IsPowerOfTwo 512 = True IsPowerOfTwo 1024 = True IsPowerOfTwo 2048 = True IsPowerOfTwo 4096 = True IsPowerOfTwo 8192 = True type family BitsInPowerOfTwo (a :: Nat) :: Nat where BitsInPowerOfTwo 1 = 0 BitsInPowerOfTwo 2 = 1 BitsInPowerOfTwo 4 = 2 BitsInPowerOfTwo 8 = 3 BitsInPowerOfTwo 16 = 4 BitsInPowerOfTwo 32 = 5 BitsInPowerOfTwo 64 = 6 BitsInPowerOfTwo 128 = 7 BitsInPowerOfTwo 256 = 8 BitsInPowerOfTwo 512 = 9 BitsInPowerOfTwo 1024 = 10 BitsInPowerOfTwo 2048 = 11 BitsInPowerOfTwo 4096 = 12 BitsInPowerOfTwo 8192 = 13 type family Find a as :: Bool where Find a '[] = 'False Find a (a ': as) = 'True Find a (b ': a ': as) = 'True Find a (c ': b ': a ': as) = 'True Find a (d ': c ': b ': a ': as) = 'True Find a (e ': d ': c ': b ': a ': as) = 'True Find a (f ': e ': d ': c ': b ': a ': as) = 'True Find a (g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (q ': p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (r ': q ': p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (s ': r ': q ': p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (t ': s ': r ': q ': p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (u ': t ': s ': r ': q ': p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (v ': u ': t ': s ': r ': q ': p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (w ': v ': u ': t ': s ': r ': q ': p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (x ': w ': v ': u ': t ': s ': r ': q ': p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (y ': x ': w ': v ': u ': t ': s ': r ': q ': p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (z ': y ': x ': w ': v ': u ': t ': s ': r ': q ': p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': a ': as) = 'True Find a (z ': y ': x ': w ': v ': u ': t ': s ': r ': q ': p ': o ': n ': m ': l ': k ': j ': i ': h ': g ': f ': e ': d ': c ': b ': aa ': as) = Find a as Find a (b ': as ) = Find a as type family HasDups (a :: [Symbol]) :: Bool where HasDups (a ': as) = Find a as || HasDups as HasDups '[] = 'False type family NoDups (a :: [Symbol]) :: Constraint where NoDups (a ': as) = If (Find a as) (TypeError (Text "Pattern is ambiguous because of " :<>: ShowType a)) (NoDups as) NoDups '[] = () -- | Determines the number of bits that a pattern will consume. type family Depth (a :: k) :: Nat where Depth (a :: Symbol) = 0 Depth (a :- b) = Depth a + Depth b Depth (a :| b) = 1 + Depth a Depth (NumberWithOffset nt a o) = a Depth (PadTo nt n a) = n -- | Get the depth of a pattern as a value-level `Integer`. -- >>> :set -XTypeApplications -XDataKinds -- >>> getDepth (Proxy @"foo" .| Proxy @"bar") -- 1 getDepth :: forall a. KnownNat (Depth a) => Proxy a -> Integer getDepth _ = natVal (Proxy :: Proxy (Depth a)) --------------------------------------------------------------------- -- Utility functions --------------------------------------------------------------------- type family NTimes (n :: Nat) (p :: *) where NTimes 1 a = a NTimes n a = a :- NTimes (n - 1) a -- | Put five things next to each other. -- Same as using '.-' repeatedly five :: Proxy a -> Proxy (a :- a :- a :- a :- a) five _ = Proxy -- | Put four things next to each other. four :: Proxy a -> Proxy (a :- a :- a :- a) four _ = Proxy -- | Put three things next to each other. three :: Proxy a -> Proxy (a :- a :- a) three _ = Proxy -- | Put two things next to each other. two :: Proxy a -> Proxy (a :- a) two _ = Proxy -- | Pad this pattern out with hex digits. Useful when you want some human -- readability, but also want full coverage of the data. See 'Hex' for details. -- -- >>> import Data.Word -- >>> import Data.Memorable.Theme.Fantasy -- >>> renderMemorable (padHex rpgWeapons) (0xdeadbeef01020304 :: Word64) -- "sacred-club-of-ghoul-charming-eef01020304" padHex :: forall n a. Proxy a -> Proxy (PadTo Hex n a) padHex _ = Proxy -- | Pad with decimal digits. See 'padHex' and 'Dec' for details. This does -- not pad with 0's padDec :: forall n a. Proxy a -> Proxy (PadTo Dec n a) padDec _ = Proxy -- | A single hex number consuming 4 bits (with leading 0's). hex4 :: Proxy (Number Hex 4) hex4 = Proxy -- | A single hex number consuming 8 bits (with leading 0's). hex8 :: Proxy (Number Hex 8) hex8 = Proxy -- | A single hex number consuming 16 bits (with leading 0's). hex16 :: Proxy (Number Hex 16) hex16 = Proxy -- | A single hex number consuming 32 bits (with leading 0's). hex32 :: Proxy (Number Hex 32) hex32 = Proxy -- | A single hex number consuming `n` bits, which it will try and figure -- out from context (with leading 0's). hex :: Proxy (Number Hex n) hex = Proxy -- | A single decimal number consuming 4 bits (no leading 0's) dec4 :: Proxy (Number Dec 4) dec4 = Proxy -- | A single decimal number consuming 8 bits (no leading 0's) dec8 :: Proxy (Number Dec 8) dec8 = Proxy -- | A single decimal number consuming 16 bits (no leading 0's) dec16 :: Proxy (Number Dec 16) dec16 = Proxy -- | A single decimal number consuming 32 bits (no leading 0's) dec32 :: Proxy (Number Dec 32) dec32 = Proxy -- | A single decimal number consuming `n` bits, which it will try and figure -- out from context (no leading 0's) dec :: Proxy (Number Dec n) dec = Proxy --------------------------------------------------------------------- -- MemRender --------------------------------------------------------------------- -- | The class that implements the main rendering function. class MemRender a where render :: Proxy a -> Coding Get String parser :: Proxy a -> ExceptT String (State ([String], Coding PutM ())) () addBits :: Coding PutM () -> ExceptT String (State ([String], Coding PutM ())) () addBits c = do (s,cs) <- get put (s,cs >> c) symbolString :: KnownSymbol a => Proxy a -> String symbolString = concatMap tr . symbolVal where tr '-' = "\\_" tr '\\' = "\\\\" tr c = [c] stringSymbol :: String -> String stringSymbol [] = [] stringSymbol ('\\':'\\':rest) = '\\' : stringSymbol rest stringSymbol ('\\':'_':rest) = '-' : stringSymbol rest stringSymbol (a:rest) = a : stringSymbol rest parsePhrase :: MemRender p => Proxy p -> String -> Maybe ByteString parsePhrase p input = let tokens = map stringSymbol $ splitOn "-" input stm = runExceptT (parser p) (e,(_,cdm)) = runState stm (tokens, pure ()) ptm = runCoding (cdm <* Data.Bytes.Put.flush) (\a _ _ -> pure a) 0 0 in case e of Left _ -> Nothing Right () -> Just $ runPutL ptm -- | Turn a memorable string back into a 'Memorable' value. parseMemorable :: (Memorable a, MemRender p, MemLen a ~ Depth p) => Proxy p -> String -> Maybe a parseMemorable p input = let bs = parsePhrase p input in runParser <$> bs -- | Convert a memorable string into a different memorable string. -- -- Useful for things like taking an existing md5, and converting it -- into a memorable one. -- -- >>> :set -XTypeApplications -XDataKinds -- >>> import Data.Memorable.Theme.Words -- >>> rerender hex (padHex @128 $ four words10) "2d4fbe4d5db8748c931b85c551d03360" -- Just "lurk-lash-atop-hole-b8748c931b85c551d03360" rerender :: (MemRender a, MemRender b, Depth a ~ Depth b) => Proxy a -> Proxy b -> String -> Maybe String rerender a b input = renderMemorableByteString b <$> parsePhrase a input instance (KnownSymbol a) => MemRender (a :: Symbol) where render = return . symbolString parser p = do (ss,cs) <- get case ss of [] -> empty s:ss' -> if s == symbolVal p then put (ss',cs) else empty instance (MemRender a, MemRender b) => MemRender (a :- b) where render _ = do sa <- render (Proxy :: Proxy a) sb <- render (Proxy :: Proxy b) return $ sa ++ "-" ++ sb parser _ = do parser (Proxy :: Proxy a) parser (Proxy :: Proxy b) instance (MemRender a, MemRender b) => MemRender (a :| b) where render _ = do b <- getBit if b then render (Proxy :: Proxy a) else render (Proxy :: Proxy b) parser _ = do s <- get catchError (do addBits (putBit True) parser (Proxy :: Proxy a) ) (\_ -> do put s addBits (putBit False) parser (Proxy :: Proxy b) ) instance (NumberRender nt, KnownNat a, KnownNat o) => MemRender (NumberWithOffset nt a o) where render _ = do let o = natVal (Proxy :: Proxy o) b = natVal (Proxy :: Proxy a) w <- getBitsFrom (fromIntegral (pred b)) 0 return $ renderNumber (Proxy :: Proxy nt) b (w + o) parser _ = do let o = natVal (Proxy :: Proxy o) b = natVal (Proxy :: Proxy a) (ss,cs) <- get case ss of [] -> empty (s:ss') -> do let n = readNumber (Proxy :: Proxy nt) b s case n of Nothing -> empty Just n' -> do let n'' = n' - o when (n'' >= 2^b) empty put (ss',cs >> putBitsFrom (fromIntegral $ pred b) n'') instance (MemRender a, Depth a <= n, NumberRender nt, KnownNat n, KnownNat (Depth a)) => MemRender (PadTo nt n a) where render _ = do s1 <- render (Proxy :: Proxy a) let diff = natVal (Proxy :: Proxy n) - natVal (Proxy :: Proxy (Depth a)) ntp = Proxy :: Proxy nt case diff of 0 -> return s1 _ -> do d <- getBitsFrom (fromIntegral (pred diff)) 0 return $ s1 ++ "-" ++ renderNumber ntp diff d parser _ = do let nt = Proxy :: Proxy nt diff = natVal (Proxy :: Proxy n) - natVal (Proxy :: Proxy (Depth a)) parser (Proxy :: Proxy a) case diff of 0 -> return () _ -> do (ss,cs) <- get when (null ss) empty let (s:ss') = ss n = readNumber nt diff s n' <- maybe empty return n when (n' >= 2^diff) empty put (ss', cs >> putBitsFrom (fromIntegral $ pred diff) n') --------------------------------------------------------------------- -- NumberRender --------------------------------------------------------------------- -- | Class for capturing how to render numbers. class NumberRender n where renderNumber :: Proxy n -> Integer -> Integer -> String readNumber :: Proxy n -> Integer -> String -> Maybe Integer -- | Render numbers as decimal numbers. Does not pad. data Dec instance NumberRender Dec where renderNumber _ _ = show readNumber _ _ input = case readDec input of [(v,"")] -> Just v _ -> Nothing -- | Render numbers as hexadecimal numbers. Pads with 0s. data Hex instance NumberRender Hex where renderNumber _ b = printf "%0*x" hexDigits where hexDigits = (b - 1) `div` 4 + 1 readNumber _ _ input = case readHex input of [(v,"")] -> Just v _ -> Nothing --------------------------------------------------------------------- -- Rendering functions for users --------------------------------------------------------------------- -- | Class for all things that can be converted to memorable strings. -- See `renderMemorable` for how to use. class Memorable a where -- Do not lie. Use @`testMemLen`@. type MemLen a :: Nat renderMem :: MonadPut m => a -> Coding m () parserMem :: MonadGet m => Coding m a memBitSize :: forall a. (KnownNat (MemLen a)) => Proxy a -> Int memBitSize _ = fromIntegral $ natVal (Proxy :: Proxy (MemLen a)) -- | Use this with tasty-quickcheck (or your prefered testing framework) to -- make sure you aren't lying about `MemLen`. -- -- @ -- testProperty "MemLen Word8" $ forAll (arbitrary :: Gen Word8) `testMemLen` -- @ testMemLen :: forall a. (KnownNat (MemLen a), Memorable a) => a -> Bool testMemLen a = let p :: Coding PutM () p = renderMem a (x,bs) = runPutM (runCoding p (\a x _ -> return x) 0 0) l = fromIntegral $ natVal (Proxy :: Proxy (MemLen a)) bl = 8 * fromIntegral (BL.length bs) - x in l == bl putUnaligned :: (MonadPut m, FiniteBits b) => b -> Coding m () putUnaligned b = putBitsFrom (pred $ finiteBitSize b) b instance Memorable Word8 where type MemLen Word8 = 8 renderMem = putUnaligned parserMem = getBitsFrom (pred $ memBitSize (Proxy :: Proxy Word8)) 0 instance Memorable Word16 where type MemLen Word16 = 16 renderMem = putUnaligned parserMem = getBitsFrom (pred $ memBitSize (Proxy :: Proxy Word16)) 0 instance Memorable Word32 where type MemLen Word32 = 32 renderMem = putUnaligned parserMem = getBitsFrom (pred $ memBitSize (Proxy :: Proxy Word32)) 0 instance Memorable Word64 where type MemLen Word64 = 64 renderMem = putUnaligned parserMem = getBitsFrom (pred $ memBitSize (Proxy :: Proxy Word64)) 0 instance Memorable Int8 where type MemLen Int8 = 8 renderMem = putUnaligned parserMem = getBitsFrom (pred $ memBitSize (Proxy :: Proxy Int8)) 0 instance Memorable Int16 where type MemLen Int16 = 16 renderMem = putUnaligned parserMem = getBitsFrom (pred $ memBitSize (Proxy :: Proxy Int16)) 0 instance Memorable Int32 where type MemLen Int32 = 32 renderMem = putUnaligned parserMem = getBitsFrom (pred $ memBitSize (Proxy :: Proxy Int32)) 0 instance Memorable Int64 where type MemLen Int64 = 64 renderMem = putUnaligned parserMem = getBitsFrom (pred $ memBitSize (Proxy :: Proxy Int64)) 0 instance (Memorable a, Memorable b) => Memorable (a,b) where type MemLen (a,b) = MemLen a + MemLen b renderMem (a,b) = renderMem a >> renderMem b parserMem = (,) <$> parserMem <*> parserMem instance (Memorable a, Memorable b, Memorable c) => Memorable (a,b,c) where type MemLen (a,b,c) = MemLen a + MemLen b + MemLen c renderMem (a,b,c) = renderMem a >> renderMem b >> renderMem c parserMem = (,,) <$> parserMem <*> parserMem <*> parserMem instance (Memorable a, Memorable b, Memorable c, Memorable d) => Memorable (a,b,c,d) where type MemLen (a,b,c,d) = MemLen a + MemLen b + MemLen c + MemLen d renderMem (a,b,c,d) = renderMem a >> renderMem b >> renderMem c >> renderMem d parserMem = (,,,) <$> parserMem <*> parserMem <*> parserMem <*> parserMem instance (Memorable a, Memorable b, Memorable c, Memorable d, Memorable e) => Memorable (a,b,c,d,e) where type MemLen (a,b,c,d,e) = MemLen a + MemLen b + MemLen c + MemLen d + MemLen e renderMem (a,b,c,d,e) = renderMem a >> renderMem b >> renderMem c >> renderMem d >> renderMem e parserMem = (,,,,) <$> parserMem <*> parserMem <*> parserMem <*> parserMem <*> parserMem #ifdef DATA_DWORD instance Memorable Word96 where type MemLen Word96 = 96 renderMem (Word96 h l) = renderMem h >> renderMem l parserMem = Word96 <$> parserMem <*> parserMem instance Memorable Word128 where type MemLen Word128 = 128 renderMem (Word128 h l) = renderMem h >> renderMem l parserMem = Word128 <$> parserMem <*> parserMem instance Memorable Word160 where type MemLen Word160 = 160 renderMem (Word160 h l) = renderMem h >> renderMem l parserMem = Word160 <$> parserMem <*> parserMem instance Memorable Word192 where type MemLen Word192 = 192 renderMem (Word192 h l) = renderMem h >> renderMem l parserMem = Word192 <$> parserMem <*> parserMem instance Memorable Word224 where type MemLen Word224 = 224 renderMem (Word224 h l) = renderMem h >> renderMem l parserMem = Word224 <$> parserMem <*> parserMem instance Memorable Word256 where type MemLen Word256 = 256 renderMem (Word256 h l) = renderMem h >> renderMem l parserMem = Word256 <$> parserMem <*> parserMem instance Memorable Int96 where type MemLen Int96 = 96 renderMem (Int96 h l) = renderMem h >> renderMem l parserMem = Int96 <$> parserMem <*> parserMem instance Memorable Int128 where type MemLen Int128 = 128 renderMem (Int128 h l) = renderMem h >> renderMem l parserMem = Int128 <$> parserMem <*> parserMem instance Memorable Int160 where type MemLen Int160 = 160 renderMem (Int160 h l) = renderMem h >> renderMem l parserMem = Int160 <$> parserMem <*> parserMem instance Memorable Int192 where type MemLen Int192 = 192 renderMem (Int192 h l) = renderMem h >> renderMem l parserMem = Int192 <$> parserMem <*> parserMem instance Memorable Int224 where type MemLen Int224 = 224 renderMem (Int224 h l) = renderMem h >> renderMem l parserMem = Int224 <$> parserMem <*> parserMem instance Memorable Int256 where type MemLen Int256 = 256 renderMem (Int256 h l) = renderMem h >> renderMem l parserMem = Int256 <$> parserMem <*> parserMem #endif #ifdef NETWORK_IP -- | >>> renderMemorable threeWordsFor32Bits (ip4FromOctets 127 0 0 1) -- "shore-pick-pets" instance Memorable IP4 where type MemLen IP4 = 32 renderMem (IP4 w) = renderMem w parserMem = IP4 <$> parserMem instance Memorable IP6 where type MemLen IP6 = 128 renderMem (IP6 w) = renderMem w parserMem = IP6 <$> parserMem #endif #ifdef CRYPTONITE #define DIGEST_INST(NAME,BITS) \ instance Memorable (Digest NAME) where {\ type MemLen (Digest NAME) = BITS; \ renderMem = mapM_ putUnaligned . B.unpack . convert; \ parserMem = do { \ let {b = (BITS) `div` 8;}; \ fromJust <$> (digestFromByteString . B.pack) <$> replicateM b (getBitsFrom 7 0); \ }} DIGEST_INST(Whirlpool,512) DIGEST_INST(Blake2s_224,224) DIGEST_INST(Blake2s_256,256) DIGEST_INST(Blake2sp_224,224) DIGEST_INST(Blake2sp_256,256) DIGEST_INST(Blake2b_512,512) DIGEST_INST(Blake2bp_512,512) DIGEST_INST(Tiger,192) DIGEST_INST(Skein512_512,512) DIGEST_INST(Skein512_384,384) DIGEST_INST(Skein512_256,256) DIGEST_INST(Skein512_224,224) DIGEST_INST(Skein256_224,224) DIGEST_INST(Skein256_256,256) DIGEST_INST(SHA512t_256,256) DIGEST_INST(SHA512t_224,224) DIGEST_INST(SHA512,512) DIGEST_INST(SHA384,384) DIGEST_INST(SHA3_512,512) DIGEST_INST(SHA3_384,384) DIGEST_INST(SHA3_256,256) DIGEST_INST(SHA3_224,224) DIGEST_INST(SHA256,256) DIGEST_INST(SHA224,224) DIGEST_INST(SHA1,160) DIGEST_INST(RIPEMD160,160) -- | -- >>> :set -XOverloadedStrings -- >>> import Data.ByteString -- >>> import Crypto.Hash -- >>> let myPattern = padHex (four flw10) -- >>> renderMemorable myPattern (hash ("anExample" :: ByteString) :: Digest MD5) -- "bark-most-gush-tuft-1b7155ab0dce3ecb4195fc" DIGEST_INST(MD5,128) DIGEST_INST(MD4,128) DIGEST_INST(MD2,128) DIGEST_INST(Keccak_512,512) DIGEST_INST(Keccak_384,384) DIGEST_INST(Keccak_256,256) DIGEST_INST(Keccak_224,224) #undef DIGEST_INST #endif -- | This is the function to use when you want to turn your values into a -- memorable strings. -- -- >>> import Data.Word -- >>> import Data.Memorable.Theme.Words -- >>> let myPattern = words8 .- words8 -- >>> renderMemorable myPattern (0x0123 :: Word16) -- "cats-bulk" renderMemorable :: (MemRender p, Depth p ~ MemLen a, Memorable a) => Proxy p -> a -> String renderMemorable p a = renderMemorableByteString p (runRender a) runRender :: Memorable a => a -> ByteString runRender c = runPutL (runCoding (renderMem c) (\_ _ _ -> pure ()) 0 0) runParser :: Memorable a => ByteString -> a runParser = runGet (runCoding parserMem (\a _ _ -> pure a) 0 0) -- | Render a `ByteString` as a more memorable `String`. renderMemorableByteString :: MemRender a => Proxy a -> ByteString -> String renderMemorableByteString p = runGetL (runCoding (render p) (\a _ _ -> return a) 0 0) --runGet (runBitGet . flip evalStateT 0 . unBitPull $ render p) -- | Generate a random string. renderRandom :: forall a. (MemRender a, KnownNat (Depth a)) => Proxy a -> IO String renderRandom p = do let nBits = getDepth p nBytes = fromIntegral $ nBits `div` 8 + 1 bs <- pack <$> replicateM nBytes randomIO return $ renderMemorableByteString p bs -- | Render any `Hashable` value as a 32 bit pattern. renderHashable32 :: (MemRender p, Depth p ~ 32, Hashable a) => Proxy p -> a -> String renderHashable32 p a = renderMemorable p (fromIntegral $ hash a :: Word32) -- | Render any `Hashable` value as a 16 bit pattern. renderHashable16 :: (MemRender p, Depth p ~ 16, Hashable a) => Proxy p -> a -> String renderHashable16 p a = renderMemorable p (fromIntegral $ hash a :: Word16) -- | Render any `Hashable` value as a 8 bit pattern. renderHashable8 :: (MemRender p, Depth p ~ 8, Hashable a) => Proxy p -> a -> String renderHashable8 p a = renderMemorable p (fromIntegral $ hash a :: Word8)
luke-clifton/memorable-bits
src/Data/Memorable/Internal.hs
bsd-2-clause
31,891
187
91
9,376
11,860
6,213
5,647
-1
-1
{-| Module: NLP.Dictionary.StarDict.Regular Copyright: (c) 2016 Al Zohali License: BSD3 Maintainer: Al Zohali <zohl@fmap.me> Stability: experimental = Description Tools for StarDict dictionaries. Every call of 'getEntries' will perform file reading operation to retrieve requested data. For faster access see 'NLP.Dictionary.StarDict.InMemory'. -} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE DeriveGeneric #-} module NLP.Dictionary.StarDict.Regular (tag) where import Prelude hiding (takeWhile) import Data.Binary.Get (runGet) import Data.Map.Strict (Map) import Data.Maybe (maybeToList) import Data.Text.Lazy (Text) import System.IO (Handle, IOMode(..), SeekMode(..), withFile, hSeek) import NLP.Dictionary (Dictionary(..)) import qualified Data.ByteString.Lazy as BS import qualified Data.Map.Strict as Map import qualified Data.Text.Lazy as T import Control.DeepSeq (NFData(..)) import GHC.Generics (Generic) import NLP.Dictionary.StarDict.Common (StarDict(..), IfoFile(..), readIfoFile, readIndexFile, getIndexNumber, checkDataFile, mkDataParser, Renderer, IfoFilePath) import Data.Tagged (Tagged(..), untag) type Index = Map Text (Int, Int) data Implementation = Implementation { sdIfoFile :: IfoFile , sdIndex :: Index , sdDataPath :: FilePath , sdRender :: Renderer } deriving Generic instance NFData Implementation instance Dictionary Implementation where getEntries str (Implementation {..}) = withFile sdDataPath ReadMode extractEntries where extractEntries :: Handle -> IO [Text] extractEntries h = mapM (extractEntry h) . maybeToList . Map.lookup str $ sdIndex extractEntry :: Handle -> (Int, Int) -> IO Text extractEntry h (offset, size) = do hSeek h AbsoluteSeek (fromIntegral offset) T.concat . map sdRender . runGet (mkDataParser . ifoSameTypeSequence $ sdIfoFile) <$> BS.hGet h size instance StarDict Implementation where getIfoFile = sdIfoFile mkDictionary taggedIfoPath sdRender = do let ifoPath = untag taggedIfoPath sdIfoFile <- readIfoFile ifoPath sdIndex <- Map.fromList <$> readIndexFile ifoPath (getIndexNumber . ifoIdxOffsetBits $ sdIfoFile) sdDataPath <- checkDataFile ifoPath return Implementation {..} -- | Tag for ifoPath to distinct dictionary type. tag :: IfoFilePath -> Tagged Implementation IfoFilePath tag = Tagged
zohl/dictionaries
src/NLP/Dictionary/StarDict/Regular.hs
bsd-3-clause
2,479
0
15
419
582
334
248
46
1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module UnitB.FunctionTable.Spec.LaTeX where import Control.Lens import Control.Monad.Writer import Control.Precondition import Data.List as L import Data.Text hiding (toUpper) import Text.LaTeX as T hiding (tex,(&)) import qualified Text.LaTeX as T import Text.LaTeX.Base.Class hiding (fromLaTeX) import Text.LaTeX.Base.Syntax import qualified Text.LaTeX.Packages.Color as T import Text.LaTeX.Packages.Graphicx import Text.LaTeX.Packages.Hyperref import UnitB.FunctionTable.Spec.Doc hiding (item,paragraph) import UnitB.FunctionTable.Spec.Types as T specToTeX :: TeXSpec () -> LaTeX specToTeX s = documentclass [] article <> usepackage [] "multirow" <> usepackage [] "amsmath" <> usepackage [] "array" <> usepackage [] "amssymb" <> usepackage [] "hyperref" <> usepackage ["normalem"] "ulem" <> usepackage [] graphicx <> usepackage ["table"] "xcolor" -- <> comm1 "newcommand" (raw "\\dom") <> braces (textsf "dom") <> mathComm' "dom" <> renewcommand "between" 3 (raw "#1 \\le #2 \\le #3") -- <> renewcommand "between" 3 (raw "#1 \\1\\le #2 \\1\\le #3") <> s^.newCommands <> document (mconcat $ L.intersperse "\n" $ either (foldMap renderDoc . ($ ())) (rendertex.snd) <$> s^.specs.contents) mathComm' :: LaTeXC t => Text -> t mathComm' txt = mathComm txt (textsf $ rendertex txt) mathComm :: LaTeXC t => Text -> t -> t mathComm c txt = comm1 "newcommand" (raw $ "\\" <> c) <> braces txt newcommand :: LaTeXC t => Text -> Int -> t -> t newcommand c n txt = commS "newcommand" <> braces (raw $ "\\" <> c) <> liftL (\t -> raw "[" <> t <> raw "]") (fromString $ show n) <> braces txt renewcommand :: LaTeXC t => Text -> Int -> t -> t renewcommand c n txt = commS "renewcommand" <> braces (raw $ "\\" <> c) <> liftL (\t -> raw "[" <> t <> raw "]") (fromString $ show n) <> braces txt arg :: LaTeXC t => Int -> t arg n = raw $ "#" <> pack (show n) sout :: LaTeXC l => l -> l sout = liftL $ \l -> TeXComm "sout" [FixArg l] cellcolor :: (Render c) => c -> LaTeX cellcolor c = TeXComm "cellcolor" [FixArg $ rendertex c] instance DocFormat LaTeX where renderDoc (Ct t) = contentToTeX t where contentToTeX (Line ln) = fromString ln contentToTeX (Verbatim _ ln) = T.verbatim $ pack ln contentToTeX (Bold ln) = textbf $ foldMap contentToTeX ln contentToTeX (Italics ln) = emph $ foldMap contentToTeX ln contentToTeX (StrikeThrough ln) = sout $ foldMap contentToTeX ln contentToTeX (Item ls) = itemize $ mconcat $ (item Nothing <>) . contentToTeX <$> ls contentToTeX (Enum ls) = enumerate $ mconcat $ (item Nothing <>) . contentToTeX <$> ls -- contentToTeX (Image _tag path) = includegraphics [] path contentToTeX (Image tag path) = hyperimage (createURL path) (contentToTeX tag) contentToTeX (Link tag path) = href [] (createURL path) (contentToTeX tag) contentToTeX (DocTable t) = tabular Nothing (L.intersperse VerticalLine $ L.replicate (columns t) LeftColumn) $ mkRow (heading t) <> lnbk <> hline <> mconcat (L.intersperse lnbk $ L.map mkRow (rows t)) where toLaTeXColor Red = T.Red toLaTeXColor Yellow = T.Yellow toLaTeXColor Green = T.Green mkCell (FormatCell c xs) = maybe mempty (cellcolor . toLaTeXColor) c <> fromString xs mkRow = mkRow' . L.map mkCell mkRow' [] = mempty mkRow' (x:xs) = L.foldl (T.&) x xs contentToTeX Nil = mempty contentToTeX (Seq x y) = contentToTeX x <> contentToTeX y renderDoc (Title lvl t) | lvl == 0 = title $ fromString t | lvl == 1 = section $ fromString t | lvl == 2 = subsection $ fromString t | lvl == 3 = subsubsection $ fromString t | lvl == 4 = paragraph $ fromString t | lvl == 5 = subparagraph $ fromString t | otherwise = assertFalse' "too much nesting"
unitb/logic-function-tables
src/UnitB/FunctionTable/Spec/LaTeX.hs
bsd-3-clause
4,478
0
19
1,421
1,456
738
718
-1
-1
module Main (main) where import Control.Applicative import Data.Maybe import Data.SemVer.Range import Test.Tasty import Test.Tasty.QuickCheck as QC infixr 0 `to` to :: a -> b -> (a, b) to a b = (a, b) main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [properties] properties :: TestTree properties = testGroup "Properties" [ exampleVersionProps , invalidVersionProps , exampleRangeProps , simpleRangeProps , advancedRangeProps ] exampleVersionProps :: TestTree exampleVersionProps = testGroup "version examples" $ mk <$> exampleVersions where mk (name, v) = testProperty name $ once $ parseVersion name === Just v invalidVersionProps :: TestTree invalidVersionProps = testGroup "invalid version examples" $ mk <$> invalidVersions where mk name = testProperty name $ once $ isNothing $ parseVersion name exampleRangeProps :: TestTree exampleRangeProps = testGroup "range examples" $ mk <$> exampleRanges where mk (name, v) = testProperty name $ once $ parseVersionRange name === Just v simpleRangeProps :: TestTree simpleRangeProps = testGroup "succeed parsing simple ranges" $ mk <$> advancedRanges where mk (_, simple) = testProperty simple $ once $ isJust $ parseVersionRange simple advancedRangeProps :: TestTree advancedRangeProps = testGroup "advanced range examples" $ mk <$> advancedRanges where mk (advanced, simple) = testProperty advanced $ once $ parseVersionRange advanced === parseVersionRange simple exampleVersions :: [(String, Version)] exampleVersions = [ "1.2.3" `to` version 1 2 3 , "1.2.3-beta.4" `to` Version 1 2 3 [IStr "beta", INum 4] ] invalidVersions :: [String] invalidVersions = [ "1.2" , "a.b.c" ] exampleRanges :: [(String, VersionRange)] exampleRanges = [ ">=1.2.7" `to` range ROGE (version 1 2 7) , "<1.3.0" `to` range ROLT (version 1 3 0) , ">=1.2.7 <1.3.0" `to` range ROGE (version 1 2 7) /\ range ROLT (version 1 3 0) , "1.2.7 || >=1.2.9 <2.0.0" `to` range ROEQ (version 1 2 7) \/ (range ROGE (version 1 2 9) /\ range ROLT (version 2 0 0)) ] advancedRanges :: [(String, String)] advancedRanges = [ "1.2.3 - 2.3.4" `to` ">=1.2.3 <=2.3.4" , "1.2 - 2.3.4" `to` ">=1.2.0 <=2.3.4" , "1.2.3 - 2.3" `to` ">=1.2.3 <2.4.0" , "1.2.3 - 2" `to` ">=1.2.3 <3.0.0" -- X-Ranges , "*" `to` ">=0.0.0" , "1.x" `to` ">=1.0.0 <2.0.0" , "1.2.x" `to` ">=1.2.0 <1.3.0" -- Partial range , "" `to` ">=0.0.0" , "1" `to` ">=1.0.0 <2.0.0" , "1.x.x" `to` ">=1.0.0 <2.0.0" , "1.2" `to` ">=1.2.0 <1.3.0" -- Tilde ranges , "~1.2.3" `to` ">=1.2.3 <1.3.0" , "~1.2" `to` ">=1.2.0 <1.3.0" , "~1" `to` ">=1.0.0 <2.0.0" , "~0.2.3" `to` ">=0.2.3 <0.3.0" , "~0.2" `to` ">=0.2.0 <0.3.0" , "~0" `to` ">=0.0.0 <1.0.0" , "~1.2.3-beta.2" `to` ">=1.2.3-beta.2 <1.3.0" -- Caret ranges , "^1.2.3" `to` ">=1.2.3 <2.0.0" , "^0.2.3" `to` ">=0.2.3 <0.3.0" , "^0.0.3" `to` ">=0.0.3 <0.0.4" , "^1.2.3-beta.2" `to` ">=1.2.3-beta.2 <2.0.0" , "^0.0.3-beta" `to` ">=0.0.3-beta <0.0.4" -- missing patch , "^1.2.x" `to` ">=1.2.0 <2.0.0" , "^0.0.x" `to` ">=0.0.0 <0.1.0" , "^0.0" `to` ">=0.0.0 <0.1.0" -- missing minor , "^1.x" `to` ">=1.0.0 <2.0.0" , "^0.x" `to` ">=0.0.0 <1.0.0" ]
phadej/semver-range
test/Tests.hs
bsd-3-clause
3,225
0
11
613
960
554
406
79
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module LLVMFrontend.Helpers where import Data.ByteString.Short import Control.Monad.State import LLVM.AST import LLVM.AST.Type import LLVM.AST.Global import qualified LLVM.AST as AST import qualified LLVM.AST.Linkage as LL import qualified LLVM.AST.Attribute as LA import qualified LLVM.AST.CallingConvention as LCC import qualified LLVM.AST.FloatingPointPredicate as LFP import qualified LLVM.AST.Instruction as LI import qualified LLVM.AST.Global as LG import qualified LLVM.AST.Constant as LC import qualified LLVM.AST.Operand as LO import qualified LLVM.AST.Name as LN import qualified LLVM.AST.Type as LT import qualified LLVM.AST.Float as LF -- Used in generation of LLVM backend code newtype LLVM a = LLVM (State AST.Module a) deriving (Functor, Applicative, Monad, MonadState AST.Module) -- Creates a simple function which returns void and takes no arguments defineFn :: LT.Type -> ShortByteString -> [BasicBlock] -> Definition defineFn typ label body = GlobalDefinition $ functionDefaults { name = Name label, returnType = typ, basicBlocks = body } -- Create a reference to a local variable local :: Type -> Name -> Operand local = LocalReference -- Create a reference to a global variable global :: Type -> Name -> LC.Constant global = LC.GlobalReference -- Create a reference to an 'extern'd variable externf :: Type -> Name -> Operand externf ty nm = ConstantOperand (LC.GlobalReference ty nm) {- Constants -} -- 32-bit integer constant int :: Integral a => a -> LC.Constant int = LC.Int 32 . fromIntegral float :: Float -> LC.Constant float = LC.Float . LF.Single add :: Operand -> Operand -> Instruction add a b = LI.Add False False a b [] mult :: Operand -> Operand -> Instruction mult a b = LI.Mul False False a b [] -- Arithmetic and Constants for floating points fadd :: Operand -> Operand -> Instruction fadd a b = FAdd NoFastMathFlags a b [] fsub :: Operand -> Operand -> Instruction fsub a b = FSub NoFastMathFlags a b [] fmul :: Operand -> Operand -> Instruction fmul a b = FMul NoFastMathFlags a b [] fdiv :: Operand -> Operand -> Instruction fdiv a b = FDiv NoFastMathFlags a b [] fcmp :: LFP.FloatingPointPredicate -> Operand -> Operand -> Instruction fcmp cond a b = FCmp cond a b [] cons :: LC.Constant -> Operand cons = ConstantOperand uitofp :: Type -> Operand -> Instruction uitofp ty a = UIToFP a ty [] toArgs :: [Operand] -> [(Operand, [LA.ParameterAttribute])] toArgs = map (\x -> (x, [])) -- Effects call :: Operand -> [Operand] -> Instruction call fn args = Call Nothing LCC.C [] (Right fn) (toArgs args) [] [] alloca :: Type -> Instruction alloca ty = Alloca ty Nothing 0 [] store :: Operand -> Operand -> Instruction store ptr val = Store False ptr val Nothing 0 [] load :: Operand -> Instruction load ptr = Load False ptr Nothing 0 [] -- Control Flow br :: Name -> Named Terminator br val = Do $ Br val [] cbr :: Operand -> Name -> Name -> Named Terminator cbr cond tr fl = Do $ CondBr cond tr fl [] phi :: Type -> [(Operand, Name)] -> Instruction phi ty incoming = Phi ty incoming [] ret :: Operand -> Named Terminator ret val = Do $ Ret (Just val) [] retvoid :: Named Terminator retvoid = Do $ Ret Nothing []
LouisJenkinsCS/Minimal-JVM
LLVMFrontend/Helpers.hs
bsd-3-clause
3,413
0
9
759
1,077
594
483
75
1
module Client.Quote where import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Resource import qualified Data.ByteString.Char8 as BS import Data.String import Data.Conduit.Binary hiding (mapM_) import Data.Conduit import Finance.TradeKing import System.IO doQuote :: [String] -> TradeKingApp -> IO () doQuote args app = do quotes <- stockQuotes app (map fromString args) mapM_ (putStrLn . show) quotes doInfo :: [String] -> TradeKingApp -> IO () doInfo args app = do infos <- stockInfos app (map fromString args) mapM_ (putStrLn . show) infos doStream :: [String] -> TradeKingApp -> IO () doStream args app = do let mySink = await >>= \x -> case x of Nothing -> return () Just x -> do liftIO (putStrLn (show x)) liftIO (hFlush stdout) mySink streamQuotes app (map fromString args) (\s -> s $$ mySink)
tathougies/hstradeking
client/Client/Quote.hs
bsd-3-clause
968
0
21
267
335
173
162
28
2
{-# LANGUAGE OverloadedStrings #-} -- | -- Module : Network.TLS.Packet -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- -- the Packet module contains everything necessary to serialize and deserialize things -- with only explicit parameters, no TLS state is involved here. -- module Network.TLS.Packet ( -- * params for encoding and decoding CurrentParams(..) -- * marshall functions for header messages , decodeHeader , decodeDeprecatedHeaderLength , decodeDeprecatedHeader , encodeHeader , encodeHeaderNoVer -- use for SSL3 -- * marshall functions for alert messages , decodeAlert , decodeAlerts , encodeAlerts -- * marshall functions for handshake messages , decodeHandshakeRecord , decodeHandshake , decodeDeprecatedHandshake , encodeHandshake , encodeHandshakes , encodeHandshakeHeader , encodeHandshakeContent -- * marshall functions for change cipher spec message , decodeChangeCipherSpec , encodeChangeCipherSpec , decodePreMasterSecret , encodePreMasterSecret , encodeSignedDHParams , encodeSignedECDHParams , decodeReallyServerKeyXchgAlgorithmData -- * generate things for packet content , generateMasterSecret , generateKeyBlock , generateClientFinished , generateServerFinished , generateCertificateVerify_SSL -- * for extensions parsing , getSignatureHashAlgorithm , putSignatureHashAlgorithm ) where import Network.TLS.Imports import Network.TLS.Struct import Network.TLS.Wire import Network.TLS.Cap import Data.Maybe (fromJust) import Data.Word import Control.Monad import Data.ASN1.Types (fromASN1, toASN1) import Data.ASN1.Encoding (decodeASN1', encodeASN1') import Data.ASN1.BinaryEncoding (DER(..)) import Data.X509 (CertificateChainRaw(..), encodeCertificateChain, decodeCertificateChain) import Network.TLS.Crypto import Network.TLS.MAC import Network.TLS.Cipher (CipherKeyExchangeType(..)) import Network.TLS.Util.Serialization (os2ip,i2ospOf_) import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Data.ByteArray (ByteArrayAccess) import qualified Data.ByteArray as B (convert) data CurrentParams = CurrentParams { cParamsVersion :: Version -- ^ current protocol version , cParamsKeyXchgType :: Maybe CipherKeyExchangeType -- ^ current key exchange type , cParamsSupportNPN :: Bool -- ^ support Next Protocol Negotiation extension } deriving (Show,Eq) {- marshall helpers -} getVersion :: Get Version getVersion = do major <- getWord8 minor <- getWord8 case verOfNum (major, minor) of Nothing -> fail ("invalid version : " ++ show major ++ "," ++ show minor) Just v -> return v putVersion :: Version -> Put putVersion ver = putWord8 major >> putWord8 minor where (major, minor) = numericalVer ver getHeaderType :: Get ProtocolType getHeaderType = do ty <- getWord8 case valToType ty of Nothing -> fail ("invalid header type: " ++ show ty) Just t -> return t putHeaderType :: ProtocolType -> Put putHeaderType = putWord8 . valOfType getHandshakeType :: Get HandshakeType getHandshakeType = do ty <- getWord8 case valToType ty of Nothing -> fail ("invalid handshake type: " ++ show ty) Just t -> return t {- - decode and encode headers -} decodeHeader :: ByteString -> Either TLSError Header decodeHeader = runGetErr "header" $ liftM3 Header getHeaderType getVersion getWord16 decodeDeprecatedHeaderLength :: ByteString -> Either TLSError Word16 decodeDeprecatedHeaderLength = runGetErr "deprecatedheaderlength" $ subtract 0x8000 <$> getWord16 decodeDeprecatedHeader :: Word16 -> ByteString -> Either TLSError Header decodeDeprecatedHeader size = runGetErr "deprecatedheader" $ do 1 <- getWord8 version <- getVersion return $ Header ProtocolType_DeprecatedHandshake version size encodeHeader :: Header -> ByteString encodeHeader (Header pt ver len) = runPut (putHeaderType pt >> putVersion ver >> putWord16 len) {- FIXME check len <= 2^14 -} encodeHeaderNoVer :: Header -> ByteString encodeHeaderNoVer (Header pt _ len) = runPut (putHeaderType pt >> putWord16 len) {- FIXME check len <= 2^14 -} {- - decode and encode ALERT -} decodeAlert :: Get (AlertLevel, AlertDescription) decodeAlert = do al <- getWord8 ad <- getWord8 case (valToType al, valToType ad) of (Just a, Just d) -> return (a, d) (Nothing, _) -> fail "cannot decode alert level" (_, Nothing) -> fail "cannot decode alert description" decodeAlerts :: ByteString -> Either TLSError [(AlertLevel, AlertDescription)] decodeAlerts = runGetErr "alerts" $ loop where loop = do r <- remaining if r == 0 then return [] else liftM2 (:) decodeAlert loop encodeAlerts :: [(AlertLevel, AlertDescription)] -> ByteString encodeAlerts l = runPut $ mapM_ encodeAlert l where encodeAlert (al, ad) = putWord8 (valOfType al) >> putWord8 (valOfType ad) {- decode and encode HANDSHAKE -} decodeHandshakeRecord :: ByteString -> GetResult (HandshakeType, Bytes) decodeHandshakeRecord = runGet "handshake-record" $ do ty <- getHandshakeType content <- getOpaque24 return (ty, content) decodeHandshake :: CurrentParams -> HandshakeType -> ByteString -> Either TLSError Handshake decodeHandshake cp ty = runGetErr ("handshake[" ++ show ty ++ "]") $ case ty of HandshakeType_HelloRequest -> decodeHelloRequest HandshakeType_ClientHello -> decodeClientHello HandshakeType_ServerHello -> decodeServerHello HandshakeType_Certificate -> decodeCertificates HandshakeType_ServerKeyXchg -> decodeServerKeyXchg cp HandshakeType_CertRequest -> decodeCertRequest cp HandshakeType_ServerHelloDone -> decodeServerHelloDone HandshakeType_CertVerify -> decodeCertVerify cp HandshakeType_ClientKeyXchg -> decodeClientKeyXchg cp HandshakeType_Finished -> decodeFinished HandshakeType_NPN -> do unless (cParamsSupportNPN cp) $ fail "unsupported handshake type" decodeNextProtocolNegotiation decodeDeprecatedHandshake :: ByteString -> Either TLSError Handshake decodeDeprecatedHandshake b = runGetErr "deprecatedhandshake" getDeprecated b where getDeprecated = do 1 <- getWord8 ver <- getVersion cipherSpecLen <- fromEnum <$> getWord16 sessionIdLen <- fromEnum <$> getWord16 challengeLen <- fromEnum <$> getWord16 ciphers <- getCipherSpec cipherSpecLen session <- getSessionId sessionIdLen random <- getChallenge challengeLen let compressions = [0] return $ ClientHello ver random session ciphers compressions [] (Just b) getCipherSpec len | len < 3 = return [] getCipherSpec len = do [c0,c1,c2] <- map fromEnum <$> replicateM 3 getWord8 ([ toEnum $ c1 * 0x100 + c2 | c0 == 0 ] ++) <$> getCipherSpec (len - 3) getSessionId 0 = return $ Session Nothing getSessionId len = Session . Just <$> getBytes len getChallenge len | 32 < len = getBytes (len - 32) >> getChallenge 32 getChallenge len = ClientRandom . B.append (B.replicate (32 - len) 0) <$> getBytes len decodeHelloRequest :: Get Handshake decodeHelloRequest = return HelloRequest decodeClientHello :: Get Handshake decodeClientHello = do ver <- getVersion random <- getClientRandom32 session <- getSession ciphers <- getWords16 compressions <- getWords8 r <- remaining exts <- if hasHelloExtensions ver && r > 0 then fmap fromIntegral getWord16 >>= getExtensions else return [] return $ ClientHello ver random session ciphers compressions exts Nothing decodeServerHello :: Get Handshake decodeServerHello = do ver <- getVersion random <- getServerRandom32 session <- getSession cipherid <- getWord16 compressionid <- getWord8 r <- remaining exts <- if hasHelloExtensions ver && r > 0 then fmap fromIntegral getWord16 >>= getExtensions else return [] return $ ServerHello ver random session cipherid compressionid exts decodeServerHelloDone :: Get Handshake decodeServerHelloDone = return ServerHelloDone decodeCertificates :: Get Handshake decodeCertificates = do certsRaw <- CertificateChainRaw <$> (getWord24 >>= \len -> getList (fromIntegral len) getCertRaw) case decodeCertificateChain certsRaw of Left (i, s) -> fail ("error certificate parsing " ++ show i ++ ":" ++ s) Right cc -> return $ Certificates cc where getCertRaw = getOpaque24 >>= \cert -> return (3 + B.length cert, cert) decodeFinished :: Get Handshake decodeFinished = Finished <$> (remaining >>= getBytes) decodeNextProtocolNegotiation :: Get Handshake decodeNextProtocolNegotiation = do opaque <- getOpaque8 _ <- getOpaque8 -- ignore padding return $ HsNextProtocolNegotiation opaque decodeCertRequest :: CurrentParams -> Get Handshake decodeCertRequest cp = do certTypes <- map (fromJust . valToType . fromIntegral) <$> getWords8 sigHashAlgs <- if cParamsVersion cp >= TLS12 then Just <$> (getWord16 >>= getSignatureHashAlgorithms) else return Nothing dNameLen <- getWord16 -- FIXME: Decide whether to remove this check completely or to make it an option. -- when (cParamsVersion cp < TLS12 && dNameLen < 3) $ fail "certrequest distinguishname not of the correct size" dNames <- getList (fromIntegral dNameLen) getDName return $ CertRequest certTypes sigHashAlgs dNames where getSignatureHashAlgorithms len = getList (fromIntegral len) (getSignatureHashAlgorithm >>= \sh -> return (2, sh)) getDName = do dName <- getOpaque16 when (B.length dName == 0) $ fail "certrequest: invalid DN length" dn <- case decodeASN1' DER dName of Left e -> fail ("cert request decoding DistinguishedName ASN1 failed: " ++ show e) Right asn1s -> case fromASN1 asn1s of Left e -> fail ("cert request parsing DistinguishedName ASN1 failed: " ++ show e) Right (d,_) -> return d return (2 + B.length dName, dn) decodeCertVerify :: CurrentParams -> Get Handshake decodeCertVerify cp = CertVerify <$> getDigitallySigned (cParamsVersion cp) decodeClientKeyXchg :: CurrentParams -> Get Handshake decodeClientKeyXchg cp = -- case ClientKeyXchg <$> (remaining >>= getBytes) case cParamsKeyXchgType cp of Nothing -> error "no client key exchange type" Just cke -> ClientKeyXchg <$> parseCKE cke where parseCKE CipherKeyExchange_RSA = CKX_RSA <$> (remaining >>= getBytes) parseCKE CipherKeyExchange_DHE_RSA = parseClientDHPublic parseCKE CipherKeyExchange_DHE_DSS = parseClientDHPublic parseCKE CipherKeyExchange_DH_Anon = parseClientDHPublic parseCKE CipherKeyExchange_ECDHE_RSA = parseClientECDHPublic parseCKE CipherKeyExchange_ECDHE_ECDSA = parseClientECDHPublic parseCKE _ = error "unsupported client key exchange type" parseClientDHPublic = CKX_DH . dhPublic <$> getInteger16 parseClientECDHPublic = do len <- getWord8 formatTy <- getWord8 case formatTy of 4 -> do -- uncompressed let siz = fromIntegral len `div` 2 xb <- getBytes siz yb <- getBytes siz let x = os2ip xb y = os2ip yb return $ CKX_ECDH $ ecdhPublic x y siz _ -> error ("unsupported EC format type: " ++ show formatTy) decodeServerKeyXchg_DH :: Get ServerDHParams decodeServerKeyXchg_DH = getServerDHParams -- We don't support ECDH_Anon at this moment -- decodeServerKeyXchg_ECDH :: Get ServerECDHParams decodeServerKeyXchg_RSA :: Get ServerRSAParams decodeServerKeyXchg_RSA = ServerRSAParams <$> getInteger16 -- modulus <*> getInteger16 -- exponent decodeServerKeyXchgAlgorithmData :: Version -> CipherKeyExchangeType -> Get ServerKeyXchgAlgorithmData decodeServerKeyXchgAlgorithmData ver cke = toCKE where toCKE = case cke of CipherKeyExchange_RSA -> SKX_RSA . Just <$> decodeServerKeyXchg_RSA CipherKeyExchange_DH_Anon -> SKX_DH_Anon <$> decodeServerKeyXchg_DH CipherKeyExchange_DHE_RSA -> do dhparams <- getServerDHParams signature <- getDigitallySigned ver return $ SKX_DHE_RSA dhparams signature CipherKeyExchange_DHE_DSS -> do dhparams <- getServerDHParams signature <- getDigitallySigned ver return $ SKX_DHE_DSS dhparams signature CipherKeyExchange_ECDHE_RSA -> do dhparams <- getServerECDHParams signature <- getDigitallySigned ver return $ SKX_ECDHE_RSA dhparams signature CipherKeyExchange_ECDHE_ECDSA -> do dhparams <- getServerECDHParams signature <- getDigitallySigned ver return $ SKX_ECDHE_ECDSA dhparams signature _ -> do bs <- remaining >>= getBytes return $ SKX_Unknown bs decodeServerKeyXchg :: CurrentParams -> Get Handshake decodeServerKeyXchg cp = case cParamsKeyXchgType cp of Just cke -> ServerKeyXchg <$> decodeServerKeyXchgAlgorithmData (cParamsVersion cp) cke Nothing -> ServerKeyXchg . SKX_Unparsed <$> (remaining >>= getBytes) encodeHandshake :: Handshake -> ByteString encodeHandshake o = let content = runPut $ encodeHandshakeContent o in let len = fromIntegral $ B.length content in let header = case o of ClientHello _ _ _ _ _ _ (Just _) -> "" -- SSLv2 ClientHello message _ -> runPut $ encodeHandshakeHeader (typeOfHandshake o) len in B.concat [ header, content ] encodeHandshakes :: [Handshake] -> ByteString encodeHandshakes hss = B.concat $ map encodeHandshake hss encodeHandshakeHeader :: HandshakeType -> Int -> Put encodeHandshakeHeader ty len = putWord8 (valOfType ty) >> putWord24 len encodeHandshakeContent :: Handshake -> Put encodeHandshakeContent (ClientHello _ _ _ _ _ _ (Just deprecated)) = do putBytes deprecated encodeHandshakeContent (ClientHello version random session cipherIDs compressionIDs exts Nothing) = do putVersion version putClientRandom32 random putSession session putWords16 cipherIDs putWords8 compressionIDs putExtensions exts return () encodeHandshakeContent (ServerHello version random session cipherID compressionID exts) = putVersion version >> putServerRandom32 random >> putSession session >> putWord16 cipherID >> putWord8 compressionID >> putExtensions exts >> return () encodeHandshakeContent (Certificates cc) = putOpaque24 (runPut $ mapM_ putOpaque24 certs) where (CertificateChainRaw certs) = encodeCertificateChain cc encodeHandshakeContent (ClientKeyXchg ckx) = do case ckx of CKX_RSA encryptedPreMaster -> putBytes encryptedPreMaster CKX_DH clientDHPublic -> putInteger16 $ dhUnwrapPublic clientDHPublic CKX_ECDH clientECDHPublic -> do let (x,y,siz) = ecdhUnwrapPublic clientECDHPublic let xb = i2ospOf_ siz x yb = i2ospOf_ siz y putOpaque8 $ B.concat [B.singleton 4,xb,yb] encodeHandshakeContent (ServerKeyXchg skg) = case skg of SKX_RSA _ -> error "encodeHandshakeContent SKX_RSA not implemented" SKX_DH_Anon params -> putServerDHParams params SKX_DHE_RSA params sig -> putServerDHParams params >> putDigitallySigned sig SKX_DHE_DSS params sig -> putServerDHParams params >> putDigitallySigned sig SKX_ECDHE_RSA params sig -> putServerECDHParams params >> putDigitallySigned sig SKX_ECDHE_ECDSA params sig -> putServerECDHParams params >> putDigitallySigned sig SKX_Unparsed bytes -> putBytes bytes _ -> error ("encodeHandshakeContent: cannot handle: " ++ show skg) encodeHandshakeContent (HelloRequest) = return () encodeHandshakeContent (ServerHelloDone) = return () encodeHandshakeContent (CertRequest certTypes sigAlgs certAuthorities) = do putWords8 (map valOfType certTypes) case sigAlgs of Nothing -> return () Just l -> putWords16 $ map (\(x,y) -> (fromIntegral $ valOfType x) * 256 + (fromIntegral $ valOfType y)) l encodeCertAuthorities certAuthorities where -- Convert a distinguished name to its DER encoding. encodeCA dn = return $ encodeASN1' DER (toASN1 dn []) --B.concat $ L.toChunks $ encodeDN dn -- Encode a list of distinguished names. encodeCertAuthorities certAuths = do enc <- mapM encodeCA certAuths let totLength = sum $ map (((+) 2) . B.length) enc putWord16 (fromIntegral totLength) mapM_ (\ b -> putWord16 (fromIntegral (B.length b)) >> putBytes b) enc encodeHandshakeContent (CertVerify digitallySigned) = putDigitallySigned digitallySigned encodeHandshakeContent (Finished opaque) = putBytes opaque encodeHandshakeContent (HsNextProtocolNegotiation protocol) = do putOpaque8 protocol putOpaque8 $ B.replicate paddingLen 0 where paddingLen = 32 - ((B.length protocol + 2) `mod` 32) {- FIXME make sure it return error if not 32 available -} getRandom32 :: Get Bytes getRandom32 = getBytes 32 getServerRandom32 :: Get ServerRandom getServerRandom32 = ServerRandom <$> getRandom32 getClientRandom32 :: Get ClientRandom getClientRandom32 = ClientRandom <$> getRandom32 putRandom32 :: Bytes -> Put putRandom32 = putBytes putClientRandom32 :: ClientRandom -> Put putClientRandom32 (ClientRandom r) = putRandom32 r putServerRandom32 :: ServerRandom -> Put putServerRandom32 (ServerRandom r) = putRandom32 r getSession :: Get Session getSession = do len8 <- getWord8 case fromIntegral len8 of 0 -> return $ Session Nothing len -> Session . Just <$> getBytes len putSession :: Session -> Put putSession (Session Nothing) = putWord8 0 putSession (Session (Just s)) = putOpaque8 s getExtensions :: Int -> Get [ExtensionRaw] getExtensions 0 = return [] getExtensions len = do extty <- getWord16 extdatalen <- getWord16 extdata <- getBytes $ fromIntegral extdatalen extxs <- getExtensions (len - fromIntegral extdatalen - 4) return $ ExtensionRaw extty extdata : extxs putExtension :: ExtensionRaw -> Put putExtension (ExtensionRaw ty l) = putWord16 ty >> putOpaque16 l putExtensions :: [ExtensionRaw] -> Put putExtensions [] = return () putExtensions es = putOpaque16 (runPut $ mapM_ putExtension es) getSignatureHashAlgorithm :: Get HashAndSignatureAlgorithm getSignatureHashAlgorithm = do h <- fromJust . valToType <$> getWord8 s <- fromJust . valToType <$> getWord8 return (h,s) putSignatureHashAlgorithm :: HashAndSignatureAlgorithm -> Put putSignatureHashAlgorithm (h,s) = putWord8 (valOfType h) >> putWord8 (valOfType s) getServerDHParams :: Get ServerDHParams getServerDHParams = ServerDHParams <$> getBigNum16 <*> getBigNum16 <*> getBigNum16 putServerDHParams :: ServerDHParams -> Put putServerDHParams (ServerDHParams p g y) = mapM_ putBigNum16 [p,g,y] getServerECDHParams :: Get ServerECDHParams getServerECDHParams = do curveType <- getWord8 case curveType of 1 -> do -- explicit prime _prime <- getOpaque8 _a <- getOpaque8 _b <- getOpaque8 _base <- getOpaque8 _order <- getOpaque8 _cofactor <- getOpaque8 error "cannot handle explicit prime ECDH Params" 2 -> -- explicit_char2 error "cannot handle explicit char2 ECDH Params" 3 -> do -- ECParameters ECCurveType: curve name type w16 <- getWord16 -- ECParameters NamedCurve mxy <- getOpaque8 -- ECPoint let xy = B.drop 1 mxy siz = B.length xy `div` 2 (xb,yb) = B.splitAt siz xy x = os2ip xb y = os2ip yb return $ ServerECDHParams (ecdhParams w16) (ecdhPublic x y siz) _ -> error "unknown type for ECDH Params" putServerECDHParams :: ServerECDHParams -> Put putServerECDHParams (ServerECDHParams ecdhparams ecdhpub) = do let (w16,x,y,siz) = ecdhUnwrap ecdhparams ecdhpub putWord8 3 -- ECParameters ECCurveType: curve name type putWord16 w16 -- ECParameters NamedCurve let xb = i2ospOf_ siz x yb = i2ospOf_ siz y putOpaque8 $ B.concat [B.singleton 4,xb,yb] -- ECPoint getDigitallySigned :: Version -> Get DigitallySigned getDigitallySigned ver | ver >= TLS12 = DigitallySigned <$> (Just <$> getSignatureHashAlgorithm) <*> getOpaque16 | otherwise = DigitallySigned Nothing <$> getOpaque16 putDigitallySigned :: DigitallySigned -> Put putDigitallySigned (DigitallySigned mhash sig) = maybe (return ()) putSignatureHashAlgorithm mhash >> putOpaque16 sig {- - decode and encode ALERT -} decodeChangeCipherSpec :: ByteString -> Either TLSError () decodeChangeCipherSpec = runGetErr "changecipherspec" $ do x <- getWord8 when (x /= 1) (fail "unknown change cipher spec content") encodeChangeCipherSpec :: ByteString encodeChangeCipherSpec = runPut (putWord8 1) -- rsa pre master secret decodePreMasterSecret :: Bytes -> Either TLSError (Version, Bytes) decodePreMasterSecret = runGetErr "pre-master-secret" $ do liftM2 (,) getVersion (getBytes 46) encodePreMasterSecret :: Version -> Bytes -> Bytes encodePreMasterSecret version bytes = runPut (putVersion version >> putBytes bytes) -- | in certain cases, we haven't manage to decode ServerKeyExchange properly, -- because the decoding was too eager and the cipher wasn't been set yet. -- we keep the Server Key Exchange in it unparsed format, and this function is -- able to really decode the server key xchange if it's unparsed. decodeReallyServerKeyXchgAlgorithmData :: Version -> CipherKeyExchangeType -> Bytes -> Either TLSError ServerKeyXchgAlgorithmData decodeReallyServerKeyXchgAlgorithmData ver cke = runGetErr "server-key-xchg-algorithm-data" (decodeServerKeyXchgAlgorithmData ver cke) {- - generate things for packet content -} type PRF = Bytes -> Bytes -> Int -> Bytes generateMasterSecret_SSL :: ByteArrayAccess preMaster => preMaster -> ClientRandom -> ServerRandom -> Bytes generateMasterSecret_SSL premasterSecret (ClientRandom c) (ServerRandom s) = B.concat $ map (computeMD5) ["A","BB","CCC"] where computeMD5 label = hash MD5 $ B.concat [ B.convert premasterSecret, computeSHA1 label ] computeSHA1 label = hash SHA1 $ B.concat [ label, B.convert premasterSecret, c, s ] generateMasterSecret_TLS :: ByteArrayAccess preMaster => PRF -> preMaster -> ClientRandom -> ServerRandom -> Bytes generateMasterSecret_TLS prf premasterSecret (ClientRandom c) (ServerRandom s) = prf (B.convert premasterSecret) seed 48 where seed = B.concat [ "master secret", c, s ] generateMasterSecret :: ByteArrayAccess preMaster => Version -> preMaster -> ClientRandom -> ServerRandom -> Bytes generateMasterSecret SSL2 = generateMasterSecret_SSL generateMasterSecret SSL3 = generateMasterSecret_SSL generateMasterSecret TLS10 = generateMasterSecret_TLS prf_MD5SHA1 generateMasterSecret TLS11 = generateMasterSecret_TLS prf_MD5SHA1 generateMasterSecret TLS12 = generateMasterSecret_TLS prf_SHA256 generateKeyBlock_TLS :: PRF -> ClientRandom -> ServerRandom -> Bytes -> Int -> Bytes generateKeyBlock_TLS prf (ClientRandom c) (ServerRandom s) mastersecret kbsize = prf mastersecret seed kbsize where seed = B.concat [ "key expansion", s, c ] generateKeyBlock_SSL :: ClientRandom -> ServerRandom -> Bytes -> Int -> Bytes generateKeyBlock_SSL (ClientRandom c) (ServerRandom s) mastersecret kbsize = B.concat $ map computeMD5 $ take ((kbsize `div` 16) + 1) labels where labels = [ uncurry BC.replicate x | x <- zip [1..] ['A'..'Z'] ] computeMD5 label = hash MD5 $ B.concat [ mastersecret, computeSHA1 label ] computeSHA1 label = hash SHA1 $ B.concat [ label, mastersecret, s, c ] generateKeyBlock :: Version -> ClientRandom -> ServerRandom -> Bytes -> Int -> Bytes generateKeyBlock SSL2 = generateKeyBlock_SSL generateKeyBlock SSL3 = generateKeyBlock_SSL generateKeyBlock TLS10 = generateKeyBlock_TLS prf_MD5SHA1 generateKeyBlock TLS11 = generateKeyBlock_TLS prf_MD5SHA1 generateKeyBlock TLS12 = generateKeyBlock_TLS prf_SHA256 generateFinished_TLS :: PRF -> Bytes -> Bytes -> HashCtx -> Bytes generateFinished_TLS prf label mastersecret hashctx = prf mastersecret seed 12 where seed = B.concat [ label, hashFinal hashctx ] generateFinished_SSL :: Bytes -> Bytes -> HashCtx -> Bytes generateFinished_SSL sender mastersecret hashctx = B.concat [md5hash, sha1hash] where md5hash = hash MD5 $ B.concat [ mastersecret, pad2, md5left ] sha1hash = hash SHA1 $ B.concat [ mastersecret, B.take 40 pad2, sha1left ] lefthash = hashFinal $ flip hashUpdateSSL (pad1, B.take 40 pad1) $ foldl hashUpdate hashctx [sender,mastersecret] (md5left,sha1left) = B.splitAt 16 lefthash pad2 = B.replicate 48 0x5c pad1 = B.replicate 48 0x36 generateClientFinished :: Version -> Bytes -> HashCtx -> Bytes generateClientFinished ver | ver < TLS10 = generateFinished_SSL "CLNT" | ver < TLS12 = generateFinished_TLS prf_MD5SHA1 "client finished" | otherwise = generateFinished_TLS prf_SHA256 "client finished" generateServerFinished :: Version -> Bytes -> HashCtx -> Bytes generateServerFinished ver | ver < TLS10 = generateFinished_SSL "SRVR" | ver < TLS12 = generateFinished_TLS prf_MD5SHA1 "server finished" | otherwise = generateFinished_TLS prf_SHA256 "server finished" generateCertificateVerify_SSL :: Bytes -> HashCtx -> Bytes generateCertificateVerify_SSL = generateFinished_SSL "" encodeSignedDHParams :: ServerDHParams -> ClientRandom -> ServerRandom -> Bytes encodeSignedDHParams dhparams cran sran = runPut $ putClientRandom32 cran >> putServerRandom32 sran >> putServerDHParams dhparams -- Combination of RFC 5246 and 4492 is ambiguous. -- Let's assume ecdhe_rsa and ecdhe_dss are identical to -- dhe_rsa and dhe_dss. encodeSignedECDHParams :: ServerECDHParams -> ClientRandom -> ServerRandom -> Bytes encodeSignedECDHParams dhparams cran sran = runPut $ putClientRandom32 cran >> putServerRandom32 sran >> putServerECDHParams dhparams
tolysz/hs-tls
core/Network/TLS/Packet.hs
bsd-3-clause
27,524
292
21
6,537
6,460
3,277
3,183
512
11
module H99.MultiwayTreesSpec (spec) where import H99.MultiwayTrees import Test.Hspec tree1 = Node 'a' [] tree2 = Node 'a' [Node 'b' []] tree3 = Node 'a' [Node 'b' [Node 'c' []]] tree4 = Node 'b' [Node 'd' [], Node 'e' []] tree5 = Node 'a' [ Node 'f' [Node 'g' []], Node 'c' [], Node 'b' [Node 'd' [], Node 'e' []] ] tree6 = Node 'a' [ Node 'f' [Node 'g' []], Node 'c' [], Node 'b' [Node 'd' [], Node 'e' [Node 'h' []]] ] spec :: Spec spec = describe "testing multiway trees problems" $ do describe "Problem 70C: Count the nodes of a multiway tree" $ do it "should work with tree2 and tree1" $ do nnodes tree2 `shouldBe` 2 nnodes tree1 `shouldBe` 1 describe "Problem 70: Tree construction from a node string" $ do describe "testing treeToString" $ do it "should work with tree5" $ do treeToString tree5 `shouldBe` "afg^^c^bd^e^^^" treeToString tree4 `shouldBe` "bd^e^^" describe "testing stringToTree" $ do it "should work with tree5 string: afg^^c^bd^e^^^" $ do stringToTree "afg^^c^bd^e^^^" `shouldBe` tree5 it "should work with tree6 string: afg^^c^bd^eh^^^^" $ do stringToTree "afg^^c^bd^eh^^^^" `shouldBe` tree6 describe "Problem 71: Determine the internal path length of a tree" $ do it "should work with tree5" $ do ipl tree5 `shouldBe` 9 it "should work with tree4" $ do ipl tree4 `shouldBe` 2 describe "Problem 72: Construct the bottom-up order sequence of the tree nodes" $ do it "should work with tree5" $ do bottomUp tree5 `shouldBe` "gfcdeba" describe "Problem 73: Lisp-like tree representation" $ do it "should work with tree4" $ do lisp tree4 `shouldBe` "(b d e)" it "should work with tree5" $ do lisp tree5 `shouldBe` "(a (f g) c (b d e))"
1yefuwang1/haskell99problems
test/H99/MultiwayTreesSpec.hs
bsd-3-clause
2,035
0
18
666
560
267
293
45
1
{-# language CPP #-} -- No documentation found for Chapter "BufferViewCreateFlags" module Vulkan.Core10.Enums.BufferViewCreateFlags (BufferViewCreateFlags(..)) where import Vulkan.Internal.Utils (enumReadPrec) import Vulkan.Internal.Utils (enumShowsPrec) import GHC.Show (showString) import Numeric (showHex) import Vulkan.Zero (Zero) import Data.Bits (Bits) import Data.Bits (FiniteBits) import Foreign.Storable (Storable) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Vulkan.Core10.FundamentalTypes (Flags) -- | VkBufferViewCreateFlags - Reserved for future use -- -- = Description -- -- 'BufferViewCreateFlags' is a bitmask type for setting a mask, but is -- currently reserved for future use. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>, -- 'Vulkan.Core10.BufferView.BufferViewCreateInfo' newtype BufferViewCreateFlags = BufferViewCreateFlags Flags deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) conNameBufferViewCreateFlags :: String conNameBufferViewCreateFlags = "BufferViewCreateFlags" enumPrefixBufferViewCreateFlags :: String enumPrefixBufferViewCreateFlags = "" showTableBufferViewCreateFlags :: [(BufferViewCreateFlags, String)] showTableBufferViewCreateFlags = [] instance Show BufferViewCreateFlags where showsPrec = enumShowsPrec enumPrefixBufferViewCreateFlags showTableBufferViewCreateFlags conNameBufferViewCreateFlags (\(BufferViewCreateFlags x) -> x) (\x -> showString "0x" . showHex x) instance Read BufferViewCreateFlags where readPrec = enumReadPrec enumPrefixBufferViewCreateFlags showTableBufferViewCreateFlags conNameBufferViewCreateFlags BufferViewCreateFlags
expipiplus1/vulkan
src/Vulkan/Core10/Enums/BufferViewCreateFlags.hs
bsd-3-clause
1,924
0
10
360
305
184
121
-1
-1
module Interface where import Data.List import System.Process import System.Exit import Translate import Parser -- count parent to split source splitSource :: String -> String -> [Int] -> [String] splitSource "" res p = if l == r then [res, ""] else ["Error"] where l = head p r = last p splitSource t res p = if (l == r && l /= 0) then [res, t] else splitSource (tail t) (res ++ [ch]) (check ch p) where ch = head t l = head p r = last p check :: Char -> [Int] -> [Int] check ch [l, r] = case ch of '(' -> [l+1, r] ')' -> [l, r+1] _ -> [l, r] -- split source recursively reader :: String -> [String] reader str = if xs == "" then [x] else [x] ++ (splitSource xs "" [0,0]) where res = splitSource str "" [0,0] x = head res xs = last res -- format reading source and remove noise passReader :: String -> [String] passReader str = filter (elem '(') $ map format $ reader str -- replace \n and \t to \space cleanSource :: String -> String cleanSource str = map (\x -> if ((x == '\n') || (x == '\t')) then ' '; else x) str -- check parent direction and number checkParent :: Int -> String -> Bool checkParent p "" = if (p == 0) then True else False checkParent p (x:xs) = if (p >= 0) then case x of '(' -> checkParent (p + 1) xs ')' -> checkParent (p - 1) xs _ -> checkParent p xs else False format :: String -> String format str = dropWhile spaceOrNewline str spaceOrNewline :: Char -> Bool spaceOrNewline x = if (x == '\n') || (x == ' ') then True else False takeFileName :: String -> String takeFileName name = case (elemIndex '.' name) of Just n -> take n name Nothing -> name gobuild :: String -> String -> IO String gobuild file source = do (_, _, e) <- readProcessWithExitCode "go" (generateGoOption file source) [] return e generateGoOption :: String -> String -> [String] generateGoOption o i = if o == "" then ["build", i] else ["build", "-o", o, i] xgobuild :: String -> String -> [String] -> IO String xgobuild file source xoption = do e <- system $ xop ++ "go " ++ (foldr (++) "" (map (++ " ") op)) if e == ExitSuccess then return "" else return $ show e where xop = generateXOption xoption op = generateGoOption file source generateXOption :: [String] -> String generateXOption [os, arch] = "GOOS=" ++ os ++ " " ++ "GOARCH=" ++ arch ++ " " -- compile clo to executable file compile :: String -> String -> IO String compile target output = do x <- readFile target let y = cleanSource x let z = passReader y let c = nub $ map (checkParent 0) z if c == [True] then do let ir = foldr (++) "" $ map ((++ "\n\n") . transClo . parsePrim) z irpath <- writeTransedFile ((takeFileName target) ++ ".go") ir r <- gobuild output irpath if r == "" then return "" else return $ "clover go compile error: \n" ++ r ++ "\n" else return "parse error: check source code\n" xcompile :: String -> String -> [String] -> IO String xcompile target output xoption = do x <- readFile target let y = cleanSource x let z = passReader y let c = nub $ map (checkParent 0) z if c == [True] then do let ir = foldr (++) "" $ map ((++ "\n\n") . transClo . parsePrim) z irpath <- writeTransedFile ((takeFileName target) ++ ".go") ir r <- xgobuild output irpath xoption if r == "" then return "" else return $ "clover go compile error: " ++ r ++ "\n" else return "parse error: check source code\n"
ak1t0/Clover
src/Interface.hs
bsd-3-clause
3,538
0
18
919
1,443
755
688
101
5
--------------------------------------------------------- -- -- Module : Fee -- Copyright : Bartosz Wójcik (2010) -- License : All rights reserved -- -- Maintainer : bartek@sudety.it -- Stability : Unstable -- Portability : portable -- -- This module implements idea of loan fee. Provides with 'FeeType' data type -- which represents different fee types. -- What is a loan fee? -- Fee is an ad hoc amount of money customer has to pay on top of usual instalments. -- It may reflect various business needs, eg. can be a one shot payment for specific -- services, can be a kind of insurance against early loan repayment, etc. -- From calculation point of view there are two significiant fee kinds: -- * fee which changes amount of one or more instalments -- * fee which doesn't change instalments' amounts. -- One may ask what brings fee that doesn't change instalments' amounts. Such fee only -- changes distribution of interest of the loan. Usually it causes that interest is to be -- paid earlier, what in turn gives creditor insurance that desipte of early repayment his -- profit is secured. --------------------------------------------------------- module Fee (FeeClass (..) ,FeeFinanced (..) ,FeeAsLateInterest (..) ,FeeLimitingFstInstalment (..) ) where import BasicType import CalcConfigurationType (instList ,initPrincipal ) import Calculator (calcInstWithKth) import CalcConstructors (InstalmentPlan ,newLoanR ,newLoanRIL) import ErrorHandling import Parameters (ParamMonad) -- | Class providing standard behaviour of adding new costs on top of the loan class FeeClass a where addFee :: a -> Amount -- ^ fee amount -> InstalmentPlan -> ValidMonad InstalmentPlan addFeeParam :: a -> Amount -- ^ fee amount -> InstalmentPlan -> ParamMonad InstalmentPlan addFeeParam ft fee ip = lift $ lift $ addFee ft fee ip -- | Increases capital amount, doesn't change total sum instalment amounts. data FeeFinanced = FeeFinanced deriving (Eq, Ord, Show) instance FeeClass FeeFinanced where addFee _ fee ip = newLoanRIL 0 (c+fee) (instList ip) where c = initPrincipal ip -- | Fee is put into 'InstalmentPlan' as late interest. Doesn't change total sum instalment amounts. data FeeAsLateInterest = FeeAsLateInterest deriving (Eq, Ord, Show) instance FeeClass FeeAsLateInterest where addFee _ fee ip = newLoanRIL (fromIntegral fee) c (instList ip) where c = initPrincipal ip -- | @1st inst amount = min fee current_1st_inst_amount@ -- makes sense for FlatBalloon products data FeeLimitingFstInstalment = FeeLimitingFstInstalment deriving (Eq, Ord, Show) instance FeeClass FeeLimitingFstInstalment where addFee _ fee ip = newLoanRIL (fromIntegral newFst) c is where is = newFst : tail ips ips = instList ip c = initPrincipal ip newFst = min fee (head ips)
bartoszw/haslo
Haslo/Fee.hs
bsd-3-clause
3,225
0
10
898
432
246
186
41
0
{-# LANGUAGE TupleSections #-} module States.IntroRunning where #include "Utils.cpp" import Control.Applicative ((<$>)) import Data.Composition ((.:)) import qualified Graphics.GL as GL import qualified Gamgine.Gfx as G import Gamgine.Gfx ((<<<)) import qualified Gamgine.Font.GLF as GLF import qualified Gamgine.State.RenderState as RS import qualified Gamgine.State.State as ST import qualified Gamgine.State.KeyInfo as KI import qualified Gamgine.State.MouseInfo as MI import qualified Rendering.Ressources as RR import qualified GameData.Data as GD IMPORT_LENS_AS_LE -- | the intro state after starting the game mkIntroRunningState :: ST.State GD.Data mkIntroRunningState = ST.State { ST.enter = (Just . (, mkIntroRunningState)) .: flip const, ST.leave = (, mkIntroRunningState), ST.update = (, mkIntroRunningState), ST.render = ((, mkIntroRunningState) <$>) .: render, ST.keyEvent = (, mkIntroRunningState) .: flip const, ST.mouseEvent = (, mkIntroRunningState) .: flip const, ST.mouseMoved = (, mkIntroRunningState) .: flip const } render :: RS.RenderState -> a -> IO a render RS.RenderState {RS.ressources = res, RS.frustumSize = (fx, fy)} gd = do G.withPushedMatrix $ do GL.glMatrixMode GL.GL_MODELVIEW GL.glLoadIdentity G.withPushedMatrix $ do GLF.setCurrentFont $ RR.fontId RR.Crystal res GLF.Bounds (minx, miny) (maxx, maxy) <- GLF.getStringBounds introStr GL.glTranslatef <<< G.xyz (fx / 2 - ((minx + maxx) * 2)) (fy / 2) 0 GL.glScalef <<< G.xyz 3.75 3 3 GLF.drawSolidString introStr G.withPushedMatrix $ do GLF.setCurrentFont $ RR.fontId RR.Courier res GLF.Bounds (minx, miny) (maxx, maxy) <- GLF.getStringBounds helpStr GL.glTranslatef <<< G.xyz (fx / 2 - ((minx + maxx) / 2)) (fy * 0.1) 0 GL.glScalef <<< G.xyz 1 1 1 GLF.drawSolidString helpStr return gd where introStr = "LAYERS" helpStr = "<Press Space>"
dan-t/layers
src/States/IntroRunning.hs
bsd-3-clause
2,010
0
20
431
638
358
280
-1
-1
-- | General tools for PowerPC programs. module Language.PowerPC ( module Language.PowerPC.Simulator ) where import Language.PowerPC.Simulator
tomahawkins/powerpc
Language/PowerPC.hs
bsd-3-clause
149
0
5
22
22
15
7
3
0
{-# LANGUAGE OverloadedStrings #-} module Finance.Forex.YQL (YQLQuery(..)) where import Finance.Forex.Types import Control.Applicative import Control.Monad import Data.Aeson import qualified Data.ByteString.Char8 as B import Data.List import qualified Data.Text as T import qualified Data.Text.Encoding as T import Network.HTTP.Conduit import Network.HTTP.Types (renderSimpleQuery) import Safe data YQLQuery = YQLQuery T.Text [T.Text] instance Query YQLQuery where url (YQLQuery base counters) = B.unpack url' where base' = T.encodeUtf8 base counters' = map T.encodeUtf8 counters url' = B.concat ["http://query.yahooapis.com/v1/public/yql" ,renderSimpleQuery True parms] parms = [("q",yql) ,("env","store://datatables.org/alltableswithkeys") ,("format","json")] yql = B.concat ["select * from yahoo.finance.xchange where pair in (" , B.concat ( intersperse "," pairs) ,")"] pairs = map (\c -> B.concat ["\"",base',c,"\""]) counters' respHandler _ = decode . responseBody instance FromJSON Quote where parseJSON (Object o) = do o' <- (.: "rate") =<< (.: "results") =<< o .: "query" Quote <$> ((.: "created") =<< o .: "query") <*> mapM parseJSON o' parseJSON _ = mzero instance FromJSON Rate where parseJSON (Object o) = Rate <$> (o .: "id") <*> (textToDouble <$> o .:? "Rate") <*> (textToDouble <$> o .:? "Ask" ) <*> (textToDouble <$> o .:? "Bid" ) parseJSON _ = mzero textToDouble :: Maybe T.Text -> Maybe Double textToDouble x = x >>= readMay . T.unpack
womfoo/forex
Finance/Forex/YQL.hs
bsd-3-clause
1,823
0
13
567
501
280
221
42
1
module Math.Graphs where import Control.Monad import Control.Applicative import Data.Monoid(Monoid,mempty,mappend) import Data.List(union,(\\)) -- import qualified Data.ByteString.Char8 as B ------------------------- -- general purpose graphs -- no notion of vertex is necessary for general purpose graphs data Edge a = Edge { from :: a , to :: a } deriving Eq instance Functor Edge where fmap f (Edge s t) = Edge (f s) (f t) instance Show a => Show (Edge a) where show (Edge v1 v2) = "(" ++ show v1 ++ "--" ++ show v2 ++ ")" data Graph a = Graph { vertices :: [a] , edges :: [Edge a]} instance Eq a => Monoid (Graph a) where mempty = newGraph mappend = graphUnion instance Functor Graph where fmap f (Graph vs es) = Graph (map f vs) (map (fmap f) es) instance Show a => Show (Graph a) where show (Graph vs es) = show vs ++ "\n" ++ show es -------------------------- -- elements marked with a boolean data Marked a = Mark { label :: a , mark :: Bool } nMark :: Marked a -> Bool nMark = not.mark markT,markF :: Marked a -> Marked a markT (Mark a _) = Mark a True markF (Mark a _) = Mark a False tMark :: Marked a -> Marked a tMark (Mark l b) = Mark l (not b) instance Monad Marked where (>>=) a f = Mark ((label.f.label) a) (mark a && (mark.f.label) a) return a = Mark a False instance Functor Marked where fmap g (Mark a b) = Mark (g a) b instance Applicative Marked where pure = return (<*>) = ap instance Eq a => Eq (Marked a) where v == v' = label v == label v' instance Show a => Show (Marked a) where show v = show (label v) ++ (if mark v then "*" else []) -------------------------- newGraph :: Graph a newGraph = Graph [] [] incoming, outgoing :: Eq a => Graph a -> a -> [a] incoming g v = map from (filter ((==v) . to) (edges g)) outgoing g v = map to (filter ((==v) . from) (edges g)) addEdge :: Eq a => Graph a -> Edge a -> Graph a addEdge g e = Graph ((vertices g \\ [f,t]) `union` [f,t]) (edges g `union` [e]) where [f,t] = [from e,to e] addVertex :: Eq a => Graph a -> a -> Graph a addVertex (Graph vs es) v = Graph vs' es where vs' = (vs \\ [v]) ++ [v] edge :: (a,a) -> Edge a edge (x,y) = Edge x y remVertex :: Eq a => Graph a -> a -> Graph a remVertex (Graph vs es) v = Graph (vs \\ [v]) (filter (\x -> from x /= v && to x /= v) es) remVertexL :: Eq a => Graph a -> [a] -> Graph a remVertexL (Graph vs es) l = Graph (vs \\ l) (filter (\x -> from x `notElem` l && to x `notElem` l) es) graphUnion :: Eq a => Graph a -> Graph a -> Graph a graphUnion ga gb = Graph (vertices ga `union` vertices gb) (edges ga `union` edges gb) uniteGraphs :: Eq a => [Graph a] -> Graph a uniteGraphs = foldr graphUnion newGraph -------------------------- -- for graphs with marked vertices mUnder, umUnder :: Eq a => Graph (Marked a) -> Marked a -> [Marked a] mUnder g v = filter mark (incoming g v) umUnder g v = filter nMark (incoming g v) mOver, umOver :: Eq a => Graph (Marked a) -> Marked a -> [Marked a] mOver g v = filter mark (outgoing g v) umOver g v = filter nMark (outgoing g v)
crvs/scythe
src/Math/Graphs.hs
bsd-3-clause
3,095
0
13
724
1,546
796
750
66
1
module Problem20 where factorial :: Integer -> Integer factorial 1 = 1 factorial n = n * (factorial $ n-1) digitSum :: Integer -> Integer digitSum 0 = 0 digitSum n = (n `mod` 10) + (digitSum $ n `div` 10) main :: IO () main = putStrLn . show $ digitSum $ factorial 100
noraesae/euler
src/Problem20.hs
bsd-3-clause
274
0
8
60
125
68
57
10
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} module Web.Spock.Internal.SessionVaultSpec (spec) where import Web.Spock.Internal.SessionVault import Control.Concurrent.STM import Test.Hspec data DummySession = DummySession { ds_key :: Int , ds_value :: Int } deriving (Show, Eq) instance IsSession DummySession where type SessionKey DummySession = Int getSessionKey = ds_key spec :: Spec spec = describe "SessionVault" $ do it "insert works correctly" $ do let sess = DummySession 1 1 vault <- atomically newSessionVault atomically $ storeSession sess vault atomically (loadSession (ds_key sess) vault) `shouldReturn` Just sess it "update works correctly" $ do let sess = DummySession 1 1 sess2 = DummySession 1 2 vault <- atomically newSessionVault atomically $ storeSession sess vault atomically (loadSession (ds_key sess) vault) `shouldReturn` Just sess atomically $ storeSession sess2 vault atomically (loadSession (ds_key sess) vault) `shouldReturn` Just sess2 it "filter and toList works correctly" $ do let sess = DummySession 1 1 sess2 = DummySession 2 2 sess3 = DummySession 3 3 vault <- atomically newSessionVault atomically $ mapM_ (`storeSession` vault) [sess, sess2, sess3] atomically (toList vault) `shouldReturn` [sess, sess2, sess3] atomically $ filterSessions (\s -> ds_value s > 2) vault atomically (toList vault) `shouldReturn` [sess3]
nmk/Spock
test/Web/Spock/Internal/SessionVaultSpec.hs
bsd-3-clause
1,703
0
16
519
461
232
229
39
1
{-# LANGUAGE NoImplicitPrelude #-} -- | -- Module: Data.Aeson.Types -- Copyright: (c) 2011-2016 Bryan O'Sullivan -- (c) 2011 MailRank, Inc. -- License: BSD3 -- Maintainer: Bryan O'Sullivan <bos@serpentine.com> -- Stability: experimental -- Portability: portable -- -- Types for working with JSON data. module Data.Aeson.Types ( -- * Core JSON types Value(..) , Key , Encoding , unsafeToEncoding , fromEncoding , Series , Array , emptyArray , Pair , Object , emptyObject -- * Convenience types and functions , DotNetTime(..) , typeMismatch , unexpected -- * Type conversion , Parser , Result(..) , FromJSON(..) , fromJSON , parse , parseEither , parseMaybe , parseFail , ToJSON(..) , KeyValue(..) , modifyFailure , prependFailure , parserThrowError , parserCatchError -- ** Keys for maps , ToJSONKey(..) , ToJSONKeyFunction(..) , toJSONKeyText , toJSONKeyKey , contramapToJSONKeyFunction , FromJSONKey(..) , FromJSONKeyFunction(..) , fromJSONKeyCoerce , coerceFromJSONKeyFunction , mapFromJSONKeyFunction -- *** Generic keys , GToJSONKey() , genericToJSONKey , GFromJSONKey() , genericFromJSONKey -- ** Liftings to unary and binary type constructors , FromJSON1(..) , parseJSON1 , FromJSON2(..) , parseJSON2 , ToJSON1(..) , toJSON1 , toEncoding1 , ToJSON2(..) , toJSON2 , toEncoding2 -- ** Generic JSON classes , GFromJSON , FromArgs , GToJSON , GToEncoding , GToJSON' , ToArgs , Zero , One , genericToJSON , genericLiftToJSON , genericToEncoding , genericLiftToEncoding , genericParseJSON , genericLiftParseJSON -- * Inspecting @'Value's@ , withObject , withText , withArray , withScientific , withBool , withEmbeddedJSON , pairs , foldable , (.:) , (.:?) , (.:!) , (.!=) , object , parseField , parseFieldMaybe , parseFieldMaybe' , explicitParseField , explicitParseFieldMaybe , explicitParseFieldMaybe' , listEncoding , listValue , listParser -- * Generic and TH encoding configuration , Options -- ** Options fields -- $optionsFields , fieldLabelModifier , constructorTagModifier , allNullaryToStringTag , omitNothingFields , sumEncoding , unwrapUnaryRecords , tagSingleConstructors , rejectUnknownFields -- ** Options utilities , SumEncoding(..) , camelTo , camelTo2 , defaultOptions , defaultTaggedObject -- ** Options for object keys , JSONKeyOptions , keyModifier , defaultJSONKeyOptions -- * Parsing context , (<?>) , JSONPath , JSONPathElement(..) , formatPath , formatRelativePath ) where import Prelude.Compat import Data.Aeson.Encoding (Encoding, unsafeToEncoding, fromEncoding, Series, pairs) import Data.Aeson.Types.Class import Data.Aeson.Types.Internal import Data.Foldable (toList) -- | Encode a 'Foldable' as a JSON array. foldable :: (Foldable t, ToJSON a) => t a -> Encoding foldable = toEncoding . toList {-# INLINE foldable #-} -- $optionsFields -- The functions here are in fact record fields of the 'Options' type.
dmjio/aeson
src/Data/Aeson/Types.hs
bsd-3-clause
3,389
0
7
945
536
370
166
126
1
{-# LANGUAGE OverloadedStrings #-} module Auth.DbAuth where import Data.Text import Database.Persist.MySQL import Database.Persist.Sql import Control.Monad.IO.Class import Control.Monad.Trans.Either import Servant.API import Servant import Auth.AuthHeader import Db.Common import qualified Db.User as Db import qualified Json.User as J import qualified Convert.UserConverter as C findUser :: ConnectionPool -> Text -> Text -> String -> IO (Maybe J.User) findUser pool login password salt = do users <- flip runSqlPool pool $ selectList [Db.UserLogin ==. unpack login, Db.UserPassword ==. encodePassword salt (unpack password)] [] return $ oneUser users where oneUser [user] = C.toJson user oneUser _ = Nothing authHeaderToUser :: MonadIO m => ConnectionPool -> Text -> String -> m (Maybe J.User) authHeaderToUser pool authHeader salt = do let auth = extractBasicAuth authHeader liftIO $ tryFindUser auth where tryFindUser Nothing = return Nothing tryFindUser (Just (login, password)) = findUser pool login password salt withUser :: ConnectionPool -> Text -> String -> (J.User -> EitherT ServantErr IO a) -> EitherT ServantErr IO a withUser pool authHeader salt func = do maybeUser <- authHeaderToUser pool authHeader salt case maybeUser of Nothing -> left $ err403 { errBody = "No user found!" } Just user -> func user
dbushenko/trurl
devrepo/servant/src/Auth/DbAuth.hs
bsd-3-clause
1,428
0
14
298
437
227
210
33
2
module Ransac.Common where import qualified Data.Vector as V import qualified Data.Vector.Generic as G import Data.Maybe import Data.List import Control.Monad.Random type FittingFunction ps model = ps -> Maybe model data Result m p c = Result { rModel :: m, rPoints :: p, rCost :: c } deriving (Show, Read, Eq) rNumInliers :: G.Vector v a => Result m (v a) c -> Int rNumInliers = G.length . rPoints bestResult :: (G.Vector v a, Ord c) => V.Vector (Result m (v a) c) -> Maybe (Result m (v a) c) bestResult = V.foldl' go Nothing where go Nothing b = Just b go (Just a) b | rNumInliers a < rNumInliers b = Just a | rNumInliers a == rNumInliers b && rCost a < rCost b = Just a | otherwise = Just b {-# INLINE bestResult #-} onlyResults :: V.Vector (Maybe (Result m p c)) -> V.Vector (Result m p c) onlyResults = V.map fromJust . V.filter isJust {-# INLINE onlyResults #-} runRansac = evalRandIO -- | draw `n` random samples from `v` drawSamples :: (MonadRandom m, G.Vector v a) => Int -> v a -> m (v a) drawSamples n v = do let l = G.length v - 1 is <- nub <$> getRandomRs (0,l) return $ G.fromListN n . map (G.unsafeIndex v) $ is {-# INLINE drawSamples #-} -- | necessaryIterations p ε s = calculate number of iterations to achieve at -- least a propability 'p' that a valid model for 's' points was draw -- considering a ratio of 'ε' of inliers / outliers. necessaryIterations :: (Floating r, Integral b, Integral b1, RealFrac r) => r -> r -> b1 -> b necessaryIterations p ε s = ceiling $ logBase (1 - (1 - ε)^s) (1 - p)
fhaust/rt-ransac
src/Ransac/Common.hs
bsd-3-clause
1,718
0
13
489
610
315
295
29
2
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude, NoRecordWildCards, DeriveGeneric #-} module Keter.Node.Internal ( defaultKeterConfig ,simpleWatcher , defaultPaths , sampleBundleConfig , activeNodes , tmpFilePath , nodeTypeFilePath ) where -- Control import CorePrelude -- import Control.Monad -- import Filesystem (createTree, isFile, rename,listDirectory,setWorkingDirectory) -- import Filesystem.Path.CurrentOS -- Containers import qualified Data.HashMap.Strict as H import qualified Data.Map as Map import qualified Data.Set as S import qualified Data.Vector as V -- Conversion -- import Data.Yaml import Data.Yaml.FilePath -- Keter Specific import Keter.Node.Types import Keter.Types -- import Keter.Main import Keter.App -- import Keter.AppManager import Data.Conduit.Process.Unix -- Totally a keter package now import qualified Keter.PortPool as PortPool import qualified Codec.Archive.TempTarball as TempFolder import qualified Keter.HostManager as HostMan import Data.Default -- ================================================== -- Keter Node Specific -- | active-nodes are those that are running -- keter-node-logs... Log info having to do with this library -- node-types... incoming .keter files which could be spawned defaultPaths :: [FilePath] defaultPaths = [an,knl,nt,tmp] where f t = "" <.> "" </> t an = activeNodes knl = f "keter-node-logs" nt = nodeTypeFilePath tmp = tmpFilePath activeNodes :: FilePath activeNodes = "active-nodes" tmpFilePath :: FilePath tmpFilePath = "node-temp" nodeTypeFilePath :: FilePath nodeTypeFilePath = "node-types" -------------------------------------------------- -- Defaults For the simpleWatcher -------------------------------------------------- defaultTempFolder :: IO TempFolder.TempFolder defaultTempFolder = TempFolder.setup $ (kconfigDir defaultKeterConfig) </> "temp" defaultPort :: NonEmptyVector ListeningPort defaultPort = NonEmptyVector (LPInsecure "*" 2066) V.empty defaultKeterConfig :: KeterConfig defaultKeterConfig = KeterConfig { kconfigDir = activeNodes , kconfigPortPool = emptyPortPool , kconfigListeners = defaultPort , kconfigSetuid = Nothing , kconfigBuiltinStanzas = V.empty , kconfigIpFromHeader = False } -- | SimpleWatcher tries to create the Keter AppStartConfig type -- with as little info as possible simpleWatcher :: IO AppStartConfig simpleWatcher = do processTracker <- initProcessTracker tf <- defaultTempFolder hostman <- HostMan.start portpool <- PortPool.start emptyPortPool let appStartConfig = AppStartConfig { ascTempFolder = tf , ascSetuid = Nothing , ascProcessTracker = processTracker , ascHostManager = hostman , ascPortPool = portpool , ascPlugins = emptyPlugins , ascLog = (\l -> print l ) , ascKeterConfig = defaultKeterConfig } return appStartConfig {-| Note Bundle Config looks like this ``` haskell instance ToJSON BundleConfig -- Defined in `Keter.Types.V10' instance ParseYamlFile BundleConfig -- Defined in `Keter.Types.V10' instance ToCurrent BundleConfig -- Defined in `Keter.Types.V10' ``` |-} sampleBundleConfig :: BundleConfig sampleBundleConfig = BundleConfig (V.fromList [defStanza]) H.empty emptyPortPool :: PortSettings emptyPortPool = PortSettings [] emptyPlugins :: [Plugin] emptyPlugins = [] defFP :: FilePath defFP = "keter-node-root" defStanza :: Stanza port defStanza = StanzaBackground (defBackgroundConfig defFP) defBackgroundConfig :: FilePath -> BackgroundConfig defBackgroundConfig fp = BackgroundConfig { bgconfigExec = fp , bgconfigArgs = V.empty , bgconfigEnvironment = Map.empty , bgconfigRestartCount = LimitedRestarts 2 , bgconfigRestartDelaySeconds = 10 } instance Default KeterNodeConfig where def = KeterNodeConfig { knCfgNodes = S.empty , knCfgKeterConfig = defaultKeterConfig , knCfgRoot = "" <.>"" </>"keter-node-root" }
plow-technologies/keter-node
src/Keter/Node/Internal.hs
bsd-3-clause
4,487
0
14
1,177
666
403
263
87
1
{-# LANGUAGE BangPatterns, CPP, MagicHash, NondecreasingIndentation #-} {-# OPTIONS_GHC -fprof-auto-top #-} ------------------------------------------------------------------------------- -- -- | Main API for compiling plain Haskell source code. -- -- This module implements compilation of a Haskell source. It is -- /not/ concerned with preprocessing of source files; this is handled -- in "DriverPipeline". -- -- There are various entry points depending on what mode we're in: -- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and -- "interactive" mode (GHCi). There are also entry points for -- individual passes: parsing, typechecking/renaming, desugaring, and -- simplification. -- -- All the functions here take an 'HscEnv' as a parameter, but none of -- them return a new one: 'HscEnv' is treated as an immutable value -- from here on in (although it has mutable components, for the -- caches). -- -- We use the Hsc monad to deal with warning messages consistently: -- specifically, while executing within an Hsc monad, warnings are -- collected. When a Hsc monad returns to an IO monad, the -- warnings are printed, or compilation aborts if the @-Werror@ -- flag is enabled. -- -- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000 -- ------------------------------------------------------------------------------- module HscMain ( -- * Making an HscEnv newHscEnv -- * Compiling complete source files , Messager, batchMsg , HscStatus (..) , hscIncrementalCompile , hscCompileCmmFile , hscGenHardCode , hscInteractive -- * Running passes separately , hscParse , hscTypecheckRename , hscDesugar , makeSimpleDetails , hscSimplify -- ToDo, shouldn't really export this -- * Safe Haskell , hscCheckSafe , hscGetSafe -- * Support for interactive evaluation , hscParseIdentifier , hscTcRcLookupName , hscTcRnGetInfo , hscIsGHCiMonad , hscGetModuleInterface , hscRnImportDecls , hscTcRnLookupRdrName , hscStmt, hscStmtWithLocation, hscParsedStmt , hscDecls, hscDeclsWithLocation , hscTcExpr, TcRnExprMode(..), hscImport, hscKcType , hscParseExpr , hscCompileCoreExpr -- * Low-level exports for hooks , hscCompileCoreExpr' -- We want to make sure that we export enough to be able to redefine -- hscFileFrontEnd in client code , hscParse', hscSimplify', hscDesugar', tcRnModule' , getHscEnv , hscSimpleIface', hscNormalIface' , oneShotMsg , hscFileFrontEnd, genericHscFrontend, dumpIfaceStats , ioMsgMaybe , showModuleIndex ) where import Id import GHCi.RemoteTypes ( ForeignHValue ) import ByteCodeGen ( byteCodeGen, coreExprToBCOs ) import Linker import CoreTidy ( tidyExpr ) import Type ( Type ) import {- Kind parts of -} Type ( Kind ) import CoreLint ( lintInteractiveExpr ) import VarEnv ( emptyTidyEnv ) import Panic import ConLike import Control.Concurrent import Module import Packages import RdrName import HsSyn import CoreSyn import StringBuffer import Parser import Lexer import SrcLoc import TcRnDriver import TcIface ( typecheckIface ) import TcRnMonad import NameCache ( initNameCache ) import LoadIface ( ifaceStats, initExternalPackageState ) import PrelInfo import MkIface import Desugar import SimplCore import TidyPgm import CorePrep import CoreToStg ( coreToStg ) import qualified StgCmm ( codeGen ) import StgSyn import CostCentre import ProfInit import TyCon import Name import SimplStg ( stg2stg ) import Cmm import CmmParse ( parseCmmFile ) import CmmBuildInfoTables import CmmPipeline import CmmInfo import CodeOutput import InstEnv import FamInstEnv import Fingerprint ( Fingerprint ) import Hooks import TcEnv import Maybes import DynFlags import ErrUtils import Outputable import NameEnv import HscStats ( ppSourceStats ) import HscTypes import FastString import UniqSupply import Bag import Exception import qualified Stream import Stream (Stream) import Util import Data.List import Control.Monad import Data.IORef import System.FilePath as FilePath import System.Directory import System.IO (fixIO) import qualified Data.Map as Map #include "HsVersions.h" {- ********************************************************************** %* * Initialisation %* * %********************************************************************* -} newHscEnv :: DynFlags -> IO HscEnv newHscEnv dflags = do eps_var <- newIORef initExternalPackageState us <- mkSplitUniqSupply 'r' nc_var <- newIORef (initNameCache us knownKeyNames) fc_var <- newIORef emptyInstalledModuleEnv iserv_mvar <- newMVar Nothing return HscEnv { hsc_dflags = dflags , hsc_targets = [] , hsc_mod_graph = [] , hsc_IC = emptyInteractiveContext dflags , hsc_HPT = emptyHomePackageTable , hsc_EPS = eps_var , hsc_NC = nc_var , hsc_FC = fc_var , hsc_type_env_var = Nothing , hsc_iserv = iserv_mvar } -- ----------------------------------------------------------------------------- getWarnings :: Hsc WarningMessages getWarnings = Hsc $ \_ w -> return (w, w) clearWarnings :: Hsc () clearWarnings = Hsc $ \_ _ -> return ((), emptyBag) logWarnings :: WarningMessages -> Hsc () logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w) getHscEnv :: Hsc HscEnv getHscEnv = Hsc $ \e w -> return (e, w) handleWarnings :: Hsc () handleWarnings = do dflags <- getDynFlags w <- getWarnings liftIO $ printOrThrowWarnings dflags w clearWarnings -- | log warning in the monad, and if there are errors then -- throw a SourceError exception. logWarningsReportErrors :: Messages -> Hsc () logWarningsReportErrors (warns,errs) = do logWarnings warns when (not $ isEmptyBag errs) $ throwErrors errs -- | Throw some errors. throwErrors :: ErrorMessages -> Hsc a throwErrors = liftIO . throwIO . mkSrcErr -- | Deal with errors and warnings returned by a compilation step -- -- In order to reduce dependencies to other parts of the compiler, functions -- outside the "main" parts of GHC return warnings and errors as a parameter -- and signal success via by wrapping the result in a 'Maybe' type. This -- function logs the returned warnings and propagates errors as exceptions -- (of type 'SourceError'). -- -- This function assumes the following invariants: -- -- 1. If the second result indicates success (is of the form 'Just x'), -- there must be no error messages in the first result. -- -- 2. If there are no error messages, but the second result indicates failure -- there should be warnings in the first result. That is, if the action -- failed, it must have been due to the warnings (i.e., @-Werror@). ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a ioMsgMaybe ioA = do ((warns,errs), mb_r) <- liftIO ioA logWarnings warns case mb_r of Nothing -> throwErrors errs Just r -> ASSERT( isEmptyBag errs ) return r -- | like ioMsgMaybe, except that we ignore error messages and return -- 'Nothing' instead. ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a) ioMsgMaybe' ioA = do ((warns,_errs), mb_r) <- liftIO $ ioA logWarnings warns return mb_r -- ----------------------------------------------------------------------------- -- | Lookup things in the compiler's environment hscTcRnLookupRdrName :: HscEnv -> Located RdrName -> IO [Name] hscTcRnLookupRdrName hsc_env0 rdr_name = runInteractiveHsc hsc_env0 $ do { hsc_env <- getHscEnv ; ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name } hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing) hscTcRcLookupName hsc_env0 name = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ioMsgMaybe' $ tcRnLookupName hsc_env name -- ignore errors: the only error we're likely to get is -- "name not found", and the Maybe in the return type -- is used to indicate that. hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [ClsInst], [FamInst])) hscTcRnGetInfo hsc_env0 name = runInteractiveHsc hsc_env0 $ do { hsc_env <- getHscEnv ; ioMsgMaybe' $ tcRnGetInfo hsc_env name } hscIsGHCiMonad :: HscEnv -> String -> IO Name hscIsGHCiMonad hsc_env name = runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env name hscGetModuleInterface :: HscEnv -> Module -> IO ModIface hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ioMsgMaybe $ getModuleInterface hsc_env mod -- ----------------------------------------------------------------------------- -- | Rename some import declarations hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ioMsgMaybe $ tcRnImportDecls hsc_env import_decls -- ----------------------------------------------------------------------------- -- | parse a file, returning the abstract syntax hscParse :: HscEnv -> ModSummary -> IO HsParsedModule hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary -- internal version, that doesn't fail due to -Werror hscParse' :: ModSummary -> Hsc HsParsedModule hscParse' mod_summary | Just r <- ms_parsed_mod mod_summary = return r | otherwise = {-# SCC "Parser" #-} withTiming getDynFlags (text "Parser"<+>brackets (ppr $ ms_mod mod_summary)) (const ()) $ do dflags <- getDynFlags let src_filename = ms_hspp_file mod_summary maybe_src_buf = ms_hspp_buf mod_summary -------------------------- Parser ---------------- -- sometimes we already have the buffer in memory, perhaps -- because we needed to parse the imports out of it, or get the -- module name. buf <- case maybe_src_buf of Just b -> return b Nothing -> liftIO $ hGetStringBuffer src_filename let loc = mkRealSrcLoc (mkFastString src_filename) 1 1 let parseMod | HsigFile == ms_hsc_src mod_summary = parseSignature | otherwise = parseModule case unP parseMod (mkPState dflags buf loc) of PFailed span err -> liftIO $ throwOneError (mkPlainErrMsg dflags span err) POk pst rdr_module -> do logWarningsReportErrors (getMessages pst dflags) liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $ ppr rdr_module liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $ ppSourceStats False rdr_module -- To get the list of extra source files, we take the list -- that the parser gave us, -- - eliminate files beginning with '<'. gcc likes to use -- pseudo-filenames like "<built-in>" and "<command-line>" -- - normalise them (elimiante differences between ./f and f) -- - filter out the preprocessed source file -- - filter out anything beginning with tmpdir -- - remove duplicates -- - filter out the .hs/.lhs source filename if we have one -- let n_hspp = FilePath.normalise src_filename srcs0 = nub $ filter (not . (tmpDir dflags `isPrefixOf`)) $ filter (not . (== n_hspp)) $ map FilePath.normalise $ filter (not . (isPrefixOf "<")) $ map unpackFS $ srcfiles pst srcs1 = case ml_hs_file (ms_location mod_summary) of Just f -> filter (/= FilePath.normalise f) srcs0 Nothing -> srcs0 -- sometimes we see source files from earlier -- preprocessing stages that cannot be found, so just -- filter them out: srcs2 <- liftIO $ filterM doesFileExist srcs1 return HsParsedModule { hpm_module = rdr_module, hpm_src_files = srcs2, hpm_annotations = (Map.fromListWith (++) $ annotations pst, Map.fromList $ ((noSrcSpan,comment_q pst) :(annotations_comments pst))) } -- XXX: should this really be a Maybe X? Check under which circumstances this -- can become a Nothing and decide whether this should instead throw an -- exception/signal an error. type RenamedStuff = (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name], Maybe LHsDocString)) -- | Rename and typecheck a module, additionally returning the renamed syntax hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule -> IO (TcGblEnv, RenamedStuff) hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do tc_result <- hscTypecheck True mod_summary (Just rdr_module) -- This 'do' is in the Maybe monad! let rn_info = do decl <- tcg_rn_decls tc_result let imports = tcg_rn_imports tc_result exports = tcg_rn_exports tc_result doc_hdr = tcg_doc_hdr tc_result return (decl,imports,exports,doc_hdr) return (tc_result, rn_info) hscTypecheck :: Bool -- ^ Keep renamed source? -> ModSummary -> Maybe HsParsedModule -> Hsc TcGblEnv hscTypecheck keep_rn mod_summary mb_rdr_module = do hsc_env <- getHscEnv let hsc_src = ms_hsc_src mod_summary dflags = hsc_dflags hsc_env outer_mod = ms_mod mod_summary mod_name = moduleName outer_mod outer_mod' = mkModule (thisPackage dflags) mod_name inner_mod = canonicalizeHomeModule dflags mod_name src_filename = ms_hspp_file mod_summary real_loc = realSrcLocSpan $ mkRealSrcLoc (mkFastString src_filename) 1 1 MASSERT( moduleUnitId outer_mod == thisPackage dflags ) if hsc_src == HsigFile && not (isHoleModule inner_mod) then ioMsgMaybe $ tcRnInstantiateSignature hsc_env outer_mod' real_loc else do hpm <- case mb_rdr_module of Just hpm -> return hpm Nothing -> hscParse' mod_summary tc_result0 <- tcRnModule' hsc_env mod_summary keep_rn hpm if hsc_src == HsigFile then do (iface, _, _) <- liftIO $ hscSimpleIface hsc_env tc_result0 Nothing ioMsgMaybe $ tcRnMergeSignatures hsc_env (tcg_top_loc tc_result0) iface else return tc_result0 -- wrapper around tcRnModule to handle safe haskell extras tcRnModule' :: HscEnv -> ModSummary -> Bool -> HsParsedModule -> Hsc TcGblEnv tcRnModule' hsc_env sum save_rn_syntax mod = do tcg_res <- {-# SCC "Typecheck-Rename" #-} ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src sum) save_rn_syntax mod -- See Note [Safe Haskell Overlapping Instances Implementation] -- although this is used for more than just that failure case. (tcSafeOK, whyUnsafe) <- liftIO $ readIORef (tcg_safeInfer tcg_res) dflags <- getDynFlags let allSafeOK = safeInferred dflags && tcSafeOK -- end of the safe haskell line, how to respond to user? if not (safeHaskellOn dflags) || (safeInferOn dflags && not allSafeOK) -- if safe Haskell off or safe infer failed, mark unsafe then markUnsafeInfer tcg_res whyUnsafe -- module (could be) safe, throw warning if needed else do tcg_res' <- hscCheckSafeImports tcg_res safe <- liftIO $ fst <$> readIORef (tcg_safeInfer tcg_res') when safe $ do case wopt Opt_WarnSafe dflags of True -> (logWarnings $ unitBag $ makeIntoWarning (Reason Opt_WarnSafe) $ mkPlainWarnMsg dflags (warnSafeOnLoc dflags) $ errSafe tcg_res') False | safeHaskell dflags == Sf_Trustworthy && wopt Opt_WarnTrustworthySafe dflags -> (logWarnings $ unitBag $ makeIntoWarning (Reason Opt_WarnTrustworthySafe) $ mkPlainWarnMsg dflags (trustworthyOnLoc dflags) $ errTwthySafe tcg_res') False -> return () return tcg_res' where pprMod t = ppr $ moduleName $ tcg_mod t errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!" errTwthySafe t = quotes (pprMod t) <+> text "is marked as Trustworthy but has been inferred as safe!" -- | Convert a typechecked module to Core hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts hscDesugar hsc_env mod_summary tc_result = runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts hscDesugar' mod_location tc_result = do hsc_env <- getHscEnv r <- ioMsgMaybe $ {-# SCC "deSugar" #-} deSugar hsc_env mod_location tc_result -- always check -Werror after desugaring, this is the last opportunity for -- warnings to arise before the backend. handleWarnings return r -- | Make a 'ModDetails' from the results of typechecking. Used when -- typechecking only, as opposed to full compilation. makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result {- ********************************************************************** %* * The main compiler pipeline %* * %********************************************************************* -} {- -------------------------------- The compilation proper -------------------------------- It's the task of the compilation proper to compile Haskell, hs-boot and core files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all (the module is still parsed and type-checked. This feature is mostly used by IDE's and the likes). Compilation can happen in either 'one-shot', 'batch', 'nothing', or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode targets hard-code, 'nothing' mode targets nothing and 'interactive' mode targets byte-code. The modes are kept separate because of their different types and meanings: * In 'one-shot' mode, we're only compiling a single file and can therefore discard the new ModIface and ModDetails. This is also the reason it only targets hard-code; compiling to byte-code or nothing doesn't make sense when we discard the result. * 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface and ModDetails. 'Batch' mode doesn't target byte-code since that require us to return the newly compiled byte-code. * 'Nothing' mode has exactly the same type as 'batch' mode but they're still kept separate. This is because compiling to nothing is fairly special: We don't output any interface files, we don't run the simplifier and we don't generate any code. * 'Interactive' mode is similar to 'batch' mode except that we return the compiled byte-code together with the ModIface and ModDetails. Trying to compile a hs-boot file to byte-code will result in a run-time error. This is the only thing that isn't caught by the type-system. -} type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO () -- | This function runs GHC's frontend with recompilation -- avoidance. Specifically, it checks if recompilation is needed, -- and if it is, it parses and typechecks the input module. -- It does not write out the results of typechecking (See -- compileOne and hscIncrementalCompile). hscIncrementalFrontend :: Bool -- always do basic recompilation check? -> Maybe TcGblEnv -> Maybe Messager -> ModSummary -> SourceModified -> Maybe ModIface -- Old interface, if available -> (Int,Int) -- (i,n) = module i of n (for msgs) -> Hsc (Either ModIface (FrontendResult, Maybe Fingerprint)) hscIncrementalFrontend always_do_basic_recompilation_check m_tc_result mHscMessage mod_summary source_modified mb_old_iface mod_index = do hsc_env <- getHscEnv let msg what = case mHscMessage of Just hscMessage -> hscMessage hsc_env mod_index what mod_summary Nothing -> return () skip iface = do liftIO $ msg UpToDate return $ Left iface compile mb_old_hash reason = do liftIO $ msg reason result <- genericHscFrontend mod_summary return $ Right (result, mb_old_hash) stable = case source_modified of SourceUnmodifiedAndStable -> True _ -> False case m_tc_result of Just tc_result | not always_do_basic_recompilation_check -> return $ Right (FrontendTypecheck tc_result, Nothing) _ -> do (recomp_reqd, mb_checked_iface) <- {-# SCC "checkOldIface" #-} liftIO $ checkOldIface hsc_env mod_summary source_modified mb_old_iface -- save the interface that comes back from checkOldIface. -- In one-shot mode we don't have the old iface until this -- point, when checkOldIface reads it from the disk. let mb_old_hash = fmap mi_iface_hash mb_checked_iface case mb_checked_iface of Just iface | not (recompileRequired recomp_reqd) -> -- If the module used TH splices when it was last -- compiled, then the recompilation check is not -- accurate enough (#481) and we must ignore -- it. However, if the module is stable (none of -- the modules it depends on, directly or -- indirectly, changed), then we *can* skip -- recompilation. This is why the SourceModified -- type contains SourceUnmodifiedAndStable, and -- it's pretty important: otherwise ghc --make -- would always recompile TH modules, even if -- nothing at all has changed. Stability is just -- the same check that make is doing for us in -- one-shot mode. case m_tc_result of Nothing | mi_used_th iface && not stable -> compile mb_old_hash (RecompBecause "TH") _ -> skip iface _ -> case m_tc_result of Nothing -> compile mb_old_hash recomp_reqd Just tc_result -> return $ Right (FrontendTypecheck tc_result, mb_old_hash) genericHscFrontend :: ModSummary -> Hsc FrontendResult genericHscFrontend mod_summary = getHooked hscFrontendHook genericHscFrontend' >>= ($ mod_summary) genericHscFrontend' :: ModSummary -> Hsc FrontendResult genericHscFrontend' mod_summary = FrontendTypecheck `fmap` hscFileFrontEnd mod_summary -------------------------------------------------------------- -- Compilers -------------------------------------------------------------- -- Compile Haskell/boot in OneShot mode. hscIncrementalCompile :: Bool -> Maybe TcGblEnv -> Maybe Messager -> HscEnv -> ModSummary -> SourceModified -> Maybe ModIface -> (Int,Int) -- HomeModInfo does not contain linkable, since we haven't -- code-genned yet -> IO (HscStatus, HomeModInfo) hscIncrementalCompile always_do_basic_recompilation_check m_tc_result mHscMessage hsc_env' mod_summary source_modified mb_old_iface mod_index = do -- One-shot mode needs a knot-tying mutable variable for interface -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var. -- See also Note [hsc_type_env_var hack] type_env_var <- newIORef emptyNameEnv let mod = ms_mod mod_summary hsc_env | isOneShot (ghcMode (hsc_dflags hsc_env')) = hsc_env' { hsc_type_env_var = Just (mod, type_env_var) } | otherwise = hsc_env' -- NB: enter Hsc monad here so that we don't bail out early with -- -Werror on typechecker warnings; we also want to run the desugarer -- to get those warnings too. (But we'll always exit at that point -- because the desugarer runs ioMsgMaybe.) runHsc hsc_env $ do let dflags = hsc_dflags hsc_env e <- hscIncrementalFrontend always_do_basic_recompilation_check m_tc_result mHscMessage mod_summary source_modified mb_old_iface mod_index case e of -- We didn't need to do any typechecking; the old interface -- file on disk was good enough. Left iface -> do -- Knot tying! See Note [Knot-tying typecheckIface] hmi <- liftIO . fixIO $ \hmi' -> do let hsc_env' = hsc_env { hsc_HPT = addToHpt (hsc_HPT hsc_env) (ms_mod_name mod_summary) hmi' } -- NB: This result is actually not that useful -- in one-shot mode, since we're not going to do -- any further typechecking. It's much more useful -- in make mode, since this HMI will go into the HPT. details <- genModDetails hsc_env' iface return HomeModInfo{ hm_details = details, hm_iface = iface, hm_linkable = Nothing } return (HscUpToDate, hmi) -- We finished type checking. (mb_old_hash is the hash of -- the interface that existed on disk; it's possible we had -- to retypecheck but the resulting interface is exactly -- the same.) Right (FrontendTypecheck tc_result, mb_old_hash) -> do (status, hmi, no_change) <- case ms_hsc_src mod_summary of HsSrcFile | hscTarget dflags /= HscNothing -> finish hsc_env mod_summary tc_result mb_old_hash _ -> finishTypecheckOnly hsc_env mod_summary tc_result mb_old_hash liftIO $ hscMaybeWriteIface dflags (hm_iface hmi) no_change mod_summary return (status, hmi) -- Generates and writes out the final interface for a typecheck. finishTypecheckOnly :: HscEnv -> ModSummary -> TcGblEnv -> Maybe Fingerprint -> Hsc (HscStatus, HomeModInfo, Bool) finishTypecheckOnly hsc_env summary tc_result mb_old_hash = do let dflags = hsc_dflags hsc_env (iface, changed, details) <- liftIO $ hscSimpleIface hsc_env tc_result mb_old_hash let hsc_status = case (hscTarget dflags, ms_hsc_src summary) of (HscNothing, _) -> HscNotGeneratingCode (_, HsBootFile) -> HscUpdateBoot (_, HsigFile) -> HscUpdateSig _ -> panic "finishTypecheckOnly" return (hsc_status, HomeModInfo{ hm_details = details, hm_iface = iface, hm_linkable = Nothing }, changed) -- Runs the post-typechecking frontend (desugar and simplify), -- and then generates and writes out the final interface. We want -- to write the interface AFTER simplification so we can get -- as up-to-date and good unfoldings and other info as possible -- in the interface file. This is only ever run for HsSrcFile, -- and NOT for HscNothing. finish :: HscEnv -> ModSummary -> TcGblEnv -> Maybe Fingerprint -> Hsc (HscStatus, HomeModInfo, Bool) finish hsc_env summary tc_result mb_old_hash = do let dflags = hsc_dflags hsc_env MASSERT( ms_hsc_src summary == HsSrcFile ) MASSERT( hscTarget dflags /= HscNothing ) guts0 <- hscDesugar' (ms_location summary) tc_result guts <- hscSimplify' guts0 (iface, changed, details, cgguts) <- liftIO $ hscNormalIface hsc_env guts mb_old_hash return (HscRecomp cgguts summary, HomeModInfo{ hm_details = details, hm_iface = iface, hm_linkable = Nothing }, changed) hscMaybeWriteIface :: DynFlags -> ModIface -> Bool -> ModSummary -> IO () hscMaybeWriteIface dflags iface changed summary = let force_write_interface = gopt Opt_WriteInterface dflags write_interface = case hscTarget dflags of HscNothing -> False HscInterpreted -> False _ -> True in when (write_interface || force_write_interface) $ hscWriteIface dflags iface changed summary -------------------------------------------------------------- -- NoRecomp handlers -------------------------------------------------------------- -- NB: this must be knot-tied appropriately, see hscIncrementalCompile genModDetails :: HscEnv -> ModIface -> IO ModDetails genModDetails hsc_env old_iface = do new_details <- {-# SCC "tcRnIface" #-} initIfaceLoad hsc_env (typecheckIface old_iface) dumpIfaceStats hsc_env return new_details -------------------------------------------------------------- -- Progress displayers. -------------------------------------------------------------- oneShotMsg :: HscEnv -> RecompileRequired -> IO () oneShotMsg hsc_env recomp = case recomp of UpToDate -> compilationProgressMsg (hsc_dflags hsc_env) $ "compilation IS NOT required" _ -> return () batchMsg :: Messager batchMsg hsc_env mod_index recomp mod_summary = case recomp of MustCompile -> showMsg "Compiling " "" UpToDate | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping " "" | otherwise -> return () RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]") where dflags = hsc_dflags hsc_env showMsg msg reason = compilationProgressMsg dflags $ (showModuleIndex mod_index ++ msg ++ showModMsg dflags (hscTarget dflags) (recompileRequired recomp) mod_summary) ++ reason -------------------------------------------------------------- -- FrontEnds -------------------------------------------------------------- -- | Given a 'ModSummary', parses and typechecks it, returning the -- 'TcGblEnv' resulting from type-checking. hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv hscFileFrontEnd mod_summary = hscTypecheck False mod_summary Nothing -------------------------------------------------------------- -- Safe Haskell -------------------------------------------------------------- -- Note [Safe Haskell Trust Check] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Safe Haskell checks that an import is trusted according to the following -- rules for an import of module M that resides in Package P: -- -- * If M is recorded as Safe and all its trust dependencies are OK -- then M is considered safe. -- * If M is recorded as Trustworthy and P is considered trusted and -- all M's trust dependencies are OK then M is considered safe. -- -- By trust dependencies we mean that the check is transitive. So if -- a module M that is Safe relies on a module N that is trustworthy, -- importing module M will first check (according to the second case) -- that N is trusted before checking M is trusted. -- -- This is a minimal description, so please refer to the user guide -- for more details. The user guide is also considered the authoritative -- source in this matter, not the comments or code. -- Note [Safe Haskell Inference] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Safe Haskell does Safe inference on modules that don't have any specific -- safe haskell mode flag. The basic approach to this is: -- * When deciding if we need to do a Safe language check, treat -- an unmarked module as having -XSafe mode specified. -- * For checks, don't throw errors but return them to the caller. -- * Caller checks if there are errors: -- * For modules explicitly marked -XSafe, we throw the errors. -- * For unmarked modules (inference mode), we drop the errors -- and mark the module as being Unsafe. -- -- It used to be that we only did safe inference on modules that had no Safe -- Haskell flags, but now we perform safe inference on all modules as we want -- to allow users to set the `-Wsafe`, `-Wunsafe` and -- `-Wtrustworthy-safe` flags on Trustworthy and Unsafe modules so that a -- user can ensure their assumptions are correct and see reasons for why a -- module is safe or unsafe. -- -- This is tricky as we must be careful when we should throw an error compared -- to just warnings. For checking safe imports we manage it as two steps. First -- we check any imports that are required to be safe, then we check all other -- imports to see if we can infer them to be safe. -- | Check that the safe imports of the module being compiled are valid. -- If not we either issue a compilation error if the module is explicitly -- using Safe Haskell, or mark the module as unsafe if we're in safe -- inference mode. hscCheckSafeImports :: TcGblEnv -> Hsc TcGblEnv hscCheckSafeImports tcg_env = do dflags <- getDynFlags tcg_env' <- checkSafeImports dflags tcg_env checkRULES dflags tcg_env' where checkRULES dflags tcg_env' = do case safeLanguageOn dflags of True -> do -- XSafe: we nuke user written RULES logWarnings $ warns dflags (tcg_rules tcg_env') return tcg_env' { tcg_rules = [] } False -- SafeInferred: user defined RULES, so not safe | safeInferOn dflags && not (null $ tcg_rules tcg_env') -> markUnsafeInfer tcg_env' $ warns dflags (tcg_rules tcg_env') -- Trustworthy OR SafeInferred: with no RULES | otherwise -> return tcg_env' warns dflags rules = listToBag $ map (warnRules dflags) rules warnRules dflags (L loc (HsRule n _ _ _ _ _ _)) = mkPlainWarnMsg dflags loc $ text "Rule \"" <> ftext (snd $ unLoc n) <> text "\" ignored" $+$ text "User defined rules are disabled under Safe Haskell" -- | Validate that safe imported modules are actually safe. For modules in the -- HomePackage (the package the module we are compiling in resides) this just -- involves checking its trust type is 'Safe' or 'Trustworthy'. For modules -- that reside in another package we also must check that the external pacakge -- is trusted. See the Note [Safe Haskell Trust Check] above for more -- information. -- -- The code for this is quite tricky as the whole algorithm is done in a few -- distinct phases in different parts of the code base. See -- RnNames.rnImportDecl for where package trust dependencies for a module are -- collected and unioned. Specifically see the Note [RnNames . Tracking Trust -- Transitively] and the Note [RnNames . Trust Own Package]. checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv checkSafeImports dflags tcg_env = do imps <- mapM condense imports' let (safeImps, regImps) = partition (\(_,_,s) -> s) imps -- We want to use the warning state specifically for detecting if safe -- inference has failed, so store and clear any existing warnings. oldErrs <- getWarnings clearWarnings -- Check safe imports are correct safePkgs <- mapM checkSafe safeImps safeErrs <- getWarnings clearWarnings -- Check non-safe imports are correct if inferring safety -- See the Note [Safe Haskell Inference] (infErrs, infPkgs) <- case (safeInferOn dflags) of False -> return (emptyBag, []) True -> do infPkgs <- mapM checkSafe regImps infErrs <- getWarnings clearWarnings return (infErrs, infPkgs) -- restore old errors logWarnings oldErrs case (isEmptyBag safeErrs) of -- Failed safe check False -> liftIO . throwIO . mkSrcErr $ safeErrs -- Passed safe check True -> do let infPassed = isEmptyBag infErrs tcg_env' <- case (not infPassed) of True -> markUnsafeInfer tcg_env infErrs False -> return tcg_env when (packageTrustOn dflags) $ checkPkgTrust dflags pkgReqs let newTrust = pkgTrustReqs safePkgs infPkgs infPassed return tcg_env' { tcg_imports = impInfo `plusImportAvails` newTrust } where impInfo = tcg_imports tcg_env -- ImportAvails imports = imp_mods impInfo -- ImportedMods imports' = moduleEnvToList imports -- (Module, [ImportedModsVal]) pkgReqs = imp_trust_pkgs impInfo -- [UnitId] condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport) condense (_, []) = panic "HscMain.condense: Pattern match failure!" condense (m, x:xs) = do imv <- foldlM cond' x xs return (m, imv_span imv, imv_is_safe imv) -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport) cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal cond' v1 v2 | imv_is_safe v1 /= imv_is_safe v2 = throwErrors $ unitBag $ mkPlainErrMsg dflags (imv_span v1) (text "Module" <+> ppr (imv_name v1) <+> (text $ "is imported both as a safe and unsafe import!")) | otherwise = return v1 -- easier interface to work with checkSafe (m, l, _) = fst `fmap` hscCheckSafe' dflags m l -- what pkg's to add to our trust requirements pkgTrustReqs req inf infPassed | safeInferOn dflags && safeHaskell dflags == Sf_None && infPassed = emptyImportAvails { imp_trust_pkgs = catMaybes req ++ catMaybes inf } pkgTrustReqs _ _ _ | safeHaskell dflags == Sf_Unsafe = emptyImportAvails pkgTrustReqs req _ _ = emptyImportAvails { imp_trust_pkgs = catMaybes req } -- | Check that a module is safe to import. -- -- We return True to indicate the import is safe and False otherwise -- although in the False case an exception may be thrown first. hscCheckSafe :: HscEnv -> Module -> SrcSpan -> IO Bool hscCheckSafe hsc_env m l = runHsc hsc_env $ do dflags <- getDynFlags pkgs <- snd `fmap` hscCheckSafe' dflags m l when (packageTrustOn dflags) $ checkPkgTrust dflags pkgs errs <- getWarnings return $ isEmptyBag errs -- | Return if a module is trusted and the pkgs it depends on to be trusted. hscGetSafe :: HscEnv -> Module -> SrcSpan -> IO (Bool, [InstalledUnitId]) hscGetSafe hsc_env m l = runHsc hsc_env $ do dflags <- getDynFlags (self, pkgs) <- hscCheckSafe' dflags m l good <- isEmptyBag `fmap` getWarnings clearWarnings -- don't want them printed... let pkgs' | Just p <- self = p:pkgs | otherwise = pkgs return (good, pkgs') -- | Is a module trusted? If not, throw or log errors depending on the type. -- Return (regardless of trusted or not) if the trust type requires the modules -- own package be trusted and a list of other packages required to be trusted -- (these later ones haven't been checked) but the own package trust has been. hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe InstalledUnitId, [InstalledUnitId]) hscCheckSafe' dflags m l = do (tw, pkgs) <- isModSafe m l case tw of False -> return (Nothing, pkgs) True | isHomePkg m -> return (Nothing, pkgs) -- TODO: do we also have to check the trust of the instantiation? -- Not necessary if that is reflected in dependencies | otherwise -> return (Just $ toInstalledUnitId (moduleUnitId m), pkgs) where isModSafe :: Module -> SrcSpan -> Hsc (Bool, [InstalledUnitId]) isModSafe m l = do iface <- lookup' m case iface of -- can't load iface to check trust! Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l $ text "Can't load the interface file for" <+> ppr m <> text ", to check that it can be safely imported" -- got iface, check trust Just iface' -> let trust = getSafeMode $ mi_trust iface' trust_own_pkg = mi_trust_pkg iface' -- check module is trusted safeM = trust `elem` [Sf_Safe, Sf_Trustworthy] -- check package is trusted safeP = packageTrusted trust trust_own_pkg m -- pkg trust reqs pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface' -- General errors we throw but Safe errors we log errs = case (safeM, safeP) of (True, True ) -> emptyBag (True, False) -> pkgTrustErr (False, _ ) -> modTrustErr in do logWarnings errs return (trust == Sf_Trustworthy, pkgRs) where pkgTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The package (" <> ppr (moduleUnitId m) <> text ") the module resides in isn't trusted." ] modTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The module itself isn't safe." ] -- | Check the package a module resides in is trusted. Safe compiled -- modules are trusted without requiring that their package is trusted. For -- trustworthy modules, modules in the home package are trusted but -- otherwise we check the package trust flag. packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool packageTrusted Sf_None _ _ = False -- shouldn't hit these cases packageTrusted Sf_Unsafe _ _ = False -- prefer for completeness. packageTrusted _ _ _ | not (packageTrustOn dflags) = True packageTrusted Sf_Safe False _ = True packageTrusted _ _ m | isHomePkg m = True | otherwise = trusted $ getPackageDetails dflags (moduleUnitId m) lookup' :: Module -> Hsc (Maybe ModIface) lookup' m = do hsc_env <- getHscEnv hsc_eps <- liftIO $ hscEPS hsc_env let pkgIfaceT = eps_PIT hsc_eps homePkgT = hsc_HPT hsc_env iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m -- the 'lookupIfaceByModule' method will always fail when calling from GHCi -- as the compiler hasn't filled in the various module tables -- so we need to call 'getModuleInterface' to load from disk iface' <- case iface of Just _ -> return iface Nothing -> snd `fmap` (liftIO $ getModuleInterface hsc_env m) return iface' isHomePkg :: Module -> Bool isHomePkg m | thisPackage dflags == moduleUnitId m = True | otherwise = False -- | Check the list of packages are trusted. checkPkgTrust :: DynFlags -> [InstalledUnitId] -> Hsc () checkPkgTrust dflags pkgs = case errors of [] -> return () _ -> (liftIO . throwIO . mkSrcErr . listToBag) errors where errors = catMaybes $ map go pkgs go pkg | trusted $ getInstalledPackageDetails dflags pkg = Nothing | otherwise = Just $ mkErrMsg dflags noSrcSpan (pkgQual dflags) $ text "The package (" <> ppr pkg <> text ") is required" <> text " to be trusted but it isn't!" -- | Set module to unsafe and (potentially) wipe trust information. -- -- Make sure to call this method to set a module to inferred unsafe, it should -- be a central and single failure method. We only wipe the trust information -- when we aren't in a specific Safe Haskell mode. -- -- While we only use this for recording that a module was inferred unsafe, we -- may call it on modules using Trustworthy or Unsafe flags so as to allow -- warning flags for safety to function correctly. See Note [Safe Haskell -- Inference]. markUnsafeInfer :: TcGblEnv -> WarningMessages -> Hsc TcGblEnv markUnsafeInfer tcg_env whyUnsafe = do dflags <- getDynFlags when (wopt Opt_WarnUnsafe dflags) (logWarnings $ unitBag $ makeIntoWarning (Reason Opt_WarnUnsafe) $ mkPlainWarnMsg dflags (warnUnsafeOnLoc dflags) (whyUnsafe' dflags)) liftIO $ writeIORef (tcg_safeInfer tcg_env) (False, whyUnsafe) -- NOTE: Only wipe trust when not in an explicity safe haskell mode. Other -- times inference may be on but we are in Trustworthy mode -- so we want -- to record safe-inference failed but not wipe the trust dependencies. case safeHaskell dflags == Sf_None of True -> return $ tcg_env { tcg_imports = wiped_trust } False -> return tcg_env where wiped_trust = (tcg_imports tcg_env) { imp_trust_pkgs = [] } pprMod = ppr $ moduleName $ tcg_mod tcg_env whyUnsafe' df = vcat [ quotes pprMod <+> text "has been inferred as unsafe!" , text "Reason:" , nest 4 $ (vcat $ badFlags df) $+$ (vcat $ pprErrMsgBagWithLoc whyUnsafe) $+$ (vcat $ badInsts $ tcg_insts tcg_env) ] badFlags df = concat $ map (badFlag df) unsafeFlagsForInfer badFlag df (str,loc,on,_) | on df = [mkLocMessage SevOutput (loc df) $ text str <+> text "is not allowed in Safe Haskell"] | otherwise = [] badInsts insts = concat $ map badInst insts checkOverlap (NoOverlap _) = False checkOverlap _ = True badInst ins | checkOverlap (overlapMode (is_flag ins)) = [mkLocMessage SevOutput (nameSrcSpan $ getName $ is_dfun ins) $ ppr (overlapMode $ is_flag ins) <+> text "overlap mode isn't allowed in Safe Haskell"] | otherwise = [] -- | Figure out the final correct safe haskell mode hscGetSafeMode :: TcGblEnv -> Hsc SafeHaskellMode hscGetSafeMode tcg_env = do dflags <- getDynFlags liftIO $ finalSafeMode dflags tcg_env -------------------------------------------------------------- -- Simplifiers -------------------------------------------------------------- hscSimplify :: HscEnv -> ModGuts -> IO ModGuts hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts hscSimplify' :: ModGuts -> Hsc ModGuts hscSimplify' ds_result = do hsc_env <- getHscEnv {-# SCC "Core2Core" #-} liftIO $ core2core hsc_env ds_result -------------------------------------------------------------- -- Interface generators -------------------------------------------------------------- hscSimpleIface :: HscEnv -> TcGblEnv -> Maybe Fingerprint -> IO (ModIface, Bool, ModDetails) hscSimpleIface hsc_env tc_result mb_old_iface = runHsc hsc_env $ hscSimpleIface' tc_result mb_old_iface hscSimpleIface' :: TcGblEnv -> Maybe Fingerprint -> Hsc (ModIface, Bool, ModDetails) hscSimpleIface' tc_result mb_old_iface = do hsc_env <- getHscEnv details <- liftIO $ mkBootModDetailsTc hsc_env tc_result safe_mode <- hscGetSafeMode tc_result (new_iface, no_change) <- {-# SCC "MkFinalIface" #-} liftIO $ mkIfaceTc hsc_env mb_old_iface safe_mode details tc_result -- And the answer is ... liftIO $ dumpIfaceStats hsc_env return (new_iface, no_change, details) hscNormalIface :: HscEnv -> ModGuts -> Maybe Fingerprint -> IO (ModIface, Bool, ModDetails, CgGuts) hscNormalIface hsc_env simpl_result mb_old_iface = runHsc hsc_env $ hscNormalIface' simpl_result mb_old_iface hscNormalIface' :: ModGuts -> Maybe Fingerprint -> Hsc (ModIface, Bool, ModDetails, CgGuts) hscNormalIface' simpl_result mb_old_iface = do hsc_env <- getHscEnv (cg_guts, details) <- {-# SCC "CoreTidy" #-} liftIO $ tidyProgram hsc_env simpl_result -- BUILD THE NEW ModIface and ModDetails -- and emit external core if necessary -- This has to happen *after* code gen so that the back-end -- info has been set. Not yet clear if it matters waiting -- until after code output (new_iface, no_change) <- {-# SCC "MkFinalIface" #-} liftIO $ mkIface hsc_env mb_old_iface details simpl_result liftIO $ dumpIfaceStats hsc_env -- Return the prepared code. return (new_iface, no_change, details, cg_guts) -------------------------------------------------------------- -- BackEnd combinators -------------------------------------------------------------- hscWriteIface :: DynFlags -> ModIface -> Bool -> ModSummary -> IO () hscWriteIface dflags iface no_change mod_summary = do let ifaceFile = ml_hi_file (ms_location mod_summary) unless no_change $ {-# SCC "writeIface" #-} writeIfaceFile dflags ifaceFile iface whenGeneratingDynamicToo dflags $ do -- TODO: We should do a no_change check for the dynamic -- interface file too -- TODO: Should handle the dynamic hi filename properly let dynIfaceFile = replaceExtension ifaceFile (dynHiSuf dflags) dynIfaceFile' = addBootSuffix_maybe (mi_boot iface) dynIfaceFile dynDflags = dynamicTooMkDynamicDynFlags dflags writeIfaceFile dynDflags dynIfaceFile' iface -- | Compile to hard-code. hscGenHardCode :: HscEnv -> CgGuts -> ModSummary -> FilePath -> IO (FilePath, Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f hscGenHardCode hsc_env cgguts mod_summary output_filename = do let CgGuts{ -- This is the last use of the ModGuts in a compilation. -- From now on, we just use the bits we need. cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_foreign = foreign_stubs0, cg_dep_pkgs = dependencies, cg_hpc_info = hpc_info } = cgguts dflags = hsc_dflags hsc_env location = ms_location mod_summary data_tycons = filter isDataTyCon tycons -- cg_tycons includes newtypes, for the benefit of External Core, -- but we don't generate any code for newtypes ------------------- -- PREPARE FOR CODE GENERATION -- Do saturation and convert to A-normal form prepd_binds <- {-# SCC "CorePrep" #-} corePrepPgm hsc_env this_mod location core_binds data_tycons ----------------- Convert to STG ------------------ (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-} myCoreToStg dflags this_mod prepd_binds let prof_init = profilingInitCode this_mod cost_centre_info foreign_stubs = foreign_stubs0 `appendStubC` prof_init ------------------ Code generation ------------------ -- The back-end is streamed: each top-level function goes -- from Stg all the way to asm before dealing with the next -- top-level function, so showPass isn't very useful here. -- Hence we have one showPass for the whole backend, the -- next showPass after this will be "Assembler". withTiming (pure dflags) (text "CodeGen"<+>brackets (ppr this_mod)) (const ()) $ do cmms <- {-# SCC "StgCmm" #-} doCodeGen hsc_env this_mod data_tycons cost_centre_info stg_binds hpc_info ------------------ Code output ----------------------- rawcmms0 <- {-# SCC "cmmToRawCmm" #-} cmmToRawCmm dflags cmms let dump a = do dumpIfSet_dyn dflags Opt_D_dump_cmm_raw "Raw Cmm" (ppr a) return a rawcmms1 = Stream.mapM dump rawcmms0 (output_filename, (_stub_h_exists, stub_c_exists)) <- {-# SCC "codeOutput" #-} codeOutput dflags this_mod output_filename location foreign_stubs dependencies rawcmms1 return (output_filename, stub_c_exists) hscInteractive :: HscEnv -> CgGuts -> ModSummary -> IO (Maybe FilePath, CompiledByteCode) hscInteractive hsc_env cgguts mod_summary = do let dflags = hsc_dflags hsc_env let CgGuts{ -- This is the last use of the ModGuts in a compilation. -- From now on, we just use the bits we need. cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_foreign = foreign_stubs, cg_modBreaks = mod_breaks } = cgguts location = ms_location mod_summary data_tycons = filter isDataTyCon tycons -- cg_tycons includes newtypes, for the benefit of External Core, -- but we don't generate any code for newtypes ------------------- -- PREPARE FOR CODE GENERATION -- Do saturation and convert to A-normal form prepd_binds <- {-# SCC "CorePrep" #-} corePrepPgm hsc_env this_mod location core_binds data_tycons ----------------- Generate byte code ------------------ comp_bc <- byteCodeGen hsc_env this_mod prepd_binds data_tycons mod_breaks ------------------ Create f-x-dynamic C-side stuff --- (_istub_h_exists, istub_c_exists) <- outputForeignStubs dflags this_mod location foreign_stubs return (istub_c_exists, comp_bc) ------------------------------ hscCompileCmmFile :: HscEnv -> FilePath -> FilePath -> IO () hscCompileCmmFile hsc_env filename output_filename = runHsc hsc_env $ do let dflags = hsc_dflags hsc_env cmm <- ioMsgMaybe $ parseCmmFile dflags filename liftIO $ do us <- mkSplitUniqSupply 'S' let initTopSRT = initUs_ us emptySRT dumpIfSet_dyn dflags Opt_D_dump_cmm_verbose "Parsed Cmm" (ppr cmm) (_, cmmgroup) <- cmmPipeline hsc_env initTopSRT cmm rawCmms <- cmmToRawCmm dflags (Stream.yield cmmgroup) let -- Make up a module name to give the NCG. We can't pass bottom here -- lest we reproduce #11784. mod_name = mkModuleName $ "Cmm$" ++ FilePath.takeFileName filename cmm_mod = mkModule (thisPackage dflags) mod_name _ <- codeOutput dflags cmm_mod output_filename no_loc NoStubs [] rawCmms return () where no_loc = ModLocation{ ml_hs_file = Just filename, ml_hi_file = panic "hscCompileCmmFile: no hi file", ml_obj_file = panic "hscCompileCmmFile: no obj file" } -------------------- Stuff for new code gen --------------------- doCodeGen :: HscEnv -> Module -> [TyCon] -> CollectedCCs -> [StgBinding] -> HpcInfo -> IO (Stream IO CmmGroup ()) -- Note we produce a 'Stream' of CmmGroups, so that the -- backend can be run incrementally. Otherwise it generates all -- the C-- up front, which has a significant space cost. doCodeGen hsc_env this_mod data_tycons cost_centre_info stg_binds hpc_info = do let dflags = hsc_dflags hsc_env let cmm_stream :: Stream IO CmmGroup () cmm_stream = {-# SCC "StgCmm" #-} StgCmm.codeGen dflags this_mod data_tycons cost_centre_info stg_binds hpc_info -- codegen consumes a stream of CmmGroup, and produces a new -- stream of CmmGroup (not necessarily synchronised: one -- CmmGroup on input may produce many CmmGroups on output due -- to proc-point splitting). let dump1 a = do dumpIfSet_dyn dflags Opt_D_dump_cmm_from_stg "Cmm produced by codegen" (ppr a) return a ppr_stream1 = Stream.mapM dump1 cmm_stream -- We are building a single SRT for the entire module, so -- we must thread it through all the procedures as we cps-convert them. us <- mkSplitUniqSupply 'S' -- When splitting, we generate one SRT per split chunk, otherwise -- we generate one SRT for the whole module. let pipeline_stream | gopt Opt_SplitObjs dflags || gopt Opt_SplitSections dflags = {-# SCC "cmmPipeline" #-} let run_pipeline us cmmgroup = do let (topSRT', us') = initUs us emptySRT (topSRT, cmmgroup) <- cmmPipeline hsc_env topSRT' cmmgroup let srt | isEmptySRT topSRT = [] | otherwise = srtToData topSRT return (us', srt ++ cmmgroup) in do _ <- Stream.mapAccumL run_pipeline us ppr_stream1 return () | otherwise = {-# SCC "cmmPipeline" #-} let initTopSRT = initUs_ us emptySRT run_pipeline = cmmPipeline hsc_env in do topSRT <- Stream.mapAccumL run_pipeline initTopSRT ppr_stream1 Stream.yield (srtToData topSRT) let dump2 a = do dumpIfSet_dyn dflags Opt_D_dump_cmm "Output Cmm" (ppr a) return a ppr_stream2 = Stream.mapM dump2 pipeline_stream return ppr_stream2 myCoreToStg :: DynFlags -> Module -> CoreProgram -> IO ( [StgBinding] -- output program , CollectedCCs) -- cost centre info (declared and used) myCoreToStg dflags this_mod prepd_binds = do let stg_binds = {-# SCC "Core2Stg" #-} coreToStg dflags this_mod prepd_binds (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-} stg2stg dflags this_mod stg_binds return (stg_binds2, cost_centre_info) {- ********************************************************************** %* * \subsection{Compiling a do-statement} %* * %********************************************************************* -} {- When the UnlinkedBCOExpr is linked you get an HValue of type *IO [HValue]* When you run it you get a list of HValues that should be the same length as the list of names; add them to the ClosureEnv. A naked expression returns a singleton Name [it]. The stmt is lifted into the IO monad as explained in Note [Interactively-bound Ids in GHCi] in HscTypes -} -- | Compile a stmt all the way to an HValue, but don't run it -- -- We return Nothing to indicate an empty statement (or comment only), not a -- parse error. hscStmt :: HscEnv -> String -> IO (Maybe ([Id], ForeignHValue, FixityEnv)) hscStmt hsc_env stmt = hscStmtWithLocation hsc_env stmt "<interactive>" 1 -- | Compile a stmt all the way to an HValue, but don't run it -- -- We return Nothing to indicate an empty statement (or comment only), not a -- parse error. hscStmtWithLocation :: HscEnv -> String -- ^ The statement -> String -- ^ The source -> Int -- ^ Starting line -> IO ( Maybe ([Id] , ForeignHValue {- IO [HValue] -} , FixityEnv)) hscStmtWithLocation hsc_env0 stmt source linenumber = runInteractiveHsc hsc_env0 $ do maybe_stmt <- hscParseStmtWithLocation source linenumber stmt case maybe_stmt of Nothing -> return Nothing Just parsed_stmt -> do hsc_env <- getHscEnv liftIO $ hscParsedStmt hsc_env parsed_stmt hscParsedStmt :: HscEnv -> GhciLStmt RdrName -- ^ The parsed statement -> IO ( Maybe ([Id] , ForeignHValue {- IO [HValue] -} , FixityEnv)) hscParsedStmt hsc_env stmt = runInteractiveHsc hsc_env $ do -- Rename and typecheck it (ids, tc_expr, fix_env) <- ioMsgMaybe $ tcRnStmt hsc_env stmt -- Desugar it ds_expr <- ioMsgMaybe $ deSugarExpr hsc_env tc_expr liftIO (lintInteractiveExpr "desugar expression" hsc_env ds_expr) handleWarnings -- Then code-gen, and link it -- It's important NOT to have package 'interactive' as thisUnitId -- for linking, else we try to link 'main' and can't find it. -- Whereas the linker already knows to ignore 'interactive' let src_span = srcLocSpan interactiveSrcLoc hval <- liftIO $ hscCompileCoreExpr hsc_env src_span ds_expr return $ Just (ids, hval, fix_env) -- | Compile a decls hscDecls :: HscEnv -> String -- ^ The statement -> IO ([TyThing], InteractiveContext) hscDecls hsc_env str = hscDeclsWithLocation hsc_env str "<interactive>" 1 -- | Compile a decls hscDeclsWithLocation :: HscEnv -> String -- ^ The statement -> String -- ^ The source -> Int -- ^ Starting line -> IO ([TyThing], InteractiveContext) hscDeclsWithLocation hsc_env0 str source linenumber = runInteractiveHsc hsc_env0 $ do L _ (HsModule{ hsmodDecls = decls }) <- hscParseThingWithLocation source linenumber parseModule str {- Rename and typecheck it -} hsc_env <- getHscEnv tc_gblenv <- ioMsgMaybe $ tcRnDeclsi hsc_env decls {- Grab the new instances -} -- We grab the whole environment because of the overlapping that may have -- been done. See the notes at the definition of InteractiveContext -- (ic_instances) for more details. let defaults = tcg_default tc_gblenv {- Desugar it -} -- We use a basically null location for iNTERACTIVE let iNTERACTIVELoc = ModLocation{ ml_hs_file = Nothing, ml_hi_file = panic "hsDeclsWithLocation:ml_hi_file", ml_obj_file = panic "hsDeclsWithLocation:ml_hi_file"} ds_result <- hscDesugar' iNTERACTIVELoc tc_gblenv {- Simplify -} simpl_mg <- liftIO $ hscSimplify hsc_env ds_result {- Tidy -} (tidy_cg, mod_details) <- liftIO $ tidyProgram hsc_env simpl_mg let !CgGuts{ cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_modBreaks = mod_breaks } = tidy_cg !ModDetails { md_insts = cls_insts , md_fam_insts = fam_insts } = mod_details -- Get the *tidied* cls_insts and fam_insts data_tycons = filter isDataTyCon tycons {- Prepare For Code Generation -} -- Do saturation and convert to A-normal form prepd_binds <- {-# SCC "CorePrep" #-} liftIO $ corePrepPgm hsc_env this_mod iNTERACTIVELoc core_binds data_tycons {- Generate byte code -} cbc <- liftIO $ byteCodeGen hsc_env this_mod prepd_binds data_tycons mod_breaks let src_span = srcLocSpan interactiveSrcLoc liftIO $ linkDecls hsc_env src_span cbc let tcs = filterOut isImplicitTyCon (mg_tcs simpl_mg) patsyns = mg_patsyns simpl_mg ext_ids = [ id | id <- bindersOfBinds core_binds , isExternalName (idName id) , not (isDFunId id || isImplicitId id) ] -- We only need to keep around the external bindings -- (as decided by TidyPgm), since those are the only ones -- that might later be looked up by name. But we can exclude -- - DFunIds, which are in 'cls_insts' (see Note [ic_tythings] in HscTypes -- - Implicit Ids, which are implicit in tcs -- c.f. TcRnDriver.runTcInteractive, which reconstructs the TypeEnv new_tythings = map AnId ext_ids ++ map ATyCon tcs ++ map (AConLike . PatSynCon) patsyns ictxt = hsc_IC hsc_env -- See Note [Fixity declarations in GHCi] fix_env = tcg_fix_env tc_gblenv new_ictxt = extendInteractiveContext ictxt new_tythings cls_insts fam_insts defaults fix_env return (new_tythings, new_ictxt) {- Note [Fixity declarations in GHCi] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To support fixity declarations on types defined within GHCi (as requested in #10018) we record the fixity environment in InteractiveContext. When we want to evaluate something TcRnDriver.runTcInteractive pulls out this fixity environment and uses it to initialize the global typechecker environment. After the typechecker has finished its business, an updated fixity environment (reflecting whatever fixity declarations were present in the statements we passed it) will be returned from hscParsedStmt. This is passed to updateFixityEnv, which will stuff it back into InteractiveContext, to be used in evaluating the next statement. -} hscImport :: HscEnv -> String -> IO (ImportDecl RdrName) hscImport hsc_env str = runInteractiveHsc hsc_env $ do (L _ (HsModule{hsmodImports=is})) <- hscParseThing parseModule str case is of [L _ i] -> return i _ -> liftIO $ throwOneError $ mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan $ text "parse error in import declaration" -- | Typecheck an expression (but don't run it) hscTcExpr :: HscEnv -> TcRnExprMode -> String -- ^ The expression -> IO Type hscTcExpr hsc_env0 mode expr = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv parsed_expr <- hscParseExpr expr ioMsgMaybe $ tcRnExpr hsc_env mode parsed_expr -- | Find the kind of a type -- Currently this does *not* generalise the kinds of the type hscKcType :: HscEnv -> Bool -- ^ Normalise the type -> String -- ^ The type as a string -> IO (Type, Kind) -- ^ Resulting type (possibly normalised) and kind hscKcType hsc_env0 normalise str = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ty <- hscParseType str ioMsgMaybe $ tcRnType hsc_env normalise ty hscParseExpr :: String -> Hsc (LHsExpr RdrName) hscParseExpr expr = do hsc_env <- getHscEnv maybe_stmt <- hscParseStmt expr case maybe_stmt of Just (L _ (BodyStmt expr _ _ _)) -> return expr _ -> throwErrors $ unitBag $ mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan (text "not an expression:" <+> quotes (text expr)) hscParseStmt :: String -> Hsc (Maybe (GhciLStmt RdrName)) hscParseStmt = hscParseThing parseStmt hscParseStmtWithLocation :: String -> Int -> String -> Hsc (Maybe (GhciLStmt RdrName)) hscParseStmtWithLocation source linenumber stmt = hscParseThingWithLocation source linenumber parseStmt stmt hscParseType :: String -> Hsc (LHsType RdrName) hscParseType = hscParseThing parseType hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName) hscParseIdentifier hsc_env str = runInteractiveHsc hsc_env $ hscParseThing parseIdentifier str hscParseThing :: (Outputable thing) => Lexer.P thing -> String -> Hsc thing hscParseThing = hscParseThingWithLocation "<interactive>" 1 hscParseThingWithLocation :: (Outputable thing) => String -> Int -> Lexer.P thing -> String -> Hsc thing hscParseThingWithLocation source linenumber parser str = withTiming getDynFlags (text "Parser [source]") (const ()) $ {-# SCC "Parser" #-} do dflags <- getDynFlags let buf = stringToStringBuffer str loc = mkRealSrcLoc (fsLit source) linenumber 1 case unP parser (mkPState dflags buf loc) of PFailed span err -> do let msg = mkPlainErrMsg dflags span err throwErrors $ unitBag msg POk pst thing -> do logWarningsReportErrors (getMessages pst dflags) liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing) return thing {- ********************************************************************** %* * Desugar, simplify, convert to bytecode, and link an expression %* * %********************************************************************* -} hscCompileCoreExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO ForeignHValue hscCompileCoreExpr hsc_env = lookupHook hscCompileCoreExprHook hscCompileCoreExpr' (hsc_dflags hsc_env) hsc_env hscCompileCoreExpr' :: HscEnv -> SrcSpan -> CoreExpr -> IO ForeignHValue hscCompileCoreExpr' hsc_env srcspan ds_expr = do { let dflags = hsc_dflags hsc_env {- Simplify it -} ; simpl_expr <- simplifyExpr dflags ds_expr {- Tidy it (temporary, until coreSat does cloning) -} ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr {- Prepare for codegen -} ; prepd_expr <- corePrepExpr dflags hsc_env tidy_expr {- Lint if necessary -} ; lintInteractiveExpr "hscCompileExpr" hsc_env prepd_expr {- Convert to BCOs -} ; bcos <- coreExprToBCOs hsc_env (icInteractiveModule (hsc_IC hsc_env)) prepd_expr {- link it -} ; hval <- linkExpr hsc_env srcspan bcos ; return hval } {- ********************************************************************** %* * Statistics on reading interfaces %* * %********************************************************************* -} dumpIfaceStats :: HscEnv -> IO () dumpIfaceStats hsc_env = do eps <- readIORef (hsc_EPS hsc_env) dumpIfSet dflags (dump_if_trace || dump_rn_stats) "Interface statistics" (ifaceStats eps) where dflags = hsc_dflags hsc_env dump_rn_stats = dopt Opt_D_dump_rn_stats dflags dump_if_trace = dopt Opt_D_dump_if_trace dflags {- ********************************************************************** %* * Progress Messages: Module i of n %* * %********************************************************************* -} showModuleIndex :: (Int, Int) -> String showModuleIndex (i,n) = "[" ++ padded ++ " of " ++ n_str ++ "] " where n_str = show n i_str = show i padded = replicate (length n_str - length i_str) ' ' ++ i_str
olsner/ghc
compiler/main/HscMain.hs
bsd-3-clause
72,747
0
27
21,699
12,094
6,153
5,941
1,037
10
module System.Win32.DHCP.IP_RANGE ( IP_RANGE (..) ) where import Data.Ip import Import data IP_RANGE = IP_RANGE !Ip !Ip instance Storable IP_RANGE where sizeOf _ = 8 alignment _ = 1 peek ptr = IP_RANGE <$> (peek . castPtr) ptr <*> castPtr ptr `peekByteOff` 4 poke ptr (IP_RANGE start end) = do pokeElemOff addrPtr 0 start pokeElemOff addrPtr 1 end where addrPtr = castPtr ptr :: Ptr Ip
mikesteele81/Win32-dhcp-server
src/System/Win32/DHCP/IP_RANGE.hs
bsd-3-clause
439
0
11
119
151
78
73
19
0
-- | <http://strava.github.io/api/v3/comments/> module Strive.Actions.Comments ( getActivityComments ) where import Network.HTTP.Types (toQuery) import Strive.Aliases (ActivityId, Result) import Strive.Client (Client) import Strive.Internal.HTTP (get) import Strive.Options (GetActivityCommentsOptions) import Strive.Types (CommentSummary) -- | <http://strava.github.io/api/v3/comments/#list> getActivityComments :: Client -> ActivityId -> GetActivityCommentsOptions -> IO (Result [CommentSummary]) getActivityComments client activityId options = get client resource query where resource = "api/v3/activities/" ++ show activityId ++ "/comments" query = toQuery options
liskin/strive
library/Strive/Actions/Comments.hs
mit
680
0
11
75
153
87
66
12
1
{-| hledger's cmdargs modes parse command-line arguments to an intermediate format, RawOpts (an association list), rather than a fixed ADT like CliOpts. This allows the modes and flags to be reused more easily by hledger commands/scripts in this and other packages. -} module Hledger.Data.RawOptions ( RawOpts, setopt, setboolopt, inRawOpts, boolopt, stringopt, maybestringopt, listofstringopt, intopt, maybeintopt ) where import Data.Maybe import qualified Data.Text as T import Safe import Hledger.Utils -- | The result of running cmdargs: an association list of option names to string values. type RawOpts = [(String,String)] setopt :: String -> String -> RawOpts -> RawOpts setopt name val = (++ [(name, quoteIfNeeded $ val)]) setboolopt :: String -> RawOpts -> RawOpts setboolopt name = (++ [(name,"")]) -- | Is the named option present ? inRawOpts :: String -> RawOpts -> Bool inRawOpts name = isJust . lookup name boolopt :: String -> RawOpts -> Bool boolopt = inRawOpts maybestringopt :: String -> RawOpts -> Maybe String maybestringopt name = maybe Nothing (Just . T.unpack . stripquotes . T.pack) . lookup name . reverse stringopt :: String -> RawOpts -> String stringopt name = fromMaybe "" . maybestringopt name listofstringopt :: String -> RawOpts -> [String] listofstringopt name rawopts = [v | (k,v) <- rawopts, k==name] maybeintopt :: String -> RawOpts -> Maybe Int maybeintopt name rawopts = let ms = maybestringopt name rawopts in case ms of Nothing -> Nothing Just s -> Just $ readDef (usageError $ "could not parse "++name++" number: "++s) s intopt :: String -> RawOpts -> Int intopt name = fromMaybe 0 . maybeintopt name
ony/hledger
hledger-lib/Hledger/Data/RawOptions.hs
gpl-3.0
1,702
0
16
322
463
252
211
37
2
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies , TypeSynonymInstances, FlexibleInstances, UndecidableInstances , OverlappingInstances #-} ----------------------------------------------------------- -- | -- Module : HDBRec -- Copyright : HWT Group (c) 2003, haskelldb-users@lists.sourceforge.net -- License : BSD-style -- -- Maintainer : haskelldb-users@lists.sourceforge.net -- Stability : experimental -- Portability : non-portable -- -- This is a replacement for some of TREX. -- -- ----------------------------------------------------------- module Database.HaskellDB.HDBRec ( -- * Record types RecNil(..), RecCons(..), Record -- * Record construction , emptyRecord, (.=.), ( # ) -- * Labels , FieldTag(..) -- * Record predicates and operations , HasField, Select(..), SetField, setField , RecCat(..) -- * Showing and reading records , ShowLabels(..), ShowRecRow(..), ReadRecRow(..) ) where import Data.List infixr 5 # infix 6 .=. -- | The empty record. data RecNil = RecNil deriving (Eq, Ord) -- | Constructor that adds a field to a record. -- f is the field tag, a is the field value and b is the rest of the record. data RecCons f a b = RecCons a b deriving (Eq, Ord) -- | The type used for records. This is a function -- that takes a 'RecNil' so that the user does not have to -- put a 'RecNil' at the end of every record. type Record r = RecNil -> r -- * Record construction -- | Creates one-field record from a label and a value ( .=. ) :: l f a -- ^ Label -> a -- ^ Value -> Record (RecCons f a RecNil) -- ^ New record _ .=. x = RecCons x -- | Adds the field from a one-field record to another record. ( # ) :: Record (RecCons f a RecNil) -- ^ Field to add -> (b -> c) -- ^ Rest of record -> (b -> RecCons f a c) -- ^ New record f # r = let RecCons x _ = f RecNil in RecCons x . r -- | The empty record emptyRecord :: Record RecNil emptyRecord = id -- * Class definitions. -- | Class for field labels. class FieldTag f where -- | Gets the name of the label. fieldName :: f -> String -- | The record @r@ has the field @f@ if there is an instance of -- @HasField f r@. class HasField f r instance HasField f (RecCons f a r) instance HasField f r => HasField f (RecCons g a r) instance HasField f r => HasField f (Record r) -- * Record concatenation class RecCat r1 r2 r3 | r1 r2 -> r3 where -- | Concatenates two records. recCat :: r1 -> r2 -> r3 instance RecCat RecNil r r where recCat ~RecNil r = r instance RecCat r1 r2 r3 => RecCat (RecCons f a r1) r2 (RecCons f a r3) where recCat ~(RecCons x r1) r2 = RecCons x (recCat r1 r2) instance RecCat r1 r2 r3 => RecCat (Record r1) (Record r2) (Record r3) where recCat r1 r2 = \n -> recCat (r1 n) (r2 n) -- * Field selection infix 9 ! class Select f r a | f r -> a where -- | Field selection operator. It is overloaded so that -- users (read HaskellDB) can redefine it for things -- with phantom record types. (!) :: r -> f -> a instance SelectField f r a => Select (l f a) (Record r) a where (!) r l = selectField (labelType l) r labelType :: l f a -> f labelType _ = undefined -- | Class which does the actual work of -- getting the value of a field from a record. -- FIXME: would like the dependency f r -> a here, but -- that makes Hugs complain about conflicting instaces class SelectField f r a where -- | Gets the value of a field from a record. selectField :: f -- ^ Field label -> r -- ^ Record -> a -- ^ Field value instance SelectField f (RecCons f a r) a where selectField _ ~(RecCons x _) = x instance SelectField f r a => SelectField f (RecCons g b r) a where selectField f ~(RecCons _ r) = selectField f r instance SelectField f r a => SelectField f (Record r) a where selectField f r = selectField f (r RecNil) -- * Field update setField :: SetField f r a => l f a -> a -> r -> r setField l = setField_ (labelType l) class SetField f r a where -- | Sets the value of a field in a record. setField_ :: f -- ^ Field label -> a -- ^ New field value -> r -- ^ Record -> r -- ^ New record instance SetField f (RecCons f a r) a where setField_ _ y ~(RecCons _ r) = RecCons y r instance SetField f r a => SetField f (RecCons g b r) a where setField_ l y ~(RecCons f r) = RecCons f (setField_ l y r) instance SetField f r a => SetField f (Record r) a where setField_ f y r = \e -> setField_ f y (r e) -- * Equality and ordering instance Eq r => Eq (Record r) where r1 == r2 = r1 RecNil == r2 RecNil instance Ord r => Ord (Record r) where r1 <= r2 = r1 RecNil <= r2 RecNil -- * Showing labels -- | Get the label name of a record entry. consFieldName :: FieldTag f => RecCons f a r -> String consFieldName = fieldName . consFieldType consFieldType :: RecCons f a r -> f consFieldType _ = undefined class ShowLabels r where recordLabels :: r -> [String] instance ShowLabels RecNil where recordLabels _ = [] instance (FieldTag f,ShowLabels r) => ShowLabels (RecCons f a r) where recordLabels ~x@(RecCons _ r) = consFieldName x : recordLabels r instance ShowLabels r => ShowLabels (Record r) where recordLabels r = recordLabels (r RecNil) -- * Showing rows -- | Convert a record to a list of label names and field values. class ShowRecRow r where showRecRow :: r -> [(String,ShowS)] -- Last entry in each record will terminate the ShowrecRow recursion. instance ShowRecRow RecNil where showRecRow _ = [] -- Recurse a record and produce a showable tuple. instance (FieldTag a, Show b, ShowRecRow c) => ShowRecRow (RecCons a b c) where showRecRow ~r@(RecCons x fs) = (consFieldName r, shows x) : showRecRow fs instance ShowRecRow r => ShowRecRow (Record r) where showRecRow r = showRecRow (r RecNil) instance Show r => Show (Record r) where showsPrec x r = showsPrec x (r RecNil) -- probably not terribly efficient showsShowRecRow :: ShowRecRow r => r -> ShowS showsShowRecRow r = shows $ [(f,v "") | (f,v) <- showRecRow r] instance Show RecNil where showsPrec _ r = showsShowRecRow r instance (FieldTag a, Show b, ShowRecRow c) => Show (RecCons a b c) where showsPrec _ r = showsShowRecRow r -- * Reading rows class ReadRecRow r where -- | Convert a list of labels and strins representating values -- to a record. readRecRow :: [(String,String)] -> [(r,[(String,String)])] instance ReadRecRow RecNil where readRecRow xs = [(RecNil,xs)] instance (FieldTag a, Read b, ReadRecRow c) => ReadRecRow (RecCons a b c) where readRecRow [] = [] readRecRow xs = let res = readRecEntry xs (fst $ head res) in res readRecEntry :: (Read a, FieldTag f, ReadRecRow r) => [(String,String)] -> RecCons f a r -- ^ Dummy to get return type right -> [(RecCons f a r,[(String,String)])] readRecEntry ((f,v):xs) r | f == consFieldName r = res | otherwise = [] where res = [(RecCons x r, xs') | (x,"") <- reads v, (r,xs') <- readRecRow xs] readsReadRecRow :: ReadRecRow r => ReadS r readsReadRecRow s = [(r,leftOver) | (l,leftOver) <- reads s, (r,[]) <- readRecRow l] instance ReadRecRow r => Read (Record r) where readsPrec _ s = [(const r, rs) | (r,rs) <- readsReadRecRow s] instance Read RecNil where readsPrec _ = readsReadRecRow instance (FieldTag a, Read b, ReadRecRow c) => Read (RecCons a b c) where readsPrec _ s = readsReadRecRow s
m4dc4p/haskelldb
src/Database/HaskellDB/HDBRec.hs
bsd-3-clause
7,580
44
13
1,835
2,329
1,245
1,084
-1
-1
module Blub ( blub , foo , bar ) where import Data.Text (Text) import Data.Maybe (Maybe(Nothing, Just))
jystic/hsimport
tests/goldenFiles/SymbolTest25.hs
bsd-3-clause
116
0
6
29
41
27
14
6
0
solveMeFirst a b = a + b main = do val1 <- readLn val2 <- readLn let sum = solveMeFirst val1 val2 print sum
icot/hackerrank
template1.hs
gpl-3.0
125
0
10
41
54
24
30
6
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.UserHooks -- Copyright : Isaac Jones 2003-2005 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This defines the API that @Setup.hs@ scripts can use to customise the way -- the build works. This module just defines the 'UserHooks' type. The -- predefined sets of hooks that implement the @Simple@, @Make@ and @Configure@ -- build systems are defined in "Distribution.Simple". The 'UserHooks' is a big -- record of functions. There are 3 for each action, a pre, post and the action -- itself. There are few other miscellaneous hooks, ones to extend the set of -- programs and preprocessors and one to override the function used to read the -- @.cabal@ file. -- -- This hooks type is widely agreed to not be the right solution. Partly this -- is because changes to it usually break custom @Setup.hs@ files and yet many -- internal code changes do require changes to the hooks. For example we cannot -- pass any extra parameters to most of the functions that implement the -- various phases because it would involve changing the types of the -- corresponding hook. At some point it will have to be replaced. {- All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Isaac Jones nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Distribution.Simple.UserHooks ( UserHooks(..), Args, emptyUserHooks, ) where import Distribution.PackageDescription (PackageDescription, GenericPackageDescription, HookedBuildInfo, emptyHookedBuildInfo) import Distribution.Simple.Program (Program) import Distribution.Simple.Command (noExtraFlags) import Distribution.Simple.PreProcess (PPSuffixHandler) import Distribution.Simple.Setup (ConfigFlags, BuildFlags, ReplFlags, CleanFlags, CopyFlags, InstallFlags, SDistFlags, RegisterFlags, HscolourFlags, HaddockFlags, TestFlags, BenchmarkFlags) import Distribution.Simple.LocalBuildInfo (LocalBuildInfo) type Args = [String] -- | Hooks allow authors to add specific functionality before and after a -- command is run, and also to specify additional preprocessors. -- -- * WARNING: The hooks interface is under rather constant flux as we try to -- understand users needs. Setup files that depend on this interface may -- break in future releases. data UserHooks = UserHooks { -- | Used for @.\/setup test@ runTests :: Args -> Bool -> PackageDescription -> LocalBuildInfo -> IO (), -- | Read the description file readDesc :: IO (Maybe GenericPackageDescription), -- | Custom preprocessors in addition to and overriding 'knownSuffixHandlers'. hookedPreProcessors :: [ PPSuffixHandler ], -- | These programs are detected at configure time. Arguments for them are -- added to the configure command. hookedPrograms :: [Program], -- |Hook to run before configure command preConf :: Args -> ConfigFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during configure. confHook :: (GenericPackageDescription, HookedBuildInfo) -> ConfigFlags -> IO LocalBuildInfo, -- |Hook to run after configure command postConf :: Args -> ConfigFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before build command. Second arg indicates verbosity level. preBuild :: Args -> BuildFlags -> IO HookedBuildInfo, -- |Over-ride this hook to gbet different behavior during build. buildHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO (), -- |Hook to run after build command. Second arg indicates verbosity level. postBuild :: Args -> BuildFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before repl command. Second arg indicates verbosity level. preRepl :: Args -> ReplFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during interpretation. replHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> ReplFlags -> [String] -> IO (), -- |Hook to run after repl command. Second arg indicates verbosity level. postRepl :: Args -> ReplFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before clean command. Second arg indicates verbosity level. preClean :: Args -> CleanFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during clean. cleanHook :: PackageDescription -> () -> UserHooks -> CleanFlags -> IO (), -- |Hook to run after clean command. Second arg indicates verbosity level. postClean :: Args -> CleanFlags -> PackageDescription -> () -> IO (), -- |Hook to run before copy command preCopy :: Args -> CopyFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during copy. copyHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> CopyFlags -> IO (), -- |Hook to run after copy command postCopy :: Args -> CopyFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before install command preInst :: Args -> InstallFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during install. instHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> InstallFlags -> IO (), -- |Hook to run after install command. postInst should be run -- on the target, not on the build machine. postInst :: Args -> InstallFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before sdist command. Second arg indicates verbosity level. preSDist :: Args -> SDistFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during sdist. sDistHook :: PackageDescription -> Maybe LocalBuildInfo -> UserHooks -> SDistFlags -> IO (), -- |Hook to run after sdist command. Second arg indicates verbosity level. postSDist :: Args -> SDistFlags -> PackageDescription -> Maybe LocalBuildInfo -> IO (), -- |Hook to run before register command preReg :: Args -> RegisterFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during registration. regHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> RegisterFlags -> IO (), -- |Hook to run after register command postReg :: Args -> RegisterFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before unregister command preUnreg :: Args -> RegisterFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during unregistration. unregHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> RegisterFlags -> IO (), -- |Hook to run after unregister command postUnreg :: Args -> RegisterFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before hscolour command. Second arg indicates verbosity level. preHscolour :: Args -> HscolourFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during hscolour. hscolourHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> HscolourFlags -> IO (), -- |Hook to run after hscolour command. Second arg indicates verbosity level. postHscolour :: Args -> HscolourFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before haddock command. Second arg indicates verbosity level. preHaddock :: Args -> HaddockFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during haddock. haddockHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> HaddockFlags -> IO (), -- |Hook to run after haddock command. Second arg indicates verbosity level. postHaddock :: Args -> HaddockFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before test command. preTest :: Args -> TestFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during test. testHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> TestFlags -> IO (), -- |Hook to run after test command. postTest :: Args -> TestFlags -> PackageDescription -> LocalBuildInfo -> IO (), -- |Hook to run before bench command. preBench :: Args -> BenchmarkFlags -> IO HookedBuildInfo, -- |Over-ride this hook to get different behavior during bench. benchHook :: Args -> PackageDescription -> LocalBuildInfo -> UserHooks -> BenchmarkFlags -> IO (), -- |Hook to run after bench command. postBench :: Args -> BenchmarkFlags -> PackageDescription -> LocalBuildInfo -> IO () } {-# DEPRECATED runTests "Please use the new testing interface instead!" #-} -- |Empty 'UserHooks' which do nothing. emptyUserHooks :: UserHooks emptyUserHooks = UserHooks { runTests = ru, readDesc = return Nothing, hookedPreProcessors = [], hookedPrograms = [], preConf = rn, confHook = (\_ _ -> return (error "No local build info generated during configure. Over-ride empty configure hook.")), postConf = ru, preBuild = rn', buildHook = ru, postBuild = ru, preRepl = \_ _ -> return emptyHookedBuildInfo, replHook = \_ _ _ _ _ -> return (), postRepl = ru, preClean = rn, cleanHook = ru, postClean = ru, preCopy = rn, copyHook = ru, postCopy = ru, preInst = rn, instHook = ru, postInst = ru, preSDist = rn, sDistHook = ru, postSDist = ru, preReg = rn, regHook = ru, postReg = ru, preUnreg = rn, unregHook = ru, postUnreg = ru, preHscolour = rn, hscolourHook = ru, postHscolour = ru, preHaddock = rn, haddockHook = ru, postHaddock = ru, preTest = rn', testHook = ru, postTest = ru, preBench = rn', benchHook = \_ -> ru, postBench = ru } where rn args _ = noExtraFlags args >> return emptyHookedBuildInfo rn' _ _ = return emptyHookedBuildInfo ru _ _ _ _ = return ()
jwiegley/ghc-release
libraries/Cabal/cabal/Distribution/Simple/UserHooks.hs
gpl-3.0
11,503
0
15
2,487
1,608
931
677
110
1
{- Copyright 2015 Google Inc. 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. -} {-# LANGUAGE PackageImports #-} {-# LANGUAGE NoImplicitPrelude #-} module GHC.Float.ConversionUtils (module M) where import "base" GHC.Float.ConversionUtils as M
Ye-Yong-Chi/codeworld
codeworld-base/src/GHC/Float/ConversionUtils.hs
apache-2.0
765
0
4
136
25
19
6
4
0
module Main where import Happstack.Server import Control.Monad {- interesting urls: /setcookie/value /setcookie/hello+world -} data MyStructure = MyStructure String instance FromData MyStructure where fromData = do str <- lookCookieValue "cookie" return $ MyStructure str main :: IO () main = do simpleHTTP nullConf $ msum [ do (MyStructure str) <- getData >>= maybe mzero return ok $ "Cookie value: " ++ str , dir "setcookie" $ path $ \value -> do -- Create cookie with a duration of 30 seconds. addCookie 30 (mkCookie "cookie" value) ok "Cookie has been set" , ok "Try /setcookie/value" ]
erantapaa/happstack-server
attic/Examples/set/FromData/Cookies.hs
bsd-3-clause
783
0
17
286
169
83
86
17
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sk-SK"> <title>&gt;Run Applications | ZAP Extensions</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/invoke/src/main/javahelp/org/zaproxy/zap/extension/invoke/resources/help_sk_SK/helpset_sk_SK.hs
apache-2.0
982
76
55
159
419
211
208
-1
-1
module Where1 where f3 :: Num t => t -> (t, t) f3 x = (ls, rs) where ls = x + 1 rs = x - 1 f1 :: Int -> Int f1 x = ls where ls = x + 1 f2 :: Int -> Int f2 x = rs where rs = x - 1
kmate/HaRe
old/testing/merging/Where1_TokOut.hs
bsd-3-clause
244
0
7
123
116
64
52
12
1
----------------------------------------------------------------------------- -- | -- Module : Text.Parsec.Combinator -- Copyright : (c) Daan Leijen 1999-2001, (c) Paolo Martini 2007 -- License : BSD-style (see the LICENSE file) -- -- Maintainer : derek.a.elkins@gmail.com -- Stability : provisional -- Portability : portable -- -- Commonly used generic combinators -- ----------------------------------------------------------------------------- module Text.Parsec.Combinator ( choice , count , between , option, optionMaybe, optional , skipMany1 , many1 , sepBy, sepBy1 , endBy, endBy1 , sepEndBy, sepEndBy1 , chainl, chainl1 , chainr, chainr1 , eof, notFollowedBy -- tricky combinators , manyTill, lookAhead, anyToken ) where import Control.Monad import Text.Parsec.Prim -- | @choice ps@ tries to apply the parsers in the list @ps@ in order, -- until one of them succeeds. Returns the value of the succeeding -- parser. choice :: (Stream s m t) => [ParsecT s u m a] -> ParsecT s u m a choice ps = foldr (<|>) mzero ps -- | @option x p@ tries to apply parser @p@. If @p@ fails without -- consuming input, it returns the value @x@, otherwise the value -- returned by @p@. -- -- > priority = option 0 (do{ d <- digit -- > ; return (digitToInt d) -- > }) option :: (Stream s m t) => a -> ParsecT s u m a -> ParsecT s u m a option x p = p <|> return x -- | @optionMaybe p@ tries to apply parser @p@. If @p@ fails without -- consuming input, it return 'Nothing', otherwise it returns -- 'Just' the value returned by @p@. optionMaybe :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m (Maybe a) optionMaybe p = option Nothing (liftM Just p) -- | @optional p@ tries to apply parser @p@. It will parse @p@ or nothing. -- It only fails if @p@ fails after consuming input. It discards the result -- of @p@. optional :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m () optional p = do{ p; return ()} <|> return () -- | @between open close p@ parses @open@, followed by @p@ and @close@. -- Returns the value returned by @p@. -- -- > braces = between (symbol "{") (symbol "}") between :: (Stream s m t) => ParsecT s u m open -> ParsecT s u m close -> ParsecT s u m a -> ParsecT s u m a between open close p = do{ open; x <- p; close; return x } -- | @skipMany1 p@ applies the parser @p@ /one/ or more times, skipping -- its result. skipMany1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m () skipMany1 p = do{ p; skipMany p } {- skipMany p = scan where scan = do{ p; scan } <|> return () -} -- | @many1 p@ applies the parser @p@ /one/ or more times. Returns a -- list of the returned values of @p@. -- -- > word = many1 letter many1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m [a] many1 p = do{ x <- p; xs <- many p; return (x:xs) } {- many p = scan id where scan f = do{ x <- p ; scan (\tail -> f (x:tail)) } <|> return (f []) -} -- | @sepBy p sep@ parses /zero/ or more occurrences of @p@, separated -- by @sep@. Returns a list of values returned by @p@. -- -- > commaSep p = p `sepBy` (symbol ",") sepBy :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a] sepBy p sep = sepBy1 p sep <|> return [] -- | @sepBy1 p sep@ parses /one/ or more occurrences of @p@, separated -- by @sep@. Returns a list of values returned by @p@. sepBy1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a] sepBy1 p sep = do{ x <- p ; xs <- many (sep >> p) ; return (x:xs) } -- | @sepEndBy1 p sep@ parses /one/ or more occurrences of @p@, -- separated and optionally ended by @sep@. Returns a list of values -- returned by @p@. sepEndBy1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a] sepEndBy1 p sep = do{ x <- p ; do{ sep ; xs <- sepEndBy p sep ; return (x:xs) } <|> return [x] } -- | @sepEndBy p sep@ parses /zero/ or more occurrences of @p@, -- separated and optionally ended by @sep@, ie. haskell style -- statements. Returns a list of values returned by @p@. -- -- > haskellStatements = haskellStatement `sepEndBy` semi sepEndBy :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a] sepEndBy p sep = sepEndBy1 p sep <|> return [] -- | @endBy1 p sep@ parses /one/ or more occurrences of @p@, separated -- and ended by @sep@. Returns a list of values returned by @p@. endBy1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a] endBy1 p sep = many1 (do{ x <- p; sep; return x }) -- | @endBy p sep@ parses /zero/ or more occurrences of @p@, separated -- and ended by @sep@. Returns a list of values returned by @p@. -- -- > cStatements = cStatement `endBy` semi endBy :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a] endBy p sep = many (do{ x <- p; sep; return x }) -- | @count n p@ parses @n@ occurrences of @p@. If @n@ is smaller or -- equal to zero, the parser equals to @return []@. Returns a list of -- @n@ values returned by @p@. count :: (Stream s m t) => Int -> ParsecT s u m a -> ParsecT s u m [a] count n p | n <= 0 = return [] | otherwise = sequence (replicate n p) -- | @chainr p op x@ parses /zero/ or more occurrences of @p@, -- separated by @op@ Returns a value obtained by a /right/ associative -- application of all functions returned by @op@ to the values returned -- by @p@. If there are no occurrences of @p@, the value @x@ is -- returned. chainr :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m (a -> a -> a) -> a -> ParsecT s u m a chainr p op x = chainr1 p op <|> return x -- | @chainl p op x@ parses /zero/ or more occurrences of @p@, -- separated by @op@. Returns a value obtained by a /left/ associative -- application of all functions returned by @op@ to the values returned -- by @p@. If there are zero occurrences of @p@, the value @x@ is -- returned. chainl :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m (a -> a -> a) -> a -> ParsecT s u m a chainl p op x = chainl1 p op <|> return x -- | @chainl1 p op x@ parses /one/ or more occurrences of @p@, -- separated by @op@ Returns a value obtained by a /left/ associative -- application of all functions returned by @op@ to the values returned -- by @p@. . This parser can for example be used to eliminate left -- recursion which typically occurs in expression grammars. -- -- > expr = term `chainl1` addop -- > term = factor `chainl1` mulop -- > factor = parens expr <|> integer -- > -- > mulop = do{ symbol "*"; return (*) } -- > <|> do{ symbol "/"; return (div) } -- > -- > addop = do{ symbol "+"; return (+) } -- > <|> do{ symbol "-"; return (-) } chainl1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m (a -> a -> a) -> ParsecT s u m a chainl1 p op = do{ x <- p; rest x } where rest x = do{ f <- op ; y <- p ; rest (f x y) } <|> return x -- | @chainr1 p op x@ parses /one/ or more occurrences of |p|, -- separated by @op@ Returns a value obtained by a /right/ associative -- application of all functions returned by @op@ to the values returned -- by @p@. chainr1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m (a -> a -> a) -> ParsecT s u m a chainr1 p op = scan where scan = do{ x <- p; rest x } rest x = do{ f <- op ; y <- scan ; return (f x y) } <|> return x ----------------------------------------------------------- -- Tricky combinators ----------------------------------------------------------- -- | The parser @anyToken@ accepts any kind of token. It is for example -- used to implement 'eof'. Returns the accepted token. anyToken :: (Stream s m t, Show t) => ParsecT s u m t anyToken = tokenPrim show (\pos _tok _toks -> pos) Just -- | This parser only succeeds at the end of the input. This is not a -- primitive parser but it is defined using 'notFollowedBy'. -- -- > eof = notFollowedBy anyToken <?> "end of input" eof :: (Stream s m t, Show t) => ParsecT s u m () eof = notFollowedBy anyToken <?> "end of input" -- | @notFollowedBy p@ only succeeds when parser @p@ fails. This parser -- does not consume any input. This parser can be used to implement the -- \'longest match\' rule. For example, when recognizing keywords (for -- example @let@), we want to make sure that a keyword is not followed -- by a legal identifier character, in which case the keyword is -- actually an identifier (for example @lets@). We can program this -- behaviour as follows: -- -- > keywordLet = try (do{ string "let" -- > ; notFollowedBy alphaNum -- > }) notFollowedBy :: (Stream s m t, Show a) => ParsecT s u m a -> ParsecT s u m () notFollowedBy p = try (do{ c <- try p; unexpected (show c) } <|> return () ) -- | @manyTill p end@ applies parser @p@ /zero/ or more times until -- parser @end@ succeeds. Returns the list of values returned by @p@. -- This parser can be used to scan comments: -- -- > simpleComment = do{ string "<!--" -- > ; manyTill anyChar (try (string "-->")) -- > } -- -- Note the overlapping parsers @anyChar@ and @string \"-->\"@, and -- therefore the use of the 'try' combinator. manyTill :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m end -> ParsecT s u m [a] manyTill p end = scan where scan = do{ end; return [] } <|> do{ x <- p; xs <- scan; return (x:xs) }
23Skidoo/parsec
Text/Parsec/Combinator.hs
bsd-2-clause
10,619
0
12
3,449
2,176
1,160
1,016
82
1
module RuleDefiningPlugin where import GhcPlugins {-# RULES "unsound" forall x. show x = "SHOWED" #-} plugin :: Plugin plugin = defaultPlugin
siddhanathan/ghc
testsuite/tests/plugins/rule-defining-plugin/RuleDefiningPlugin.hs
bsd-3-clause
145
0
4
24
18
12
6
5
1
{-# LANGUAGE Unsafe #-} module UnsafeInfered09_B where f :: Int f = 1
ghc-android/ghc
testsuite/tests/safeHaskell/safeInfered/UnsafeInfered09_B.hs
bsd-3-clause
72
0
4
15
15
10
5
4
1
module Mod124_A where data T = T
urbanslug/ghc
testsuite/tests/module/Mod124_A.hs
bsd-3-clause
34
0
5
8
11
7
4
2
0
-- Pattern synonyms {-# LANGUAGE PatternSynonyms #-} module Main where pattern Single x y = [(x,y)] foo [] = 0 foo [(True, True)] = 1 foo (Single True True) = 2 foo (Single False False) = 3 foo _ = 4 main = mapM_ (print . foo) tests where tests = [ [(True, True)] , [] , [(True, False)] , [(False, False)] , repeat (True, True) ]
urbanslug/ghc
testsuite/tests/patsyn/should_run/match.hs
bsd-3-clause
445
0
9
182
172
99
73
14
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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 Thrift.Transport.Empty ( EmptyTransport(..) ) where import Thrift.Transport data EmptyTransport = EmptyTransport instance Transport EmptyTransport where tIsOpen = const $ return False tClose = const $ return () tRead _ _ = return "" tPeek = const $ return Nothing tWrite _ _ = return () tFlush = const$ return ()
jcgruenhage/dendrite
vendor/src/github.com/apache/thrift/lib/hs/src/Thrift/Transport/Empty.hs
apache-2.0
1,240
0
8
234
136
81
55
13
0
module Futhark.CodeGen.SetDefaultSpace ( setDefaultSpace ) where import Futhark.CodeGen.ImpCode -- | Set all uses of 'DefaultSpace' in the given functions to another memory space. setDefaultSpace :: Space -> Functions op -> Functions op setDefaultSpace space (Functions fundecs) = Functions [ (fname, setFunctionSpace space func) | (fname, func) <- fundecs ] setFunctionSpace :: Space -> Function op -> Function op setFunctionSpace space (Function entry outputs inputs body results args) = Function entry (map (setParamSpace space) outputs) (map (setParamSpace space) inputs) (setBodySpace space body) (map (setExtValueSpace space) results) (map (setExtValueSpace space) args) setParamSpace :: Space -> Param -> Param setParamSpace space (MemParam name DefaultSpace) = MemParam name space setParamSpace _ param = param setExtValueSpace :: Space -> ExternalValue -> ExternalValue setExtValueSpace space (OpaqueValue desc vs) = OpaqueValue desc $ map (setValueSpace space) vs setExtValueSpace space (TransparentValue v) = TransparentValue $ setValueSpace space v setValueSpace :: Space -> ValueDesc -> ValueDesc setValueSpace space (ArrayValue mem memsize _ bt ept shape) = ArrayValue mem memsize space bt ept shape setValueSpace _ (ScalarValue bt ept v) = ScalarValue bt ept v setBodySpace :: Space -> Code op -> Code op setBodySpace space (Allocate v e old_space) = Allocate v (setCountSpace space e) $ setSpace space old_space setBodySpace space (DeclareMem name old_space) = DeclareMem name $ setSpace space old_space setBodySpace space (DeclareArray name _ t vs) = DeclareArray name space t vs setBodySpace space (Copy dest dest_offset dest_space src src_offset src_space n) = Copy dest (setCountSpace space dest_offset) dest_space' src (setCountSpace space src_offset) src_space' $ setCountSpace space n where dest_space' = setSpace space dest_space src_space' = setSpace space src_space setBodySpace space (Write dest dest_offset bt dest_space vol e) = Write dest (setCountSpace space dest_offset) bt (setSpace space dest_space) vol (setExpSpace space e) setBodySpace space (c1 :>>: c2) = setBodySpace space c1 :>>: setBodySpace space c2 setBodySpace space (For i it e body) = For i it (setExpSpace space e) $ setBodySpace space body setBodySpace space (While e body) = While (setExpSpace space e) $ setBodySpace space body setBodySpace space (If e c1 c2) = If (setExpSpace space e) (setBodySpace space c1) (setBodySpace space c2) setBodySpace space (Comment s c) = Comment s $ setBodySpace space c setBodySpace _ Skip = Skip setBodySpace _ (DeclareScalar name bt) = DeclareScalar name bt setBodySpace space (SetScalar name e) = SetScalar name $ setExpSpace space e setBodySpace space (SetMem to from old_space) = SetMem to from $ setSpace space old_space setBodySpace space (Call dests fname args) = Call dests fname $ map setArgSpace args where setArgSpace (MemArg m) = MemArg m setArgSpace (ExpArg e) = ExpArg $ setExpSpace space e setBodySpace space (Assert e msg loc) = Assert (setExpSpace space e) msg loc setBodySpace space (DebugPrint s t e) = DebugPrint s t (setExpSpace space e) setBodySpace _ (Op op) = Op op setCountSpace :: Space -> Count a -> Count a setCountSpace space (Count e) = Count $ setExpSpace space e setExpSpace :: Space -> Exp -> Exp setExpSpace space = fmap setLeafSpace where setLeafSpace (Index mem i bt DefaultSpace vol) = Index mem i bt space vol setLeafSpace e = e setSpace :: Space -> Space -> Space setSpace space DefaultSpace = space setSpace _ space = space
ihc/futhark
src/Futhark/CodeGen/SetDefaultSpace.hs
isc
3,665
0
9
695
1,281
627
654
86
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Strict #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} -- | Conversion of a monomorphic, first-order, defunctorised source -- program to a core Futhark program. module Futhark.Internalise.Exps (transformProg) where import Control.Monad.Reader import Data.List (find, intercalate, intersperse, transpose) import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as M import qualified Data.Set as S import Futhark.IR.SOACS as I hiding (stmPat) import Futhark.Internalise.AccurateSizes import Futhark.Internalise.Bindings import Futhark.Internalise.Lambdas import Futhark.Internalise.Monad as I import Futhark.Internalise.TypesValues import Futhark.Transform.Rename as I import Futhark.Util (splitAt3) import Futhark.Util.Pretty (prettyOneLine) import Language.Futhark as E hiding (TypeArg) -- | Convert a program in source Futhark to a program in the Futhark -- core language. transformProg :: MonadFreshNames m => Bool -> [E.ValBind] -> m (I.Prog SOACS) transformProg always_safe vbinds = do (consts, funs) <- runInternaliseM always_safe (internaliseValBinds vbinds) I.renameProg $ I.Prog consts funs internaliseValBinds :: [E.ValBind] -> InternaliseM () internaliseValBinds = mapM_ internaliseValBind internaliseFunName :: VName -> Name internaliseFunName = nameFromString . pretty internaliseValBind :: E.ValBind -> InternaliseM () internaliseValBind fb@(E.ValBind entry fname retdecl (Info rettype) tparams params body _ attrs loc) = do localConstsScope . bindingFParams tparams params $ \shapeparams params' -> do let shapenames = map I.paramName shapeparams msg <- case retdecl of Just dt -> errorMsg . ("Function return value does not match shape of type " :) <$> typeExpForError dt Nothing -> return $ errorMsg ["Function return value does not match shape of declared return type."] (body', rettype') <- buildBody $ do body_res <- internaliseExp (baseString fname <> "_res") body rettype' <- fmap zeroExts . internaliseReturnType rettype =<< mapM subExpType body_res body_res' <- ensureResultExtShape msg loc (map I.fromDecl rettype') $ subExpsRes body_res pure ( body_res', replicate (length (shapeContext rettype')) (I.Prim int64) ++ rettype' ) let all_params = shapeparams ++ concat params' attrs' <- internaliseAttrs attrs let fd = I.FunDef Nothing attrs' (internaliseFunName fname) rettype' all_params body' if null params' then bindConstant fname fd else bindFunction fname fd ( shapenames, map declTypeOf $ concat params', all_params, applyRetType rettype' all_params ) case entry of Just (Info entry') -> generateEntryPoint entry' fb Nothing -> return () where zeroExts ts = generaliseExtTypes ts ts generateEntryPoint :: E.EntryPoint -> E.ValBind -> InternaliseM () generateEntryPoint (E.EntryPoint e_params e_rettype) vb = localConstsScope $ do let (E.ValBind _ ofname _ (Info rettype) tparams params _ _ attrs loc) = vb bindingFParams tparams params $ \shapeparams params' -> do entry_rettype <- internaliseEntryReturnType rettype let entry' = entryPoint (baseName ofname) (zip e_params params') (e_rettype, entry_rettype) args = map (I.Var . I.paramName) $ concat params' (entry_body, ctx_ts) <- buildBody $ do -- Special case the (rare) situation where the entry point is -- not a function. maybe_const <- lookupConst ofname vals <- case maybe_const of Just ses -> return ses Nothing -> fst <$> funcall "entry_result" (E.qualName ofname) args loc ctx <- extractShapeContext (zeroExts $ concat entry_rettype) <$> mapM (fmap I.arrayDims . subExpType) vals pure (subExpsRes $ ctx ++ vals, map (const (I.Prim int64)) ctx) attrs' <- internaliseAttrs attrs addFunDef $ I.FunDef (Just entry') attrs' ("entry_" <> baseName ofname) (ctx_ts ++ zeroExts (concat entry_rettype)) (shapeparams ++ concat params') entry_body where zeroExts ts = generaliseExtTypes ts ts entryPoint :: Name -> [(E.EntryParam, [I.FParam])] -> ( E.EntryType, [[I.TypeBase ExtShape Uniqueness]] ) -> I.EntryPoint entryPoint name params (eret, crets) = ( name, map onParam params, case ( isTupleRecord $ entryType eret, entryAscribed eret ) of (Just ts, Just (E.TETuple e_ts _)) -> zipWith entryPointType (zipWith E.EntryType ts (map Just e_ts)) crets (Just ts, Nothing) -> zipWith entryPointType (map (`E.EntryType` Nothing) ts) crets _ -> [entryPointType eret $ concat crets] ) where onParam (E.EntryParam e_p e_t, ps) = I.EntryParam e_p $ entryPointType e_t $ staticShapes $ map I.paramDeclType ps entryPointType t ts | E.Scalar (E.Prim E.Unsigned {}) <- E.entryType t = I.TypeUnsigned u | E.Array _ _ (E.Prim E.Unsigned {}) _ <- E.entryType t = I.TypeUnsigned u | E.Scalar E.Prim {} <- E.entryType t = I.TypeDirect u | E.Array _ _ E.Prim {} _ <- E.entryType t = I.TypeDirect u | otherwise = I.TypeOpaque u desc $ length ts where u = foldl max Nonunique $ map I.uniqueness ts desc = maybe (prettyOneLine t') typeExpOpaqueName $ E.entryAscribed t t' = noSizes (E.entryType t) `E.setUniqueness` Nonunique typeExpOpaqueName (TEApply te TypeArgExpDim {} _) = typeExpOpaqueName te typeExpOpaqueName (TEArray te _ _) = let (d, te') = withoutDims te in "arr_" ++ typeExpOpaqueName te' ++ "_" ++ show (1 + d) ++ "d" typeExpOpaqueName (TEUnique te _) = prettyOneLine te typeExpOpaqueName te = prettyOneLine te withoutDims (TEArray te _ _) = let (d, te') = withoutDims te in (d + 1, te') withoutDims te = (0 :: Int, te) internaliseBody :: String -> E.Exp -> InternaliseM Body internaliseBody desc e = buildBody_ $ subExpsRes <$> internaliseExp (desc <> "_res") e bodyFromStms :: InternaliseM (Result, a) -> InternaliseM (Body, a) bodyFromStms m = do ((res, a), stms) <- collectStms m (,a) <$> mkBodyM stms res -- | Only returns those pattern names that are not used in the pattern -- itself (the "non-existential" part, you could say). letValExp :: String -> I.Exp -> InternaliseM [VName] letValExp name e = do e_t <- expExtType e names <- replicateM (length e_t) $ newVName name letBindNames names e let ctx = shapeContext e_t pure $ map fst $ filter ((`S.notMember` ctx) . snd) $ zip names [0 ..] letValExp' :: String -> I.Exp -> InternaliseM [SubExp] letValExp' _ (BasicOp (SubExp se)) = pure [se] letValExp' name ses = map I.Var <$> letValExp name ses eValBody :: [InternaliseM I.Exp] -> InternaliseM I.Body eValBody es = buildBody_ $ do es' <- sequence es varsRes . concat <$> mapM (letValExp "x") es' internaliseAppExp :: String -> [VName] -> E.AppExp -> InternaliseM [I.SubExp] internaliseAppExp desc _ (E.Index e idxs loc) = do vs <- internaliseExpToVars "indexed" e dims <- case vs of [] -> return [] -- Will this happen? v : _ -> I.arrayDims <$> lookupType v (idxs', cs) <- internaliseSlice loc dims idxs let index v = do v_t <- lookupType v return $ I.BasicOp $ I.Index v $ fullSlice v_t idxs' certifying cs $ letSubExps desc =<< mapM index vs internaliseAppExp desc _ (E.Range start maybe_second end loc) = do start' <- internaliseExp1 "range_start" start end' <- internaliseExp1 "range_end" $ case end of DownToExclusive e -> e ToInclusive e -> e UpToExclusive e -> e maybe_second' <- traverse (internaliseExp1 "range_second") maybe_second -- Construct an error message in case the range is invalid. let conv = case E.typeOf start of E.Scalar (E.Prim (E.Unsigned _)) -> asIntZ Int64 _ -> asIntS Int64 start'_i64 <- conv start' end'_i64 <- conv end' maybe_second'_i64 <- traverse conv maybe_second' let errmsg = errorMsg $ ["Range "] ++ [ErrorVal int64 start'_i64] ++ ( case maybe_second'_i64 of Nothing -> [] Just second_i64 -> ["..", ErrorVal int64 second_i64] ) ++ ( case end of DownToExclusive {} -> ["..>"] ToInclusive {} -> ["..."] UpToExclusive {} -> ["..<"] ) ++ [ErrorVal int64 end'_i64, " is invalid."] (it, le_op, lt_op) <- case E.typeOf start of E.Scalar (E.Prim (E.Signed it)) -> return (it, CmpSle it, CmpSlt it) E.Scalar (E.Prim (E.Unsigned it)) -> return (it, CmpUle it, CmpUlt it) start_t -> error $ "Start value in range has type " ++ pretty start_t let one = intConst it 1 negone = intConst it (-1) default_step = case end of DownToExclusive {} -> negone ToInclusive {} -> one UpToExclusive {} -> one (step, step_zero) <- case maybe_second' of Just second' -> do subtracted_step <- letSubExp "subtracted_step" $ I.BasicOp $ I.BinOp (I.Sub it I.OverflowWrap) second' start' step_zero <- letSubExp "step_zero" $ I.BasicOp $ I.CmpOp (I.CmpEq $ IntType it) start' second' return (subtracted_step, step_zero) Nothing -> return (default_step, constant False) step_sign <- letSubExp "s_sign" $ BasicOp $ I.UnOp (I.SSignum it) step step_sign_i64 <- asIntS Int64 step_sign bounds_invalid_downwards <- letSubExp "bounds_invalid_downwards" $ I.BasicOp $ I.CmpOp le_op start' end' bounds_invalid_upwards <- letSubExp "bounds_invalid_upwards" $ I.BasicOp $ I.CmpOp lt_op end' start' (distance, step_wrong_dir, bounds_invalid) <- case end of DownToExclusive {} -> do step_wrong_dir <- letSubExp "step_wrong_dir" $ I.BasicOp $ I.CmpOp (I.CmpEq $ IntType it) step_sign one distance <- letSubExp "distance" $ I.BasicOp $ I.BinOp (Sub it I.OverflowWrap) start' end' distance_i64 <- asIntS Int64 distance return (distance_i64, step_wrong_dir, bounds_invalid_downwards) UpToExclusive {} -> do step_wrong_dir <- letSubExp "step_wrong_dir" $ I.BasicOp $ I.CmpOp (I.CmpEq $ IntType it) step_sign negone distance <- letSubExp "distance" $ I.BasicOp $ I.BinOp (Sub it I.OverflowWrap) end' start' distance_i64 <- asIntS Int64 distance return (distance_i64, step_wrong_dir, bounds_invalid_upwards) ToInclusive {} -> do downwards <- letSubExp "downwards" $ I.BasicOp $ I.CmpOp (I.CmpEq $ IntType it) step_sign negone distance_downwards_exclusive <- letSubExp "distance_downwards_exclusive" $ I.BasicOp $ I.BinOp (Sub it I.OverflowWrap) start' end' distance_upwards_exclusive <- letSubExp "distance_upwards_exclusive" $ I.BasicOp $ I.BinOp (Sub it I.OverflowWrap) end' start' bounds_invalid <- letSubExp "bounds_invalid" $ I.If downwards (resultBody [bounds_invalid_downwards]) (resultBody [bounds_invalid_upwards]) $ ifCommon [I.Prim I.Bool] distance_exclusive <- letSubExp "distance_exclusive" $ I.If downwards (resultBody [distance_downwards_exclusive]) (resultBody [distance_upwards_exclusive]) $ ifCommon [I.Prim $ IntType it] distance_exclusive_i64 <- asIntS Int64 distance_exclusive distance <- letSubExp "distance" $ I.BasicOp $ I.BinOp (Add Int64 I.OverflowWrap) distance_exclusive_i64 (intConst Int64 1) return (distance, constant False, bounds_invalid) step_invalid <- letSubExp "step_invalid" $ I.BasicOp $ I.BinOp I.LogOr step_wrong_dir step_zero invalid <- letSubExp "range_invalid" $ I.BasicOp $ I.BinOp I.LogOr step_invalid bounds_invalid valid <- letSubExp "valid" $ I.BasicOp $ I.UnOp I.Not invalid cs <- assert "range_valid_c" valid errmsg loc step_i64 <- asIntS Int64 step pos_step <- letSubExp "pos_step" $ I.BasicOp $ I.BinOp (Mul Int64 I.OverflowWrap) step_i64 step_sign_i64 num_elems <- certifying cs $ letSubExp "num_elems" $ I.BasicOp $ I.BinOp (SDivUp Int64 I.Unsafe) distance pos_step se <- letSubExp desc (I.BasicOp $ I.Iota num_elems start' step it) return [se] internaliseAppExp desc ext (E.Coerce e (TypeDecl dt (Info et)) loc) = do ses <- internaliseExp desc e ts <- internaliseReturnType (E.RetType ext et) =<< mapM subExpType ses dt' <- typeExpForError dt forM (zip ses ts) $ \(e', t') -> do dims <- arrayDims <$> subExpType e' let parts = ["Value of (core language) shape ("] ++ intersperse ", " (map (ErrorVal int64) dims) ++ [") cannot match shape of type `"] ++ dt' ++ ["`."] ensureExtShape (errorMsg parts) loc (I.fromDecl t') desc e' internaliseAppExp desc _ e@E.Apply {} = do (qfname, args) <- findFuncall e -- Argument evaluation is outermost-in so that any existential sizes -- created by function applications can be brought into scope. let fname = nameFromString $ pretty $ baseName $ qualLeaf qfname loc = srclocOf e arg_desc = nameToString fname ++ "_arg" -- Some functions are magical (overloaded) and we handle that here. case () of -- Overloaded functions never take array arguments (except -- equality, but those cannot be existential), so we can safely -- ignore the existential dimensions. () | Just internalise <- isOverloadedFunction qfname (map fst args) loc -> internalise desc | baseTag (qualLeaf qfname) <= maxIntrinsicTag, Just (rettype, _) <- M.lookup fname I.builtInFunctions -> do let tag ses = [(se, I.Observe) | se <- ses] args' <- reverse <$> mapM (internaliseArg arg_desc) (reverse args) let args'' = concatMap tag args' letValExp' desc $ I.Apply fname args'' [I.Prim rettype] (Safe, loc, []) | otherwise -> do args' <- concat . reverse <$> mapM (internaliseArg arg_desc) (reverse args) fst <$> funcall desc qfname args' loc internaliseAppExp desc _ (E.LetPat sizes pat e body _) = internalisePat desc sizes pat e body (internaliseExp desc) internaliseAppExp _ _ (E.LetFun ofname _ _ _) = error $ "Unexpected LetFun " ++ pretty ofname internaliseAppExp desc _ (E.DoLoop sparams mergepat mergeexp form loopbody loc) = do ses <- internaliseExp "loop_init" mergeexp ((loopbody', (form', shapepat, mergepat', mergeinit')), initstms) <- collectStms $ handleForm ses form addStms initstms mergeinit_ts' <- mapM subExpType mergeinit' ctxinit <- argShapes (map I.paramName shapepat) mergepat' mergeinit_ts' -- Ensure that the initial loop values match the shapes of the loop -- parameters. XXX: Ideally they should already match (by the -- source language type rules), but some of our transformations -- (esp. defunctionalisation) strips out some size information. For -- a type-correct source program, these reshapes should simplify -- away. let args = ctxinit ++ mergeinit' args' <- ensureArgShapes "initial loop values have right shape" loc (map I.paramName shapepat) (map paramType $ shapepat ++ mergepat') args let dropCond = case form of E.While {} -> drop 1 _ -> id -- As above, ensure that the result has the right shape. let merge = zip (shapepat ++ mergepat') args' merge_ts = map (I.paramType . fst) merge loopbody'' <- localScope (scopeOfFParams $ map fst merge) . inScopeOf form' . buildBody_ $ fmap subExpsRes . ensureArgShapes "shape of loop result does not match shapes in loop parameter" loc (map (I.paramName . fst) merge) merge_ts . map resSubExp =<< bodyBind loopbody' attrs <- asks envAttrs map I.Var . dropCond <$> attributing attrs (letValExp desc (I.DoLoop merge form' loopbody'')) where sparams' = map (`TypeParamDim` mempty) sparams forLoop mergepat' shapepat mergeinit form' = bodyFromStms . inScopeOf form' $ do ses <- internaliseExp "loopres" loopbody sets <- mapM subExpType ses shapeargs <- argShapes (map I.paramName shapepat) mergepat' sets pure ( subExpsRes $ shapeargs ++ ses, ( form', shapepat, mergepat', mergeinit ) ) handleForm mergeinit (E.ForIn x arr) = do arr' <- internaliseExpToVars "for_in_arr" arr arr_ts <- mapM lookupType arr' let w = arraysSize 0 arr_ts i <- newVName "i" ts <- mapM subExpType mergeinit bindingLoopParams sparams' mergepat ts $ \shapepat mergepat' -> bindingLambdaParams [x] (map rowType arr_ts) $ \x_params -> do let loopvars = zip x_params arr' forLoop mergepat' shapepat mergeinit $ I.ForLoop i Int64 w loopvars handleForm mergeinit (E.For i num_iterations) = do num_iterations' <- internaliseExp1 "upper_bound" num_iterations num_iterations_t <- I.subExpType num_iterations' it <- case num_iterations_t of I.Prim (IntType it) -> pure it _ -> error "internaliseExp DoLoop: invalid type" ts <- mapM subExpType mergeinit bindingLoopParams sparams' mergepat ts $ \shapepat mergepat' -> forLoop mergepat' shapepat mergeinit $ I.ForLoop (E.identName i) it num_iterations' [] handleForm mergeinit (E.While cond) = do ts <- mapM subExpType mergeinit bindingLoopParams sparams' mergepat ts $ \shapepat mergepat' -> do mergeinit_ts <- mapM subExpType mergeinit -- We need to insert 'cond' twice - once for the initial -- condition (do we enter the loop at all?), and once with the -- result values of the loop (do we continue into the next -- iteration?). This is safe, as the type rules for the -- external language guarantees that 'cond' does not consume -- anything. shapeinit <- argShapes (map I.paramName shapepat) mergepat' mergeinit_ts (loop_initial_cond, init_loop_cond_stms) <- collectStms $ do forM_ (zip shapepat shapeinit) $ \(p, se) -> letBindNames [paramName p] $ BasicOp $ SubExp se forM_ (zip mergepat' mergeinit) $ \(p, se) -> unless (se == I.Var (paramName p)) $ letBindNames [paramName p] $ BasicOp $ case se of I.Var v | not $ primType $ paramType p -> Reshape (map DimCoercion $ arrayDims $ paramType p) v _ -> SubExp se internaliseExp1 "loop_cond" cond addStms init_loop_cond_stms bodyFromStms $ do ses <- internaliseExp "loopres" loopbody sets <- mapM subExpType ses loop_while <- newParam "loop_while" $ I.Prim I.Bool shapeargs <- argShapes (map I.paramName shapepat) mergepat' sets -- Careful not to clobber anything. loop_end_cond_body <- renameBody <=< buildBody_ $ do forM_ (zip shapepat shapeargs) $ \(p, se) -> unless (se == I.Var (paramName p)) $ letBindNames [paramName p] $ BasicOp $ SubExp se forM_ (zip mergepat' ses) $ \(p, se) -> unless (se == I.Var (paramName p)) $ letBindNames [paramName p] $ BasicOp $ case se of I.Var v | not $ primType $ paramType p -> Reshape (map DimCoercion $ arrayDims $ paramType p) v _ -> SubExp se subExpsRes <$> internaliseExp "loop_cond" cond loop_end_cond <- bodyBind loop_end_cond_body pure ( subExpsRes shapeargs ++ loop_end_cond ++ subExpsRes ses, ( I.WhileLoop $ I.paramName loop_while, shapepat, loop_while : mergepat', loop_initial_cond : mergeinit ) ) internaliseAppExp desc _ (E.LetWith name src idxs ve body loc) = do let pat = E.Id (E.identName name) (E.identType name) loc src_t = E.fromStruct <$> E.identType src e = E.Update (E.Var (E.qualName $ E.identName src) src_t loc) idxs ve loc internaliseExp desc $ E.AppExp (E.LetPat [] pat e body loc) (Info (AppRes (E.typeOf body) mempty)) internaliseAppExp desc _ (E.Match e cs _) = do ses <- internaliseExp (desc ++ "_scrutinee") e case NE.uncons cs of (CasePat pCase eCase _, Nothing) -> do (_, pertinent) <- generateCond pCase ses internalisePat' [] pCase pertinent eCase (internaliseExp desc) (c, Just cs') -> do let CasePat pLast eLast _ = NE.last cs' bFalse <- do (_, pertinent) <- generateCond pLast ses eLast' <- internalisePat' [] pLast pertinent eLast (internaliseBody desc) foldM (\bf c' -> eValBody $ return $ generateCaseIf ses c' bf) eLast' $ reverse $ NE.init cs' letValExp' desc =<< generateCaseIf ses c bFalse internaliseAppExp desc _ (E.If ce te fe _) = letValExp' desc =<< eIf (BasicOp . SubExp <$> internaliseExp1 "cond" ce) (internaliseBody (desc <> "_t") te) (internaliseBody (desc <> "_f") fe) internaliseAppExp _ _ e@E.BinOp {} = error $ "internaliseAppExp: Unexpected BinOp " ++ pretty e internaliseExp :: String -> E.Exp -> InternaliseM [I.SubExp] internaliseExp desc (E.Parens e _) = internaliseExp desc e internaliseExp desc (E.QualParens _ e _) = internaliseExp desc e internaliseExp desc (E.StringLit vs _) = fmap pure . letSubExp desc $ I.BasicOp $ I.ArrayLit (map constant vs) $ I.Prim int8 internaliseExp _ (E.Var (E.QualName _ name) _ _) = do subst <- lookupSubst name case subst of Just substs -> return substs Nothing -> pure [I.Var name] internaliseExp desc (E.AppExp e (Info appres)) = do ses <- internaliseAppExp desc (appResExt appres) e bindExtSizes appres ses pure ses -- XXX: we map empty records and tuples to units, because otherwise -- arrays of unit will lose their sizes. internaliseExp _ (E.TupLit [] _) = return [constant UnitValue] internaliseExp _ (E.RecordLit [] _) = return [constant UnitValue] internaliseExp desc (E.TupLit es _) = concat <$> mapM (internaliseExp desc) es internaliseExp desc (E.RecordLit orig_fields _) = concatMap snd . sortFields . M.unions <$> mapM internaliseField orig_fields where internaliseField (E.RecordFieldExplicit name e _) = M.singleton name <$> internaliseExp desc e internaliseField (E.RecordFieldImplicit name t loc) = internaliseField $ E.RecordFieldExplicit (baseName name) (E.Var (E.qualName name) t loc) loc internaliseExp desc (E.ArrayLit es (Info arr_t) loc) -- If this is a multidimensional array literal of primitives, we -- treat it specially by flattening it out followed by a reshape. -- This cuts down on the amount of statements that are produced, and -- thus allows us to efficiently handle huge array literals - a -- corner case, but an important one. | Just ((eshape, e') : es') <- mapM isArrayLiteral es, not $ null eshape, all ((eshape ==) . fst) es', Just basetype <- E.peelArray (length eshape) arr_t = do let flat_lit = E.ArrayLit (e' ++ concatMap snd es') (Info basetype) loc new_shape = length es : eshape flat_arrs <- internaliseExpToVars "flat_literal" flat_lit forM flat_arrs $ \flat_arr -> do flat_arr_t <- lookupType flat_arr let new_shape' = reshapeOuter (map (DimNew . intConst Int64 . toInteger) new_shape) 1 $ I.arrayShape flat_arr_t letSubExp desc $ I.BasicOp $ I.Reshape new_shape' flat_arr | otherwise = do es' <- mapM (internaliseExp "arr_elem") es arr_t_ext <- internaliseType $ E.toStruct arr_t rowtypes <- case mapM (fmap rowType . hasStaticShape . I.fromDecl) arr_t_ext of Just ts -> pure ts Nothing -> -- XXX: the monomorphiser may create single-element array -- literals with an unknown row type. In those cases we -- need to look at the types of the actual elements. -- Fixing this in the monomorphiser is a lot more tricky -- than just working around it here. case es' of [] -> error $ "internaliseExp ArrayLit: existential type: " ++ pretty arr_t e' : _ -> mapM subExpType e' let arraylit ks rt = do ks' <- mapM ( ensureShape "shape of element differs from shape of first element" loc rt "elem_reshaped" ) ks return $ I.BasicOp $ I.ArrayLit ks' rt letSubExps desc =<< if null es' then mapM (arraylit []) rowtypes else zipWithM arraylit (transpose es') rowtypes where isArrayLiteral :: E.Exp -> Maybe ([Int], [E.Exp]) isArrayLiteral (E.ArrayLit inner_es _ _) = do (eshape, e) : inner_es' <- mapM isArrayLiteral inner_es guard $ all ((eshape ==) . fst) inner_es' return (length inner_es : eshape, e ++ concatMap snd inner_es') isArrayLiteral e = Just ([], [e]) internaliseExp desc (E.Ascript e _ _) = internaliseExp desc e internaliseExp desc (E.Negate e _) = do e' <- internaliseExp1 "negate_arg" e et <- subExpType e' case et of I.Prim (I.IntType t) -> letTupExp' desc $ I.BasicOp $ I.BinOp (I.Sub t I.OverflowWrap) (I.intConst t 0) e' I.Prim (I.FloatType t) -> letTupExp' desc $ I.BasicOp $ I.BinOp (I.FSub t) (I.floatConst t 0) e' _ -> error "Futhark.Internalise.internaliseExp: non-numeric type in Negate" internaliseExp desc (E.Not e _) = do e' <- internaliseExp1 "not_arg" e et <- subExpType e' case et of I.Prim (I.IntType t) -> letTupExp' desc $ I.BasicOp $ I.UnOp (I.Complement t) e' I.Prim I.Bool -> letTupExp' desc $ I.BasicOp $ I.UnOp I.Not e' _ -> error "Futhark.Internalise.internaliseExp: non-int/bool type in Not" internaliseExp desc (E.Update src slice ve loc) = do ves <- internaliseExp "lw_val" ve srcs <- internaliseExpToVars "src" src dims <- case srcs of [] -> return [] -- Will this happen? v : _ -> I.arrayDims <$> lookupType v (idxs', cs) <- internaliseSlice loc dims slice let comb sname ve' = do sname_t <- lookupType sname let full_slice = fullSlice sname_t idxs' rowtype = sname_t `setArrayDims` sliceDims full_slice ve'' <- ensureShape "shape of value does not match shape of source array" loc rowtype "lw_val_correct_shape" ve' letInPlace desc sname full_slice $ BasicOp $ SubExp ve'' certifying cs $ map I.Var <$> zipWithM comb srcs ves internaliseExp desc (E.RecordUpdate src fields ve _ _) = do src' <- internaliseExp desc src ve' <- internaliseExp desc ve replace (E.typeOf src `setAliases` ()) fields ve' src' where replace (E.Scalar (E.Record m)) (f : fs) ve' src' | Just t <- M.lookup f m = do i <- fmap sum $ mapM (internalisedTypeSize . snd) $ takeWhile ((/= f) . fst) $ sortFields m k <- internalisedTypeSize t let (bef, to_update, aft) = splitAt3 i k src' src'' <- replace t fs ve' to_update return $ bef ++ src'' ++ aft replace _ _ ve' _ = return ve' internaliseExp desc (E.Attr attr e loc) = do attr' <- internaliseAttr attr e' <- local (f attr') $ internaliseExp desc e case attr' of "trace" -> traceRes (locStr loc) e' I.AttrComp "trace" [I.AttrName tag] -> traceRes (nameToString tag) e' "opaque" -> mapM (letSubExp desc . BasicOp . Opaque OpaqueNil) e' _ -> pure e' where traceRes tag' = mapM (letSubExp desc . BasicOp . Opaque (OpaqueTrace tag')) f attr' env | attr' == "unsafe", not $ envSafe env = env {envDoBoundsChecks = False} | otherwise = env {envAttrs = envAttrs env <> oneAttr attr'} internaliseExp desc (E.Assert e1 e2 (Info check) loc) = do e1' <- internaliseExp1 "assert_cond" e1 c <- assert "assert_c" e1' (errorMsg [ErrorString $ "Assertion is false: " <> check]) loc -- Make sure there are some bindings to certify. certifying c $ mapM rebind =<< internaliseExp desc e2 where rebind v = do v' <- newVName "assert_res" letBindNames [v'] $ I.BasicOp $ I.SubExp v return $ I.Var v' internaliseExp _ (E.Constr c es (Info (E.Scalar (E.Sum fs))) _) = do (ts, constr_map) <- internaliseSumType $ M.map (map E.toStruct) fs es' <- concat <$> mapM (internaliseExp "payload") es let noExt _ = return $ intConst Int64 0 ts' <- instantiateShapes noExt $ map fromDecl ts case M.lookup c constr_map of Just (i, js) -> (intConst Int8 (toInteger i) :) <$> clauses 0 ts' (zip js es') Nothing -> error "internaliseExp Constr: missing constructor" where clauses j (t : ts) js_to_es | Just e <- j `lookup` js_to_es = (e :) <$> clauses (j + 1) ts js_to_es | otherwise = do blank <- letSubExp "zero" =<< eBlank t (blank :) <$> clauses (j + 1) ts js_to_es clauses _ [] _ = return [] internaliseExp _ (E.Constr _ _ (Info t) loc) = error $ "internaliseExp: constructor with type " ++ pretty t ++ " at " ++ locStr loc -- The "interesting" cases are over, now it's mostly boilerplate. internaliseExp _ (E.Literal v _) = return [I.Constant $ internalisePrimValue v] internaliseExp _ (E.IntLit v (Info t) _) = case t of E.Scalar (E.Prim (E.Signed it)) -> return [I.Constant $ I.IntValue $ intValue it v] E.Scalar (E.Prim (E.Unsigned it)) -> return [I.Constant $ I.IntValue $ intValue it v] E.Scalar (E.Prim (E.FloatType ft)) -> return [I.Constant $ I.FloatValue $ floatValue ft v] _ -> error $ "internaliseExp: nonsensical type for integer literal: " ++ pretty t internaliseExp _ (E.FloatLit v (Info t) _) = case t of E.Scalar (E.Prim (E.FloatType ft)) -> return [I.Constant $ I.FloatValue $ floatValue ft v] _ -> error $ "internaliseExp: nonsensical type for float literal: " ++ pretty t -- Builtin operators are handled specially because they are -- overloaded. internaliseExp desc (E.Project k e (Info rt) _) = do n <- internalisedTypeSize $ rt `setAliases` () i' <- fmap sum $ mapM internalisedTypeSize $ case E.typeOf e `setAliases` () of E.Scalar (Record fs) -> map snd $ takeWhile ((/= k) . fst) $ sortFields fs t -> [t] take n . drop i' <$> internaliseExp desc e internaliseExp _ e@E.Lambda {} = error $ "internaliseExp: Unexpected lambda at " ++ locStr (srclocOf e) internaliseExp _ e@E.OpSection {} = error $ "internaliseExp: Unexpected operator section at " ++ locStr (srclocOf e) internaliseExp _ e@E.OpSectionLeft {} = error $ "internaliseExp: Unexpected left operator section at " ++ locStr (srclocOf e) internaliseExp _ e@E.OpSectionRight {} = error $ "internaliseExp: Unexpected right operator section at " ++ locStr (srclocOf e) internaliseExp _ e@E.ProjectSection {} = error $ "internaliseExp: Unexpected projection section at " ++ locStr (srclocOf e) internaliseExp _ e@E.IndexSection {} = error $ "internaliseExp: Unexpected index section at " ++ locStr (srclocOf e) internaliseArg :: String -> (E.Exp, Maybe VName) -> InternaliseM [SubExp] internaliseArg desc (arg, argdim) = do exists <- askScope case argdim of Just d | d `M.member` exists -> pure [I.Var d] _ -> do arg' <- internaliseExp desc arg case (arg', argdim) of ([se], Just d) -> do letBindNames [d] $ BasicOp $ SubExp se _ -> return () pure arg' subExpPrimType :: I.SubExp -> InternaliseM I.PrimType subExpPrimType = fmap I.elemType . subExpType generateCond :: E.Pat -> [I.SubExp] -> InternaliseM (I.SubExp, [I.SubExp]) generateCond orig_p orig_ses = do (cmps, pertinent, _) <- compares orig_p orig_ses cmp <- letSubExp "matches" =<< eAll cmps return (cmp, pertinent) where -- Literals are always primitive values. compares (E.PatLit l t _) (se : ses) = do e' <- case l of PatLitPrim v -> pure $ constant $ internalisePrimValue v PatLitInt x -> internaliseExp1 "constant" $ E.IntLit x t mempty PatLitFloat x -> internaliseExp1 "constant" $ E.FloatLit x t mempty t' <- subExpPrimType se cmp <- letSubExp "match_lit" $ I.BasicOp $ I.CmpOp (I.CmpEq t') e' se return ([cmp], [se], ses) compares (E.PatConstr c (Info (E.Scalar (E.Sum fs))) pats _) (se : ses) = do (payload_ts, m) <- internaliseSumType $ M.map (map toStruct) fs case M.lookup c m of Just (i, payload_is) -> do let i' = intConst Int8 $ toInteger i let (payload_ses, ses') = splitAt (length payload_ts) ses cmp <- letSubExp "match_constr" $ I.BasicOp $ I.CmpOp (I.CmpEq int8) i' se (cmps, pertinent, _) <- comparesMany pats $ map (payload_ses !!) payload_is return (cmp : cmps, pertinent, ses') Nothing -> error "generateCond: missing constructor" compares (E.PatConstr _ (Info t) _ _) _ = error $ "generateCond: PatConstr has nonsensical type: " ++ pretty t compares (E.Id _ t loc) ses = compares (E.Wildcard t loc) ses compares (E.Wildcard (Info t) _) ses = do n <- internalisedTypeSize $ E.toStruct t let (id_ses, rest_ses) = splitAt n ses return ([], id_ses, rest_ses) compares (E.PatParens pat _) ses = compares pat ses compares (E.PatAttr _ pat _) ses = compares pat ses -- XXX: treat empty tuples and records as bool. compares (E.TuplePat [] loc) ses = compares (E.Wildcard (Info $ E.Scalar $ E.Prim E.Bool) loc) ses compares (E.RecordPat [] loc) ses = compares (E.Wildcard (Info $ E.Scalar $ E.Prim E.Bool) loc) ses compares (E.TuplePat pats _) ses = comparesMany pats ses compares (E.RecordPat fs _) ses = comparesMany (map snd $ E.sortFields $ M.fromList fs) ses compares (E.PatAscription pat _ _) ses = compares pat ses compares pat [] = error $ "generateCond: No values left for pattern " ++ pretty pat comparesMany [] ses = return ([], [], ses) comparesMany (pat : pats) ses = do (cmps1, pertinent1, ses') <- compares pat ses (cmps2, pertinent2, ses'') <- comparesMany pats ses' return ( cmps1 <> cmps2, pertinent1 <> pertinent2, ses'' ) generateCaseIf :: [I.SubExp] -> Case -> I.Body -> InternaliseM I.Exp generateCaseIf ses (CasePat p eCase _) bFail = do (cond, pertinent) <- generateCond p ses eCase' <- internalisePat' [] p pertinent eCase (internaliseBody "case") eIf (eSubExp cond) (return eCase') (return bFail) internalisePat :: String -> [E.SizeBinder VName] -> E.Pat -> E.Exp -> E.Exp -> (E.Exp -> InternaliseM a) -> InternaliseM a internalisePat desc sizes p e body m = do ses <- internaliseExp desc' e internalisePat' sizes p ses body m where desc' = case S.toList $ E.patIdents p of [v] -> baseString $ E.identName v _ -> desc internalisePat' :: [E.SizeBinder VName] -> E.Pat -> [I.SubExp] -> E.Exp -> (E.Exp -> InternaliseM a) -> InternaliseM a internalisePat' sizes p ses body m = do ses_ts <- mapM subExpType ses stmPat p ses_ts $ \pat_names -> do bindExtSizes (AppRes (E.patternType p) (map E.sizeName sizes)) ses forM_ (zip pat_names ses) $ \(v, se) -> letBindNames [v] $ I.BasicOp $ I.SubExp se m body internaliseSlice :: SrcLoc -> [SubExp] -> [E.DimIndex] -> InternaliseM ([I.DimIndex SubExp], Certs) internaliseSlice loc dims idxs = do (idxs', oks, parts) <- unzip3 <$> zipWithM internaliseDimIndex dims idxs ok <- letSubExp "index_ok" =<< eAll oks let msg = errorMsg $ ["Index ["] ++ intercalate [", "] parts ++ ["] out of bounds for array of shape ["] ++ intersperse "][" (map (ErrorVal int64) $ take (length idxs) dims) ++ ["]."] c <- assert "index_certs" ok msg loc return (idxs', c) internaliseDimIndex :: SubExp -> E.DimIndex -> InternaliseM (I.DimIndex SubExp, SubExp, [ErrorMsgPart SubExp]) internaliseDimIndex w (E.DimFix i) = do (i', _) <- internaliseDimExp "i" i let lowerBound = I.BasicOp $ I.CmpOp (I.CmpSle I.Int64) (I.constant (0 :: I.Int64)) i' upperBound = I.BasicOp $ I.CmpOp (I.CmpSlt I.Int64) i' w ok <- letSubExp "bounds_check" =<< eBinOp I.LogAnd (pure lowerBound) (pure upperBound) return (I.DimFix i', ok, [ErrorVal int64 i']) -- Special-case an important common case that otherwise leads to horrible code. internaliseDimIndex w ( E.DimSlice Nothing Nothing (Just (E.Negate (E.IntLit 1 _ _) _)) ) = do w_minus_1 <- letSubExp "w_minus_1" $ BasicOp $ I.BinOp (Sub Int64 I.OverflowWrap) w one return ( I.DimSlice w_minus_1 w $ intConst Int64 (-1), constant True, mempty ) where one = constant (1 :: Int64) internaliseDimIndex w (E.DimSlice i j s) = do s' <- maybe (return one) (fmap fst . internaliseDimExp "s") s s_sign <- letSubExp "s_sign" $ BasicOp $ I.UnOp (I.SSignum Int64) s' backwards <- letSubExp "backwards" $ I.BasicOp $ I.CmpOp (I.CmpEq int64) s_sign negone w_minus_1 <- letSubExp "w_minus_1" $ BasicOp $ I.BinOp (Sub Int64 I.OverflowWrap) w one let i_def = letSubExp "i_def" $ I.If backwards (resultBody [w_minus_1]) (resultBody [zero]) $ ifCommon [I.Prim int64] j_def = letSubExp "j_def" $ I.If backwards (resultBody [negone]) (resultBody [w]) $ ifCommon [I.Prim int64] i' <- maybe i_def (fmap fst . internaliseDimExp "i") i j' <- maybe j_def (fmap fst . internaliseDimExp "j") j j_m_i <- letSubExp "j_m_i" $ BasicOp $ I.BinOp (Sub Int64 I.OverflowWrap) j' i' -- Something like a division-rounding-up, but accomodating negative -- operands. let divRounding x y = eBinOp (SQuot Int64 Safe) ( eBinOp (Add Int64 I.OverflowWrap) x (eBinOp (Sub Int64 I.OverflowWrap) y (eSignum $ toExp s')) ) y n <- letSubExp "n" =<< divRounding (toExp j_m_i) (toExp s') zero_stride <- letSubExp "zero_stride" $ I.BasicOp $ I.CmpOp (CmpEq int64) s_sign zero nonzero_stride <- letSubExp "nonzero_stride" $ I.BasicOp $ I.UnOp I.Not zero_stride -- Bounds checks depend on whether we are slicing forwards or -- backwards. If forwards, we must check '0 <= i && i <= j'. If -- backwards, '-1 <= j && j <= i'. In both cases, we check '0 <= -- i+n*s && i+(n-1)*s < w'. We only check if the slice is nonempty. empty_slice <- letSubExp "empty_slice" $ I.BasicOp $ I.CmpOp (CmpEq int64) n zero m <- letSubExp "m" $ I.BasicOp $ I.BinOp (Sub Int64 I.OverflowWrap) n one m_t_s <- letSubExp "m_t_s" $ I.BasicOp $ I.BinOp (Mul Int64 I.OverflowWrap) m s' i_p_m_t_s <- letSubExp "i_p_m_t_s" $ I.BasicOp $ I.BinOp (Add Int64 I.OverflowWrap) i' m_t_s zero_leq_i_p_m_t_s <- letSubExp "zero_leq_i_p_m_t_s" $ I.BasicOp $ I.CmpOp (I.CmpSle Int64) zero i_p_m_t_s i_p_m_t_s_leq_w <- letSubExp "i_p_m_t_s_leq_w" $ I.BasicOp $ I.CmpOp (I.CmpSle Int64) i_p_m_t_s w i_p_m_t_s_lth_w <- letSubExp "i_p_m_t_s_leq_w" $ I.BasicOp $ I.CmpOp (I.CmpSlt Int64) i_p_m_t_s w zero_lte_i <- letSubExp "zero_lte_i" $ I.BasicOp $ I.CmpOp (I.CmpSle Int64) zero i' i_lte_j <- letSubExp "i_lte_j" $ I.BasicOp $ I.CmpOp (I.CmpSle Int64) i' j' forwards_ok <- letSubExp "forwards_ok" =<< eAll [zero_lte_i, zero_lte_i, i_lte_j, zero_leq_i_p_m_t_s, i_p_m_t_s_lth_w] negone_lte_j <- letSubExp "negone_lte_j" $ I.BasicOp $ I.CmpOp (I.CmpSle Int64) negone j' j_lte_i <- letSubExp "j_lte_i" $ I.BasicOp $ I.CmpOp (I.CmpSle Int64) j' i' backwards_ok <- letSubExp "backwards_ok" =<< eAll [negone_lte_j, negone_lte_j, j_lte_i, zero_leq_i_p_m_t_s, i_p_m_t_s_leq_w] slice_ok <- letSubExp "slice_ok" $ I.If backwards (resultBody [backwards_ok]) (resultBody [forwards_ok]) $ ifCommon [I.Prim I.Bool] ok_or_empty <- letSubExp "ok_or_empty" $ I.BasicOp $ I.BinOp I.LogOr empty_slice slice_ok acceptable <- letSubExp "slice_acceptable" $ I.BasicOp $ I.BinOp I.LogAnd nonzero_stride ok_or_empty let parts = case (i, j, s) of (_, _, Just {}) -> [ maybe "" (const $ ErrorVal int64 i') i, ":", maybe "" (const $ ErrorVal int64 j') j, ":", ErrorVal int64 s' ] (_, Just {}, _) -> [ maybe "" (const $ ErrorVal int64 i') i, ":", ErrorVal int64 j' ] ++ maybe mempty (const [":", ErrorVal int64 s']) s (_, Nothing, Nothing) -> [ErrorVal int64 i', ":"] return (I.DimSlice i' n s', acceptable, parts) where zero = constant (0 :: Int64) negone = constant (-1 :: Int64) one = constant (1 :: Int64) internaliseScanOrReduce :: String -> String -> (SubExp -> I.Lambda -> [SubExp] -> [VName] -> InternaliseM (SOAC SOACS)) -> (E.Exp, E.Exp, E.Exp, SrcLoc) -> InternaliseM [SubExp] internaliseScanOrReduce desc what f (lam, ne, arr, loc) = do arrs <- internaliseExpToVars (what ++ "_arr") arr nes <- internaliseExp (what ++ "_ne") ne nes' <- forM (zip nes arrs) $ \(ne', arr') -> do rowtype <- I.stripArray 1 <$> lookupType arr' ensureShape "Row shape of input array does not match shape of neutral element" loc rowtype (what ++ "_ne_right_shape") ne' nests <- mapM I.subExpType nes' arrts <- mapM lookupType arrs lam' <- internaliseFoldLambda internaliseLambda lam nests arrts w <- arraysSize 0 <$> mapM lookupType arrs letValExp' desc . I.Op =<< f w lam' nes' arrs internaliseHist :: String -> E.Exp -> E.Exp -> E.Exp -> E.Exp -> E.Exp -> E.Exp -> SrcLoc -> InternaliseM [SubExp] internaliseHist desc rf hist op ne buckets img loc = do rf' <- internaliseExp1 "hist_rf" rf ne' <- internaliseExp "hist_ne" ne hist' <- internaliseExpToVars "hist_hist" hist buckets' <- letExp "hist_buckets" . BasicOp . SubExp =<< internaliseExp1 "hist_buckets" buckets img' <- internaliseExpToVars "hist_img" img -- reshape neutral element to have same size as the destination array ne_shp <- forM (zip ne' hist') $ \(n, h) -> do rowtype <- I.stripArray 1 <$> lookupType h ensureShape "Row shape of destination array does not match shape of neutral element" loc rowtype "hist_ne_right_shape" n ne_ts <- mapM I.subExpType ne_shp his_ts <- mapM lookupType hist' op' <- internaliseFoldLambda internaliseLambda op ne_ts his_ts -- reshape return type of bucket function to have same size as neutral element -- (modulo the index) bucket_param <- newParam "bucket_p" $ I.Prim int64 img_params <- mapM (newParam "img_p" . rowType) =<< mapM lookupType img' let params = bucket_param : img_params rettype = I.Prim int64 : ne_ts body = mkBody mempty $ varsRes $ map paramName params lam' <- mkLambda params $ ensureResultShape "Row shape of value array does not match row shape of hist target" (srclocOf img) rettype =<< bodyBind body -- get sizes of histogram and image arrays w_hist <- arraysSize 0 <$> mapM lookupType hist' w_img <- arraysSize 0 <$> mapM lookupType img' -- Generate an assertion and reshapes to ensure that buckets' and -- img' are the same size. b_shape <- I.arrayShape <$> lookupType buckets' let b_w = shapeSize 0 b_shape cmp <- letSubExp "bucket_cmp" $ I.BasicOp $ I.CmpOp (I.CmpEq I.int64) b_w w_img c <- assert "bucket_cert" cmp "length of index and value array does not match" loc buckets'' <- certifying c . letExp (baseString buckets') $ I.BasicOp $ I.Reshape (reshapeOuter [DimCoercion w_img] 1 b_shape) buckets' letValExp' desc . I.Op $ I.Hist w_img (buckets'' : img') [HistOp w_hist rf' hist' ne_shp op'] lam' internaliseStreamMap :: String -> StreamOrd -> E.Exp -> E.Exp -> InternaliseM [SubExp] internaliseStreamMap desc o lam arr = do arrs <- internaliseExpToVars "stream_input" arr lam' <- internaliseStreamMapLambda internaliseLambda lam $ map I.Var arrs w <- arraysSize 0 <$> mapM lookupType arrs let form = I.Parallel o Commutative (I.Lambda [] (mkBody mempty []) []) letValExp' desc $ I.Op $ I.Stream w arrs form [] lam' internaliseStreamRed :: String -> StreamOrd -> Commutativity -> E.Exp -> E.Exp -> E.Exp -> InternaliseM [SubExp] internaliseStreamRed desc o comm lam0 lam arr = do arrs <- internaliseExpToVars "stream_input" arr rowts <- mapM (fmap I.rowType . lookupType) arrs (lam_params, lam_body) <- internaliseStreamLambda internaliseLambda lam rowts let (chunk_param, _, lam_val_params) = partitionChunkedFoldParameters 0 lam_params -- Synthesize neutral elements by applying the fold function -- to an empty chunk. letBindNames [I.paramName chunk_param] $ I.BasicOp $ I.SubExp $ constant (0 :: Int64) forM_ lam_val_params $ \p -> letBindNames [I.paramName p] $ I.BasicOp . I.Scratch (I.elemType $ I.paramType p) $ I.arrayDims $ I.paramType p nes <- bodyBind =<< renameBody lam_body nes_ts <- mapM I.subExpResType nes outsz <- arraysSize 0 <$> mapM lookupType arrs let acc_arr_tps = [I.arrayOf t (I.Shape [outsz]) NoUniqueness | t <- nes_ts] lam0' <- internaliseFoldLambda internaliseLambda lam0 nes_ts acc_arr_tps let lam0_acc_params = take (length nes) $ I.lambdaParams lam0' lam_acc_params <- forM lam0_acc_params $ \p -> do name <- newVName $ baseString $ I.paramName p return p {I.paramName = name} -- Make sure the chunk size parameter comes first. let lam_params' = chunk_param : lam_acc_params ++ lam_val_params lam' <- mkLambda lam_params' $ do lam_res <- bodyBind lam_body lam_res' <- ensureArgShapes "shape of chunk function result does not match shape of initial value" (srclocOf lam) [] (map I.typeOf $ I.lambdaParams lam0') (map resSubExp lam_res) ensureResultShape "shape of result does not match shape of initial value" (srclocOf lam0) nes_ts =<< ( eLambda lam0' . map eSubExp $ map (I.Var . paramName) lam_acc_params ++ lam_res' ) let form = I.Parallel o comm lam0' w <- arraysSize 0 <$> mapM lookupType arrs letValExp' desc $ I.Op $ I.Stream w arrs form (map resSubExp nes) lam' internaliseStreamAcc :: String -> E.Exp -> Maybe (E.Exp, E.Exp) -> E.Exp -> E.Exp -> InternaliseM [SubExp] internaliseStreamAcc desc dest op lam bs = do dest' <- internaliseExpToVars "scatter_dest" dest bs' <- internaliseExpToVars "scatter_input" bs acc_cert_v <- newVName "acc_cert" dest_ts <- mapM lookupType dest' let dest_w = arraysSize 0 dest_ts acc_t = Acc acc_cert_v (Shape [dest_w]) (map rowType dest_ts) NoUniqueness acc_p <- newParam "acc_p" acc_t withacc_lam <- mkLambda [Param mempty acc_cert_v (I.Prim I.Unit), acc_p] $ do lam' <- internaliseMapLambda internaliseLambda lam $ map I.Var $ paramName acc_p : bs' w <- arraysSize 0 <$> mapM lookupType bs' fmap subExpsRes . letValExp' "acc_res" $ I.Op $ I.Screma w (paramName acc_p : bs') (I.mapSOAC lam') op' <- case op of Just (op_lam, ne) -> do ne' <- internaliseExp "hist_ne" ne ne_ts <- mapM I.subExpType ne' (lam_params, lam_body, lam_rettype) <- internaliseLambda op_lam $ ne_ts ++ ne_ts idxp <- newParam "idx" $ I.Prim int64 let op_lam' = I.Lambda (idxp : lam_params) lam_body lam_rettype return $ Just (op_lam', ne') Nothing -> return Nothing destw <- arraysSize 0 <$> mapM lookupType dest' fmap (map I.Var) $ letTupExp desc $ WithAcc [(Shape [destw], dest', op')] withacc_lam internaliseExp1 :: String -> E.Exp -> InternaliseM I.SubExp internaliseExp1 desc e = do vs <- internaliseExp desc e case vs of [se] -> return se _ -> error "Internalise.internaliseExp1: was passed not just a single subexpression" -- | Promote to dimension type as appropriate for the original type. -- Also return original type. internaliseDimExp :: String -> E.Exp -> InternaliseM (I.SubExp, IntType) internaliseDimExp s e = do e' <- internaliseExp1 s e case E.typeOf e of E.Scalar (E.Prim (Signed it)) -> (,it) <$> asIntS Int64 e' _ -> error "internaliseDimExp: bad type" internaliseExpToVars :: String -> E.Exp -> InternaliseM [I.VName] internaliseExpToVars desc e = mapM asIdent =<< internaliseExp desc e where asIdent (I.Var v) = return v asIdent se = letExp desc $ I.BasicOp $ I.SubExp se internaliseOperation :: String -> E.Exp -> (I.VName -> InternaliseM I.BasicOp) -> InternaliseM [I.SubExp] internaliseOperation s e op = do vs <- internaliseExpToVars s e letSubExps s =<< mapM (fmap I.BasicOp . op) vs certifyingNonzero :: SrcLoc -> IntType -> SubExp -> InternaliseM a -> InternaliseM a certifyingNonzero loc t x m = do zero <- letSubExp "zero" $ I.BasicOp $ CmpOp (CmpEq (IntType t)) x (intConst t 0) nonzero <- letSubExp "nonzero" $ I.BasicOp $ UnOp I.Not zero c <- assert "nonzero_cert" nonzero "division by zero" loc certifying c m certifyingNonnegative :: SrcLoc -> IntType -> SubExp -> InternaliseM a -> InternaliseM a certifyingNonnegative loc t x m = do nonnegative <- letSubExp "nonnegative" . I.BasicOp $ CmpOp (CmpSle t) (intConst t 0) x c <- assert "nonzero_cert" nonnegative "negative exponent" loc certifying c m internaliseBinOp :: SrcLoc -> String -> E.BinOp -> I.SubExp -> I.SubExp -> E.PrimType -> E.PrimType -> InternaliseM [I.SubExp] internaliseBinOp _ desc E.Plus x y (E.Signed t) _ = simpleBinOp desc (I.Add t I.OverflowWrap) x y internaliseBinOp _ desc E.Plus x y (E.Unsigned t) _ = simpleBinOp desc (I.Add t I.OverflowWrap) x y internaliseBinOp _ desc E.Plus x y (E.FloatType t) _ = simpleBinOp desc (I.FAdd t) x y internaliseBinOp _ desc E.Minus x y (E.Signed t) _ = simpleBinOp desc (I.Sub t I.OverflowWrap) x y internaliseBinOp _ desc E.Minus x y (E.Unsigned t) _ = simpleBinOp desc (I.Sub t I.OverflowWrap) x y internaliseBinOp _ desc E.Minus x y (E.FloatType t) _ = simpleBinOp desc (I.FSub t) x y internaliseBinOp _ desc E.Times x y (E.Signed t) _ = simpleBinOp desc (I.Mul t I.OverflowWrap) x y internaliseBinOp _ desc E.Times x y (E.Unsigned t) _ = simpleBinOp desc (I.Mul t I.OverflowWrap) x y internaliseBinOp _ desc E.Times x y (E.FloatType t) _ = simpleBinOp desc (I.FMul t) x y internaliseBinOp loc desc E.Divide x y (E.Signed t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.SDiv t I.Unsafe) x y internaliseBinOp loc desc E.Divide x y (E.Unsigned t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.UDiv t I.Unsafe) x y internaliseBinOp _ desc E.Divide x y (E.FloatType t) _ = simpleBinOp desc (I.FDiv t) x y internaliseBinOp _ desc E.Pow x y (E.FloatType t) _ = simpleBinOp desc (I.FPow t) x y internaliseBinOp loc desc E.Pow x y (E.Signed t) _ = certifyingNonnegative loc t y $ simpleBinOp desc (I.Pow t) x y internaliseBinOp _ desc E.Pow x y (E.Unsigned t) _ = simpleBinOp desc (I.Pow t) x y internaliseBinOp loc desc E.Mod x y (E.Signed t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.SMod t I.Unsafe) x y internaliseBinOp loc desc E.Mod x y (E.Unsigned t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.UMod t I.Unsafe) x y internaliseBinOp _ desc E.Mod x y (E.FloatType t) _ = simpleBinOp desc (I.FMod t) x y internaliseBinOp loc desc E.Quot x y (E.Signed t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.SQuot t I.Unsafe) x y internaliseBinOp loc desc E.Quot x y (E.Unsigned t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.UDiv t I.Unsafe) x y internaliseBinOp loc desc E.Rem x y (E.Signed t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.SRem t I.Unsafe) x y internaliseBinOp loc desc E.Rem x y (E.Unsigned t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.UMod t I.Unsafe) x y internaliseBinOp _ desc E.ShiftR x y (E.Signed t) _ = simpleBinOp desc (I.AShr t) x y internaliseBinOp _ desc E.ShiftR x y (E.Unsigned t) _ = simpleBinOp desc (I.LShr t) x y internaliseBinOp _ desc E.ShiftL x y (E.Signed t) _ = simpleBinOp desc (I.Shl t) x y internaliseBinOp _ desc E.ShiftL x y (E.Unsigned t) _ = simpleBinOp desc (I.Shl t) x y internaliseBinOp _ desc E.Band x y (E.Signed t) _ = simpleBinOp desc (I.And t) x y internaliseBinOp _ desc E.Band x y (E.Unsigned t) _ = simpleBinOp desc (I.And t) x y internaliseBinOp _ desc E.Xor x y (E.Signed t) _ = simpleBinOp desc (I.Xor t) x y internaliseBinOp _ desc E.Xor x y (E.Unsigned t) _ = simpleBinOp desc (I.Xor t) x y internaliseBinOp _ desc E.Bor x y (E.Signed t) _ = simpleBinOp desc (I.Or t) x y internaliseBinOp _ desc E.Bor x y (E.Unsigned t) _ = simpleBinOp desc (I.Or t) x y internaliseBinOp _ desc E.Equal x y t _ = simpleCmpOp desc (I.CmpEq $ internalisePrimType t) x y internaliseBinOp _ desc E.NotEqual x y t _ = do eq <- letSubExp (desc ++ "true") $ I.BasicOp $ I.CmpOp (I.CmpEq $ internalisePrimType t) x y fmap pure $ letSubExp desc $ I.BasicOp $ I.UnOp I.Not eq internaliseBinOp _ desc E.Less x y (E.Signed t) _ = simpleCmpOp desc (I.CmpSlt t) x y internaliseBinOp _ desc E.Less x y (E.Unsigned t) _ = simpleCmpOp desc (I.CmpUlt t) x y internaliseBinOp _ desc E.Leq x y (E.Signed t) _ = simpleCmpOp desc (I.CmpSle t) x y internaliseBinOp _ desc E.Leq x y (E.Unsigned t) _ = simpleCmpOp desc (I.CmpUle t) x y internaliseBinOp _ desc E.Greater x y (E.Signed t) _ = simpleCmpOp desc (I.CmpSlt t) y x -- Note the swapped x and y internaliseBinOp _ desc E.Greater x y (E.Unsigned t) _ = simpleCmpOp desc (I.CmpUlt t) y x -- Note the swapped x and y internaliseBinOp _ desc E.Geq x y (E.Signed t) _ = simpleCmpOp desc (I.CmpSle t) y x -- Note the swapped x and y internaliseBinOp _ desc E.Geq x y (E.Unsigned t) _ = simpleCmpOp desc (I.CmpUle t) y x -- Note the swapped x and y internaliseBinOp _ desc E.Less x y (E.FloatType t) _ = simpleCmpOp desc (I.FCmpLt t) x y internaliseBinOp _ desc E.Leq x y (E.FloatType t) _ = simpleCmpOp desc (I.FCmpLe t) x y internaliseBinOp _ desc E.Greater x y (E.FloatType t) _ = simpleCmpOp desc (I.FCmpLt t) y x -- Note the swapped x and y internaliseBinOp _ desc E.Geq x y (E.FloatType t) _ = simpleCmpOp desc (I.FCmpLe t) y x -- Note the swapped x and y -- Relational operators for booleans. internaliseBinOp _ desc E.Less x y E.Bool _ = simpleCmpOp desc I.CmpLlt x y internaliseBinOp _ desc E.Leq x y E.Bool _ = simpleCmpOp desc I.CmpLle x y internaliseBinOp _ desc E.Greater x y E.Bool _ = simpleCmpOp desc I.CmpLlt y x -- Note the swapped x and y internaliseBinOp _ desc E.Geq x y E.Bool _ = simpleCmpOp desc I.CmpLle y x -- Note the swapped x and y internaliseBinOp _ _ op _ _ t1 t2 = error $ "Invalid binary operator " ++ pretty op ++ " with operand types " ++ pretty t1 ++ ", " ++ pretty t2 simpleBinOp :: String -> I.BinOp -> I.SubExp -> I.SubExp -> InternaliseM [I.SubExp] simpleBinOp desc bop x y = letTupExp' desc $ I.BasicOp $ I.BinOp bop x y simpleCmpOp :: String -> I.CmpOp -> I.SubExp -> I.SubExp -> InternaliseM [I.SubExp] simpleCmpOp desc op x y = letTupExp' desc $ I.BasicOp $ I.CmpOp op x y findFuncall :: E.AppExp -> InternaliseM ( E.QualName VName, [(E.Exp, Maybe VName)] ) findFuncall (E.Apply f arg (Info (_, argext)) _) | E.AppExp f_e _ <- f = do (fname, args) <- findFuncall f_e return (fname, args ++ [(arg, argext)]) | E.Var fname _ _ <- f = return (fname, [(arg, argext)]) findFuncall e = error $ "Invalid function expression in application: " ++ pretty e -- The type of a body. Watch out: this only works for the degenerate -- case where the body does not already return its context. bodyExtType :: Body -> InternaliseM [ExtType] bodyExtType (Body _ stms res) = existentialiseExtTypes (M.keys stmsscope) . staticShapes <$> extendedScope (traverse subExpResType res) stmsscope where stmsscope = scopeOf stms internaliseLambda :: InternaliseLambda internaliseLambda (E.Parens e _) rowtypes = internaliseLambda e rowtypes internaliseLambda (E.Lambda params body _ (Info (_, RetType _ rettype)) _) rowtypes = bindingLambdaParams params rowtypes $ \params' -> do body' <- internaliseBody "lam" body rettype' <- internaliseLambdaReturnType rettype =<< bodyExtType body' return (params', body', rettype') internaliseLambda e _ = error $ "internaliseLambda: unexpected expression:\n" ++ pretty e -- | Some operators and functions are overloaded or otherwise special -- - we detect and treat them here. isOverloadedFunction :: E.QualName VName -> [E.Exp] -> SrcLoc -> Maybe (String -> InternaliseM [SubExp]) isOverloadedFunction qname args loc = do guard $ baseTag (qualLeaf qname) <= maxIntrinsicTag let handlers = [ handleSign, handleIntrinsicOps, handleOps, handleSOACs, handleAccs, handleRest ] msum [h args $ baseString $ qualLeaf qname | h <- handlers] where handleSign [x] "sign_i8" = Just $ toSigned I.Int8 x handleSign [x] "sign_i16" = Just $ toSigned I.Int16 x handleSign [x] "sign_i32" = Just $ toSigned I.Int32 x handleSign [x] "sign_i64" = Just $ toSigned I.Int64 x handleSign [x] "unsign_i8" = Just $ toUnsigned I.Int8 x handleSign [x] "unsign_i16" = Just $ toUnsigned I.Int16 x handleSign [x] "unsign_i32" = Just $ toUnsigned I.Int32 x handleSign [x] "unsign_i64" = Just $ toUnsigned I.Int64 x handleSign _ _ = Nothing handleIntrinsicOps [x] s | Just unop <- find ((== s) . pretty) allUnOps = Just $ \desc -> do x' <- internaliseExp1 "x" x fmap pure $ letSubExp desc $ I.BasicOp $ I.UnOp unop x' handleIntrinsicOps [TupLit [x, y] _] s | Just bop <- find ((== s) . pretty) allBinOps = Just $ \desc -> do x' <- internaliseExp1 "x" x y' <- internaliseExp1 "y" y fmap pure $ letSubExp desc $ I.BasicOp $ I.BinOp bop x' y' | Just cmp <- find ((== s) . pretty) allCmpOps = Just $ \desc -> do x' <- internaliseExp1 "x" x y' <- internaliseExp1 "y" y fmap pure $ letSubExp desc $ I.BasicOp $ I.CmpOp cmp x' y' handleIntrinsicOps [x] s | Just conv <- find ((== s) . pretty) allConvOps = Just $ \desc -> do x' <- internaliseExp1 "x" x fmap pure $ letSubExp desc $ I.BasicOp $ I.ConvOp conv x' handleIntrinsicOps _ _ = Nothing -- Short-circuiting operators are magical. handleOps [x, y] "&&" = Just $ \desc -> internaliseExp desc $ E.AppExp (E.If x y (E.Literal (E.BoolValue False) mempty) mempty) (Info $ AppRes (E.Scalar $ E.Prim E.Bool) []) handleOps [x, y] "||" = Just $ \desc -> internaliseExp desc $ E.AppExp (E.If x (E.Literal (E.BoolValue True) mempty) y mempty) (Info $ AppRes (E.Scalar $ E.Prim E.Bool) []) -- Handle equality and inequality specially, to treat the case of -- arrays. handleOps [xe, ye] op | Just cmp_f <- isEqlOp op = Just $ \desc -> do xe' <- internaliseExp "x" xe ye' <- internaliseExp "y" ye rs <- zipWithM (doComparison desc) xe' ye' cmp_f desc =<< letSubExp "eq" =<< eAll rs where isEqlOp "!=" = Just $ \desc eq -> letTupExp' desc $ I.BasicOp $ I.UnOp I.Not eq isEqlOp "==" = Just $ \_ eq -> return [eq] isEqlOp _ = Nothing doComparison desc x y = do x_t <- I.subExpType x y_t <- I.subExpType y case x_t of I.Prim t -> letSubExp desc $ I.BasicOp $ I.CmpOp (I.CmpEq t) x y _ -> do let x_dims = I.arrayDims x_t y_dims = I.arrayDims y_t dims_match <- forM (zip x_dims y_dims) $ \(x_dim, y_dim) -> letSubExp "dim_eq" $ I.BasicOp $ I.CmpOp (I.CmpEq int64) x_dim y_dim shapes_match <- letSubExp "shapes_match" =<< eAll dims_match compare_elems_body <- runBodyBuilder $ do -- Flatten both x and y. x_num_elems <- letSubExp "x_num_elems" =<< foldBinOp (I.Mul Int64 I.OverflowUndef) (constant (1 :: Int64)) x_dims x' <- letExp "x" $ I.BasicOp $ I.SubExp x y' <- letExp "x" $ I.BasicOp $ I.SubExp y x_flat <- letExp "x_flat" $ I.BasicOp $ I.Reshape [I.DimNew x_num_elems] x' y_flat <- letExp "y_flat" $ I.BasicOp $ I.Reshape [I.DimNew x_num_elems] y' -- Compare the elements. cmp_lam <- cmpOpLambda $ I.CmpEq (elemType x_t) cmps <- letExp "cmps" $ I.Op $ I.Screma x_num_elems [x_flat, y_flat] (I.mapSOAC cmp_lam) -- Check that all were equal. and_lam <- binOpLambda I.LogAnd I.Bool reduce <- I.reduceSOAC [Reduce Commutative and_lam [constant True]] all_equal <- letSubExp "all_equal" $ I.Op $ I.Screma x_num_elems [cmps] reduce return $ resultBody [all_equal] letSubExp "arrays_equal" $ I.If shapes_match compare_elems_body (resultBody [constant False]) $ ifCommon [I.Prim I.Bool] handleOps [x, y] name | Just bop <- find ((name ==) . pretty) [minBound .. maxBound :: E.BinOp] = Just $ \desc -> do x' <- internaliseExp1 "x" x y' <- internaliseExp1 "y" y case (E.typeOf x, E.typeOf y) of (E.Scalar (E.Prim t1), E.Scalar (E.Prim t2)) -> internaliseBinOp loc desc bop x' y' t1 t2 _ -> error "Futhark.Internalise.internaliseExp: non-primitive type in BinOp." handleOps _ _ = Nothing handleSOACs [TupLit [lam, arr] _] "map" = Just $ \desc -> do arr' <- internaliseExpToVars "map_arr" arr lam' <- internaliseMapLambda internaliseLambda lam $ map I.Var arr' w <- arraysSize 0 <$> mapM lookupType arr' letTupExp' desc $ I.Op $ I.Screma w arr' (I.mapSOAC lam') handleSOACs [TupLit [k, lam, arr] _] "partition" = do k' <- fromIntegral <$> fromInt32 k Just $ \_desc -> do arrs <- internaliseExpToVars "partition_input" arr lam' <- internalisePartitionLambda internaliseLambda k' lam $ map I.Var arrs uncurry (++) <$> partitionWithSOACS (fromIntegral k') lam' arrs where fromInt32 (Literal (SignedValue (Int32Value k')) _) = Just k' fromInt32 (IntLit k' (Info (E.Scalar (E.Prim (Signed Int32)))) _) = Just $ fromInteger k' fromInt32 _ = Nothing handleSOACs [TupLit [lam, ne, arr] _] "reduce" = Just $ \desc -> internaliseScanOrReduce desc "reduce" reduce (lam, ne, arr, loc) where reduce w red_lam nes arrs = I.Screma w arrs <$> I.reduceSOAC [Reduce Noncommutative red_lam nes] handleSOACs [TupLit [lam, ne, arr] _] "reduce_comm" = Just $ \desc -> internaliseScanOrReduce desc "reduce" reduce (lam, ne, arr, loc) where reduce w red_lam nes arrs = I.Screma w arrs <$> I.reduceSOAC [Reduce Commutative red_lam nes] handleSOACs [TupLit [lam, ne, arr] _] "scan" = Just $ \desc -> internaliseScanOrReduce desc "scan" reduce (lam, ne, arr, loc) where reduce w scan_lam nes arrs = I.Screma w arrs <$> I.scanSOAC [Scan scan_lam nes] handleSOACs [TupLit [op, f, arr] _] "reduce_stream" = Just $ \desc -> internaliseStreamRed desc InOrder Noncommutative op f arr handleSOACs [TupLit [op, f, arr] _] "reduce_stream_per" = Just $ \desc -> internaliseStreamRed desc Disorder Commutative op f arr handleSOACs [TupLit [f, arr] _] "map_stream" = Just $ \desc -> internaliseStreamMap desc InOrder f arr handleSOACs [TupLit [f, arr] _] "map_stream_per" = Just $ \desc -> internaliseStreamMap desc Disorder f arr handleSOACs [TupLit [rf, dest, op, ne, buckets, img] _] "hist" = Just $ \desc -> internaliseHist desc rf dest op ne buckets img loc handleSOACs _ _ = Nothing handleAccs [TupLit [dest, f, bs] _] "scatter_stream" = Just $ \desc -> internaliseStreamAcc desc dest Nothing f bs handleAccs [TupLit [dest, op, ne, f, bs] _] "hist_stream" = Just $ \desc -> internaliseStreamAcc desc dest (Just (op, ne)) f bs handleAccs [TupLit [acc, i, v] _] "acc_write" = Just $ \desc -> do acc' <- head <$> internaliseExpToVars "acc" acc i' <- internaliseExp1 "acc_i" i vs <- internaliseExp "acc_v" v fmap pure $ letSubExp desc $ BasicOp $ UpdateAcc acc' [i'] vs handleAccs _ _ = Nothing handleRest [E.TupLit [a, si, v] _] "scatter" = Just $ scatterF 1 a si v handleRest [E.TupLit [a, si, v] _] "scatter_2d" = Just $ scatterF 2 a si v handleRest [E.TupLit [a, si, v] _] "scatter_3d" = Just $ scatterF 3 a si v handleRest [E.TupLit [n, m, arr] _] "unflatten" = Just $ \desc -> do arrs <- internaliseExpToVars "unflatten_arr" arr n' <- internaliseExp1 "n" n m' <- internaliseExp1 "m" m -- The unflattened dimension needs to have the same number of elements -- as the original dimension. old_dim <- I.arraysSize 0 <$> mapM lookupType arrs dim_ok <- letSubExp "dim_ok" =<< eCmpOp (I.CmpEq I.int64) (eBinOp (I.Mul Int64 I.OverflowUndef) (eSubExp n') (eSubExp m')) (eSubExp old_dim) dim_ok_cert <- assert "dim_ok_cert" dim_ok "new shape has different number of elements than old shape" loc certifying dim_ok_cert $ forM arrs $ \arr' -> do arr_t <- lookupType arr' letSubExp desc $ I.BasicOp $ I.Reshape (reshapeOuter [DimNew n', DimNew m'] 1 $ I.arrayShape arr_t) arr' handleRest [arr] "flatten" = Just $ \desc -> do arrs <- internaliseExpToVars "flatten_arr" arr forM arrs $ \arr' -> do arr_t <- lookupType arr' let n = arraySize 0 arr_t m = arraySize 1 arr_t k <- letSubExp "flat_dim" $ I.BasicOp $ I.BinOp (Mul Int64 I.OverflowUndef) n m letSubExp desc $ I.BasicOp $ I.Reshape (reshapeOuter [DimNew k] 2 $ I.arrayShape arr_t) arr' handleRest [TupLit [x, y] _] "concat" = Just $ \desc -> do xs <- internaliseExpToVars "concat_x" x ys <- internaliseExpToVars "concat_y" y outer_size <- arraysSize 0 <$> mapM lookupType xs let sumdims xsize ysize = letSubExp "conc_tmp" $ I.BasicOp $ I.BinOp (I.Add I.Int64 I.OverflowUndef) xsize ysize ressize <- foldM sumdims outer_size =<< mapM (fmap (arraysSize 0) . mapM lookupType) [ys] let conc xarr yarr = I.BasicOp $ I.Concat 0 xarr [yarr] ressize letSubExps desc $ zipWith conc xs ys handleRest [TupLit [offset, e] _] "rotate" = Just $ \desc -> do offset' <- internaliseExp1 "rotation_offset" offset internaliseOperation desc e $ \v -> do r <- I.arrayRank <$> lookupType v let zero = intConst Int64 0 offsets = offset' : replicate (r - 1) zero return $ I.Rotate offsets v handleRest [e] "transpose" = Just $ \desc -> internaliseOperation desc e $ \v -> do r <- I.arrayRank <$> lookupType v return $ I.Rearrange ([1, 0] ++ [2 .. r - 1]) v handleRest [TupLit [x, y] _] "zip" = Just $ \desc -> mapM (letSubExp "zip_copy" . BasicOp . Copy) =<< ( (++) <$> internaliseExpToVars (desc ++ "_zip_x") x <*> internaliseExpToVars (desc ++ "_zip_y") y ) handleRest [x] "unzip" = Just $ flip internaliseExp x handleRest [TupLit [arr, offset, n1, s1, n2, s2] _] "flat_index_2d" = Just $ \desc -> do flatIndexHelper desc loc arr offset [(n1, s1), (n2, s2)] handleRest [TupLit [arr1, offset, s1, s2, arr2] _] "flat_update_2d" = Just $ \desc -> do flatUpdateHelper desc loc arr1 offset [s1, s2] arr2 handleRest [TupLit [arr, offset, n1, s1, n2, s2, n3, s3] _] "flat_index_3d" = Just $ \desc -> do flatIndexHelper desc loc arr offset [(n1, s1), (n2, s2), (n3, s3)] handleRest [TupLit [arr1, offset, s1, s2, s3, arr2] _] "flat_update_3d" = Just $ \desc -> do flatUpdateHelper desc loc arr1 offset [s1, s2, s3] arr2 handleRest [TupLit [arr, offset, n1, s1, n2, s2, n3, s3, n4, s4] _] "flat_index_4d" = Just $ \desc -> do flatIndexHelper desc loc arr offset [(n1, s1), (n2, s2), (n3, s3), (n4, s4)] handleRest [TupLit [arr1, offset, s1, s2, s3, s4, arr2] _] "flat_update_4d" = Just $ \desc -> do flatUpdateHelper desc loc arr1 offset [s1, s2, s3, s4] arr2 handleRest _ _ = Nothing toSigned int_to e desc = do e' <- internaliseExp1 "trunc_arg" e case E.typeOf e of E.Scalar (E.Prim E.Bool) -> letTupExp' desc $ I.If e' (resultBody [intConst int_to 1]) (resultBody [intConst int_to 0]) $ ifCommon [I.Prim $ I.IntType int_to] E.Scalar (E.Prim (E.Signed int_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.SExt int_from int_to) e' E.Scalar (E.Prim (E.Unsigned int_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.ZExt int_from int_to) e' E.Scalar (E.Prim (E.FloatType float_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.FPToSI float_from int_to) e' _ -> error "Futhark.Internalise: non-numeric type in ToSigned" toUnsigned int_to e desc = do e' <- internaliseExp1 "trunc_arg" e case E.typeOf e of E.Scalar (E.Prim E.Bool) -> letTupExp' desc $ I.If e' (resultBody [intConst int_to 1]) (resultBody [intConst int_to 0]) $ ifCommon [I.Prim $ I.IntType int_to] E.Scalar (E.Prim (E.Signed int_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.ZExt int_from int_to) e' E.Scalar (E.Prim (E.Unsigned int_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.ZExt int_from int_to) e' E.Scalar (E.Prim (E.FloatType float_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.FPToUI float_from int_to) e' _ -> error "Futhark.Internalise.internaliseExp: non-numeric type in ToUnsigned" scatterF dim a si v desc = do si' <- internaliseExpToVars "write_arg_i" si svs <- internaliseExpToVars "write_arg_v" v sas <- internaliseExpToVars "write_arg_a" a si_w <- I.arraysSize 0 <$> mapM lookupType si' sv_ts <- mapM lookupType svs svs' <- forM (zip svs sv_ts) $ \(sv, sv_t) -> do let sv_shape = I.arrayShape sv_t sv_w = arraySize 0 sv_t -- Generate an assertion and reshapes to ensure that sv and si' are the same -- size. cmp <- letSubExp "write_cmp" $ I.BasicOp $ I.CmpOp (I.CmpEq I.int64) si_w sv_w c <- assert "write_cert" cmp "length of index and value array does not match" loc certifying c $ letExp (baseString sv ++ "_write_sv") $ I.BasicOp $ I.Reshape (reshapeOuter [DimCoercion si_w] 1 sv_shape) sv indexType <- fmap rowType <$> mapM lookupType si' indexName <- mapM (\_ -> newVName "write_index") indexType valueNames <- replicateM (length sv_ts) $ newVName "write_value" sa_ts <- mapM lookupType sas let bodyTypes = concat (replicate (length sv_ts) indexType) ++ map (I.stripArray dim) sa_ts paramTypes = indexType <> map rowType sv_ts bodyNames = indexName <> valueNames bodyParams = zipWith (I.Param mempty) bodyNames paramTypes -- This body is pretty boring right now, as every input is exactly the output. -- But it can get funky later on if fused with something else. body <- localScope (scopeOfLParams bodyParams) . buildBody_ $ do let outs = concat (replicate (length valueNames) indexName) ++ valueNames results <- forM outs $ \name -> letSubExp "write_res" $ I.BasicOp $ I.SubExp $ I.Var name ensureResultShape "scatter value has wrong size" loc bodyTypes (subExpsRes results) let lam = I.Lambda { I.lambdaParams = bodyParams, I.lambdaReturnType = bodyTypes, I.lambdaBody = body } sivs = si' <> svs' let sa_ws = map (Shape . take dim . arrayDims) sa_ts letTupExp' desc $ I.Op $ I.Scatter si_w sivs lam $ zip3 sa_ws (repeat 1) sas flatIndexHelper :: String -> SrcLoc -> E.Exp -> E.Exp -> [(E.Exp, E.Exp)] -> InternaliseM [SubExp] flatIndexHelper desc loc arr offset slices = do arrs <- internaliseExpToVars "arr" arr offset' <- internaliseExp1 "offset" offset old_dim <- I.arraysSize 0 <$> mapM lookupType arrs offset_inbounds_down <- letSubExp "offset_inbounds_down" $ I.BasicOp $ I.CmpOp (I.CmpUle Int64) (intConst Int64 0) offset' offset_inbounds_up <- letSubExp "offset_inbounds_up" $ I.BasicOp $ I.CmpOp (I.CmpUlt Int64) offset' old_dim slices' <- mapM ( \(n, s) -> do n' <- internaliseExp1 "n" n s' <- internaliseExp1 "s" s return (n', s') ) slices (min_bound, max_bound) <- foldM ( \(lower, upper) (n, s) -> do n_m1 <- letSubExp "span" $ I.BasicOp $ I.BinOp (I.Sub Int64 I.OverflowUndef) n (intConst Int64 1) spn <- letSubExp "span" $ I.BasicOp $ I.BinOp (I.Mul Int64 I.OverflowUndef) n_m1 s span_and_lower <- letSubExp "span_and_lower" $ I.BasicOp $ I.BinOp (I.Add Int64 I.OverflowUndef) spn lower span_and_upper <- letSubExp "span_and_upper" $ I.BasicOp $ I.BinOp (I.Add Int64 I.OverflowUndef) spn upper lower' <- letSubExp "minimum" $ I.BasicOp $ I.BinOp (I.UMin Int64) span_and_lower lower upper' <- letSubExp "maximum" $ I.BasicOp $ I.BinOp (I.UMax Int64) span_and_upper upper return (lower', upper') ) (offset', offset') slices' min_in_bounds <- letSubExp "min_in_bounds" $ I.BasicOp $ I.CmpOp (I.CmpUle Int64) (intConst Int64 0) min_bound max_in_bounds <- letSubExp "max_in_bounds" $ I.BasicOp $ I.CmpOp (I.CmpUlt Int64) max_bound old_dim all_bounds <- foldM (\x y -> letSubExp "inBounds" $ I.BasicOp $ I.BinOp I.LogAnd x y) offset_inbounds_down [offset_inbounds_up, min_in_bounds, max_in_bounds] c <- assert "bounds_cert" all_bounds (ErrorMsg [ErrorString $ "Flat slice out of bounds: " ++ pretty old_dim ++ " and " ++ pretty slices']) loc let slice = I.FlatSlice offset' $ map (uncurry FlatDimIndex) slices' certifying c $ forM arrs $ \arr' -> letSubExp desc $ I.BasicOp $ I.FlatIndex arr' slice flatUpdateHelper :: String -> SrcLoc -> E.Exp -> E.Exp -> [E.Exp] -> E.Exp -> InternaliseM [SubExp] flatUpdateHelper desc loc arr1 offset slices arr2 = do arrs1 <- internaliseExpToVars "arr" arr1 offset' <- internaliseExp1 "offset" offset old_dim <- I.arraysSize 0 <$> mapM lookupType arrs1 offset_inbounds_down <- letSubExp "offset_inbounds_down" $ I.BasicOp $ I.CmpOp (I.CmpUle Int64) (intConst Int64 0) offset' offset_inbounds_up <- letSubExp "offset_inbounds_up" $ I.BasicOp $ I.CmpOp (I.CmpUlt Int64) offset' old_dim arrs2 <- internaliseExpToVars "arr" arr2 ts <- mapM lookupType arrs2 slices' <- mapM ( \(s, i) -> do s' <- internaliseExp1 "s" s let n = arraysSize i ts return (n, s') ) $ zip slices [0 ..] (min_bound, max_bound) <- foldM ( \(lower, upper) (n, s) -> do n_m1 <- letSubExp "span" $ I.BasicOp $ I.BinOp (I.Sub Int64 I.OverflowUndef) n (intConst Int64 1) spn <- letSubExp "span" $ I.BasicOp $ I.BinOp (I.Mul Int64 I.OverflowUndef) n_m1 s span_and_lower <- letSubExp "span_and_lower" $ I.BasicOp $ I.BinOp (I.Add Int64 I.OverflowUndef) spn lower span_and_upper <- letSubExp "span_and_upper" $ I.BasicOp $ I.BinOp (I.Add Int64 I.OverflowUndef) spn upper lower' <- letSubExp "minimum" $ I.BasicOp $ I.BinOp (I.UMin Int64) span_and_lower lower upper' <- letSubExp "maximum" $ I.BasicOp $ I.BinOp (I.UMax Int64) span_and_upper upper return (lower', upper') ) (offset', offset') slices' min_in_bounds <- letSubExp "min_in_bounds" $ I.BasicOp $ I.CmpOp (I.CmpUle Int64) (intConst Int64 0) min_bound max_in_bounds <- letSubExp "max_in_bounds" $ I.BasicOp $ I.CmpOp (I.CmpUlt Int64) max_bound old_dim all_bounds <- foldM (\x y -> letSubExp "inBounds" $ I.BasicOp $ I.BinOp I.LogAnd x y) offset_inbounds_down [offset_inbounds_up, min_in_bounds, max_in_bounds] c <- assert "bounds_cert" all_bounds (ErrorMsg [ErrorString $ "Flat slice out of bounds: " ++ pretty old_dim ++ " and " ++ pretty slices']) loc let slice = I.FlatSlice offset' $ map (uncurry FlatDimIndex) slices' certifying c $ forM (zip arrs1 arrs2) $ \(arr1', arr2') -> letSubExp desc $ I.BasicOp $ I.FlatUpdate arr1' slice arr2' funcall :: String -> QualName VName -> [SubExp] -> SrcLoc -> InternaliseM ([SubExp], [I.ExtType]) funcall desc (QualName _ fname) args loc = do (shapes, value_paramts, fun_params, rettype_fun) <- lookupFunction fname argts <- mapM subExpType args shapeargs <- argShapes shapes fun_params argts let diets = replicate (length shapeargs) I.ObservePrim ++ map I.diet value_paramts args' <- ensureArgShapes "function arguments of wrong shape" loc (map I.paramName fun_params) (map I.paramType fun_params) (shapeargs ++ args) argts' <- mapM subExpType args' case rettype_fun $ zip args' argts' of Nothing -> error $ concat [ "Cannot apply ", pretty fname, " to ", show (length args'), " arguments\n ", pretty args', "\nof types\n ", pretty argts', "\nFunction has ", show (length fun_params), " parameters\n ", pretty fun_params ] Just ts -> do safety <- askSafety attrs <- asks envAttrs ses <- attributing attrs . letValExp' desc $ I.Apply (internaliseFunName fname) (zip args' diets) ts (safety, loc, mempty) return (ses, map I.fromDecl ts) -- Bind existential names defined by an expression, based on the -- concrete values that expression evaluated to. This most -- importantly should be done after function calls, but also -- everything else that can produce existentials in the source -- language. bindExtSizes :: AppRes -> [SubExp] -> InternaliseM () bindExtSizes (AppRes ret retext) ses = do ts <- internaliseType $ E.toStruct ret ses_ts <- mapM subExpType ses let combine t1 t2 = mconcat $ zipWith combine' (arrayExtDims t1) (arrayDims t2) combine' (I.Free (I.Var v)) se | v `elem` retext = M.singleton v se combine' _ _ = mempty forM_ (M.toList $ mconcat $ zipWith combine ts ses_ts) $ \(v, se) -> letBindNames [v] $ BasicOp $ SubExp se askSafety :: InternaliseM Safety askSafety = do check <- asks envDoBoundsChecks return $ if check then I.Safe else I.Unsafe -- Implement partitioning using maps, scans and writes. partitionWithSOACS :: Int -> I.Lambda -> [I.VName] -> InternaliseM ([I.SubExp], [I.SubExp]) partitionWithSOACS k lam arrs = do arr_ts <- mapM lookupType arrs let w = arraysSize 0 arr_ts classes_and_increments <- letTupExp "increments" $ I.Op $ I.Screma w arrs (mapSOAC lam) (classes, increments) <- case classes_and_increments of classes : increments -> return (classes, take k increments) _ -> error "partitionWithSOACS" add_lam_x_params <- replicateM k $ newParam "x" (I.Prim int64) add_lam_y_params <- replicateM k $ newParam "y" (I.Prim int64) add_lam_body <- runBodyBuilder $ localScope (scopeOfLParams $ add_lam_x_params ++ add_lam_y_params) $ fmap resultBody $ forM (zip add_lam_x_params add_lam_y_params) $ \(x, y) -> letSubExp "z" $ I.BasicOp $ I.BinOp (I.Add Int64 I.OverflowUndef) (I.Var $ I.paramName x) (I.Var $ I.paramName y) let add_lam = I.Lambda { I.lambdaBody = add_lam_body, I.lambdaParams = add_lam_x_params ++ add_lam_y_params, I.lambdaReturnType = replicate k $ I.Prim int64 } nes = replicate (length increments) $ intConst Int64 0 scan <- I.scanSOAC [I.Scan add_lam nes] all_offsets <- letTupExp "offsets" $ I.Op $ I.Screma w increments scan -- We have the offsets for each of the partitions, but we also need -- the total sizes, which are the last elements in the offests. We -- just have to be careful in case the array is empty. last_index <- letSubExp "last_index" $ I.BasicOp $ I.BinOp (I.Sub Int64 OverflowUndef) w $ constant (1 :: Int64) nonempty_body <- runBodyBuilder $ fmap resultBody $ forM all_offsets $ \offset_array -> letSubExp "last_offset" $ I.BasicOp $ I.Index offset_array $ Slice [I.DimFix last_index] let empty_body = resultBody $ replicate k $ constant (0 :: Int64) is_empty <- letSubExp "is_empty" $ I.BasicOp $ I.CmpOp (CmpEq int64) w $ constant (0 :: Int64) sizes <- letTupExp "partition_size" $ I.If is_empty empty_body nonempty_body $ ifCommon $ replicate k $ I.Prim int64 -- The total size of all partitions must necessarily be equal to the -- size of the input array. -- Create scratch arrays for the result. blanks <- forM arr_ts $ \arr_t -> letExp "partition_dest" $ I.BasicOp $ Scratch (I.elemType arr_t) (w : drop 1 (I.arrayDims arr_t)) -- Now write into the result. write_lam <- do c_param <- newParam "c" (I.Prim int64) offset_params <- replicateM k $ newParam "offset" (I.Prim int64) value_params <- mapM (newParam "v" . I.rowType) arr_ts (offset, offset_stms) <- collectStms $ mkOffsetLambdaBody (map I.Var sizes) (I.Var $ I.paramName c_param) 0 offset_params return I.Lambda { I.lambdaParams = c_param : offset_params ++ value_params, I.lambdaReturnType = replicate (length arr_ts) (I.Prim int64) ++ map I.rowType arr_ts, I.lambdaBody = mkBody offset_stms $ replicate (length arr_ts) (subExpRes offset) ++ I.varsRes (map I.paramName value_params) } results <- letTupExp "partition_res" . I.Op $ I.Scatter w (classes : all_offsets ++ arrs) write_lam $ zip3 (repeat $ Shape [w]) (repeat 1) blanks sizes' <- letSubExp "partition_sizes" $ I.BasicOp $ I.ArrayLit (map I.Var sizes) $ I.Prim int64 return (map I.Var results, [sizes']) where mkOffsetLambdaBody :: [SubExp] -> SubExp -> Int -> [I.LParam] -> InternaliseM SubExp mkOffsetLambdaBody _ _ _ [] = return $ constant (-1 :: Int64) mkOffsetLambdaBody sizes c i (p : ps) = do is_this_one <- letSubExp "is_this_one" $ I.BasicOp $ I.CmpOp (CmpEq int64) c $ intConst Int64 $ toInteger i next_one <- mkOffsetLambdaBody sizes c (i + 1) ps this_one <- letSubExp "this_offset" =<< foldBinOp (Add Int64 OverflowUndef) (constant (-1 :: Int64)) (I.Var (I.paramName p) : take i sizes) letSubExp "total_res" $ I.If is_this_one (resultBody [this_one]) (resultBody [next_one]) $ ifCommon [I.Prim int64] typeExpForError :: E.TypeExp VName -> InternaliseM [ErrorMsgPart SubExp] typeExpForError (E.TEVar qn _) = return [ErrorString $ pretty qn] typeExpForError (E.TEUnique te _) = ("*" :) <$> typeExpForError te typeExpForError (E.TEDim dims te _) = (ErrorString ("?" <> dims' <> ".") :) <$> typeExpForError te where dims' = mconcat (map onDim dims) onDim d = "[" <> pretty d <> "]" typeExpForError (E.TEArray te d _) = do d' <- dimExpForError d te' <- typeExpForError te return $ ["[", d', "]"] ++ te' typeExpForError (E.TETuple tes _) = do tes' <- mapM typeExpForError tes return $ ["("] ++ intercalate [", "] tes' ++ [")"] typeExpForError (E.TERecord fields _) = do fields' <- mapM onField fields return $ ["{"] ++ intercalate [", "] fields' ++ ["}"] where onField (k, te) = (ErrorString (pretty k ++ ": ") :) <$> typeExpForError te typeExpForError (E.TEArrow _ t1 t2 _) = do t1' <- typeExpForError t1 t2' <- typeExpForError t2 return $ t1' ++ [" -> "] ++ t2' typeExpForError (E.TEApply t arg _) = do t' <- typeExpForError t arg' <- case arg of TypeArgExpType argt -> typeExpForError argt TypeArgExpDim d _ -> pure <$> dimExpForError d return $ t' ++ [" "] ++ arg' typeExpForError (E.TESum cs _) = do cs' <- mapM (onClause . snd) cs return $ intercalate [" | "] cs' where onClause c = do c' <- mapM typeExpForError c return $ intercalate [" "] c' dimExpForError :: E.DimExp VName -> InternaliseM (ErrorMsgPart SubExp) dimExpForError (DimExpNamed d _) = do substs <- lookupSubst $ E.qualLeaf d d' <- case substs of Just [v] -> return v _ -> return $ I.Var $ E.qualLeaf d return $ ErrorVal int64 d' dimExpForError (DimExpConst d _) = return $ ErrorString $ pretty d dimExpForError DimExpAny = return "" -- A smart constructor that compacts neighbouring literals for easier -- reading in the IR. errorMsg :: [ErrorMsgPart a] -> ErrorMsg a errorMsg = ErrorMsg . compact where compact [] = [] compact (ErrorString x : ErrorString y : parts) = compact (ErrorString (x ++ y) : parts) compact (x : y) = x : compact y
HIPERFIT/futhark
src/Futhark/Internalise/Exps.hs
isc
87,807
699
39
23,449
21,703
11,818
9,885
1,947
59
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} -- | -- Module: Tests.BoolOption -- Description: Tests for 'boolOption' and 'boolOption_' -- Copyright: Copyright © 2015 PivotCloud, Inc. -- License: MIT -- Maintainer: Lars Kuhtz <lkuhtz@pivotmail.com> -- Stability: experimental -- -- load in ghci with: -- -- > ghci -isrc -idist/build/autogen -itest -iexamples -DREMOTE_CONFIGS test/TestExample.hs -- module Tests.BoolOption ( mainA , boolOptionTests ) where import Configuration.Utils import Configuration.Utils.Internal import TestTools import Data.Monoid.Unicode -- -------------------------------------------------------------------------- -- -- Setup data A = A { _a ∷ !Bool , _b ∷ !Bool , _c ∷ !Bool } deriving (Show, Read, Eq, Ord) a ∷ Lens' A Bool a = lens _a $ \s x → s { _a = x } b ∷ Lens' A Bool b = lens _b $ \s x → s { _b = x } c ∷ Lens' A Bool c = lens _c $ \s x → s { _c = x } defaultA ∷ A defaultA = A True True True pA ∷ MParser A pA = id <$< a .:: boolOption_ % long "a" ⊕ short 'a' ⊕ help "a flag" <*< b .:: boolOption % long "b" ⊕ short 'b' ⊕ help "b flag" <*< c .:: enableDisableFlag % long "c" ⊕ long "c_" ⊕ short 'd' -- 'c' is taken by --config-file ⊕ help "c flag" instance ToJSON A where toJSON A{..} = object [ "a" .= _a , "b" .= _b , "c" .= _c ] instance FromJSON (A → A) where parseJSON = withObject "A" $ \o → id <$< a ..: "a" % o <*< b ..: "b" % o <*< c ..: "c" % o infoA ∷ ProgramInfo A infoA = programInfo "BoolOptionTest" pA (A True True True) infoA_ ∷ ProgramInfo A infoA_ = programInfo "BoolOptionTest" pA (A False False False) mainA ∷ IO () mainA = runWithConfiguration infoA print -- -------------------------------------------------------------------------- -- -- Tests da ∷ ConfAssertion A da = ConfAssertion [] a $ _a defaultA db ∷ ConfAssertion A db = ConfAssertion [] b $ _b defaultA dc ∷ ConfAssertion A dc = ConfAssertion [] c $ _c defaultA boolOptionTests ∷ PkgInfo → [IO Bool] boolOptionTests pkgInfo = atests ⊕ btests ⊕ ctests ⊕ ctests_ where atests = [ runA 1 True [da, db, dc] , runA 2 True [ConfAssertion ["--a"] a True] , runA 3 True [ConfAssertion ["-a"] a True] , runA 4 False [ConfAssertion ["-no-a"] a True] , runA 5 False [ConfAssertion ["--a=true"] a True] , runA 6 False [ConfAssertion ["--a=false"] a False] , runA 7 False [ConfAssertion ["--a", "true"] a True] , runA 8 False [ConfAssertion ["--a", "false"] a False] , runA 9 True [ConfAssertion ["--no-a"] a False] , runA 10 False [ConfAssertion ["--no-a=true"] a True] , runA 11 False [ConfAssertion ["--no-a=false"] a False] , runA 12 False [ConfAssertion ["--no-a", "true"] a True] , runA 13 False [ConfAssertion ["--no-a", "false"] a False] , runA 14 True [ConfAssertion ["-a"] a True] , runA 15 False [ConfAssertion ["-a=true"] a True] , runA 16 False [ConfAssertion ["-a=false"] a False] , runA 17 False [ConfAssertion ["-a", "true"] a True] , runA 18 False [ConfAssertion ["-a", "false"] a False] ] btests = [ runB 1 False [ConfAssertion ["--b"] b True] , runB 2 False [ConfAssertion ["-b"] b True] , runB 3 False [ConfAssertion ["-no-b"] b True] , runB 4 True [ConfAssertion ["--b=true"] b True] , runB 5 True [ConfAssertion ["--b=false"] b False] , runB 6 True [ConfAssertion ["--b", "true"] b True] , runB 7 True [ConfAssertion ["--b", "false"] b False] , runB 8 False [ConfAssertion ["-b=true"] b True] , runB 9 False [ConfAssertion ["-b=false"] b False] , runB 10 True [ConfAssertion ["-b", "true"] b True] , runB 12 True [ConfAssertion ["-b", "false"] b False] , runB 13 True [ConfAssertion ["--b=TRUE"] b True] , runB 14 True [ConfAssertion ["--b=FALSE"] b False] , runB 15 True [ConfAssertion ["--b", "TRUE"] b True] , runB 16 True [ConfAssertion ["--b", "FALSE"] b False] , runB 17 True [ConfAssertion ["--b=True"] b True] , runB 18 True [ConfAssertion ["--b=False"] b False] , runB 19 True [ConfAssertion ["--b", "True"] b True] , runB 20 True [ConfAssertion ["--b", "False"] b False] ] ctests = [ runC 1 True [da, db, dc] , runC 2 False [ConfAssertion ["--c"] c True] , runC 3 False [ConfAssertion ["--c_"] c True] , runC 4 False [ConfAssertion ["--c"] c False] , runC 5 False [ConfAssertion ["--c_"] c False] , runC 6 True [ConfAssertion ["--enable-c"] c True] , runC 7 True [ConfAssertion ["--enable-c_"] c True] , runC 8 True [ConfAssertion ["-d"] c True] , runC 9 False [ConfAssertion ["-disable-c"] c False] , runC 10 False [ConfAssertion ["-disable-c"] c True] , runC 9 False [ConfAssertion ["-disable-d"] c False] , runC 10 False [ConfAssertion ["-disable-d"] c True] , runC 10 False [ConfAssertion ["--disable-d"] c False] , runC 11 True [ConfAssertion ["--disable-c"] c False] , runC 12 True [ConfAssertion ["--disable-c_"] c False] ] ctests_ = [ runC_ 1 False [da, db, dc] , runC_ 2 False [ConfAssertion ["--c"] c True] , runC_ 3 False [ConfAssertion ["--c_"] c True] , runC_ 4 False [ConfAssertion ["--c"] c False] , runC_ 5 False [ConfAssertion ["--c_"] c False] , runC_ 6 True [ConfAssertion ["--enable-c"] c True] , runC_ 7 True [ConfAssertion ["--enable-c_"] c True] , runC_ 8 True [ConfAssertion ["-d"] c True] , runC_ 9 False [ConfAssertion ["-disable-c"] c False] , runC_ 10 False [ConfAssertion ["-disable-c"] c True] , runC_ 11 True [ConfAssertion ["--disable-c"] c False] , runC_ 12 True [ConfAssertion ["--disable-c_"] c False] ] runA (x ∷ Int) = runTest pkgInfo infoA ("boolOption-a-" ⊕ sshow x) runB (x ∷ Int) = runTest pkgInfo infoA ("boolOption-b-" ⊕ sshow x) runC (x ∷ Int) = runTest pkgInfo infoA ("boolOption-c1-" ⊕ sshow x) runC_ (x ∷ Int) = runTest pkgInfo infoA_ ("boolOption-c2-" ⊕ sshow x)
alephcloud/hs-configuration-tools
test/Tests/BoolOption.hs
mit
6,569
0
20
1,753
2,303
1,216
1,087
143
1
module Example18 where import qualified WeightedLPA as WLPA import Graph import qualified Data.Map as M import qualified Data.Set as S import Data.Matrix weighted_graph_E :: WeightedGraph String String weighted_graph_E = WeightedGraph (buildGraphFromEdges [("e",("v","v")),("f",("v","v"))]) (M.fromList [("e",1),("f",2)]) weighted_graph_G :: Int -> WeightedGraph (String,Int) (String,Int) weighted_graph_G n = WeightedGraph (buildGraphFromEdges edges) (M.fromList weights) where edges = concat [[(("e",i),(("v",i),("v",i+1))),(("f",i),(("v",i),("v",i+1)))] | i <- [1..n-1]] weights = concat [[(("e",i),1),(("f",i),2)] | i <- [1..n-1]] atom = WLPA.Atom 1 vertex = atom . WLPA.vertex edge = atom . (flip WLPA.edge 1) ghostEdge = atom . (flip WLPA.ghostEdge 1) edge2 = atom . (flip WLPA.edge 2) ghostEdge2 = atom . (flip WLPA.ghostEdge 2) s = WLPA.adjoint v = vertex "v" e1 = edge "e" f1 = edge "f" f2 = edge2 "f" adjoint m = fmap s (transpose m) phi :: Int -> WLPA.AtomType (String,Int) (String,Int) -> Matrix (WLPA.Term String String Integer) phi n (WLPA.AVertex ("v",i)) = setElem v (i,i) (zero n n) phi n (WLPA.AEdge ("e",i) 1) = setElem e1 (i,i+1) (zero n n) phi n (WLPA.AEdge ("f",i) 1) = setElem f1 (i,i+1) (zero n n) phi n (WLPA.AEdge ("f",i) 2) = setElem f2 (i,i+1) (zero n n) phi n (WLPA.AGhostEdge e w) = adjoint (phi n (WLPA.AEdge e w)) phi n _ = zero n n testHomomorphism :: Int -> [Matrix (WLPA.Term String String Integer)] testHomomorphism n = WLPA.wLPA_relations_map' (zero n n) (phi n) (weighted_graph_G n) fmapBasisForm wgraph = fmap (WLPA.convertToBasisForm wgraph) check n = map (fmapBasisForm weighted_graph_E) (testHomomorphism n) main n = do putStr $ unlines $ map show (zip checks rels) putStrLn (show $ and checks) where checks = map (matrix n n (const []) ==) (check n) rels = WLPA.wLPA_relations_show (weighted_graph_G n)
rzil/honours
LeavittPathAlgebras/Example18.hs
mit
1,877
0
13
308
996
540
456
40
1
import qualified Text.PrettyPrint.Boxes as B import Text.PrettyPrint.Boxes (Box, Alignment) import Text.Parsec import Text.Parsec.Text (Parser) import qualified Data.Text.IO as IO import Control.Applicative ((*>), (<*)) import Data.Monoid import System.Environment (getArgs) main = do [infile] <- getArgs contents <- IO.readFile infile case parse latex "" contents of Left err -> putStrLn $ show err Right bx -> B.printBox bx latex :: Parser Box latex = do chunks <- many latexChunk return . toBox $ mconcat chunks latexChunk :: Parser LatexChunk latexChunk = command <|> plaintex command :: Parser LatexChunk command = backSlashCommand <|> try subsuper <|> subscript <|> superscript <?> "valid command" arg = between (char '{') (char '}') latex <?> "bracketed argument" backSlashCommand = do char '\\' frac <|> psqrt <|> root <|> ppi <?> "backslash command" frac = do string "frac" num <- arg denom <- arg let width = max (B.cols num) (B.cols denom) let new_box = B.vcat B.center1 [num, B.text (replicate width '-'), denom] return $ chunkInLine new_box psqrt = do string "sqrt" contents <- arg let width = B.cols contents let height = B.rows contents let ceiling = B.text (replicate width '_') let aligned_ceil = B.alignHoriz B.right (width + height) ceiling let radical = makeRadical height return $ chunk aligned_ceil (B.hcat B.center1 [radical, contents]) B.nullBox root = do string "root" power <- arg contents <- arg let width = B.cols contents let height = B.rows contents let ceiling = B.text (replicate width '_') let radical = makeRadical height return $ chunk (B.hcat B.center1 [B.alignHoriz B.right height power, ceiling]) (B.hcat B.center1 [radical, contents]) B.nullBox ppi = string "pi" *> return (chunkInLine (B.char '\x03c0')) subsuper = do char '_' sub <- arg char '^' super <- arg return $ chunk super B.nullBox sub subscript = do char '_' sub <- arg return $ chunkBelow sub superscript = do char '^' super <- arg return $ chunkAbove super plaintex = do contents <- many1 $ noneOf "\\_^{}" return $ chunkInLine (B.text $ filter (/= '\n') contents) makeRadical 1 = B.char '\x221a' makeRadical height = B.hcat B.top [B.moveDown 1 $ makeRadical (height-1), B.char '/'] data ChunkPosition = Inline | Above | Below data LatexChunk = LatexChunk { above :: Box, inLine :: Box, below :: Box } instance Monoid LatexChunk where mempty = LatexChunk B.nullBox B.nullBox B.nullBox mappend a b = let combine f = B.hcat B.center1 [f a, f b] in LatexChunk (combine above) (combine inLine) (combine below) chunk :: Box -> Box -> Box -> LatexChunk chunk top mid bot = let width = maximum $ map B.cols [top, mid, bot] align = B.alignHoriz B.left width in LatexChunk (align top) (align mid) (align bot) chunkAbove :: Box -> LatexChunk chunkAbove top = chunk top B.nullBox B.nullBox chunkInLine :: Box -> LatexChunk chunkInLine mid = chunk B.nullBox mid B.nullBox chunkBelow :: Box -> LatexChunk chunkBelow bot = chunk B.nullBox B.nullBox bot toBox :: LatexChunk -> Box toBox lc = B.vcat B.left [above lc, inLine lc, below lc]
devonhollowood/dailyprog
2015-06-05/latex.hs
mit
3,437
0
14
898
1,294
635
659
97
2
import MinHS.Parse import MinHS.Syntax import MinHS.TypeChecker import MinHS.Pretty import MinHS.Evaluator import Control.Monad import Data.Either import Options.Applicative import Text.PrettyPrint.ANSI.Leijen (Pretty (..),Doc, putDoc, plain) type Action a b = a -> Either (IO ()) b main = execParser argsInfo >>= main' where main' (pipeline, filter, file) = (pipeline filter <$> readFile file) >>= either id id argsInfo = info (helper <*> args) (fullDesc <> progDesc "A interpreter for a small functional language" <> header "MinHS - COMP3161 Concepts of Programming Languages") args = (,,) <$> nullOption ( long "dump" <> metavar "STAGE" <> reader readAction <> value (evaluatorAction) <> help "stage after which to dump the current state. \n [parser,parser-raw,typechecker,evaluator]") <*> flag id plain (long "no-colour" <> help "do not use colour when pretty printing") <*> argument str (metavar "FILE") readAction :: String -> ReadM ((Doc -> Doc) -> Action String (IO ())) readAction str = case str of "parser" -> return $ \f -> parser >=> printer f "parser-raw" -> return $ \f -> parser >=> rawPrinter "typechecker" -> return $ \f -> parser >=> typechecker f >=> printer f "evaluator" -> return $ evaluatorAction _ -> readerAbort (ShowHelpText) evaluatorAction :: (Doc -> Doc) -> Action String (IO ()) evaluatorAction f = parser >=> typechecker f >=> evaluator >=> printer f parser :: Action String Program parser = either (Left . putStrLn . show) Right . parseProgram "" typechecker :: (Doc -> Doc) -> Action Program Program typechecker f p | Just v <- typecheck p = Left . (>> putStrLn "") . putDoc . f . pretty $ v | otherwise = Right $ p evaluator p = Right $ evaluate p rawPrinter :: (Show a) => Action a (IO ()) rawPrinter = Right . putStrLn . show printer :: (Pretty a) => (Doc -> Doc) -> Action a (IO ()) printer filter = Right . (>> putStrLn "") . putDoc . filter . pretty fromRight = either (error "fromRight on Left") id
pierzchalski/cs3161a1
Main.hs
mit
2,489
0
16
873
733
375
358
43
5
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.WebKitNamespace (js_getMessageHandlers, getMessageHandlers, WebKitNamespace, castToWebKitNamespace, gTypeWebKitNamespace) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"messageHandlers\"]" js_getMessageHandlers :: JSRef WebKitNamespace -> IO (JSRef UserMessageHandlersNamespace) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitNamespace.messageHandlers Mozilla WebKitNamespace.messageHandlers documentation> getMessageHandlers :: (MonadIO m) => WebKitNamespace -> m (Maybe UserMessageHandlersNamespace) getMessageHandlers self = liftIO ((js_getMessageHandlers (unWebKitNamespace self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/WebKitNamespace.hs
mit
1,549
6
11
210
377
238
139
27
1
-- Copyright 2015 Ian D. Bollinger -- -- Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -- http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT -- or http://opensource.org/licenses/MIT>, at your option. This file may not be -- copied, modified, or distributed except according to those terms. {-# LANGUAGE CPP #-} module Main ( main, ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>), (<*>)) #endif import Data.Char (toUpper) import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as Text import Graphics.UI.Gtk (AttrOp ((:=))) import qualified Graphics.UI.Gtk as Gtk import Nomegen ( Nomicon, explainYamlParseException, generate, nameToText, yamlDeserializer, ) data Application = Application { nameLabel :: Gtk.Label, fileChooserButton :: Gtk.FileChooserButton, generateButton :: Gtk.Button, nomicon :: IORef (Maybe Nomicon) } main :: IO () main = do _ <- Gtk.initGUI app <- Application <$> buildNameLabel <*> buildFileChooserButton <*> buildGenerateButton <*> newIORef Nothing window <- buildWindow app Gtk.widgetShowAll window Gtk.mainGUI buildWindow :: Application -> IO Gtk.Window buildWindow app = do window <- Gtk.windowNew _ <- Gtk.on window Gtk.objectDestroy Gtk.mainQuit Gtk.set window [ Gtk.containerBorderWidth := 10, Gtk.windowTitle := "nomegen" ] connectSignals app hBox <- Gtk.hBoxNew False 10 Gtk.containerAdd hBox (fileChooserButton app) Gtk.containerAdd hBox (generateButton app) vBox <- Gtk.vBoxNew False 10 Gtk.boxPackStart vBox (nameLabel app) Gtk.PackGrow 0 Gtk.boxPackStart vBox hBox Gtk.PackNatural 0 Gtk.containerAdd window vBox return window connectSignals :: Application -> IO () connectSignals app = do _ <- Gtk.on (fileChooserButton app) Gtk.fileSelectionChanged $ onFileSelectionChanged app _ <- Gtk.on (generateButton app) Gtk.buttonActivated $ onGenerateButtonActivated (nameLabel app) (nomicon app) return () onFileSelectionChanged :: Application -> IO () onFileSelectionChanged app = do Gtk.set (generateButton app) [Gtk.widgetSensitive := True] fileName' <- Gtk.fileChooserGetFilename (fileChooserButton app) let fileName = fromMaybe (error "impossible") fileName' x <- yamlDeserializer fileName case x of Left err -> error (explainYamlParseException err) Right lexicon' -> writeIORef (nomicon app) (Just lexicon') onGenerateButtonActivated :: Gtk.Label -> IORef (Maybe Nomicon) -> IO () onGenerateButtonActivated label lexicon = do lexicon' <- readIORef lexicon case lexicon' of Just lexicon'' -> do name <- getName lexicon'' Gtk.set label [ Gtk.labelLabel := Text.pack "<span size=\"xx-large\">" <> name <> Text.pack "</span>", Gtk.labelSelectable := True ] Nothing -> error "impossible" buildNameLabel :: IO Gtk.Label buildNameLabel = do label <- Gtk.labelNew (Just "<span size=\"xx-large\"> </span>") Gtk.set label [Gtk.labelUseMarkup := True] return label buildGenerateButton :: IO Gtk.Button buildGenerateButton = do button <- Gtk.buttonNew Gtk.set button [ Gtk.buttonLabel := "Generate", Gtk.widgetSensitive := False ] return button buildFileChooserButton :: IO Gtk.FileChooserButton buildFileChooserButton = do button <- Gtk.fileChooserButtonNew "Select nomicon" Gtk.FileChooserActionOpen fileFilter <- buildFileFilter Gtk.set button [Gtk.fileChooserFilter := fileFilter] return button buildFileFilter :: IO Gtk.FileFilter buildFileFilter = do fileFilter <- Gtk.fileFilterNew Gtk.set fileFilter [Gtk.fileFilterName := "nomicon file"] Gtk.fileFilterAddPattern fileFilter "*.yaml" Gtk.fileFilterAddPattern fileFilter "*.yml" Gtk.fileFilterAddPattern fileFilter "*.nomicon" return fileFilter getName :: Nomicon -> IO Text getName nomicon' = capitalize . nameToText <$> generate nomicon' capitalize :: Text -> Text capitalize = Text.cons . toUpper . Text.head <*> Text.tail
ianbollinger/nomegen
gui/Main.hs
mit
4,342
0
18
927
1,171
580
591
104
2
module TwentySix where import Control.Monad (liftM) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Trans.Class (MonadTrans, lift) -- Exercises: EitherT newtype EitherT e m a = EitherT { runEitherT :: m (Either e a) } -- 1 instance Functor m => Functor (EitherT e m) where fmap f (EitherT me) = EitherT $ (fmap . fmap) f me -- 2 instance Applicative m => Applicative (EitherT e m) where pure x = EitherT $ (pure . pure) x (EitherT f) <*> (EitherT a) = EitherT $ (<*>) <$> f <*> a -- 3 instance Monad m => Monad (EitherT e m) where return = pure (EitherT me) >>= f = EitherT $ do v <- me case v of Left x -> return $ Left x Right y -> runEitherT (f y) -- 4 swapEither :: Either e a -> Either a e swapEither (Left e) = Right e swapEither (Right a) = Left a swapEitherT :: Functor m => EitherT e m a -> EitherT a m e swapEitherT (EitherT me) = EitherT $ swapEither <$> me -- 5 eitherT :: Monad m => (a -> m c) -> (b -> m c) -> EitherT a m b -> m c eitherT fa fb (EitherT me) = do v <- me case v of Left a -> fa a Right b -> fb b -- Exercises: StateT newtype StateT s m a = StateT { runStateT :: s -> m (a,s) } -- 1 instance Functor m => Functor (StateT s m) where -- fmap :: (a -> b) -> StateT s m a -> StateT s m b fmap f (StateT sma) = StateT $ (fmap . fmap) g sma where g (a,s) = (f a, s) -- 2 instance Monad m => Applicative (StateT s m) where pure a = StateT (\s -> pure (a, s)) (StateT smfab) <*> (StateT sma) = StateT $ \s -> do (fab, s1) <- smfab s (a, s2) <- sma s1 return (fab a, s2) -- 3 instance Monad m => Monad (StateT s m) where return = pure (StateT smfab) >>= g = StateT $ \s -> do (a, s1) <- smfab s let (StateT smb) = g a smb s1 -- Exercise: Wrap It Up newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a )} newtype ExceptT e m a = ExceptT { runExceptT :: m (Either e a) } newtype ReaderT r m a = ReaderT { runReaderT :: r -> m a } embedded :: MaybeT (ExceptT String (ReaderT () IO)) Int embedded = MaybeT $ ExceptT $ ReaderT $ return <$> (const (Right (Just 1))) -- Exercises: Lift More -- 1 instance MonadTrans (EitherT a) where lift = EitherT . liftM Right -- 2 instance MonadTrans (StateT s) where lift m = StateT $ \s -> do a <- m return (a, s) -- Exercises: Some Instances -- class (Monad m) => MonadIO m where -- liftIO :: IO a -> m a newtype IdentityT f a = IdentityT { runIdentityT :: f a } deriving (Eq, Show) instance (Functor m) => Functor (IdentityT m) where fmap f (IdentityT fa) = IdentityT (fmap f fa) instance (Applicative m) => Applicative (IdentityT m) where pure x = IdentityT (pure x) (IdentityT fab) <*> (IdentityT fa) = IdentityT (fab <*> fa) instance (Monad m) => Monad (IdentityT m) where return = pure (IdentityT ma) >>= f = IdentityT $ ma >>= runIdentityT . f instance (MonadIO m) => MonadIO (IdentityT m) where liftIO = IdentityT . liftIO -- 1. MaybeT instance (Functor m) => Functor (MaybeT m) where fmap f (MaybeT ma) = MaybeT $ (fmap . fmap) f ma instance (Applicative m) => Applicative (MaybeT m) where pure x = MaybeT (pure (pure x)) (MaybeT fab) <*> (MaybeT mma) = MaybeT $ (<*>) <$> fab <*> mma instance (Monad m) => Monad (MaybeT m) where return = pure -- (>>=) :: MaybeT m a -- -> (a -> MaybeT m b) -- -> MaybeT m b (MaybeT ma) >>= f = MaybeT $ do v <- ma case v of Nothing -> return Nothing Just y -> runMaybeT (f y) instance MonadTrans MaybeT where lift = MaybeT . liftM Just instance MonadIO m => MonadIO (MaybeT m) where -- liftIO :: IO a -> m a liftIO = lift . liftIO -- 2. ReaderT instance (Functor m) => Functor (ReaderT r m) where fmap f (ReaderT rma) = ReaderT $ (fmap . fmap) f rma instance (Applicative m) => Applicative (ReaderT r m) where pure a = ReaderT (pure (pure a)) (ReaderT fmab) <*> (ReaderT rma) = ReaderT $ (<*>) <$> fmab <*> rma instance (Monad m) => Monad (ReaderT r m) where return = pure -- (>>=) :: ReaderT r m a -- -> (a -> ReaderT r m b) -- -> ReaderT r m b (ReaderT rma) >>= f = ReaderT $ \r -> do a <- rma r runReaderT (f a) r instance MonadTrans (ReaderT r) where -- lift :: Monad m => m a -> t m a lift ma = ReaderT $ \r -> do a <- ma return a instance MonadIO m => MonadIO (ReaderT r m) where liftIO = lift . liftIO -- 3. StateT instance MonadIO m => MonadIO (StateT s m) where liftIO = lift . liftIO -- Chapter Exercises newtype Reader r a = Reader { runReader :: r -> a } instance Functor (Reader r) where -- fmap :: (a -> b) -> Reader r a -> Reader r b fmap f (Reader ra) = Reader $ \r -> f (ra r) instance Applicative (Reader r) where -- pure :: a -> Reader r a pure a = Reader $ (\_ -> a) -- (<*>) :: Reader r (a -> b) -- -> Reader r a -- -> Reader r b (Reader rab) <*> (Reader ra) = Reader $ \r -> (rab r) (ra r) instance Monad (Reader r) where return = pure -- (>>=) :: Reader r a -- -> (a -> Reader r b) -- -> Reader r b (Reader ra) >>= aRb = Reader $ \r -> runReader (aRb $ ra r) $ r -- 1 rDec rDec :: Num a => Reader a a rDec = Reader $ \x -> x - 1 -- 2 rDec - pointfree rDec' :: Num a => Reader a a rDec' = Reader $ subtract 1 -- 3 rShow newtype Identity a = Identity { runIdentity :: a } deriving (Eq, Show) -- newtype ReaderT r m a = -- ReaderT { runReaderT :: r -> m a } rShow :: Show a => ReaderT a Identity String rShow = ReaderT $ \x -> Identity (show x) -- 4 rShow - pointfree rShow' :: Show a => ReaderT a Identity String rShow' = ReaderT $ Identity . show -- 5 rPrintAndInc :: (Num a, Show a) => ReaderT a IO a rPrintAndInc = ReaderT $ \x -> do putStrLn $ "Hi:" ++ show x return $ x + 1 -- 6 -- newtype StateT s m a = -- StateT { runStateT :: s -> m (a,s) } sPrintIncAccum :: (Num a, Show a) => StateT a IO String sPrintIncAccum = StateT $ \x -> do let str = show x putStrLn $ "Hi:" ++ str return (str, x + 1)
mudphone/HaskellBook
src/TwentySix.hs
mit
6,127
0
14
1,711
2,487
1,291
1,196
154
2
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# LANGUAGE OverloadedStrings #-} {-| Module : Linux.Parser.Internal.Proc Descripition : Parsers for the /proc vfs. The examples below use the __io-streams__ library. -} module Linux.Parser.Internal.Proc ( -- * Data Types -- ** MappedMemory : \/proc\/[pid]\/maps MappedMemory (..) -- ** Limits : \/proc\/[pid]\/limits , Limit () -- ** Statm : \/proc\/[pid]\/statm , Statm (..) -- ** MountInfo : \/proc\/[pid]\/mountinfo , MountInfo () -- * MemInfo : \/proc\/meminfo , MemInfo (..) -- * ProcessStat : \/proc\/\[pid\]\/stat , ProcessStat (..) , LoadAvg (..) , Uptime (..) , ProcIO (..) -- * Parsers , meminfop , loadavgp , uptimep , commp , iop , mapsp , environp , procstatp , statmp , numamapsp , limitsp , mountInfop ) where import Control.Applicative hiding (empty) import Data.Attoparsec.Combinator import Data.Attoparsec.ByteString.Char8 import Data.Maybe import Data.ByteString hiding (takeWhile, count, foldl) import Prelude hiding (takeWhile) import Linux.Parser.Internal.Common ------------------------------------------------------------------------------- -- | Data type for __\/proc\/[pid]\/maps__. data MappedMemory = MappedMemory { _address :: (ByteString, ByteString) -- ^ Memory address in the form (start-address, end-address) , _perms :: ByteString , _offset :: ByteString , _dev :: (ByteString, ByteString) -- ^ Device number in the form (Major num, Minor num) , _inode :: ByteString , _pathname:: Maybe ByteString } deriving (Eq, Show) -- | Data type for __\/proc\/[pid]\/limits__. data Limit = Limit { _limit :: [ByteString] , _slimit :: ByteString , _hlimit :: ByteString , _unit :: Maybe ByteString } deriving (Eq, Show) -- | Data type for __\/proc\/[pid]\/statm__. data Statm = Statm { _size :: ByteString , _resident :: ByteString , _share :: ByteString , _text :: ByteString , _lib :: ByteString , _data :: ByteString , _dt :: ByteString } deriving (Eq, Show) -- Data type for __\/proc\/[pid]\/mountinfo__. data MountInfo = MountInfo { _mountid :: ByteString , _parentid :: ByteString , _devmajmin :: (ByteString, ByteString) , _root :: ByteString , _mountpoint :: ByteString , _mountopts :: [ByteString] , _optionalfields :: Maybe [(ByteString, ByteString)] , _fstype :: ByteString , _mountsource :: ByteString , _superoptions :: [ByteString] } deriving (Eq, Show) data MemInfo = MemInfo { _miParam :: ByteString , _miSize :: ByteString , _miQualifier :: Maybe ByteString } deriving (Eq, Show) -- | Data type for \/proc\/[pid]\/stat. See __man_proc__ for more in -- depth information. data ProcessStat = ProcessStat { _pid :: ByteString -- ^ PID , _comm :: ByteString -- ^ File name of executable , _state :: ByteString -- ^ Processes state , _ppid :: ByteString -- ^ Parent processes PID , _pgrp :: ByteString -- ^ Process group ID , _session :: ByteString -- ^ Session ID , _tty_nr :: ByteString -- ^ Controlling terminal -- | Foreground process group ID of controlling terminal , _tpgid :: ByteString , _flags :: ByteString -- ^ Kernel flags word -- | The number of minor faults the process has made which have not -- required loading a memory page from disk. , _minflt :: ByteString -- | The number of minor faults that the process's waited-for children -- have made. , _cminflt :: ByteString -- | The number of major faults the process has made which have -- required loading a memory page from disk. , _majflt :: ByteString -- |The number of major faults that the process's waited-for children -- have made. , _cmajflt :: ByteString -- | Amount of time, in clock ticks, scheduled in user mode. , _utime :: ByteString -- | Amount of time, in clock ticks, that this process's waited-for -- children have been scheduled in user mode. , _stime :: ByteString -- | Amount of time that this process's waited-for children have -- been scheduled in user mode, measured in clock ticks -- (divide by sysconf(_SC_CLK_TCK)). , _cutime :: ByteString -- | Amount of time that this process's waited-for children -- have been scheduled in kernel mode, measured in clock ticks -- (divide by sysconf(_SC_CLK_TCK)). , _cstime :: ByteString , _priority :: ByteString -- ^ Processes prority , _nice :: ByteString -- ^ Processes nice value , _num_threads:: ByteString -- ^ Number of threads in this process -- | The time in jiffies before the next SIGALRM is sent to the -- process due to an interval timer. , _itrealvalue:: ByteString -- | Time, in clock ticks, the process started after system boot. , _starttime :: ByteString , _vsize :: ByteString -- ^ Virtual memory size in bytes. , _rss :: ByteString -- ^ Resident set size. -- | Current soft limit in bytes on the rss of the process. , _rsslim :: ByteString -- | Address above which program text can run. , _startcode :: ByteString -- | Address below which program text can run. , _endcode :: ByteString , _startstack :: ByteString -- ^ Address of the start of the stack. , _kstkesp :: ByteString -- ^ Current value of ESP (stack pointer). , _kstkeip :: ByteString -- ^ Current EIP (instruction pointer). -- | The bitmap of pending signals, displayed as a decimal number. -- Obsolete, use __\/proc\/[pid]\/status__ instead. , _signal :: ByteString -- | The bitmap of blocked signals, displayed as a decimal number. -- Obsolete, use __\/proc\/[pid]\/status__ instead. , _blocked :: ByteString -- | The bitmap of ignored signals, displayed as a decimal number. -- Obsolete, use __\/proc\/[pid]\/status__ instead. , _sigignore :: ByteString -- | The bitmap of caught signals, displayed as a decimal number. -- Obsolete, use __\/proc\/[pid]\/status__ instead. , _sigcatch :: ByteString , _wchan :: ByteString -- ^ Channel which the process is waiting. -- | Number of pages swapped (not maintained). , _nswap :: ByteString -- | Cumulative __nswap__ for child processes (not maintained). , _cnswap :: ByteString -- | Signal to be sent to parent when process dies. , _exiti_signal :: ByteString , _processor :: ByteString -- ^ CPU number last executed on. , _rt_priority:: ByteString -- ^ Real-time scheduling priority. , _policy :: ByteString -- ^ Scheduling policy. -- | Aggregated block IO delays. , _delayacct_blkio_ticks :: ByteString -- | Guest time of the process (time spent running a virtual CPU for -- a guest operating system), measured in clock ticks (divide by -- sysconf(_SC_CLK_TCK)). , _guest_time :: ByteString -- | Guest time of the process's children, measured in clock ticks -- (divide by sysconf(_SC_CLK_TCK)). , _cguest_time:: ByteString -- | Address above which program initialized and uninitialized (BSS) -- data are placed. , _start_data :: ByteString -- | Address below which program initialized and uninitialized (BSS) -- data are placed. , _end_data :: ByteString -- | Address above which program heap can be expanded with brk(2). , _start_brk :: ByteString -- | Address above which program command-line arguments (argv) are placed. , _arg_start :: ByteString -- | Address below program command-line arguments (argv) are placed. , _arg_end :: ByteString -- | Address above which program environment is placed. , _env_start :: ByteString -- | Address below which program environment is placed , _env_end :: ByteString -- | The thread's exit status in the form reported by waitpid(2). , _exit_code :: ByteString } deriving (Eq, Show) ------------------------------------------------------------------------------- -- | Parser for __\/proc\/meminfo__. -- -- @ -- openFile "\/proc\/meminfo" ReadMode >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream meminfop is -- -- [("MemTotal","4052076",Just "kB"),("MemFree","3450628",Just "kB"), ...] -- @ meminfop :: Parser [MemInfo] --[(ByteString, ByteString, Maybe ByteString)] meminfop = manyTill ( MemInfo <$> idp <*> ( skipJustSpacep *> intp <* skipJustSpacep ) <*> unitp <* skipMany space) endOfInput ------------------------------------------------------------------------------- -- | Parser for __\/proc\/[pid]\/stat__. -- -- @ -- openFile "\/proc\/1\/stat" ReadMode >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream procstatp is -- -- ["1","(systemd)",\"S\","0","1", ...] -- @ procstatp :: Parser ProcessStat --[ByteString] procstatp = ProcessStat <$> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval <*> psval psval :: Parser ByteString psval = ( takeWhile ( inClass "a-zA-z0-9()-" ) <* space ) ------------------------------------------------------------------------------ -- | Parser for __\/proc\/[pid]\/statm__. -- -- @ -- openFile "/proc/1/statm" ReadMode >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream (statmp) is -- -- Statm {_size = "6490", _resident = "1143", ...] -- @ statmp :: Parser Statm statmp = Statm <$> parseVal <*> parseVal <*> parseVal <*> parseVal <*> parseVal <*> parseVal <*> parseVal where parseVal :: Parser ByteString parseVal = ( takeWhile isDigit ) <* skipJustSpacep ------------------------------------------------------------------------------ -- | Parser for __\/proc\/loadavg__. Only parses the 1, 5 and 15 minute load -- average, discards the fourth and fifth fields (kernel scheduling entities -- and latest PID assigned). -- -- @ -- openFile "\/proc\/loadavg" ReadMode >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream loadavgp is -- -- ("0.00","0.01","0.05") -- @ data LoadAvg = LoadAvg { _runQLen1 :: ByteString , _runQLen5 :: ByteString , _runQLen15:: ByteString , _runnable :: ByteString , _exists :: ByteString , _latestPid:: ByteString } deriving (Eq, Show) loadavgp :: Parser LoadAvg loadavgp = LoadAvg <$> doublep <*> doublep <*> doublep <*> intp <* char '/' <* skipJustSpacep <*> intp <* skipJustSpacep <*> intp ------------------------------------------------------------------------------ -- | Parser for __\/proc\/uptime__. The first field is the uptime of the system -- (seconds), the second is the amount of time spent in the idle process -- (seconds). -- -- @ -- openFile "\/proc\/uptime" ReadMode >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream uptimep is -- -- ("13048.12","78085.17") -- @ data Uptime = Uptime { _upSec :: ByteString , _idleTime :: ByteString } deriving (Eq,Show) uptimep :: Parser Uptime uptimep = Uptime <$> doublep <*> doublep ------------------------------------------------------------------------------ -- | Parser for __\/proc\/[pid]\/comm__. -- -- @ -- openFile "\/proc\/1\/comm" ReadMode >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream (commp) is -- -- "systemd" -- @ commp :: Parser ByteString commp = takeWhile ( inClass "a-zA-Z0-9:/" ) ------------------------------------------------------------------------------- -- | Parser for __\/proc\/[pid]\/io__. -- -- @ -- openFile "\/proc\/1\/io" ReadMode >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream (iop) is -- -- [("rchar","12983399"),("wchar","14957379"), ...] -- -- @ data ProcIO = ProcIO { _rchar :: ByteString , _wchar :: ByteString , _syscr :: ByteString , _syscw :: ByteString , _readBytes :: ByteString , _writeBytes :: ByteString , _cancelledWriteBytes :: ByteString } deriving (Eq, Show) iop :: Parser ProcIO iop = ProcIO <$> rowp <*> rowp <*> rowp <*> rowp <*> rowp <*> rowp <*> rowp <* endOfInput where rowp = idp *> ( skipJustSpacep *> intp <* skipMany space ) ------------------------------------------------------------------------------- -- | Parser for __\/proc\/[pid]\/maps__. -- -- @ -- openFile "\/proc\/1\/maps" ReadMode >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream mapsp is -- -- [MappedMemory {_address = ("7f9c51069000","7f9c5107e000"), _perms = "r-xp", ...] -- @ mapsp :: Parser [MappedMemory] mapsp = manyTill ( mapsrowp <* endOfLine ) endOfInput -- | Parse a row of \/proc\/[pid]\/maps mapsrowp :: Parser MappedMemory mapsrowp = MappedMemory <$> addressp <* skipJustSpacep <*> permp <* skipJustSpacep <*> hdp <* skipJustSpacep <*> devicep <* skipJustSpacep <*> intp <* skipJustSpacep <*> pathnamep where addressp :: Parser (ByteString, ByteString) addressp = (,) <$> ( hdp <* char '-' ) <*> hdp permp :: Parser ByteString permp = takeWhile $ inClass "-rwxp" devicep :: Parser (ByteString, ByteString) devicep = (,) <$> ( hdp <* char ':' ) <*> hdp pathnamep :: Parser (Maybe ByteString) pathnamep = peekChar >>= \c -> case c of Just '\n' -> return Nothing _ -> liftA Just $ takeTill ( inClass "\n" ) ----------------------------------------------------------------------------- -- | Parser for __\/proc\/[pid]\/environ__. -- -- @ -- openFile "/proc/373/environ" ReadMode >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream environp is -- -- [("LANG","en_IE.UTF-8"),("PATH","/usr/local/sbin"), ...] -- @ environp :: Parser [(ByteString, ByteString)] environp = sepBy environrowp $ char '\NUL' environrowp :: Parser (ByteString, ByteString) environrowp = (,) <$> ( ( takeTill $ inClass "=" ) <* char '=' ) <*> ( takeTill $ inClass "\NUL" ) ----------------------------------------------------------------------------- -- | Parser for \/proc\/[pid]\/numa_maps. Generates a list of 3-tuples : -- (start addr of mem range, mem policy for range, extra info on pages in -- range). -- -- @ -- openFile "/proc/1/numa_maps" ReadMode >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream numamapsp is -- -- [("7f9c51069000","default",["file=/usr/lib/libz.so.1.2.8", ...] -- @ numamapsp :: Parser [(ByteString, ByteString, [ByteString])] numamapsp = manyTill ( (,,) <$> ( hdp <* skipJustSpacep ) <*> ( takeWhile ( inClass "a-zA-Z" ) <* skipJustSpacep ) <*> ( sepBy ( takeWhile $ inClass "-a-zA-Z0-9=/." ) $ char ' ' ) <* endOfLine ) endOfInput ----------------------------------------------------------------------------- -- | Parser for \/proc\/[pid]\/limits. -- -- @ -- openFile "/proc/1/limits" ReadMode >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream limitsp is -- -- [Limits {_limit = ["Max","cpu","time"], _slimit = "unlimited" -- @ limitsp :: Parser [Limit] limitsp = parseHeaders *> sepBy limitrowp endOfLine where parseHeaders :: Parser ByteString parseHeaders = takeTill (\c -> if c == '\n' then True else False) <* endOfLine limitrowp :: Parser Limit limitrowp = Limit <$> limitnamep <* skipJustSpacep <*> shlimitp <* skipJustSpacep <*> shlimitp <* skipJustSpacep <*> lunitp <* skipJustSpacep limitnamep :: Parser [ByteString] limitnamep = manyTill ( takeWhile ( inClass "a-zA-Z" ) <* char ' ' ) $ char ' ' shlimitp :: Parser ByteString shlimitp = takeWhile $ inClass "a-zA-Z0-9" lunitp :: Parser (Maybe ByteString) lunitp = peekChar >>= \c -> case c of Just '\n' -> return Nothing _ -> liftA Just $ takeWhile ( inClass "a-zA-Z" ) ----------------------------------------------------------------------------- -- | Parser for __\/proc\/[pid]\/mountinfo__. -- -- @ -- (openFile "/proc/1/mountinfo" ReadMode) >>= -- \\h -> handleToInputStream h >>= -- \\is -> parseFromStream mountInfop is -- -- [MountInfo {_mountid = "14", _parentid = "18", ...] -- @ mountInfop :: Parser [MountInfo] mountInfop = sepBy mountInfoForRowp endOfLine mountInfoForRowp :: Parser MountInfo mountInfoForRowp = MountInfo <$> takeWhile isDigit <* skipJustSpacep <*> takeWhile isDigit <* skipJustSpacep <*> devMajMinNum <* skipJustSpacep <*> filePathp <* skipJustSpacep <*> filePathp <* skipJustSpacep <*> mountOptionsp <* skipJustSpacep <*> parseOptionalIfExists <* skipJustSpacep <*> fsTypep <* skipJustSpacep <*> mntSrcp <* skipJustSpacep <*> superOptionsp devMajMinNum :: Parser (ByteString, ByteString) devMajMinNum = (,) <$> (parseDigits <* char ':') <*> parseDigits parseDigits :: Parser ByteString parseDigits = takeWhile isDigit parseOptionalIfExists :: Parser ( Maybe [(ByteString, ByteString)] ) parseOptionalIfExists = peekChar >>= (\c -> case c of Just '-' -> return Nothing _ -> liftA Just $ manyTill ( optionalFieldp <* skipJustSpacep ) $ char '-' ) optionalFieldp :: Parser (ByteString, ByteString) optionalFieldp = let tagVal = takeWhile ( notInClass ": " ) in (,) <$> ( tagVal <* char ':' ) <*> tagVal mountOptionsp :: Parser [ByteString] mountOptionsp = sepBy ( takeWhile $ notInClass ", " ) $ char ',' fsTypep :: Parser ByteString fsTypep = takeWhile $ notInClass " " mntSrcp :: Parser ByteString mntSrcp = fsTypep superOptionsp :: Parser [ByteString] superOptionsp = sepBy ( takeTill $ inClass ",\n " ) $ char ',' ----------------------------------------------------------------------------- -- * Helper functions -- | Parse the characters a-z A-Z 0-9 ( ) _ until a ":" is reached idp :: Parser ByteString idp = takeWhile ( inClass "a-zA-z0-9()_" ) <* (skipMany $ char ' ') <* char ':' -- | Parse kB unitp :: Parser (Maybe ByteString) unitp = option Nothing (string "kB" >>= \p -> return $ Just p) doublep :: Parser ByteString doublep = takeWhile ( inClass "0-9." ) <* space -- | Parse hexadecimal hdp :: Parser ByteString hdp = takeWhile $ inClass "0-9a-f" -- | Common parser for file paths filePathp :: Parser ByteString filePathp = takeWhile $ inClass "-a-zA-Z0-9.()[]_/,"
wayofthepie/sip
src/Linux/Parser/Internal/Proc.hs
mit
19,407
0
56
4,656
3,009
1,780
1,229
293
2