code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
module Lang.Csharp where import Lang.Value import Generic.Control.Function import Generic.Data.Bool import Generic.Data.Either import Generic.Data.List import Generic.Data.Maybe import Generic.Data.Number import Generic.Data.Tuple import qualified Prelude data Csharp type Cs a = Val Csharp a instance Prelude.Show (Primitive Csharp) where show (Fun ys body) = case ys of [] -> body x:xs -> let b = if Prelude.null xs then body else Prelude.show (Fun xs body :: Primitive Csharp) cc = (Prelude.++) in x `cc` " => " `cc` b -- * Csharp instances for AwesomePrelude 'data types' instance FunC (Val Csharp) where lam f = "lam" `Name` Lam f app f g = "app" `Name` App f g fix f = "fix" `Name` fun1 ["f", ""] "f(fix(f))" (lam f) instance BoolC (Val Csharp) where true = "true" `Name` con "true" false = "fales" `Name` con "false" bool t e b = "bool" `Name` fun3 ["t", "e", "b"] "b ? t : e" t e b instance NumC (Val Csharp) where a + b = "add" `Name` fun2 ["a", "b"] "a + b" a b a - b = "sub" `Name` fun2 ["a", "b"] "a - b" a b a * b = "mul" `Name` fun2 ["a", "b"] "a * b" a b a / b = "div" `Name` fun2 ["a", "b"] "a / b" a b num x = con (Prelude.show x) instance TupleC (Val Csharp) where mkTuple a b = "mkTuple" `Name` fun2 ["a", "b"] "new Tuple(a, b)" a b tuple f t = "tuple" `Name` fun2 ["f", "t"] "f(t.Item1, t.Item2)" (lam2 f) t instance MaybeC (Val Csharp) where nothing = "nothing" `Name` con "new Nothing()" just x = "just" `Name` fun1 ["x"] "new Just(x)" x maybe n j m = "maybe" `Name` fun3 ["n", "j", "m"] "m.maybe(" n (lam j) m instance EitherC (Val Csharp) where left l = "left" `Name` fun1 ["l"] "new Left(l)" l right r = "right" `Name` fun1 ["r"] "{ right : x }" r either l r e = "either" `Name` fun3 ["l", "r", "e"] "m.left ? l(x.left) : r(x.right)" (lam l) (lam r) e instance ListC (Val Csharp) where nil = "nil" `Name` con "new Nil()" cons x xs = "cons" `Name` fun2 ["x", "xs"] "new Cons(x, xs)" x xs list b f xs = "list" `Name` fun3 ["a", "f", "xs"] "xs.nil ? b : f(x.head, x.tail)" b (lam2 f) xs -- * Csharp instances of AwesomePrelude 'type classes' instance Eq (Val Csharp) Bool where a == b = "eq" `Name` fun2 ["a", "b"] "a == b" a b a /= b = "neq" `Name` fun2 ["a", "b"] "a /= b" a b instance (Eq (Val Csharp) a, Eq (Val Csharp) b) => Eq (Val Csharp) (a, b) where a == b = "eq" `Name` fun2 ["a", "b"] "a == b" a b a /= b = "neq" `Name` fun2 ["a", "b"] "a /= b" a b instance Eq (Val Csharp) a => Eq (Val Csharp) [a] where a == b = "eq" `Name` fun2 ["a", "b"] "a == b" a b a /= b = "neq" `Name` fun2 ["a", "b"] "a /= b" a b
tomlokhorst/AwesomePrelude
src/Lang/Csharp.hs
Haskell
bsd-3-clause
2,713
module System.Taffybar.Widget.Text.MemoryMonitor (textMemoryMonitorNew, showMemoryInfo) where import Control.Monad.IO.Class ( MonadIO ) import qualified Data.Text as T import qualified Text.StringTemplate as ST import System.Taffybar.Information.Memory import System.Taffybar.Widget.Generic.PollingLabel ( pollingLabelNew ) import qualified GI.Gtk import Text.Printf ( printf ) -- | Creates a simple textual memory monitor. It updates once every polling -- period (in seconds). textMemoryMonitorNew :: MonadIO m => String -- ^ Format. You can use variables: "used", "total", "free", "buffer", -- "cache", "rest", "available", "swapUsed", "swapTotal", "swapFree". -> Double -- ^ Polling period in seconds. -> m GI.Gtk.Widget textMemoryMonitorNew fmt period = do label <- pollingLabelNew period (showMemoryInfo fmt 3 <$> parseMeminfo) GI.Gtk.toWidget label showMemoryInfo :: String -> Int -> MemoryInfo -> T.Text showMemoryInfo fmt prec info = let template = ST.newSTMP fmt labels = [ "used" , "total" , "free" , "buffer" , "cache" , "rest" , "available" , "swapUsed" , "swapTotal" , "swapFree" ] actions = [ memoryUsed , memoryTotal , memoryFree , memoryBuffer , memoryCache , memoryRest , memoryAvailable , memorySwapUsed , memorySwapTotal , memorySwapFree ] actions' = map (toAuto prec .) actions stats = [f info | f <- actions'] template' = ST.setManyAttrib (zip labels stats) template in ST.render template' toAuto :: Int -> Double -> String toAuto prec value = printf "%.*f%s" p v unit where value' = max 0 value mag :: Int mag = if value' == 0 then 0 else max 0 $ min 2 $ floor $ logBase 1024 value' v = value' / 1024 ** fromIntegral mag unit = case mag of 0 -> "MiB" 1 -> "GiB" 2 -> "TiB" _ -> "??B" -- unreachable p :: Int p = max 0 $ floor $ fromIntegral prec - logBase 10 v
teleshoes/taffybar
src/System/Taffybar/Widget/Text/MemoryMonitor.hs
Haskell
bsd-3-clause
2,323
module TodoFormat ( MyTime , hasTime , whenToRec , unWhen , whenToDay , whenToTime , whenToDayOfMonth , whenToDayOfWeek , whenToDuration , matchDay , compareTime , toMyTime , toMyTimeAllDay , daily , monthly , weekly , yearly , dailyFull , monthlyFull , weeklyFull , yearlyFull , dailyFromTo , fromTo ) where import Data.Time.LocalTime import Data.Time.Calendar.WeekDate import Data.Time.Calendar data Recurrence = NotRecurrent | Monthly | Yearly | Weekly | Daily | DailyRange LocalTime LocalTime deriving (Show, Eq) data MyDuration = FullDay | NoDuration | EndTime LocalTime deriving (Eq) data MyTime = TheTime MyDuration Recurrence LocalTime deriving (Eq) --data When = When Recurrence LocalTime | AllDay Recurrence LocalTime | AllDayRange When When | OnlyDay Day deriving (Show, Eq) thrd (_, _, z) = z snd' (_, z, _) = z {- instance Eq When where (When Weekly x) == (OnlyDay y) = thrd (toWeekDate (localDay x)) == thrd (toWeekDate (y)) (OnlyDay x) == (When Weekly y) = thrd (toWeekDate (x)) == thrd (toWeekDate (localDay y)) (OnlyDay x) == (When _ y) = x == localDay y (When _ x) == (OnlyDay y) = y == localDay x (OnlyDay x) == (AllDay _ y) = x == localDay y (AllDay _ x) == (OnlyDay y) = localDay x == y -} hasTime (TheTime NoDuration _ _) = True hasTime _ = False whenToRec (TheTime NoDuration r _) = r whenToRec (TheTime FullDay r _) = r whenToRec (TheTime _ r _) = r unWhen (TheTime NoDuration _ x) = x unWhen (TheTime _ _ x) = x whenToDay :: MyTime -> Day whenToDay = localDay . unWhen whenToTime :: MyTime -> TimeOfDay whenToTime = localTimeOfDay . unWhen whenToDayOfWeek :: MyTime -> Int whenToDayOfWeek = thrd . toWeekDate . whenToDay whenToDayOfMonth :: MyTime -> Int whenToDayOfMonth = thrd . toGregorian . whenToDay whenToDuration :: MyTime -> MyDuration whenToDuration (TheTime d _ _ ) = d matchDay :: Day -> MyTime -> Bool matchDay d (TheTime (EndTime t) _ t') = localDay t' <= d && d <= localDay t matchDay y x = case whenToRec x of Weekly -> thrd (toWeekDate y) == thrd (toWeekDate d) Monthly -> thrd (toGregorian y) == thrd (toGregorian d) Yearly -> (thrd (toGregorian y) == thrd (toGregorian d)) && (snd' (toGregorian y) == snd' (toGregorian d)) DailyRange t' t -> localDay t' <= d && d <= localDay t Daily -> True _ -> y == d where d = whenToDay x instance Ord MyTime where compare (TheTime NoDuration _ x) (TheTime NoDuration _ y) = compare x y compare (TheTime FullDay _ x) (TheTime FullDay _ y) = compare x y compare (TheTime NoDuration _ x) (TheTime FullDay _ y) = if localDay x == localDay y then GT else compare x y compare (TheTime FullDay _ x) (TheTime NoDuration _ y) = if localDay x == localDay y then LT else compare x y compareTime :: MyTime -> MyTime -> Ordering compareTime (TheTime NoDuration _ x) (TheTime NoDuration _ y) = compare (localTimeOfDay x) (localTimeOfDay y) compareTime (TheTime NoDuration _ x) (TheTime _ _ y) = GT compareTime (TheTime _ _ x) (TheTime NoDuration _ y) = LT compareTime (TheTime _ _ x) (TheTime _ _ y) = EQ toMyTimeAllDay = TheTime FullDay NotRecurrent toMyTime = TheTime NoDuration NotRecurrent weekly = TheTime NoDuration Weekly monthly = TheTime NoDuration Monthly daily = TheTime NoDuration Daily yearly = TheTime NoDuration Yearly weeklyFull = TheTime FullDay Weekly monthlyFull = TheTime FullDay Monthly dailyFull = TheTime FullDay Daily yearlyFull = TheTime FullDay Yearly dailyFromTo x y = TheTime NoDuration (DailyRange x y) x fromTo f1 f2 = TheTime (EndTime f2) NotRecurrent f1
sejdm/smartWallpaper
src/TodoFormat.hs
Haskell
bsd-3-clause
3,701
-- | Double-buffered storage -- -- This module provides a safer alternative to the methods of the classes -- 'Manifestable' and 'Manifestable2': -- -- * 'store' instead of 'manifest' -- * 'store2' instead of 'manifest2' -- * 'setStore' instead of 'manifestStore' -- * 'setStore2' instead of 'manifestStore2' -- -- Consider the following example: -- -- > bad = do -- > arr <- newArr 20 -- > vec1 <- manifest arr (1...20) -- > vec2 <- manifest arr $ map (*10) $ reverse vec1 -- > printf "%d\n" $ sum vec2 -- -- First the vector @(1...20)@ is stored into @arr@. Then the result is used to -- compute a new vector which is also stored into @arr@. So the storage is -- updated while it is being read from, leading to unexpected results. -- -- Using this module, we can make a small change to the program: -- -- > good = do -- > st <- newStore 20 -- > vec1 <- store st (1...20) -- > vec2 <- store st $ map (*10) $ reverse vec1 -- > printf "%d\n" $ sum vec2 -- -- Now the program works as expected; i.e. gives the same result as the normal -- Haskell expression -- -- > sum $ map (*10) $ reverse [1..20] -- -- The price we have to pay for safe storage is that @`newStore` l@ allocates -- twice as much memory as @`newArr` l@. However, none of the other functions in -- this module allocate any memory. -- -- Note that this module does not protect against improper use of -- 'unsafeFreezeStore'. A vector from a frozen 'Store' is only valid as long as -- the 'Store' is not updated. module Feldspar.Data.Buffered ( Store , newStore , unsafeFreezeStore , unsafeFreezeStore2 , setStore , setStore2 , store , store2 , loopStore , loopStore2 ) where -- By only allowing `Store` to be created using `newStore`, we ensure that -- `unsafeSwapArr` is only used in a safe way (on two arrays allocated in the -- same scope). import Prelude () import Control.Monad.State import Feldspar.Representation import Feldspar.Run import Feldspar.Data.Vector -- | Double-buffered storage data Store a = Store { activeBuf :: Arr a , freeBuf :: Arr a } -- | Create a new double-buffered 'Store', initialized to a 0x0 matrix -- -- This operation allocates two arrays of the given length. newStore :: (Syntax a, MonadComp m) => Data Length -> m (Store a) newStore l = Store <$> newNamedArr "store" l <*> newNamedArr "store" l -- | Read the contents of a 'Store' without making a copy. This is generally -- only safe if the the 'Store' is not updated as long as the resulting vector -- is alive. unsafeFreezeStore :: (Syntax a, MonadComp m) => Data Length -> Store a -> m (Manifest a) unsafeFreezeStore l = unsafeFreezeSlice l . activeBuf -- | Read the contents of a 'Store' without making a copy (2-dimensional -- version). This is generally only safe if the the 'Store' is not updated as -- long as the resulting vector is alive. unsafeFreezeStore2 :: (Syntax a, MonadComp m) => Data Length -- ^ Number of rows -> Data Length -- ^ Number of columns -> Store a -> m (Manifest2 a) unsafeFreezeStore2 r c Store {..} = nest r c <$> unsafeFreezeSlice (r*c) activeBuf -- | Cheap swapping of the two buffers in a 'Store' swapStore :: Syntax a => Store a -> Run () swapStore Store {..} = unsafeSwapArr activeBuf freeBuf -- | Write a 1-dimensional vector to a 'Store'. The operation may become a no-op -- if the vector is already in the 'Store'. setStore :: (Manifestable Run vec a, Finite vec, Syntax a) => Store a -> vec -> Run () setStore st@Store {..} vec = case viewManifest vec of Just iarr | unsafeEqArrIArr activeBuf iarr -> iff (iarrOffset iarr == arrOffset activeBuf) (return ()) saveAndSwap -- We don't check if `iarr` is equal to the free buffer, because that -- would mean that we're trying to overwrite a frozen buffer while -- reading it, which should lead to undefined behavior. _ -> saveAndSwap where saveAndSwap = manifestStore freeBuf vec >> swapStore st -- | Write a 2-dimensional vector to a 'Store'. The operation may become a no-op -- if the vector is already in the 'Store'. setStore2 :: (Manifestable2 Run vec a, Finite2 vec, Syntax a) => Store a -> vec -> Run () setStore2 st@Store {..} vec = case viewManifest2 vec of Just arr | let iarr = unnest arr , unsafeEqArrIArr activeBuf iarr -> iff (iarrOffset iarr == arrOffset activeBuf) (return ()) saveAndSwap -- See comment to `setStore` _ -> saveAndSwap where saveAndSwap = manifestStore2 freeBuf vec >> swapStore st -- | Write the contents of a vector to a 'Store' and get it back as a -- 'Manifest' vector store :: (Manifestable Run vec a, Finite vec, Syntax a) => Store a -> vec -> Run (Manifest a) store st vec = setStore st vec >> unsafeFreezeStore (length vec) st -- | Write the contents of a vector to a 'Store' and get it back as a -- 'Manifest2' vector store2 :: (Manifestable2 Run vec a, Finite2 vec, Syntax a) => Store a -> vec -> Run (Manifest2 a) store2 st vec = setStore2 st vec >> unsafeFreezeStore2 r c st where (r,c) = extent2 vec loopStore :: ( Syntax a , Manifestable Run vec1 a , Finite vec1 , Manifestable Run vec2 a , Finite vec2 ) => Store a -> IxRange (Data Length) -> (Data Index -> Manifest a -> Run vec1) -> vec2 -> Run (Manifest a) loopStore st rng body init = do setStore st init lr <- initRef $ length init for rng $ \i -> do l <- unsafeFreezeRef lr next <- body i =<< unsafeFreezeStore l st setStore st next setRef lr $ length next l <- unsafeFreezeRef lr unsafeFreezeStore l st loopStore2 :: ( Syntax a , Manifestable2 Run vec1 a , Finite2 vec1 , Manifestable2 Run vec2 a , Finite2 vec2 ) => Store a -> IxRange (Data Length) -> (Data Index -> Manifest2 a -> Run vec1) -> vec2 -> Run (Manifest2 a) loopStore2 st rng body init = do setStore2 st init rr <- initRef $ numRows init cr <- initRef $ numCols init for rng $ \i -> do r <- unsafeFreezeRef rr c <- unsafeFreezeRef cr next <- body i =<< unsafeFreezeStore2 r c st setStore2 st next setRef rr $ numRows next setRef cr $ numCols next r <- unsafeFreezeRef rr c <- unsafeFreezeRef cr unsafeFreezeStore2 r c st
kmate/raw-feldspar
src/Feldspar/Data/Buffered.hs
Haskell
bsd-3-clause
6,440
{-| Funsat aims to be a reasonably efficient modern SAT solver that is easy to integrate as a backend to other projects. SAT is NP-complete, and thus has reductions from many other interesting problems. We hope this implementation is efficient enough to make it useful to solve medium-size, real-world problem mapped from another space. We also have taken pains test the solver rigorously to encourage confidence in its output. One particular nicetie facilitating integration of Funsat into other projects is the efficient calculation of an /unsatisfiable core/ for unsatisfiable problems (see the "Funsat.Resolution" module). In the case a problem is unsatisfiable, as a by-product of checking the proof of unsatisfiability, Funsat will generate a minimal set of input clauses that are also unsatisfiable. Another is the ability to compile high-level circuits into CNF. Seen the "Funsat.Circuit" module. * 07 Jun 2008 21:43:42: N.B. because of the use of mutable arrays in the ST monad, the solver will actually give _wrong_ answers if you compile without optimisation. Which is okay, 'cause that's really slow anyway. [@Bibliography@] * ''Abstract DPLL and DPLL Modulo Theories'' * ''Chaff: Engineering an Efficient SAT solver'' * ''An Extensible SAT-solver'' by Niklas Een, Niklas Sorensson * ''Efficient Conflict Driven Learning in a Boolean Satisfiability Solver'' by Zhang, Madigan, Moskewicz, Malik * ''SAT-MICRO: petit mais costaud!'' by Conchon, Kanig, and Lescuyer -} module Funsat.Solver #ifndef TESTING ( -- * Interface solve , solve1 , Solution(..) -- ** Verification , verify , VerifyError(..) -- ** Configuration , FunsatConfig(..) , defaultConfig -- * Solver statistics , Stats(..) , ShowWrapped(..) , statTable , statSummary ) #endif where {- This file is part of funsat. funsat is free software: it is released under the BSD3 open source license. You can find details of this license in the file LICENSE at the root of the source tree. Copyright 2008 Denis Bueno -} import Control.Arrow( (&&&) ) import Control.Exception( assert ) import Control.Monad.Error hiding ( (>=>), forM_, runErrorT ) import Control.Monad.MonadST( MonadST(..) ) import Control.Monad.ST.Strict import Control.Monad.State.Lazy hiding ( (>=>), forM_ ) import Data.Array.ST import Data.Array.Unboxed import Data.Foldable hiding ( sequence_ ) import Data.Graph.Inductive.Tree import Data.Int( Int64 ) import Data.List( nub, tails, sortBy, sort ) import Data.Maybe import Data.Ord( comparing ) import Data.STRef import Data.Sequence( Seq ) -- import Debug.Trace (trace) import Funsat.Monad import Funsat.Utils import Funsat.Utils.Internal import Funsat.Resolution( ResolutionTrace(..), initResolutionTrace ) import Funsat.Types import Funsat.Types.Internal import Prelude hiding ( sum, concatMap, elem, foldr, foldl, any, maximum ) import Funsat.Resolution( ResolutionError(..) ) import Text.Printf( printf ) import qualified Data.Foldable as Fl import qualified Data.List as List import qualified Data.Map as Map import qualified Data.Sequence as Seq import qualified Data.Set as Set import qualified Funsat.Resolution as Resolution import qualified Text.Tabular as Tabular -- * Interface -- | Run the DPLL-based SAT solver on the given CNF instance. Returns a -- solution, along with internal solver statistics and possibly a resolution -- trace. The trace is for checking a proof of `Unsat', and thus is only -- present when the result is `Unsat'. solve :: FunsatConfig -> CNF -> (Solution, Stats, Maybe ResolutionTrace) solve cfg fIn = -- To solve, we simply take baby steps toward the solution using solveStep, -- starting with an initial assignment. -- trace ("input " ++ show f) $ either (error "solve: invariant violated") id $ runST $ evalSSTErrMonad (do initialAssignment <- liftST $ newSTUArray (V 1, V (numVars f)) 0 (a, isUnsat) <- initialState initialAssignment if isUnsat then reportSolution (Unsat a) else stepToSolution initialAssignment >>= reportSolution) SC{ cnf = f{ clauses = Set.empty }, dl = [] , watches = undefined, learnt = undefined , propQ = Seq.empty, trail = [], level = undefined , stats = FunStats{numConfl = 0,numConflTotal = 0,numDecisions = 0,numImpl = 0} , reason = Map.empty, varOrder = undefined , resolutionTrace = PartialResolutionTrace 1 [] [] Map.empty , dpllConfig = cfg } where f = preprocessCNF fIn -- If returns True, then problem is unsat. initialState :: MAssignment s -> FunMonad s (IAssignment, Bool) initialState m = do initialLevel <- liftST $ newSTUArray (V 1, V (numVars f)) noLevel modify $ \s -> s{ level = initialLevel } initialWatches <- liftST $ newSTArray (L (- (numVars f)), L (numVars f)) [] modify $ \s -> s{ watches = initialWatches } initialLearnts <- liftST $ newSTArray (L (- (numVars f)), L (numVars f)) [] modify $ \s -> s{ learnt = initialLearnts } initialVarOrder <- liftST $ newSTUArray (V 1, V (numVars f)) initialActivity modify $ \s -> s{ varOrder = VarOrder initialVarOrder } -- Watch each clause, making sure to bork if we find a contradiction. (`catchError` (const $ funFreeze m >>= \a -> return (a,True))) $ do forM_ (clauses f) (\c -> do cid <- nextTraceId isConsistent <- watchClause m (c, cid) False when (not isConsistent) -- conflict data is ignored here, so safe to fake (do traceClauseId cid ; throwError (L 0, [], 0))) a <- funFreeze m return (a, False) -- | Solve with the default configuration `defaultConfig'. solve1 :: CNF -> (Solution, Stats, Maybe ResolutionTrace) solve1 = solve defaultConfig -- | This function applies `solveStep' recursively until SAT instance is -- solved, starting with the given initial assignment. It also implements the -- conflict-based restarting (see `FunsatConfig'). stepToSolution :: MAssignment s -> FunMonad s Solution stepToSolution assignment = do step <- solveStep assignment useRestarts <- gets (configUseRestarts . dpllConfig) isTimeToRestart <- uncurry ((>=)) `liftM` gets ((numConfl . stats) &&& (configRestart . dpllConfig)) case step of Left m -> do when (useRestarts && isTimeToRestart) (do _stats <- extractStats -- trace ("Restarting...") $ -- trace (statSummary stats) $ resetState m) stepToSolution m Right s -> return s where resetState m = do modify $ \s -> let st = stats s in s{ stats = st{numConfl = 0} } -- Require more conflicts before next restart. modifySlot dpllConfig $ \s c -> s{ dpllConfig = c{ configRestart = ceiling (configRestartBump c * fromIntegral (configRestart c)) } } lvl <- gets level >>= funFreeze undoneLits <- takeWhile (\l -> lvl ! (var l) > 0) `liftM` gets trail forM_ undoneLits $ const (undoOne m) modify $ \s -> s{ dl = [], propQ = Seq.empty } compactDB funFreeze m >>= simplifyDB reportSolution :: Solution -> FunMonad s (Solution, Stats, Maybe ResolutionTrace) reportSolution s = do stats <- extractStats case s of Sat _ -> return (s, stats, Nothing) Unsat _ -> do resTrace <- constructResTrace s return (s, stats, Just resTrace) -- | A default configuration based on the formula to solve. -- -- * restarts every 100 conflicts -- -- * requires 1.5 as many restarts after restarting as before, each time -- -- * VSIDS to be enabled -- -- * restarts to be enabled defaultConfig :: FunsatConfig defaultConfig = Cfg { configRestart = 100 -- fromIntegral $ max (numVars f `div` 10) 100 , configRestartBump = 1.5 , configUseVSIDS = True , configUseRestarts = True , configCut = FirstUipCut } -- * Preprocessing -- | Some kind of preprocessing. -- -- * remove duplicates preprocessCNF :: CNF -> CNF preprocessCNF f = f{clauses = simpClauses (clauses f)} where simpClauses = Set.map nub -- rm dups -- | Simplify the clause database. Eventually should supersede, probably, -- `preprocessCNF'. -- -- Precondition: decision level 0. simplifyDB :: IAssignment -> FunMonad s () simplifyDB mFr = do -- For each clause in the database, remove it if satisfied; if it contains a -- literal whose negation is assigned, delete that literal. n <- numVars `liftM` gets cnf s <- get liftST . forM_ [V 1 .. V n] $ \i -> when (mFr!i /= 0) $ do let l = L (mFr!i) filterL _i = map (\(p, c, cid) -> (p, filter (/= negate l) c, cid)) -- Remove unsat literal `negate l' from clauses. -- modifyArray (watches s) l filterL modifyArray (learnt s) l filterL -- Clauses containing `l' are Sat. -- writeArray (watches s) (negate l) [] writeArray (learnt s) (negate l) [] -- * Internals -- | The DPLL procedure is modeled as a state transition system. This -- function takes one step in that transition system. Given an unsatisfactory -- assignment, perform one state transition, producing a new assignment and a -- new state. solveStep :: MAssignment s -> FunMonad s (Either (MAssignment s) Solution) solveStep m = do funFreeze m >>= solveStepInvariants conf <- gets dpllConfig let selector = if configUseVSIDS conf then select else selectStatic maybeConfl <- bcp m mFr <- funFreeze m voArr <- gets (varOrderArr . varOrder) voFr <- FrozenVarOrder `liftM` funFreeze voArr s <- get stepForward $ -- Check if unsat. unsat maybeConfl s ==> postProcessUnsat maybeConfl -- Unit propagation may reveal conflicts; check. >< maybeConfl >=> backJump m -- No conflicts. Decide. >< selector mFr voFr >=> decide m where -- Take the step chosen by the transition guards above. stepForward Nothing = (Right . Sat) `liftM` funFreeze m stepForward (Just step) = do r <- step case r of Nothing -> (Right . Unsat) `liftM` funFreeze m Just m -> return . Left $ m -- | /Precondition:/ problem determined to be unsat. -- -- Records id of conflicting clause in trace before failing. Always returns -- `Nothing'. postProcessUnsat :: Maybe (Lit, Clause, ClauseId) -> FunMonad s (Maybe a) postProcessUnsat maybeConfl = do traceClauseId $ (thd . fromJust) maybeConfl return Nothing where thd (_,_,i) = i -- | Check data structure invariants. Unless @-fno-ignore-asserts@ is passed, -- this should be optimised away to nothing. solveStepInvariants :: IAssignment -> FunMonad s () {-# INLINE solveStepInvariants #-} solveStepInvariants _m = assert True $ do s <- get -- no dups in decision list or trail assert ((length . dl) s == (length . nub . dl) s) $ assert ((length . trail) s == (length . nub . trail) s) $ return () -- ** Internals -- | Value of the `level' array if corresponding variable unassigned. Had -- better be less that 0. noLevel :: Level noLevel = -1 -- *** Boolean constraint propagation -- | Assign a new literal, and enqueue any implied assignments. If a conflict -- is detected, return @Just (impliedLit, conflictingClause)@; otherwise -- return @Nothing@. The @impliedLit@ is implied by the clause, but conflicts -- with the assignment. -- -- If no new clauses are unit (i.e. no implied assignments), simply update -- watched literals. bcpLit :: MAssignment s -> Lit -- ^ Assigned literal which might propagate. -> FunMonad s (Maybe (Lit, Clause, ClauseId)) bcpLit m l = do ws <- gets watches ; ls <- gets learnt clauses <- liftST $ readArray ws l learnts <- liftST $ readArray ls l liftST $ do writeArray ws l [] ; writeArray ls l [] -- Update wather lists for normal & learnt clauses; if conflict is found, -- return that and don't update anything else. (`catchError` return . Just) $ do {-# SCC "bcpWatches" #-} forM_ (tails clauses) (updateWatches (\ f l -> liftST $ modifyArray ws l (const f))) {-# SCC "bcpLearnts" #-} forM_ (tails learnts) (updateWatches (\ f l -> liftST $ modifyArray ls l (const f))) return Nothing -- no conflict where -- updateWatches: `l' has been assigned, so we look at the clauses in -- which contain @negate l@, namely the watcher list for l. For each -- annotated clause, find the status of its watched literals. If a -- conflict is found, the at-fault clause is returned through Left, and -- the unprocessed clauses are placed back into the appropriate watcher -- list. {-# INLINE updateWatches #-} updateWatches _ [] = return () updateWatches alter (annCl@(watchRef, c, cid) : restClauses) = do mFr :: IAssignment <- funFreeze m q <- liftST $ do (x, y) <- readSTRef watchRef return $ if x == l then y else x -- l,q are the (negated) literals being watched for clause c. if negate q `isTrueUnder` mFr -- if other true, clause already sat then alter (annCl:) l else case find (\x -> x /= negate q && x /= negate l && not (x `isFalseUnder` mFr)) c of Just l' -> do -- found unassigned literal, negate l', to watch liftST $ writeSTRef watchRef (q, negate l') alter (annCl:) (negate l') Nothing -> do -- all other lits false, clause is unit incNumImpl alter (annCl:) l isConsistent <- enqueue m (negate q) (Just (c, cid)) when (not isConsistent) $ do -- unit literal is conflicting alter (restClauses ++) l clearQueue throwError (negate q, c, cid) -- | Boolean constraint propagation of all literals in `propQ'. If a conflict -- is found it is returned exactly as described for `bcpLit'. bcp :: MAssignment s -> FunMonad s (Maybe (Lit, Clause, ClauseId)) bcp m = do q <- gets propQ if Seq.null q then return Nothing else do p <- dequeue bcpLit m p >>= maybe (bcp m) (return . Just) -- *** Decisions -- | Find and return a decision variable. A /decision variable/ must be (1) -- undefined under the assignment and (2) it or its negation occur in the -- formula. -- -- Select a decision variable, if possible, and return it and the adjusted -- `VarOrder'. select :: IAssignment -> FrozenVarOrder -> Maybe Var {-# INLINE select #-} select = varOrderGet selectStatic :: IAssignment -> a -> Maybe Var {-# INLINE selectStatic #-} selectStatic m _ = find (`isUndefUnder` m) (range . bounds $ m) -- | Assign given decision variable. Records the current assignment before -- deciding on the decision variable indexing the assignment. decide :: MAssignment s -> Var -> FunMonad s (Maybe (MAssignment s)) decide m v = do let ld = L (unVar v) (SC{dl=dl}) <- get -- trace ("decide " ++ show ld) $ return () incNumDecisions modify $ \s -> s{ dl = ld:dl } enqueue m ld Nothing return $ Just m -- *** Backtracking -- | The current returns the learned clause implied by the first unique -- implication point cut of the conflict graph. backJump :: MAssignment s -> (Lit, Clause, ClauseId) -- ^ @(l, c)@, where attempting to assign @l@ conflicted with -- clause @c@. -> FunMonad s (Maybe (MAssignment s)) backJump m c@(_, _conflict, _) = get >>= \(SC{dl=dl, reason=_reason}) -> do _theTrail <- gets trail -- trace ("********** conflict = " ++ show c) $ return () -- trace ("trail = " ++ show _theTrail) $ return () -- trace ("dlits (" ++ show (length dl) ++ ") = " ++ show dl) $ return () -- ++ "reason: " ++ Map.showTree _reason -- ) ( incNumConfl ; incNumConflTotal levelArr <- gets level >>= funFreeze -- levelArr <- do s <- get -- funFreeze (level s) (learntCl, learntClId, newLevel) <- analyse m levelArr dl c s <- get let numDecisionsToUndo = length dl - newLevel dl' = drop numDecisionsToUndo dl undoneLits = takeWhile (\lit -> levelArr ! (var lit) > newLevel) (trail s) forM_ undoneLits $ const (undoOne m) -- backtrack mFr <- funFreeze m assert (numDecisionsToUndo > 0) $ assert (not (null learntCl)) $ assert (learntCl `isUnitUnder` mFr) $ modify $ \s -> s{ dl = dl' } -- undo decisions -- trace ("new mFr: " ++ showAssignment mFr) $ return () -- TODO once I'm sure this works I don't need getUnit, I can just use the -- uip of the cut. watchClause m (learntCl, learntClId) True mFr <- funFreeze m enqueue m (getUnit learntCl mFr) (Just (learntCl, learntClId)) -- learntCl is asserting return $ Just m -- | Analyse a the conflict graph and produce a learned clause. We use the -- First UIP cut of the conflict graph. -- -- May undo part of the trail, but not past the current decision level. analyse :: MAssignment s -> FrozenLevelArray -> [Lit] -> (Lit, Clause, ClauseId) -> FunMonad s (Clause, ClauseId, Int) -- ^ learned clause and new decision level analyse m levelArr dlits (cLit, cClause, cCid) = do conf <- gets dpllConfig mFr <- funFreeze m st <- get -- let conflGraph = mkConflGraph mFr levelArr (reason st) dlits (cLit, cClause) -- :: ConflictGraph Gr -- trace ("graphviz graph:\n" ++ graphviz' conflGraph) $ return () -- trace ("cut: " ++ show firstUIPCut) $ return () -- trace ("topSort: " ++ show topSortNodes) $ return () -- trace ("dlits (" ++ show (length dlits) ++ "): " ++ show dlits) $ return () -- trace ("learnt: " ++ show (map (\l -> (l, levelArr!(var l))) learntCl, newLevel)) $ return () -- outputConflict "conflict.dot" (graphviz' conflGraph) $ return () -- return $ (learntCl, newLevel) a <- case configCut conf of FirstUipCut -> firstUIPBFS m (numVars . cnf $ st) (reason st) DecisionLitCut -> error "decisionlitcut unimplemented" -- let lastDecision = fromMaybe $ find (\ -- trace ("learned: " ++ show a) $ return () return a where -- BFS by undoing the trail backward. From Minisat paper. Returns -- conflict clause and backtrack level. firstUIPBFS :: MAssignment s -> Int -> ReasonMap -> FunMonad s (Clause, ClauseId, Int) firstUIPBFS m nVars reasonMap = do resolveSourcesR <- liftST $ newSTRef [] -- trace sources let addResolveSource clauseId = liftST $ modifySTRef resolveSourcesR (clauseId:) -- Literals we should process. seenArr <- liftST $ newSTUArray (V 1, V nVars) False counterR <- liftST $ newSTRef (0 :: Int) -- Number of unprocessed current-level -- lits we know about. pR <- liftST $ newSTRef cLit -- Invariant: literal from current dec. lev. out_learnedR <- liftST $ newSTRef [] out_btlevelR <- liftST $ newSTRef 0 let reasonL l = if l == cLit then (cClause, cCid) else let (r, rid) = Map.findWithDefault (error "analyse: reasonL") (var l) reasonMap in (r `without` l, rid) (`doWhile` (liftM (> 0) (liftST $ readSTRef counterR))) $ do p <- liftST $ readSTRef pR let (p_reason, p_rid) = reasonL p traceClauseId p_rid addResolveSource p_rid forM_ p_reason (bump . var) -- For each unseen reason, -- > from the current level, bump counter -- > from lower level, put in learned clause liftST . forM_ p_reason $ \q -> do seenq <- readArray seenArr (var q) when (not seenq) $ do writeArray seenArr (var q) True if levelL q == currentLevel then modifySTRef counterR (+ 1) else if levelL q > 0 then do modifySTRef out_learnedR (q:) modifySTRef out_btlevelR $ max (levelL q) else return () -- Select next literal to look at: (`doWhile` (liftST (readSTRef pR >>= readArray seenArr . var) >>= return . not)) $ do p <- head `liftM` gets trail -- a dec. var. only if the counter = -- 1, i.e., loop terminates now liftST $ writeSTRef pR p undoOne m -- Invariant states p is from current level, so when we're done -- with it, we've thrown away one lit. from counting toward -- counter. liftST $ modifySTRef counterR (\c -> c - 1) p <- liftST $ readSTRef pR liftST $ modifySTRef out_learnedR (negate p:) bump . var $ p out_learned <- liftST $ readSTRef out_learnedR out_btlevel <- liftST $ readSTRef out_btlevelR learnedClauseId <- nextTraceId storeResolvedSources resolveSourcesR learnedClauseId traceClauseId learnedClauseId return (out_learned, learnedClauseId, out_btlevel) -- helpers currentLevel = length dlits levelL l = levelArr!(var l) storeResolvedSources rsR clauseId = do rsReversed <- liftST $ readSTRef rsR modifySlot resolutionTrace $ \s rt -> s{resolutionTrace = rt{resSourceMap = Map.insert clauseId (reverse rsReversed) (resSourceMap rt)}} -- | Delete the assignment to last-assigned literal. Undoes the trail, the -- assignment, sets `noLevel', undoes reason. -- -- Does /not/ touch `dl'. undoOne :: MAssignment s -> FunMonad s () {-# INLINE undoOne #-} undoOne m = do trl <- gets trail lvl <- gets level case trl of [] -> error "undoOne of empty trail" (l:trl') -> do liftST $ m `unassign` l liftST $ writeArray lvl (var l) noLevel modify $ \s -> s{ trail = trl' , reason = Map.delete (var l) (reason s) } -- | Increase the recorded activity of given variable. bump :: Var -> FunMonad s () {-# INLINE bump #-} bump v = varOrderMod v (+ varInc) -- | Constant amount by which a variable is `bump'ed. varInc :: Double varInc = 1.0 -- *** Impossible to satisfy -- | /O(1)/. Test for unsatisfiability. -- -- The DPLL paper says, ''A problem is unsatisfiable if there is a conflicting -- clause and there are no decision literals in @m@.'' But we were deciding -- on all literals *without* creating a conflicting clause. So now we also -- test whether we've made all possible decisions, too. unsat :: Maybe a -> FunsatState s -> Bool {-# INLINE unsat #-} unsat maybeConflict (SC{dl=dl}) = isUnsat where isUnsat = (null dl && isJust maybeConflict) -- or BitSet.size bad == numVars cnf -- ** Helpers -- *** Clause compaction -- | Keep the smaller half of the learned clauses. compactDB :: FunMonad s () compactDB = do n <- numVars `liftM` gets cnf lArr <- gets learnt clauses <- liftST $ (nub . Fl.concat) `liftM` forM [L (- n) .. L n] (\v -> do val <- readArray lArr v ; writeArray lArr v [] return val) let clauses' = take (length clauses `div` 2) $ sortBy (comparing (length . (\(_,s,_) -> s))) clauses liftST $ forM_ clauses' (\ wCl@(r, _, _) -> do (x, y) <- readSTRef r modifyArray lArr x $ const (wCl:) modifyArray lArr y $ const (wCl:)) -- *** Unit propagation -- | Add clause to the watcher lists, unless clause is a singleton; if clause -- is a singleton, `enqueue's fact and returns `False' if fact is in conflict, -- `True' otherwise. This function should be called exactly once per clause, -- per run. It should not be called to reconstruct the watcher list when -- propagating. -- -- Currently the watched literals in each clause are the first two. -- -- Also adds unique clause ids to trace. watchClause :: MAssignment s -> (Clause, ClauseId) -> Bool -- ^ Is this clause learned? -> FunMonad s Bool {-# INLINE watchClause #-} watchClause m (c, cid) isLearnt = do case c of [] -> return True [l] -> do result <- enqueue m l (Just (c, cid)) levelArr <- gets level liftST $ writeArray levelArr (var l) 0 when (not isLearnt) ( modifySlot resolutionTrace $ \s rt -> s{resolutionTrace=rt{resTraceOriginalSingles= (c,cid):resTraceOriginalSingles rt}}) return result _ -> do let p = (negate (c !! 0), negate (c !! 1)) _insert annCl@(_, cl) list -- avoid watching dup clauses | any (\(_, c) -> cl == c) list = list | otherwise = annCl:list r <- liftST $ newSTRef p let annCl = (r, c, cid) addCl arr = do modifyArray arr (fst p) $ const (annCl:) modifyArray arr (snd p) $ const (annCl:) get >>= liftST . addCl . (if isLearnt then learnt else watches) return True -- | Enqueue literal in the `propQ' and place it in the current assignment. -- If this conflicts with an existing assignment, returns @False@; otherwise -- returns @True@. In case there is a conflict, the assignment is /not/ -- altered. -- -- Also records decision level, modifies trail, and records reason for -- assignment. enqueue :: MAssignment s -> Lit -- ^ The literal that has been assigned true. -> Maybe (Clause, ClauseId) -- ^ The reason for enqueuing the literal. Including a -- non-@Nothing@ value here adjusts the `reason' map. -> FunMonad s Bool {-# INLINE enqueue #-} -- enqueue _m l _r | trace ("enqueue " ++ show l) $ False = undefined enqueue m l r = do mFr <- funFreeze m case l `statusUnder` mFr of Right b -> return b -- conflict/already assigned Left () -> do liftST $ m `assign` l -- assign decision level for literal gets (level &&& (length . dl)) >>= \(levelArr, dlInt) -> liftST (writeArray levelArr (var l) dlInt) modify $ \s -> s{ trail = l : (trail s) , propQ = propQ s Seq.|> l } when (isJust r) $ modifySlot reason $ \s m -> s{reason = Map.insert (var l) (fromJust r) m} return True -- | Pop the `propQ'. Error (crash) if it is empty. dequeue :: FunMonad s Lit {-# INLINE dequeue #-} dequeue = do q <- gets propQ case Seq.viewl q of Seq.EmptyL -> error "dequeue of empty propQ" top Seq.:< q' -> do modify $ \s -> s{propQ = q'} return top -- | Clear the `propQ'. clearQueue :: FunMonad s () {-# INLINE clearQueue #-} clearQueue = modify $ \s -> s{propQ = Seq.empty} -- *** Dynamic variable ordering -- | Modify priority of variable; takes care of @Double@ overflow. varOrderMod :: Var -> (Double -> Double) -> FunMonad s () varOrderMod v f = do vo <- varOrderArr `liftM` gets varOrder vActivity <- liftST $ readArray vo v when (f vActivity > 1e100) $ rescaleActivities vo liftST $ writeArray vo v (f vActivity) where rescaleActivities vo = liftST $ do indices <- range `liftM` getBounds vo forM_ indices (\i -> modifyArray vo i $ const (* 1e-100)) -- | Retrieve the maximum-priority variable from the variable order. varOrderGet :: IAssignment -> FrozenVarOrder -> Maybe Var {-# INLINE varOrderGet #-} varOrderGet mFr (FrozenVarOrder voFr) = -- find highest var undef under mFr, then find one with highest activity (`fmap` goUndef highestIndex) $ \start -> goActivity start start where highestIndex = snd . bounds $ voFr maxActivity v v' = if voFr!v > voFr!v' then v else v' -- @goActivity current highest@ returns highest-activity var goActivity !(V 0) !h = h goActivity !v@(V n) !h = if v `isUndefUnder` mFr then goActivity (V $! n-1) (v `maxActivity` h) else goActivity (V $! n-1) h -- returns highest var that is undef under mFr goUndef !(V 0) = Nothing goUndef !v@(V n) | v `isUndefUnder` mFr = Just v | otherwise = goUndef (V $! n-1) -- | Generate a new clause identifier (always unique). nextTraceId :: FunMonad s Int nextTraceId = do counter <- gets (resTraceIdCount . resolutionTrace) modifySlot resolutionTrace $ \s rt -> s{ resolutionTrace = rt{ resTraceIdCount = succ counter }} return $! counter -- | Add the given clause id to the trace. traceClauseId :: ClauseId -> FunMonad s () traceClauseId cid = do modifySlot resolutionTrace $ \s rt -> s{resolutionTrace = rt{ resTrace = [cid] }} -- *** Generic state transition notation -- | Guard a transition action. If the boolean is true, return the action -- given as an argument. Otherwise, return `Nothing'. (==>) :: (Monad m) => Bool -> m a -> Maybe (m a) {-# INLINE (==>) #-} (==>) b amb = guard b >> return amb infixr 6 ==> -- | @flip fmap@. (>=>) :: (Monad m) => Maybe a -> (a -> m b) -> Maybe (m b) {-# INLINE (>=>) #-} (>=>) = flip fmap infixr 6 >=> -- | Choice of state transitions. Choose the leftmost action that isn't -- @Nothing@, or return @Nothing@ otherwise. (><) :: (Monad m) => Maybe (m a) -> Maybe (m a) -> Maybe (m a) a1 >< a2 = case (a1, a2) of (Nothing, Nothing) -> Nothing (Just _, _) -> a1 _ -> a2 infixl 5 >< -- *** Misc initialActivity :: Double initialActivity = 1.0 instance Error (Lit, Clause, ClauseId) where noMsg = (L 0, [], 0) instance Error () where noMsg = () data VerifyError = SatError [(Clause, Either () Bool)] -- ^ Indicates a unsatisfactory assignment that was claimed -- satisfactory. Each clause is tagged with its status using -- 'Funsat.Types.Model'@.statusUnder@. | UnsatError ResolutionError -- ^ Indicates an error in the resultion checking process. deriving (Show) -- | Verify the solution. In case of `Sat', checks that the assignment is -- well-formed and satisfies the CNF problem. In case of `Unsat', runs a -- resolution-based checker on a trace of the SAT solver. verify :: Solution -> Maybe ResolutionTrace -> CNF -> Maybe VerifyError verify sol maybeRT cnf = -- m is well-formed -- Fl.all (\l -> m!(V l) == l || m!(V l) == negate l || m!(V l) == 0) [1..numVars cnf] case sol of Sat m -> let unsatClauses = toList $ Set.filter (not . isTrue . snd) $ Set.map (\c -> (c, c `statusUnder` m)) (clauses cnf) in if null unsatClauses then Nothing else Just . SatError $ unsatClauses Unsat _ -> case Resolution.checkDepthFirst (fromJust maybeRT) of Left er -> Just . UnsatError $ er Right _ -> Nothing where isTrue (Right True) = True isTrue _ = False --------------------------------------- -- Statistics & trace data Stats = Stats { statsNumConfl :: Int64 -- ^ Number of conflicts since last restart. , statsNumConflTotal :: Int64 -- ^ Number of conflicts since beginning of solving. , statsNumLearnt :: Int64 -- ^ Number of learned clauses currently in DB (fluctuates because DB is -- compacted every restart). , statsAvgLearntLen :: Double -- ^ Avg. number of literals per learnt clause. , statsNumDecisions :: Int64 -- ^ Total number of decisions since beginning of solving. , statsNumImpl :: Int64 -- ^ Total number of unit implications since beginning of solving. } -- | The show instance uses the wrapped string. newtype ShowWrapped = WrapString { unwrapString :: String } instance Show ShowWrapped where show = unwrapString instance Show Stats where show = show . statTable -- | Convert statistics to a nice-to-display tabular form. statTable :: Stats -> Tabular.Table ShowWrapped statTable s = Tabular.mkTable [ [WrapString "Num. Conflicts" ,WrapString $ show (statsNumConflTotal s)] , [WrapString "Num. Learned Clauses" ,WrapString $ show (statsNumLearnt s)] , [WrapString " --> Avg. Lits/Clause" ,WrapString $ show (statsAvgLearntLen s)] , [WrapString "Num. Decisions" ,WrapString $ show (statsNumDecisions s)] , [WrapString "Num. Propagations" ,WrapString $ show (statsNumImpl s)] ] -- | Converts statistics into a tabular, human-readable summary. statSummary :: Stats -> String statSummary s = show (Tabular.mkTable [[WrapString $ show (statsNumConflTotal s) ++ " Conflicts" ,WrapString $ "| " ++ show (statsNumLearnt s) ++ " Learned Clauses" ++ " (avg " ++ printf "%.2f" (statsAvgLearntLen s) ++ " lits/clause)"]]) extractStats :: FunMonad s Stats extractStats = do s <- gets stats learntArr <- get >>= funFreeze . learnt let learnts = (nub . Fl.concat) [ map (sort . (\(_,c,_) -> c)) (learntArr!i) | i <- (range . bounds) learntArr ] :: [Clause] stats = Stats { statsNumConfl = numConfl s , statsNumConflTotal = numConflTotal s , statsNumLearnt = fromIntegral $ length learnts , statsAvgLearntLen = fromIntegral (foldl' (+) 0 (map length learnts)) / fromIntegral (statsNumLearnt stats) , statsNumDecisions = numDecisions s , statsNumImpl = numImpl s } return stats constructResTrace :: Solution -> FunMonad s ResolutionTrace constructResTrace sol = do s <- get watchesIndices <- range `liftM` liftST (getBounds (watches s)) origClauseMap <- foldM (\origMap i -> do clauses <- liftST $ readArray (watches s) i return $ foldr (\(_, clause, clauseId) origMap -> Map.insert clauseId clause origMap) origMap clauses) Map.empty watchesIndices let singleClauseMap = foldr (\(clause, clauseId) m -> Map.insert clauseId clause m) Map.empty (resTraceOriginalSingles . resolutionTrace $ s) anteMap = foldr (\l anteMap -> Map.insert (var l) (getAnteId s (var l)) anteMap) Map.empty (litAssignment . finalAssignment $ sol) return (initResolutionTrace (head (resTrace . resolutionTrace $ s)) (finalAssignment sol)) { traceSources = resSourceMap . resolutionTrace $ s , traceOriginalClauses = origClauseMap `Map.union` singleClauseMap , traceAntecedents = anteMap } where getAnteId s v = snd $ Map.findWithDefault (error $ "no reason for assigned var " ++ show v) v (reason s)
dbueno/funsat
src/Funsat/Solver.hs
Haskell
bsd-3-clause
35,895
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Bench -- Copyright : Johan Tibell 2011 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This is the entry point into running the benchmarks in a built -- package. It performs the \"@.\/setup bench@\" action. It runs -- benchmarks designated in the package description. module Distribution.Simple.Bench ( bench ) where import Prelude () import Distribution.Compat.Prelude import qualified Distribution.PackageDescription as PD import Distribution.Simple.BuildPaths import Distribution.Simple.Compiler import Distribution.Simple.InstallDirs import qualified Distribution.Simple.LocalBuildInfo as LBI import Distribution.Simple.Setup import Distribution.Simple.UserHooks import Distribution.Simple.Utils import Distribution.Text import System.Exit ( ExitCode(..), exitFailure, exitSuccess ) import System.Directory ( doesFileExist ) import System.FilePath ( (</>), (<.>) ) -- | Perform the \"@.\/setup bench@\" action. bench :: Args -- ^positional command-line arguments -> PD.PackageDescription -- ^information from the .cabal file -> LBI.LocalBuildInfo -- ^information from the configure step -> BenchmarkFlags -- ^flags sent to benchmark -> IO () bench args pkg_descr lbi flags = do let verbosity = fromFlag $ benchmarkVerbosity flags benchmarkNames = args pkgBenchmarks = PD.benchmarks pkg_descr enabledBenchmarks = map fst (LBI.enabledBenchLBIs pkg_descr lbi) -- Run the benchmark doBench :: PD.Benchmark -> IO ExitCode doBench bm = case PD.benchmarkInterface bm of PD.BenchmarkExeV10 _ _ -> do let cmd = LBI.buildDir lbi </> PD.benchmarkName bm </> PD.benchmarkName bm <.> exeExtension options = map (benchOption pkg_descr lbi bm) $ benchmarkOptions flags name = PD.benchmarkName bm -- Check that the benchmark executable exists. exists <- doesFileExist cmd unless exists $ die $ "Error: Could not find benchmark program \"" ++ cmd ++ "\". Did you build the package first?" notice verbosity $ startMessage name -- This will redirect the child process -- stdout/stderr to the parent process. exitcode <- rawSystemExitCode verbosity cmd options notice verbosity $ finishMessage name exitcode return exitcode _ -> do notice verbosity $ "No support for running " ++ "benchmark " ++ PD.benchmarkName bm ++ " of type: " ++ show (disp $ PD.benchmarkType bm) exitFailure unless (PD.hasBenchmarks pkg_descr) $ do notice verbosity "Package has no benchmarks." exitSuccess when (PD.hasBenchmarks pkg_descr && null enabledBenchmarks) $ die $ "No benchmarks enabled. Did you remember to configure with " ++ "\'--enable-benchmarks\'?" bmsToRun <- case benchmarkNames of [] -> return enabledBenchmarks names -> for names $ \bmName -> let benchmarkMap = zip enabledNames enabledBenchmarks enabledNames = map PD.benchmarkName enabledBenchmarks allNames = map PD.benchmarkName pkgBenchmarks in case lookup bmName benchmarkMap of Just t -> return t _ | bmName `elem` allNames -> die $ "Package configured with benchmark " ++ bmName ++ " disabled." | otherwise -> die $ "no such benchmark: " ++ bmName let totalBenchmarks = length bmsToRun notice verbosity $ "Running " ++ show totalBenchmarks ++ " benchmarks..." exitcodes <- traverse doBench bmsToRun let allOk = totalBenchmarks == length (filter (== ExitSuccess) exitcodes) unless allOk exitFailure where startMessage name = "Benchmark " ++ name ++ ": RUNNING...\n" finishMessage name exitcode = "Benchmark " ++ name ++ ": " ++ (case exitcode of ExitSuccess -> "FINISH" ExitFailure _ -> "ERROR") -- TODO: This is abusing the notion of a 'PathTemplate'. The result isn't -- necessarily a path. benchOption :: PD.PackageDescription -> LBI.LocalBuildInfo -> PD.Benchmark -> PathTemplate -> String benchOption pkg_descr lbi bm template = fromPathTemplate $ substPathTemplate env template where env = initialPathTemplateEnv (PD.package pkg_descr) (LBI.localUnitId lbi) (compilerInfo $ LBI.compiler lbi) (LBI.hostPlatform lbi) ++ [(BenchmarkNameVar, toPathTemplate $ PD.benchmarkName bm)]
sopvop/cabal
Cabal/Distribution/Simple/Bench.hs
Haskell
bsd-3-clause
5,187
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} module Data.Logic.Boolean.Class where import Control.Applicative import Data.Functor.Identity import Data.Functor.Compose class Boolean r where tt :: r ff :: r fromBool :: Bool -> r fromBool b = if b then tt else ff data AnyBoolean = AnyBoolean { getBoolean :: forall r. Boolean r => r } instance Boolean AnyBoolean where tt = AnyBoolean tt ff = AnyBoolean ff -- Boolean instances {{{ instance Boolean Bool where tt = True ff = False instance Boolean r => Boolean (Identity r) where tt = pure tt ff = pure ff instance Boolean (f (g r)) => Boolean (Compose f g r) where tt = Compose tt ff = Compose ff instance Boolean r => Boolean (Maybe r) where tt = pure tt ff = pure ff instance Boolean r => Boolean [r] where tt = pure tt ff = pure ff instance Boolean r => Boolean (Either a r) where tt = pure tt ff = pure ff instance Boolean r => Boolean (a -> r) where tt = pure tt ff = pure ff instance Boolean r => Boolean (IO r) where tt = pure tt ff = pure ff instance ( Boolean r , Boolean s ) => Boolean (r,s) where tt = ( tt , tt ) ff = ( ff , ff ) instance ( Boolean r , Boolean s , Boolean t ) => Boolean (r,s,t) where tt = ( tt , tt , tt ) ff = ( ff , ff , ff ) instance ( Boolean r , Boolean s , Boolean t , Boolean u ) => Boolean (r,s,t,u) where tt = ( tt , tt , tt , tt ) ff = ( ff , ff , ff , ff ) instance ( Boolean r , Boolean s , Boolean t , Boolean u , Boolean v ) => Boolean (r,s,t,u,v) where tt = ( tt , tt , tt , tt , tt ) ff = ( ff , ff , ff , ff , ff ) -- }}}
kylcarte/finally-logical
src/Data/Logic/Boolean/Class.hs
Haskell
bsd-3-clause
1,653
module Paths_AutoComplete ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName ) where import Data.Version (Version(..)) import System.Environment (getEnv) version :: Version version = Version {versionBranch = [0,1], versionTags = []} bindir, libdir, datadir, libexecdir :: FilePath bindir = "/home/satvik/.cabal/bin" libdir = "/home/satvik/.cabal/lib/AutoComplete-0.1/ghc-7.0.3" datadir = "/home/satvik/.cabal/share/AutoComplete-0.1" libexecdir = "/home/satvik/.cabal/libexec" getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath getBinDir = catch (getEnv "AutoComplete_bindir") (\_ -> return bindir) getLibDir = catch (getEnv "AutoComplete_libdir") (\_ -> return libdir) getDataDir = catch (getEnv "AutoComplete_datadir") (\_ -> return datadir) getLibexecDir = catch (getEnv "AutoComplete_libexecdir") (\_ -> return libexecdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
satvikc/Trie
dist/build/autogen/Paths_AutoComplete.hs
Haskell
bsd-3-clause
1,013
import System.Environment import System.Directory import System.IO import Control.Exception import qualified Data.ByteString.Lazy as B main = do (fileName1:fileName2:_) <- getArgs copy fileName1 fileName2 copy source dest = do contents <- B.readFile source bracketOnError (openTempFile "." "temp") (\(tempName, tempHandle) -> do hClose tempHandle removeFile tempName) (\(tempName, tempHandle) -> do B.hPutStr tempHandle contents hClose tempHandle renameFile tempName dest)
ku00/h-book
src/ByteStringCopy.hs
Haskell
bsd-3-clause
575
{-# LANGUAGE DeriveDataTypeable #-} import System.Console.CmdArgs import Data.Word import Contract.Types import Contract.Symbols data Arguments = Arguments { symbol :: Symbol , startTime :: TimeOffset , startRate :: Rate , points :: Word32 } deriving (Show, Data, Typeable) arguments = Arguments { symbol = eurusd &= typ "Symbol" &= help "Symbol for which to generate data" , startTime = 0 &= typ "TimeOffset" &= help "Time of first tick" , startRate = 5555555 &= typ "Rate" &= help "Rate of first tick" , points = 100 &= typ "Word32" &= help "Number of ticks to generate" } &= summary "Random Data Generator version 0.0.1" main = print =<< cmdArgs arguments
thlorenz/Pricetory
src/spikes/CmdArgsSample.hs
Haskell
bsd-3-clause
830
{-# LANGUAGE TemplateHaskell, ScopedTypeVariables#-} module UUTReader where import Control.Monad import Data.String.Utils import Language.Haskell.TH import GHC.Generics import Sized import Arbitrary import TemplateAllv import TemplateArbitrary import TemplateSized import UUT import UUTReaderUtilities import UUTReaderUtilitiesDeep -------------call to gen_all and gen_arbitrary ------------------------------------- $(gen_allv_str_listQ (notDefTypesQMonad (get_f_inp_types (head uutMethods)))) -------------call to gen_sized and gen_arbitrary ------------------------------------- $(gen_sized_str_listQ (notDefTypesQMonad (get_f_inp_types (head uutMethods)))) ------------------main test function------------------------------------------------ test_UUT = test --------------Printing the ending information--------------------------------------- printInfoTuple (xs,ys,zs) = printInfo xs ys zs printInfo xs ys zs = "Testing the function " ++ uutName ++ " generating a total of " ++ (show (length ys)) ++ " test cases of which " ++ (show (length zs)) ++ " passed the precondition " ++ "\n\n\nTest cases:" ++ (printTestCases ys) ++ "\n\n\nTest cases that passed the precondition:" ++ (printTestCases zs) ++ if ((length $ filter (== True) xs) == (length xs)) then " None of them failed" else "\n\n\nAnd these are the ones that failed.\n" ++ (printInfoAux xs zs) printInfoAux [] [] = "" printInfoAux (x:xs) (y:ys) | (x == True) = (printInfoAux xs ys) | otherwise = (show y) ++ "\n" ++ (printInfoAux xs ys) printTestCases [] = "" printTestCases (y:ys) = (show y) ++ ", " ++ (printTestCases ys) ----------------------test function------------------------------------- test = prueba listArgs where listArgs = (smallest :: $(inputT (head uutMethods)))
pegartillo95/CaseGenerator
src/UUTReader.hs
Haskell
bsd-3-clause
1,873
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} module Application ( app ) where import Control.Exception import Control.Monad (when) import Data.Default.Class import Data.Int (Int64) import Data.Monoid import Data.Pool (Pool) import Data.Text.Lazy as Text import Database.PostgreSQL.Simple (Connection) import Network.HTTP.Types.Status import Network.Wai (Application, Middleware) import Network.Wai.Middleware.RequestLogger (Destination(Handle), mkRequestLogger, RequestLoggerSettings(destination, outputFormat), OutputFormat(CustomOutputFormat)) import Network.Wai.Middleware.Static import System.IO import Text.Blaze.Html.Renderer.Text (renderHtml) import Text.Blaze.Html5 (Html) import Views.DomainList (domainListT) import Views.DomainPrivileges (domainPrivilegesT) import Views.ErrorPage (errorPageT) import Views.GroupList (groupListT) import Views.Homepage (homepageT) import Views.MemberList (memberListT) import Views.PrivilegeRules (privilegeRulesT) import Views.Search (searchResultsT) import Web.Scotty.Trans import DB import Entities import LogFormat (logFormat) import SproxyError app :: Pool Connection -> FilePath -> IO Application app c p = do logger <- mkRequestLogger def{ destination = Handle stderr , outputFormat = CustomOutputFormat logFormat } scottyAppT id (sproxyWeb c p logger) sproxyWeb :: Pool Connection -> FilePath -> Middleware -> ScottyT SproxyError IO () sproxyWeb pool dataDirectory logger = do middleware logger middleware (staticPolicy (hasPrefix "static" >-> addBase dataDirectory)) -- error page for uncaught exceptions defaultHandler handleEx get "/" $ homepage pool post "/search" $ searchUserH pool post "/delete-user" $ deleteUserH pool post "/rename-user" $ renameUserH pool -- groups get "/groups" $ groupList pool -- this is the group listing page get "/groups.json" $ jsonGroupList pool -- json endpoint returning an array of group names post "/groups" $ jsonUpdateGroup pool -- endpoint where we POST requests for modifications of groups -- group get "/group/:group/members" $ memberList pool -- list of members for a group post "/group/:group/members" $ jsonPostMembers pool -- endpoint for POSTing updates to the member list -- domains get "/domains" $ domainList pool -- list of domains handled by sproxy post "/domains" $ jsonUpdateDomain pool -- endpoint for POSTing updates -- privileges for a given domain get "/domain/:domain/privileges" $ domainPrivileges pool -- listing of privileges available on a domain get "/domain/:domain/privileges.json" $ jsonDomainPrivileges pool -- json endpoint, array of privilege names post "/domain/:domain/privileges" $ jsonPostDomainPrivileges pool -- endpoint for POSTing updates -- rules for a given privilege on a given domain get "/domain/:domain/privilege/:privilege/rules" $ privilegeRules pool -- listing of paths/methods associated to a privilege post "/domain/:domain/privilege/:privilege/rules" $ jsonPostRule pool -- endpoint for POSTing updates about these -- add/remove group privileges post "/domain/:domain/group_privileges" $ handleGPs pool -- endpoint for POSTing privilege granting/removal for groups blaze :: Html -> ActionT SproxyError IO () blaze = Web.Scotty.Trans.html . renderHtml handleEx :: SproxyError -> ActionT SproxyError IO () handleEx = errorPage errorPage :: SproxyError -> ActionT SproxyError IO () errorPage err = blaze (errorPageT err) homepage :: Pool Connection -> ActionT SproxyError IO () homepage _ = blaze homepageT ------------------------------------------ -- handlers related to the group list page ------------------------------------------ -- POST /groups jsonUpdateGroup :: Pool Connection -> ActionT SproxyError IO () jsonUpdateGroup pool = do (operation :: Text) <- param "operation" (t, n) <- case operation of "add" -> do g <- param "group" checked pool (addGroup g) "del" -> do g <- param "group" checked pool (removeGroup g) "upd" -> do old <- param "old" new <- param "new" checked pool (updateGroup old new) _ -> status badRequest400 >> return ("incorrect operation", -1) outputFor t n -- GET /groups groupList :: Pool Connection -> ActionT SproxyError IO () groupList pool = do groups <- Prelude.map Prelude.head `fmap` withDB pool getGroups blaze (groupListT groups) -- GET /groups.json jsonGroupList :: Pool Connection -> ActionT SproxyError IO () jsonGroupList pool = do groups <- Prelude.map Prelude.head `fmap` withDB pool getGroups json groups --------------------------------------------------- -- handlers related to the group members list page --------------------------------------------------- -- GET /group/:group memberList :: Pool Connection -> ActionT SproxyError IO () memberList pool = do groupName <- param "group" members <- Prelude.map Prelude.head `fmap` withDB pool (getMembersFor groupName) blaze (memberListT members groupName) -- POST /group/:group/members jsonPostMembers :: Pool Connection -> ActionT SproxyError IO () jsonPostMembers pool = do groupName <- param "group" (operation :: Text) <- param "operation" (t, n) <- case operation of "add" -> do m <- param "member" checked pool (addMemberTo m groupName) "del" -> do m <- param "member" checked pool (removeMemberOf m groupName) "upd" -> do old <- param "old" new <- param "new" checked pool (updateMemberOf old new groupName) _ -> status badRequest400 >> return ("incorrect operation", -1) outputFor t n -------------------------------------- -- handlers related to the domain list -------------------------------------- -- GET /domains domainList :: Pool Connection -> ActionT SproxyError IO () domainList pool = do domains <- Prelude.map Prelude.head `fmap` withDB pool getDomains blaze (domainListT domains) -- POST /domains jsonUpdateDomain :: Pool Connection -> ActionT SproxyError IO () jsonUpdateDomain pool = do (operation :: Text) <- param "operation" (t, n) <- case operation of "add" -> do d <- param "domain" checked pool (addDomain d) "del" -> do d <- param "domain" checked pool (removeDomain d) "upd" -> do old <- param "old" new <- param "new" checked pool (updateDomain old new) _ -> status badRequest400 >> return ("incorrect operation", -1) outputFor t n ------------------------------------------------------------------------- -- handlers related to the list of possible privileges for a given domain ------------------------------------------------------------------------- -- GET /domain/:domain/privileges domainPrivileges :: Pool Connection -> ActionT SproxyError IO () domainPrivileges pool = do domain <- param "domain" privileges <- Prelude.map Prelude.head `fmap` withDB pool (getDomainPrivileges domain) groups <- Prelude.map Prelude.head `fmap` withDB pool getGroups groupPrivs <- withDB pool (getGroupPrivsFor domain) blaze (domainPrivilegesT domain privileges groups groupPrivs) -- GET /domain/:domain/privileges.json jsonDomainPrivileges :: Pool Connection -> ActionT SproxyError IO () jsonDomainPrivileges pool = do domain <- param "domain" privileges <- Prelude.map Prelude.head `fmap` withDB pool (getDomainPrivileges domain) json privileges -- POST /domain/:domain/group_privileges handleGPs :: Pool Connection -> ActionT SproxyError IO () handleGPs pool = do domain <- param "domain" (operation :: Text) <- param "operation" (t, n) <- case operation of "add" -> do grp <- param "group" priv <- param "privilege" checked pool (addGPFor domain grp priv) "del" -> do grp <- param "group" priv <- param "privilege" checked pool (deleteGPOf domain grp priv) _ -> status badRequest400 >> return ("incorrect operation", -1) outputFor t n -- POST /domain/:domain/privileges jsonPostDomainPrivileges :: Pool Connection -> ActionT SproxyError IO () jsonPostDomainPrivileges pool = do domain <- param "domain" (operation :: Text) <- param "operation" (t, n) <- case operation of "add" -> do p <- param "privilege" checked pool (addPrivilegeToDomain p domain) "del" -> do p <- param "privilege" checked pool (removePrivilegeOfDomain p domain) "upd" -> do old <- param "old" new <- param "new" checked pool (updatePrivilegeOfDomain old new domain) _ -> status badRequest400 >> return ("incorrect operation", -1) outputFor t n ------------------------------------------------------------------------------- -- handlers related to the rules associated to a given privilege on some domain ------------------------------------------------------------------------------- -- GET /domain/:domain/privilege/:privilege/rules privilegeRules :: Pool Connection -> ActionT SproxyError IO () privilegeRules pool = do -- TODO: check that the domain and privilege exist domain <- param "domain" privilege <- param "privilege" rules <- withDB pool (getRules domain privilege) blaze (privilegeRulesT domain privilege rules) -- POST /domain/:domain/privilege/:privilege/rules jsonPostRule :: Pool Connection -> ActionT SproxyError IO () jsonPostRule pool = do -- TODO: check that the domain and privilege exist domain <- param "domain" privilege <- param "privilege" operation <- param "operation" case operation :: Text of "add" -> addRule domain privilege "del" -> delRule domain privilege "upd" -> updRule domain privilege _ -> status badRequest400 >> text "bad operation" where addRule domain privilege = do path <- param "path" method <- param "method" (t, n) <- checked pool (addRuleToPrivilege domain privilege path method) outputFor t n delRule domain privilege = do path <- param "path" method <- param "method" (t, n) <- checked pool (deleteRuleFromPrivilege domain privilege path method) outputFor t n updRule domain privilege = do what <- param "what" when (what /= "path" && what /= "method") $ text "invalid 'what'" let updFunc = if what == "path" then updatePathFor else updateMethodFor old <- param ("old" <> what) new <- param ("new" <> what) otherField <- param $ if what == "path" then "method" else "path" (t, n) <- checked pool (updFunc domain privilege new old otherField) outputFor t n -- | POST /search, search string in "search_query" searchUserH :: Pool Connection -> ActionT SproxyError IO () searchUserH pool = do searchStr <- param "search_query" matchingEmails <- withDB pool (searchUser searchStr) blaze (searchResultsT searchStr matchingEmails) -- | POST /delete-user, email to delete in "user_email" deleteUserH :: Pool Connection -> ActionT SproxyError IO () deleteUserH pool = do userEmail <- param "user_email" (t, n) <- checked pool (removeUser userEmail) outputFor t n -- | POST /rename-user: -- - old email in "old_email" -- - new email in "new_email" renameUserH :: Pool Connection -> ActionT SproxyError IO () renameUserH pool = do oldEmail <- param "old_email" newEmail <- param "new_email" (resp, n) <- checked pool (renameUser oldEmail newEmail) outputFor resp n -- utility functions outputFor :: Text -> Int64 -> ActionT SproxyError IO () outputFor t 0 = status badRequest400 >> text ("no: " <> t) outputFor t (-1) = status badRequest400 >> text ("error: " <> t) outputFor t _ = text t checked :: Pool Connection -> (Connection -> IO Int64) -- request -> ActionT SproxyError IO (Text, Int64) checked pool req = withDB pool req' where req' c = handle (\(e :: SomeException) -> return (Text.pack (show e), -1)) ( ("",) <$> req c )
zalora/sproxy-web
src/Application.hs
Haskell
mit
12,687
module Tandoori.GHC.Parse (parseMod, getDecls) where import Tandoori.GHC.Internals import HsSyn (hsmodDecls) import Parser (parseModule) import Lexer (unP, mkPState, ParseResult(..)) import StringBuffer (hGetStringBuffer) import DynFlags (defaultDynFlags) getDecls mod = hsmodDecls $ unLoc mod parseMod src_filename = do buf <- hGetStringBuffer src_filename let loc = mkSrcLoc (mkFastString src_filename) 1 0 dflags = defaultDynFlags case unP Parser.parseModule (mkPState dflags buf loc) of POk pst rdr_module -> return rdr_module PFailed srcspan message -> error $ showSDoc message
bitemyapp/tandoori
src/Tandoori/GHC/Parse.hs
Haskell
bsd-3-clause
746
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.GHC -- Copyright : Isaac Jones 2003-2007 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This is a fairly large module. It contains most of the GHC-specific code for -- configuring, building and installing packages. It also exports a function -- for finding out what packages are already installed. Configuring involves -- finding the @ghc@ and @ghc-pkg@ programs, finding what language extensions -- this version of ghc supports and returning a 'Compiler' value. -- -- 'getInstalledPackages' involves calling the @ghc-pkg@ program to find out -- what packages are installed. -- -- Building is somewhat complex as there is quite a bit of information to take -- into account. We have to build libs and programs, possibly for profiling and -- shared libs. We have to support building libraries that will be usable by -- GHCi and also ghc's @-split-objs@ feature. We have to compile any C files -- using ghc. Linking, especially for @split-objs@ is remarkably complex, -- partly because there tend to be 1,000's of @.o@ files and this can often be -- more than we can pass to the @ld@ or @ar@ programs in one go. -- -- Installing for libs and exes involves finding the right files and copying -- them to the right places. One of the more tricky things about this module is -- remembering the layout of files in the build directory (which is not -- explicitly documented) and thus what search dirs are used for various kinds -- of files. module Distribution.Simple.GHC ( getGhcInfo, configure, getInstalledPackages, getPackageDBContents, buildLib, buildExe, replLib, replExe, startInterpreter, installLib, installExe, libAbiHash, hcPkgInfo, registerPackage, componentGhcOptions, componentCcGhcOptions, getLibDir, isDynamic, getGlobalPackageDB, pkgRoot ) where import qualified Distribution.Simple.GHC.IPI641 as IPI641 import qualified Distribution.Simple.GHC.IPI642 as IPI642 import qualified Distribution.Simple.GHC.Internal as Internal import Distribution.Simple.GHC.ImplInfo import Distribution.PackageDescription as PD ( PackageDescription(..), BuildInfo(..), Executable(..), Library(..) , allExtensions, libModules, exeModules , hcOptions, hcSharedOptions, hcProfOptions ) import Distribution.InstalledPackageInfo ( InstalledPackageInfo ) import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo ( InstalledPackageInfo_(..) ) import Distribution.Simple.PackageIndex (InstalledPackageIndex) import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..), ComponentLocalBuildInfo(..) , absoluteInstallDirs, depLibraryPaths ) import qualified Distribution.Simple.Hpc as Hpc import Distribution.Simple.InstallDirs hiding ( absoluteInstallDirs ) import Distribution.Simple.BuildPaths import Distribution.Simple.Utils import Distribution.Package ( PackageName(..) ) import qualified Distribution.ModuleName as ModuleName import Distribution.Simple.Program ( Program(..), ConfiguredProgram(..), ProgramConfiguration , ProgramSearchPath , rawSystemProgramStdout, rawSystemProgramStdoutConf , getProgramInvocationOutput, requireProgramVersion, requireProgram , userMaybeSpecifyPath, programPath, lookupProgram, addKnownProgram , ghcProgram, ghcPkgProgram, haddockProgram, hsc2hsProgram, ldProgram ) import qualified Distribution.Simple.Program.HcPkg as HcPkg import qualified Distribution.Simple.Program.Ar as Ar import qualified Distribution.Simple.Program.Ld as Ld import qualified Distribution.Simple.Program.Strip as Strip import Distribution.Simple.Program.GHC import Distribution.Simple.Setup ( toFlag, fromFlag, configCoverage, configDistPref ) import qualified Distribution.Simple.Setup as Cabal ( Flag(..) ) import Distribution.Simple.Compiler ( CompilerFlavor(..), CompilerId(..), Compiler(..), compilerVersion , PackageDB(..), PackageDBStack, AbiTag(..) ) import Distribution.Version ( Version(..), anyVersion, orLaterVersion ) import Distribution.System ( Platform(..), OS(..) ) import Distribution.Verbosity import Distribution.Text ( display ) import Distribution.Utils.NubList ( NubListR, overNubListR, toNubListR ) import Language.Haskell.Extension (Extension(..), KnownExtension(..)) import Control.Monad ( unless, when ) import Data.Char ( isDigit, isSpace ) import Data.List import qualified Data.Map as M ( fromList ) import Data.Maybe ( catMaybes ) #if __GLASGOW_HASKELL__ < 710 import Data.Monoid ( Monoid(..) ) #endif import Data.Version ( showVersion ) import System.Directory ( doesFileExist, getAppUserDataDirectory, createDirectoryIfMissing ) import System.FilePath ( (</>), (<.>), takeExtension, takeDirectory, replaceExtension, splitExtension, isRelative ) import qualified System.Info -- ----------------------------------------------------------------------------- -- Configuring configure :: Verbosity -> Maybe FilePath -> Maybe FilePath -> ProgramConfiguration -> IO (Compiler, Maybe Platform, ProgramConfiguration) configure verbosity hcPath hcPkgPath conf0 = do (ghcProg, ghcVersion, conf1) <- requireProgramVersion verbosity ghcProgram (orLaterVersion (Version [6,4] [])) (userMaybeSpecifyPath "ghc" hcPath conf0) let implInfo = ghcVersionImplInfo ghcVersion -- This is slightly tricky, we have to configure ghc first, then we use the -- location of ghc to help find ghc-pkg in the case that the user did not -- specify the location of ghc-pkg directly: (ghcPkgProg, ghcPkgVersion, conf2) <- requireProgramVersion verbosity ghcPkgProgram { programFindLocation = guessGhcPkgFromGhcPath ghcProg } anyVersion (userMaybeSpecifyPath "ghc-pkg" hcPkgPath conf1) when (ghcVersion /= ghcPkgVersion) $ die $ "Version mismatch between ghc and ghc-pkg: " ++ programPath ghcProg ++ " is version " ++ display ghcVersion ++ " " ++ programPath ghcPkgProg ++ " is version " ++ display ghcPkgVersion -- Likewise we try to find the matching hsc2hs and haddock programs. let hsc2hsProgram' = hsc2hsProgram { programFindLocation = guessHsc2hsFromGhcPath ghcProg } haddockProgram' = haddockProgram { programFindLocation = guessHaddockFromGhcPath ghcProg } conf3 = addKnownProgram haddockProgram' $ addKnownProgram hsc2hsProgram' conf2 languages <- Internal.getLanguages verbosity implInfo ghcProg extensions <- Internal.getExtensions verbosity implInfo ghcProg ghcInfo <- Internal.getGhcInfo verbosity implInfo ghcProg let ghcInfoMap = M.fromList ghcInfo let comp = Compiler { compilerId = CompilerId GHC ghcVersion, compilerAbiTag = NoAbiTag, compilerCompat = [], compilerLanguages = languages, compilerExtensions = extensions, compilerProperties = ghcInfoMap } compPlatform = Internal.targetPlatform ghcInfo -- configure gcc and ld conf4 = Internal.configureToolchain implInfo ghcProg ghcInfoMap conf3 return (comp, compPlatform, conf4) -- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find -- the corresponding tool; e.g. if the tool is ghc-pkg, we try looking -- for a versioned or unversioned ghc-pkg in the same dir, that is: -- -- > /usr/local/bin/ghc-pkg-ghc-6.6.1(.exe) -- > /usr/local/bin/ghc-pkg-6.6.1(.exe) -- > /usr/local/bin/ghc-pkg(.exe) -- guessToolFromGhcPath :: Program -> ConfiguredProgram -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath) guessToolFromGhcPath tool ghcProg verbosity searchpath = do let toolname = programName tool path = programPath ghcProg dir = takeDirectory path versionSuffix = takeVersionSuffix (dropExeExtension path) guessNormal = dir </> toolname <.> exeExtension guessGhcVersioned = dir </> (toolname ++ "-ghc" ++ versionSuffix) <.> exeExtension guessVersioned = dir </> (toolname ++ versionSuffix) <.> exeExtension guesses | null versionSuffix = [guessNormal] | otherwise = [guessGhcVersioned, guessVersioned, guessNormal] info verbosity $ "looking for tool " ++ toolname ++ " near compiler in " ++ dir exists <- mapM doesFileExist guesses case [ file | (file, True) <- zip guesses exists ] of -- If we can't find it near ghc, fall back to the usual -- method. [] -> programFindLocation tool verbosity searchpath (fp:_) -> do info verbosity $ "found " ++ toolname ++ " in " ++ fp return (Just fp) where takeVersionSuffix :: FilePath -> String takeVersionSuffix = takeWhileEndLE isSuffixChar isSuffixChar :: Char -> Bool isSuffixChar c = isDigit c || c == '.' || c == '-' dropExeExtension :: FilePath -> FilePath dropExeExtension filepath = case splitExtension filepath of (filepath', extension) | extension == exeExtension -> filepath' | otherwise -> filepath -- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a -- corresponding ghc-pkg, we try looking for both a versioned and unversioned -- ghc-pkg in the same dir, that is: -- -- > /usr/local/bin/ghc-pkg-ghc-6.6.1(.exe) -- > /usr/local/bin/ghc-pkg-6.6.1(.exe) -- > /usr/local/bin/ghc-pkg(.exe) -- guessGhcPkgFromGhcPath :: ConfiguredProgram -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath) guessGhcPkgFromGhcPath = guessToolFromGhcPath ghcPkgProgram -- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a -- corresponding hsc2hs, we try looking for both a versioned and unversioned -- hsc2hs in the same dir, that is: -- -- > /usr/local/bin/hsc2hs-ghc-6.6.1(.exe) -- > /usr/local/bin/hsc2hs-6.6.1(.exe) -- > /usr/local/bin/hsc2hs(.exe) -- guessHsc2hsFromGhcPath :: ConfiguredProgram -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath) guessHsc2hsFromGhcPath = guessToolFromGhcPath hsc2hsProgram -- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a -- corresponding haddock, we try looking for both a versioned and unversioned -- haddock in the same dir, that is: -- -- > /usr/local/bin/haddock-ghc-6.6.1(.exe) -- > /usr/local/bin/haddock-6.6.1(.exe) -- > /usr/local/bin/haddock(.exe) -- guessHaddockFromGhcPath :: ConfiguredProgram -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath) guessHaddockFromGhcPath = guessToolFromGhcPath haddockProgram getGhcInfo :: Verbosity -> ConfiguredProgram -> IO [(String, String)] getGhcInfo verbosity ghcProg = Internal.getGhcInfo verbosity implInfo ghcProg where Just version = programVersion ghcProg implInfo = ghcVersionImplInfo version -- | Given a single package DB, return all installed packages. getPackageDBContents :: Verbosity -> PackageDB -> ProgramConfiguration -> IO InstalledPackageIndex getPackageDBContents verbosity packagedb conf = do pkgss <- getInstalledPackages' verbosity [packagedb] conf toPackageIndex verbosity pkgss conf -- | Given a package DB stack, return all installed packages. getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration -> IO InstalledPackageIndex getInstalledPackages verbosity packagedbs conf = do checkPackageDbEnvVar checkPackageDbStack packagedbs pkgss <- getInstalledPackages' verbosity packagedbs conf index <- toPackageIndex verbosity pkgss conf return $! hackRtsPackage index where hackRtsPackage index = case PackageIndex.lookupPackageName index (PackageName "rts") of [(_,[rts])] -> PackageIndex.insert (removeMingwIncludeDir rts) index _ -> index -- No (or multiple) ghc rts package is registered!! -- Feh, whatever, the ghc test suite does some crazy stuff. -- | Given a list of @(PackageDB, InstalledPackageInfo)@ pairs, produce a -- @PackageIndex@. Helper function used by 'getPackageDBContents' and -- 'getInstalledPackages'. toPackageIndex :: Verbosity -> [(PackageDB, [InstalledPackageInfo])] -> ProgramConfiguration -> IO InstalledPackageIndex toPackageIndex verbosity pkgss conf = do -- On Windows, various fields have $topdir/foo rather than full -- paths. We need to substitute the right value in so that when -- we, for example, call gcc, we have proper paths to give it. topDir <- getLibDir' verbosity ghcProg let indices = [ PackageIndex.fromList (map (Internal.substTopDir topDir) pkgs) | (_, pkgs) <- pkgss ] return $! (mconcat indices) where Just ghcProg = lookupProgram ghcProgram conf getLibDir :: Verbosity -> LocalBuildInfo -> IO FilePath getLibDir verbosity lbi = dropWhileEndLE isSpace `fmap` rawSystemProgramStdoutConf verbosity ghcProgram (withPrograms lbi) ["--print-libdir"] getLibDir' :: Verbosity -> ConfiguredProgram -> IO FilePath getLibDir' verbosity ghcProg = dropWhileEndLE isSpace `fmap` rawSystemProgramStdout verbosity ghcProg ["--print-libdir"] -- | Return the 'FilePath' to the global GHC package database. getGlobalPackageDB :: Verbosity -> ConfiguredProgram -> IO FilePath getGlobalPackageDB verbosity ghcProg = dropWhileEndLE isSpace `fmap` rawSystemProgramStdout verbosity ghcProg ["--print-global-package-db"] checkPackageDbEnvVar :: IO () checkPackageDbEnvVar = Internal.checkPackageDbEnvVar "GHC" "GHC_PACKAGE_PATH" checkPackageDbStack :: PackageDBStack -> IO () checkPackageDbStack (GlobalPackageDB:rest) | GlobalPackageDB `notElem` rest = return () checkPackageDbStack rest | GlobalPackageDB `notElem` rest = die $ "With current ghc versions the global package db is always used " ++ "and must be listed first. This ghc limitation may be lifted in " ++ "future, see http://hackage.haskell.org/trac/ghc/ticket/5977" checkPackageDbStack _ = die $ "If the global package db is specified, it must be " ++ "specified first and cannot be specified multiple times" -- GHC < 6.10 put "$topdir/include/mingw" in rts's installDirs. This -- breaks when you want to use a different gcc, so we need to filter -- it out. removeMingwIncludeDir :: InstalledPackageInfo -> InstalledPackageInfo removeMingwIncludeDir pkg = let ids = InstalledPackageInfo.includeDirs pkg ids' = filter (not . ("mingw" `isSuffixOf`)) ids in pkg { InstalledPackageInfo.includeDirs = ids' } -- | Get the packages from specific PackageDBs, not cumulative. -- getInstalledPackages' :: Verbosity -> [PackageDB] -> ProgramConfiguration -> IO [(PackageDB, [InstalledPackageInfo])] getInstalledPackages' verbosity packagedbs conf | ghcVersion >= Version [6,9] [] = sequence [ do pkgs <- HcPkg.dump (hcPkgInfo conf) verbosity packagedb return (packagedb, pkgs) | packagedb <- packagedbs ] where Just ghcProg = lookupProgram ghcProgram conf Just ghcVersion = programVersion ghcProg getInstalledPackages' verbosity packagedbs conf = do str <- rawSystemProgramStdoutConf verbosity ghcPkgProgram conf ["list"] let pkgFiles = [ init line | line <- lines str, last line == ':' ] dbFile packagedb = case (packagedb, pkgFiles) of (GlobalPackageDB, global:_) -> return $ Just global (UserPackageDB, _global:user:_) -> return $ Just user (UserPackageDB, _global:_) -> return $ Nothing (SpecificPackageDB specific, _) -> return $ Just specific _ -> die "cannot read ghc-pkg package listing" pkgFiles' <- mapM dbFile packagedbs sequence [ withFileContents file $ \content -> do pkgs <- readPackages file content return (db, pkgs) | (db , Just file) <- zip packagedbs pkgFiles' ] where -- Depending on the version of ghc we use a different type's Read -- instance to parse the package file and then convert. -- It's a bit yuck. But that's what we get for using Read/Show. readPackages | ghcVersion >= Version [6,4,2] [] = \file content -> case reads content of [(pkgs, _)] -> return (map IPI642.toCurrent pkgs) _ -> failToRead file | otherwise = \file content -> case reads content of [(pkgs, _)] -> return (map IPI641.toCurrent pkgs) _ -> failToRead file Just ghcProg = lookupProgram ghcProgram conf Just ghcVersion = programVersion ghcProg failToRead file = die $ "cannot read ghc package database " ++ file -- ----------------------------------------------------------------------------- -- Building -- | Build a library with GHC. -- buildLib, replLib :: Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildLib = buildOrReplLib False replLib = buildOrReplLib True buildOrReplLib :: Bool -> Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildOrReplLib forRepl verbosity numJobs pkg_descr lbi lib clbi = do libName <- case componentLibraries clbi of [libName] -> return libName [] -> die "No library name found when building library" _ -> die "Multiple library names found when building library" let libTargetDir = buildDir lbi whenVanillaLib forceVanilla = when (forceVanilla || withVanillaLib lbi) whenProfLib = when (withProfLib lbi) whenSharedLib forceShared = when (forceShared || withSharedLib lbi) whenGHCiLib = when (withGHCiLib lbi && withVanillaLib lbi) ifReplLib = when forRepl comp = compiler lbi ghcVersion = compilerVersion comp implInfo = getImplInfo comp (Platform _hostArch hostOS) = hostPlatform lbi hole_insts = map (\(k,(p,n)) -> (k, (InstalledPackageInfo.packageKey p,n))) (instantiatedWith lbi) (ghcProg, _) <- requireProgram verbosity ghcProgram (withPrograms lbi) let runGhcProg = runGHC verbosity ghcProg comp libBi <- hackThreadedFlag verbosity comp (withProfLib lbi) (libBuildInfo lib) let isGhcDynamic = isDynamic comp dynamicTooSupported = supportsDynamicToo comp doingTH = EnableExtension TemplateHaskell `elem` allExtensions libBi forceVanillaLib = doingTH && not isGhcDynamic forceSharedLib = doingTH && isGhcDynamic -- TH always needs default libs, even when building for profiling -- Determine if program coverage should be enabled and if so, what -- '-hpcdir' should be. let isCoverageEnabled = fromFlag $ configCoverage $ configFlags lbi -- Component name. Not 'libName' because that has the "HS" prefix -- that GHC gives Haskell libraries. cname = display $ PD.package $ localPkgDescr lbi distPref = fromFlag $ configDistPref $ configFlags lbi hpcdir way | isCoverageEnabled = toFlag $ Hpc.mixDir distPref way cname | otherwise = mempty createDirectoryIfMissingVerbose verbosity True libTargetDir -- TODO: do we need to put hs-boot files into place for mutually recursive -- modules? let cObjs = map (`replaceExtension` objExtension) (cSources libBi) baseOpts = componentGhcOptions verbosity lbi libBi clbi libTargetDir vanillaOpts = baseOpts `mappend` mempty { ghcOptMode = toFlag GhcModeMake, ghcOptNumJobs = numJobs, ghcOptPackageKey = toFlag (pkgKey lbi), ghcOptSigOf = hole_insts, ghcOptInputModules = toNubListR $ libModules lib, ghcOptHPCDir = hpcdir Hpc.Vanilla } profOpts = vanillaOpts `mappend` mempty { ghcOptProfilingMode = toFlag True, ghcOptHiSuffix = toFlag "p_hi", ghcOptObjSuffix = toFlag "p_o", ghcOptExtra = toNubListR $ hcProfOptions GHC libBi, ghcOptHPCDir = hpcdir Hpc.Prof } sharedOpts = vanillaOpts `mappend` mempty { ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptFPic = toFlag True, ghcOptHiSuffix = toFlag "dyn_hi", ghcOptObjSuffix = toFlag "dyn_o", ghcOptExtra = toNubListR $ hcSharedOptions GHC libBi, ghcOptHPCDir = hpcdir Hpc.Dyn } linkerOpts = mempty { ghcOptLinkOptions = toNubListR $ PD.ldOptions libBi, ghcOptLinkLibs = toNubListR $ extraLibs libBi, ghcOptLinkLibPath = toNubListR $ extraLibDirs libBi, ghcOptLinkFrameworks = toNubListR $ PD.frameworks libBi, ghcOptInputFiles = toNubListR [libTargetDir </> x | x <- cObjs] } replOpts = vanillaOpts { ghcOptExtra = overNubListR Internal.filterGhciFlags $ (ghcOptExtra vanillaOpts), ghcOptNumJobs = mempty } `mappend` linkerOpts `mappend` mempty { ghcOptMode = toFlag GhcModeInteractive, ghcOptOptimisation = toFlag GhcNoOptimisation } vanillaSharedOpts = vanillaOpts `mappend` mempty { ghcOptDynLinkMode = toFlag GhcStaticAndDynamic, ghcOptDynHiSuffix = toFlag "dyn_hi", ghcOptDynObjSuffix = toFlag "dyn_o", ghcOptHPCDir = hpcdir Hpc.Dyn } unless (forRepl || null (libModules lib)) $ do let vanilla = whenVanillaLib forceVanillaLib (runGhcProg vanillaOpts) shared = whenSharedLib forceSharedLib (runGhcProg sharedOpts) useDynToo = dynamicTooSupported && (forceVanillaLib || withVanillaLib lbi) && (forceSharedLib || withSharedLib lbi) && null (hcSharedOptions GHC libBi) if useDynToo then do runGhcProg vanillaSharedOpts case (hpcdir Hpc.Dyn, hpcdir Hpc.Vanilla) of (Cabal.Flag dynDir, Cabal.Flag vanillaDir) -> do -- When the vanilla and shared library builds are done -- in one pass, only one set of HPC module interfaces -- are generated. This set should suffice for both -- static and dynamically linked executables. We copy -- the modules interfaces so they are available under -- both ways. copyDirectoryRecursive verbosity dynDir vanillaDir _ -> return () else if isGhcDynamic then do shared; vanilla else do vanilla; shared whenProfLib (runGhcProg profOpts) -- build any C sources unless (null (cSources libBi)) $ do info verbosity "Building C Sources..." sequence_ [ do let baseCcOpts = Internal.componentCcGhcOptions verbosity implInfo lbi libBi clbi libTargetDir filename vanillaCcOpts = if isGhcDynamic -- Dynamic GHC requires C sources to be built -- with -fPIC for REPL to work. See #2207. then baseCcOpts { ghcOptFPic = toFlag True } else baseCcOpts profCcOpts = vanillaCcOpts `mappend` mempty { ghcOptProfilingMode = toFlag True, ghcOptObjSuffix = toFlag "p_o" } sharedCcOpts = vanillaCcOpts `mappend` mempty { ghcOptFPic = toFlag True, ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptObjSuffix = toFlag "dyn_o" } odir = fromFlag (ghcOptObjDir vanillaCcOpts) createDirectoryIfMissingVerbose verbosity True odir runGhcProg vanillaCcOpts unless forRepl $ whenSharedLib forceSharedLib (runGhcProg sharedCcOpts) unless forRepl $ whenProfLib (runGhcProg profCcOpts) | filename <- cSources libBi] -- TODO: problem here is we need the .c files built first, so we can load them -- with ghci, but .c files can depend on .h files generated by ghc by ffi -- exports. ifReplLib $ do when (null (libModules lib)) $ warn verbosity "No exposed modules" ifReplLib (runGhcProg replOpts) -- link: unless forRepl $ do info verbosity "Linking..." let cProfObjs = map (`replaceExtension` ("p_" ++ objExtension)) (cSources libBi) cSharedObjs = map (`replaceExtension` ("dyn_" ++ objExtension)) (cSources libBi) cid = compilerId (compiler lbi) vanillaLibFilePath = libTargetDir </> mkLibName libName profileLibFilePath = libTargetDir </> mkProfLibName libName sharedLibFilePath = libTargetDir </> mkSharedLibName cid libName ghciLibFilePath = libTargetDir </> Internal.mkGHCiLibName libName libInstallPath = libdir $ absoluteInstallDirs pkg_descr lbi NoCopyDest sharedLibInstallPath = libInstallPath </> mkSharedLibName cid libName stubObjs <- fmap catMaybes $ sequence [ findFileWithExtension [objExtension] [libTargetDir] (ModuleName.toFilePath x ++"_stub") | ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files , x <- libModules lib ] stubProfObjs <- fmap catMaybes $ sequence [ findFileWithExtension ["p_" ++ objExtension] [libTargetDir] (ModuleName.toFilePath x ++"_stub") | ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files , x <- libModules lib ] stubSharedObjs <- fmap catMaybes $ sequence [ findFileWithExtension ["dyn_" ++ objExtension] [libTargetDir] (ModuleName.toFilePath x ++"_stub") | ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files , x <- libModules lib ] hObjs <- Internal.getHaskellObjects implInfo lib lbi libTargetDir objExtension True hProfObjs <- if (withProfLib lbi) then Internal.getHaskellObjects implInfo lib lbi libTargetDir ("p_" ++ objExtension) True else return [] hSharedObjs <- if (withSharedLib lbi) then Internal.getHaskellObjects implInfo lib lbi libTargetDir ("dyn_" ++ objExtension) False else return [] unless (null hObjs && null cObjs && null stubObjs) $ do rpaths <- getRPaths lbi clbi let staticObjectFiles = hObjs ++ map (libTargetDir </>) cObjs ++ stubObjs profObjectFiles = hProfObjs ++ map (libTargetDir </>) cProfObjs ++ stubProfObjs ghciObjFiles = hObjs ++ map (libTargetDir </>) cObjs ++ stubObjs dynamicObjectFiles = hSharedObjs ++ map (libTargetDir </>) cSharedObjs ++ stubSharedObjs -- After the relocation lib is created we invoke ghc -shared -- with the dependencies spelled out as -package arguments -- and ghc invokes the linker with the proper library paths ghcSharedLinkArgs = mempty { ghcOptShared = toFlag True, ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptInputFiles = toNubListR dynamicObjectFiles, ghcOptOutputFile = toFlag sharedLibFilePath, -- For dynamic libs, Mac OS/X needs to know the install location -- at build time. This only applies to GHC < 7.8 - see the -- discussion in #1660. ghcOptDylibName = if (hostOS == OSX && ghcVersion < Version [7,8] []) then toFlag sharedLibInstallPath else mempty, ghcOptPackageKey = toFlag (pkgKey lbi), ghcOptNoAutoLinkPackages = toFlag True, ghcOptPackageDBs = withPackageDB lbi, ghcOptPackages = toNubListR $ Internal.mkGhcOptPackages clbi , ghcOptLinkLibs = toNubListR $ extraLibs libBi, ghcOptLinkLibPath = toNubListR $ extraLibDirs libBi, ghcOptRPaths = rpaths } info verbosity (show (ghcOptPackages ghcSharedLinkArgs)) whenVanillaLib False $ do Ar.createArLibArchive verbosity lbi vanillaLibFilePath staticObjectFiles whenProfLib $ do Ar.createArLibArchive verbosity lbi profileLibFilePath profObjectFiles whenGHCiLib $ do (ldProg, _) <- requireProgram verbosity ldProgram (withPrograms lbi) Ld.combineObjectFiles verbosity ldProg ghciLibFilePath ghciObjFiles whenSharedLib False $ runGhcProg ghcSharedLinkArgs -- | Start a REPL without loading any source files. startInterpreter :: Verbosity -> ProgramConfiguration -> Compiler -> PackageDBStack -> IO () startInterpreter verbosity conf comp packageDBs = do let replOpts = mempty { ghcOptMode = toFlag GhcModeInteractive, ghcOptPackageDBs = packageDBs } checkPackageDbStack packageDBs (ghcProg, _) <- requireProgram verbosity ghcProgram conf runGHC verbosity ghcProg comp replOpts -- | Build an executable with GHC. -- buildExe, replExe :: Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO () buildExe = buildOrReplExe False replExe = buildOrReplExe True buildOrReplExe :: Bool -> Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO () buildOrReplExe forRepl verbosity numJobs _pkg_descr lbi exe@Executable { exeName = exeName', modulePath = modPath } clbi = do (ghcProg, _) <- requireProgram verbosity ghcProgram (withPrograms lbi) let comp = compiler lbi implInfo = getImplInfo comp runGhcProg = runGHC verbosity ghcProg comp exeBi <- hackThreadedFlag verbosity comp (withProfExe lbi) (buildInfo exe) -- exeNameReal, the name that GHC really uses (with .exe on Windows) let exeNameReal = exeName' <.> (if takeExtension exeName' /= ('.':exeExtension) then exeExtension else "") let targetDir = (buildDir lbi) </> exeName' let exeDir = targetDir </> (exeName' ++ "-tmp") createDirectoryIfMissingVerbose verbosity True targetDir createDirectoryIfMissingVerbose verbosity True exeDir -- TODO: do we need to put hs-boot files into place for mutually recursive -- modules? FIX: what about exeName.hi-boot? -- Determine if program coverage should be enabled and if so, what -- '-hpcdir' should be. let isCoverageEnabled = fromFlag $ configCoverage $ configFlags lbi distPref = fromFlag $ configDistPref $ configFlags lbi hpcdir way | isCoverageEnabled = toFlag $ Hpc.mixDir distPref way exeName' | otherwise = mempty -- build executables srcMainFile <- findFile (exeDir : hsSourceDirs exeBi) modPath rpaths <- getRPaths lbi clbi let isGhcDynamic = isDynamic comp dynamicTooSupported = supportsDynamicToo comp isHaskellMain = elem (takeExtension srcMainFile) [".hs", ".lhs"] cSrcs = cSources exeBi ++ [srcMainFile | not isHaskellMain] cObjs = map (`replaceExtension` objExtension) cSrcs baseOpts = (componentGhcOptions verbosity lbi exeBi clbi exeDir) `mappend` mempty { ghcOptMode = toFlag GhcModeMake, ghcOptInputFiles = toNubListR [ srcMainFile | isHaskellMain], ghcOptInputModules = toNubListR [ m | not isHaskellMain, m <- exeModules exe] } staticOpts = baseOpts `mappend` mempty { ghcOptDynLinkMode = toFlag GhcStaticOnly, ghcOptHPCDir = hpcdir Hpc.Vanilla } profOpts = baseOpts `mappend` mempty { ghcOptProfilingMode = toFlag True, ghcOptHiSuffix = toFlag "p_hi", ghcOptObjSuffix = toFlag "p_o", ghcOptExtra = toNubListR $ hcProfOptions GHC exeBi, ghcOptHPCDir = hpcdir Hpc.Prof } dynOpts = baseOpts `mappend` mempty { ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptHiSuffix = toFlag "dyn_hi", ghcOptObjSuffix = toFlag "dyn_o", ghcOptExtra = toNubListR $ hcSharedOptions GHC exeBi, ghcOptHPCDir = hpcdir Hpc.Dyn } dynTooOpts = staticOpts `mappend` mempty { ghcOptDynLinkMode = toFlag GhcStaticAndDynamic, ghcOptDynHiSuffix = toFlag "dyn_hi", ghcOptDynObjSuffix = toFlag "dyn_o", ghcOptHPCDir = hpcdir Hpc.Dyn } linkerOpts = mempty { ghcOptLinkOptions = toNubListR $ PD.ldOptions exeBi, ghcOptLinkLibs = toNubListR $ extraLibs exeBi, ghcOptLinkLibPath = toNubListR $ extraLibDirs exeBi, ghcOptLinkFrameworks = toNubListR $ PD.frameworks exeBi, ghcOptInputFiles = toNubListR [exeDir </> x | x <- cObjs], ghcOptRPaths = rpaths } replOpts = baseOpts { ghcOptExtra = overNubListR Internal.filterGhciFlags (ghcOptExtra baseOpts) } -- For a normal compile we do separate invocations of ghc for -- compiling as for linking. But for repl we have to do just -- the one invocation, so that one has to include all the -- linker stuff too, like -l flags and any .o files from C -- files etc. `mappend` linkerOpts `mappend` mempty { ghcOptMode = toFlag GhcModeInteractive, ghcOptOptimisation = toFlag GhcNoOptimisation } commonOpts | withProfExe lbi = profOpts | withDynExe lbi = dynOpts | otherwise = staticOpts compileOpts | useDynToo = dynTooOpts | otherwise = commonOpts withStaticExe = (not $ withProfExe lbi) && (not $ withDynExe lbi) -- For building exe's that use TH with -prof or -dynamic we actually have -- to build twice, once without -prof/-dynamic and then again with -- -prof/-dynamic. This is because the code that TH needs to run at -- compile time needs to be the vanilla ABI so it can be loaded up and run -- by the compiler. -- With dynamic-by-default GHC the TH object files loaded at compile-time -- need to be .dyn_o instead of .o. doingTH = EnableExtension TemplateHaskell `elem` allExtensions exeBi -- Should we use -dynamic-too instead of compiling twice? useDynToo = dynamicTooSupported && isGhcDynamic && doingTH && withStaticExe && null (hcSharedOptions GHC exeBi) compileTHOpts | isGhcDynamic = dynOpts | otherwise = staticOpts compileForTH | forRepl = False | useDynToo = False | isGhcDynamic = doingTH && (withProfExe lbi || withStaticExe) | otherwise = doingTH && (withProfExe lbi || withDynExe lbi) linkOpts = commonOpts `mappend` linkerOpts `mappend` mempty { ghcOptLinkNoHsMain = toFlag (not isHaskellMain) } -- Build static/dynamic object files for TH, if needed. when compileForTH $ runGhcProg compileTHOpts { ghcOptNoLink = toFlag True , ghcOptNumJobs = numJobs } unless forRepl $ runGhcProg compileOpts { ghcOptNoLink = toFlag True , ghcOptNumJobs = numJobs } -- build any C sources unless (null cSrcs) $ do info verbosity "Building C Sources..." sequence_ [ do let opts = (Internal.componentCcGhcOptions verbosity implInfo lbi exeBi clbi exeDir filename) `mappend` mempty { ghcOptDynLinkMode = toFlag (if withDynExe lbi then GhcDynamicOnly else GhcStaticOnly), ghcOptProfilingMode = toFlag (withProfExe lbi) } odir = fromFlag (ghcOptObjDir opts) createDirectoryIfMissingVerbose verbosity True odir runGhcProg opts | filename <- cSrcs ] -- TODO: problem here is we need the .c files built first, so we can load them -- with ghci, but .c files can depend on .h files generated by ghc by ffi -- exports. when forRepl $ runGhcProg replOpts -- link: unless forRepl $ do info verbosity "Linking..." runGhcProg linkOpts { ghcOptOutputFile = toFlag (targetDir </> exeNameReal) } -- | Calculate the RPATHs for the component we are building. -- -- Calculates relative RPATHs when 'relocatable' is set. getRPaths :: LocalBuildInfo -> ComponentLocalBuildInfo -- ^ Component we are building -> IO (NubListR FilePath) getRPaths lbi clbi | supportRPaths hostOS = do libraryPaths <- depLibraryPaths False (relocatable lbi) lbi clbi let hostPref = case hostOS of OSX -> "@loader_path" _ -> "$ORIGIN" relPath p = if isRelative p then hostPref </> p else p rpaths = toNubListR (map relPath libraryPaths) return rpaths where (Platform _ hostOS) = hostPlatform lbi -- The list of RPath-supported operating systems below reflects the -- platforms on which Cabal's RPATH handling is tested. It does _NOT_ -- reflect whether the OS supports RPATH. -- E.g. when this comment was written, the *BSD operating systems were -- untested with regards to Cabal RPATH handling, and were hence set to -- 'False', while those operating systems themselves do support RPATH. supportRPaths Linux   = True supportRPaths Windows = False supportRPaths OSX   = True supportRPaths FreeBSD   = False supportRPaths OpenBSD   = False supportRPaths NetBSD   = False supportRPaths DragonFly = False supportRPaths Solaris = False supportRPaths AIX = False supportRPaths HPUX = False supportRPaths IRIX = False supportRPaths HaLVM = False supportRPaths IOS = False supportRPaths Android = False supportRPaths Ghcjs = False supportRPaths Hurd = False supportRPaths (OtherOS _) = False -- Do _not_ add a default case so that we get a warning here when a new OS -- is added. getRPaths _ _ = return mempty -- | Filter the "-threaded" flag when profiling as it does not -- work with ghc-6.8 and older. hackThreadedFlag :: Verbosity -> Compiler -> Bool -> BuildInfo -> IO BuildInfo hackThreadedFlag verbosity comp prof bi | not mustFilterThreaded = return bi | otherwise = do warn verbosity $ "The ghc flag '-threaded' is not compatible with " ++ "profiling in ghc-6.8 and older. It will be disabled." return bi { options = filterHcOptions (/= "-threaded") (options bi) } where mustFilterThreaded = prof && compilerVersion comp < Version [6, 10] [] && "-threaded" `elem` hcOptions GHC bi filterHcOptions p hcoptss = [ (hc, if hc == GHC then filter p opts else opts) | (hc, opts) <- hcoptss ] -- | Extracts a String representing a hash of the ABI of a built -- library. It can fail if the library has not yet been built. -- libAbiHash :: Verbosity -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO String libAbiHash verbosity _pkg_descr lbi lib clbi = do libBi <- hackThreadedFlag verbosity (compiler lbi) (withProfLib lbi) (libBuildInfo lib) let comp = compiler lbi vanillaArgs = (componentGhcOptions verbosity lbi libBi clbi (buildDir lbi)) `mappend` mempty { ghcOptMode = toFlag GhcModeAbiHash, ghcOptPackageKey = toFlag (pkgKey lbi), ghcOptInputModules = toNubListR $ exposedModules lib } sharedArgs = vanillaArgs `mappend` mempty { ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptFPic = toFlag True, ghcOptHiSuffix = toFlag "dyn_hi", ghcOptObjSuffix = toFlag "dyn_o", ghcOptExtra = toNubListR $ hcSharedOptions GHC libBi } profArgs = vanillaArgs `mappend` mempty { ghcOptProfilingMode = toFlag True, ghcOptHiSuffix = toFlag "p_hi", ghcOptObjSuffix = toFlag "p_o", ghcOptExtra = toNubListR $ hcProfOptions GHC libBi } ghcArgs = if withVanillaLib lbi then vanillaArgs else if withSharedLib lbi then sharedArgs else if withProfLib lbi then profArgs else error "libAbiHash: Can't find an enabled library way" -- (ghcProg, _) <- requireProgram verbosity ghcProgram (withPrograms lbi) hash <- getProgramInvocationOutput verbosity (ghcInvocation ghcProg comp ghcArgs) return (takeWhile (not . isSpace) hash) componentGhcOptions :: Verbosity -> LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> GhcOptions componentGhcOptions = Internal.componentGhcOptions componentCcGhcOptions :: Verbosity -> LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> FilePath -> GhcOptions componentCcGhcOptions verbosity lbi = Internal.componentCcGhcOptions verbosity implInfo lbi where comp = compiler lbi implInfo = getImplInfo comp -- ----------------------------------------------------------------------------- -- Installing -- |Install executables for GHC. installExe :: Verbosity -> LocalBuildInfo -> InstallDirs FilePath -- ^Where to copy the files to -> FilePath -- ^Build location -> (FilePath, FilePath) -- ^Executable (prefix,suffix) -> PackageDescription -> Executable -> IO () installExe verbosity lbi installDirs buildPref (progprefix, progsuffix) _pkg exe = do let binDir = bindir installDirs createDirectoryIfMissingVerbose verbosity True binDir let exeFileName = exeName exe <.> exeExtension fixedExeBaseName = progprefix ++ exeName exe ++ progsuffix installBinary dest = do installExecutableFile verbosity (buildPref </> exeName exe </> exeFileName) (dest <.> exeExtension) when (stripExes lbi) $ Strip.stripExe verbosity (hostPlatform lbi) (withPrograms lbi) (dest <.> exeExtension) installBinary (binDir </> fixedExeBaseName) -- |Install for ghc, .hi, .a and, if --with-ghci given, .o installLib :: Verbosity -> LocalBuildInfo -> FilePath -- ^install location -> FilePath -- ^install location for dynamic libraries -> FilePath -- ^Build location -> PackageDescription -> Library -> ComponentLocalBuildInfo -> IO () installLib verbosity lbi targetDir dynlibTargetDir builtDir _pkg lib clbi = do -- copy .hi files over: whenVanilla $ copyModuleFiles "hi" whenProf $ copyModuleFiles "p_hi" whenShared $ copyModuleFiles "dyn_hi" -- copy the built library files over: whenVanilla $ mapM_ (installOrdinary builtDir targetDir) vanillaLibNames whenProf $ mapM_ (installOrdinary builtDir targetDir) profileLibNames whenGHCi $ mapM_ (installOrdinary builtDir targetDir) ghciLibNames whenShared $ mapM_ (installShared builtDir dynlibTargetDir) sharedLibNames where install isShared srcDir dstDir name = do let src = srcDir </> name dst = dstDir </> name createDirectoryIfMissingVerbose verbosity True dstDir if isShared then do when (stripLibs lbi) $ Strip.stripLib verbosity (hostPlatform lbi) (withPrograms lbi) src installExecutableFile verbosity src dst else installOrdinaryFile verbosity src dst installOrdinary = install False installShared = install True copyModuleFiles ext = findModuleFiles [builtDir] [ext] (libModules lib) >>= installOrdinaryFiles verbosity targetDir cid = compilerId (compiler lbi) libNames = componentLibraries clbi vanillaLibNames = map mkLibName libNames profileLibNames = map mkProfLibName libNames ghciLibNames = map Internal.mkGHCiLibName libNames sharedLibNames = map (mkSharedLibName cid) libNames hasLib = not $ null (libModules lib) && null (cSources (libBuildInfo lib)) whenVanilla = when (hasLib && withVanillaLib lbi) whenProf = when (hasLib && withProfLib lbi) whenGHCi = when (hasLib && withGHCiLib lbi) whenShared = when (hasLib && withSharedLib lbi) -- ----------------------------------------------------------------------------- -- Registering hcPkgInfo :: ProgramConfiguration -> HcPkg.HcPkgInfo hcPkgInfo conf = HcPkg.HcPkgInfo { HcPkg.hcPkgProgram = ghcPkgProg , HcPkg.noPkgDbStack = v < [6,9] , HcPkg.noVerboseFlag = v < [6,11] , HcPkg.flagPackageConf = v < [7,5] , HcPkg.useSingleFileDb = v < [7,9] } where v = versionBranch ver Just ghcPkgProg = lookupProgram ghcPkgProgram conf Just ver = programVersion ghcPkgProg registerPackage :: Verbosity -> InstalledPackageInfo -> PackageDescription -> LocalBuildInfo -> Bool -> PackageDBStack -> IO () registerPackage verbosity installedPkgInfo _pkg lbi _inplace packageDbs = HcPkg.reregister (hcPkgInfo $ withPrograms lbi) verbosity packageDbs (Right installedPkgInfo) pkgRoot :: Verbosity -> LocalBuildInfo -> PackageDB -> IO FilePath pkgRoot verbosity lbi = pkgRoot' where pkgRoot' GlobalPackageDB = let Just ghcProg = lookupProgram ghcProgram (withPrograms lbi) in fmap takeDirectory (getGlobalPackageDB verbosity ghcProg) pkgRoot' UserPackageDB = do appDir <- getAppUserDataDirectory "ghc" let ver = compilerVersion (compiler lbi) subdir = System.Info.arch ++ '-':System.Info.os ++ '-':showVersion ver rootDir = appDir </> subdir -- We must create the root directory for the user package database if it -- does not yet exists. Otherwise '${pkgroot}' will resolve to a -- directory at the time of 'ghc-pkg register', and registration will -- fail. createDirectoryIfMissing True rootDir return rootDir pkgRoot' (SpecificPackageDB fp) = return (takeDirectory fp) -- ----------------------------------------------------------------------------- -- Utils isDynamic :: Compiler -> Bool isDynamic = Internal.ghcLookupProperty "GHC Dynamic" supportsDynamicToo :: Compiler -> Bool supportsDynamicToo = Internal.ghcLookupProperty "Support dynamic-too"
seereason/cabal
Cabal/Distribution/Simple/GHC.hs
Haskell
bsd-3-clause
50,626
-- (c) The University of Glasgow, 1997-2006 {-# LANGUAGE BangPatterns, CPP, MagicHash, UnboxedTuples, GeneralizedNewtypeDeriving #-} {-# OPTIONS_GHC -O -funbox-strict-fields #-} -- We always optimise this, otherwise performance of a non-optimised -- compiler is severely affected -- | -- There are two principal string types used internally by GHC: -- -- ['FastString'] -- -- * A compact, hash-consed, representation of character strings. -- * Comparison is O(1), and you can get a 'Unique.Unique' from them. -- * Generated by 'fsLit'. -- * Turn into 'Outputable.SDoc' with 'Outputable.ftext'. -- -- ['LitString'] -- -- * Just a wrapper for the @Addr#@ of a C string (@Ptr CChar@). -- * Practically no operations. -- * Outputing them is fast. -- * Generated by 'sLit'. -- * Turn into 'Outputable.SDoc' with 'Outputable.ptext' -- * Requires manual memory management. -- Improper use may lead to memory leaks or dangling pointers. -- * It assumes Latin-1 as the encoding, therefore it cannot represent -- arbitrary Unicode strings. -- -- Use 'LitString' unless you want the facilities of 'FastString'. module FastString ( -- * ByteString fastStringToByteString, mkFastStringByteString, fastZStringToByteString, unsafeMkByteString, hashByteString, -- * FastZString FastZString, hPutFZS, zString, lengthFZS, -- * FastStrings FastString(..), -- not abstract, for now. -- ** Construction fsLit, mkFastString, mkFastStringBytes, mkFastStringByteList, mkFastStringForeignPtr, mkFastString#, -- ** Deconstruction unpackFS, -- :: FastString -> String bytesFS, -- :: FastString -> [Word8] -- ** Encoding zEncodeFS, -- ** Operations uniqueOfFS, lengthFS, nullFS, appendFS, headFS, tailFS, concatFS, consFS, nilFS, -- ** Outputing hPutFS, -- ** Internal getFastStringTable, hasZEncoding, -- * LitStrings LitString, -- ** Construction sLit, mkLitString#, mkLitString, -- ** Deconstruction unpackLitString, -- ** Operations lengthLS ) where #include "HsVersions.h" import Encoding import FastFunctions import Panic import Util import Control.DeepSeq import Control.Monad import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Internal as BS import qualified Data.ByteString.Unsafe as BS import Foreign.C import GHC.Exts import System.IO import System.IO.Unsafe ( unsafePerformIO ) import Data.Data import Data.IORef ( IORef, newIORef, readIORef, atomicModifyIORef' ) import Data.Maybe ( isJust ) import Data.Char import Data.List ( elemIndex ) import GHC.IO ( IO(..), unsafeDupablePerformIO ) import Foreign #if STAGE >= 2 import GHC.Conc.Sync (sharedCAF) #endif import GHC.Base ( unpackCString# ) #define hASH_TBL_SIZE 4091 #define hASH_TBL_SIZE_UNBOXED 4091# fastStringToByteString :: FastString -> ByteString fastStringToByteString f = fs_bs f fastZStringToByteString :: FastZString -> ByteString fastZStringToByteString (FastZString bs) = bs -- This will drop information if any character > '\xFF' unsafeMkByteString :: String -> ByteString unsafeMkByteString = BSC.pack hashByteString :: ByteString -> Int hashByteString bs = inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(ptr, len) -> return $ hashStr (castPtr ptr) len -- ----------------------------------------------------------------------------- newtype FastZString = FastZString ByteString deriving NFData hPutFZS :: Handle -> FastZString -> IO () hPutFZS handle (FastZString bs) = BS.hPut handle bs zString :: FastZString -> String zString (FastZString bs) = inlinePerformIO $ BS.unsafeUseAsCStringLen bs peekCAStringLen lengthFZS :: FastZString -> Int lengthFZS (FastZString bs) = BS.length bs mkFastZStringString :: String -> FastZString mkFastZStringString str = FastZString (BSC.pack str) -- ----------------------------------------------------------------------------- {-| A 'FastString' is an array of bytes, hashed to support fast O(1) comparison. It is also associated with a character encoding, so that we know how to convert a 'FastString' to the local encoding, or to the Z-encoding used by the compiler internally. 'FastString's support a memoized conversion to the Z-encoding via zEncodeFS. -} data FastString = FastString { uniq :: {-# UNPACK #-} !Int, -- unique id n_chars :: {-# UNPACK #-} !Int, -- number of chars fs_bs :: {-# UNPACK #-} !ByteString, fs_ref :: {-# UNPACK #-} !(IORef (Maybe FastZString)) } instance Eq FastString where f1 == f2 = uniq f1 == uniq f2 instance Ord FastString where -- Compares lexicographically, not by unique a <= b = case cmpFS a b of { LT -> True; EQ -> True; GT -> False } a < b = case cmpFS a b of { LT -> True; EQ -> False; GT -> False } a >= b = case cmpFS a b of { LT -> False; EQ -> True; GT -> True } a > b = case cmpFS a b of { LT -> False; EQ -> False; GT -> True } max x y | x >= y = x | otherwise = y min x y | x <= y = x | otherwise = y compare a b = cmpFS a b instance IsString FastString where fromString = fsLit instance Monoid FastString where mempty = nilFS mappend = appendFS mconcat = concatFS instance Show FastString where show fs = show (unpackFS fs) instance Data FastString where -- don't traverse? toConstr _ = abstractConstr "FastString" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "FastString" cmpFS :: FastString -> FastString -> Ordering cmpFS f1@(FastString u1 _ _ _) f2@(FastString u2 _ _ _) = if u1 == u2 then EQ else compare (fastStringToByteString f1) (fastStringToByteString f2) foreign import ccall unsafe "ghc_memcmp" memcmp :: Ptr a -> Ptr b -> Int -> IO Int -- ----------------------------------------------------------------------------- -- Construction {- Internally, the compiler will maintain a fast string symbol table, providing sharing and fast comparison. Creation of new @FastString@s then covertly does a lookup, re-using the @FastString@ if there was a hit. The design of the FastString hash table allows for lockless concurrent reads and updates to multiple buckets with low synchronization overhead. See Note [Updating the FastString table] on how it's updated. -} data FastStringTable = FastStringTable {-# UNPACK #-} !(IORef Int) -- the unique ID counter shared with all buckets (MutableArray# RealWorld (IORef [FastString])) -- the array of mutable buckets string_table :: FastStringTable {-# NOINLINE string_table #-} string_table = unsafePerformIO $ do uid <- newIORef 603979776 -- ord '$' * 0x01000000 tab <- IO $ \s1# -> case newArray# hASH_TBL_SIZE_UNBOXED (panic "string_table") s1# of (# s2#, arr# #) -> (# s2#, FastStringTable uid arr# #) forM_ [0.. hASH_TBL_SIZE-1] $ \i -> do bucket <- newIORef [] updTbl tab i bucket -- use the support wired into the RTS to share this CAF among all images of -- libHSghc #if STAGE < 2 return tab #else sharedCAF tab getOrSetLibHSghcFastStringTable -- from the RTS; thus we cannot use this mechanism when STAGE<2; the previous -- RTS might not have this symbol foreign import ccall unsafe "getOrSetLibHSghcFastStringTable" getOrSetLibHSghcFastStringTable :: Ptr a -> IO (Ptr a) #endif {- We include the FastString table in the `sharedCAF` mechanism because we'd like FastStrings created by a Core plugin to have the same uniques as corresponding strings created by the host compiler itself. For example, this allows plugins to lookup known names (eg `mkTcOcc "MySpecialType"`) in the GlobalRdrEnv or even re-invoke the parser. In particular, the following little sanity test was failing in a plugin prototyping safe newtype-coercions: GHC.NT.Type.NT was imported, but could not be looked up /by the plugin/. let rdrName = mkModuleName "GHC.NT.Type" `mkRdrQual` mkTcOcc "NT" putMsgS $ showSDoc dflags $ ppr $ lookupGRE_RdrName rdrName $ mg_rdr_env guts `mkTcOcc` involves the lookup (or creation) of a FastString. Since the plugin's FastString.string_table is empty, constructing the RdrName also allocates new uniques for the FastStrings "GHC.NT.Type" and "NT". These uniques are almost certainly unequal to the ones that the host compiler originally assigned to those FastStrings. Thus the lookup fails since the domain of the GlobalRdrEnv is affected by the RdrName's OccName's FastString's unique. Maintaining synchronization of the two instances of this global is rather difficult because of the uses of `unsafePerformIO` in this module. Not synchronizing them risks breaking the rather major invariant that two FastStrings with the same unique have the same string. Thus we use the lower-level `sharedCAF` mechanism that relies on Globals.c. -} lookupTbl :: FastStringTable -> Int -> IO (IORef [FastString]) lookupTbl (FastStringTable _ arr#) (I# i#) = IO $ \ s# -> readArray# arr# i# s# updTbl :: FastStringTable -> Int -> IORef [FastString] -> IO () updTbl (FastStringTable _uid arr#) (I# i#) ls = do (IO $ \ s# -> case writeArray# arr# i# ls s# of { s2# -> (# s2#, () #) }) mkFastString# :: Addr# -> FastString mkFastString# a# = mkFastStringBytes ptr (ptrStrLength ptr) where ptr = Ptr a# {- Note [Updating the FastString table] The procedure goes like this: 1. Read the relevant bucket and perform a look up of the string. 2. If it exists, return it. 3. Otherwise grab a unique ID, create a new FastString and atomically attempt to update the relevant bucket with this FastString: * Double check that the string is not in the bucket. Another thread may have inserted it while we were creating our string. * Return the existing FastString if it exists. The one we preemptively created will get GCed. * Otherwise, insert and return the string we created. -} {- Note [Double-checking the bucket] It is not necessary to check the entire bucket the second time. We only have to check the strings that are new to the bucket since the last time we read it. -} mkFastStringWith :: (Int -> IO FastString) -> Ptr Word8 -> Int -> IO FastString mkFastStringWith mk_fs !ptr !len = do let hash = hashStr ptr len bucket <- lookupTbl string_table hash ls1 <- readIORef bucket res <- bucket_match ls1 len ptr case res of Just v -> return v Nothing -> do n <- get_uid new_fs <- mk_fs n atomicModifyIORef' bucket $ \ls2 -> -- Note [Double-checking the bucket] let delta_ls = case ls1 of [] -> ls2 l:_ -> case l `elemIndex` ls2 of Nothing -> panic "mkFastStringWith" Just idx -> take idx ls2 -- NB: Might as well use inlinePerformIO, since the call to -- bucket_match doesn't perform any IO that could be floated -- out of this closure or erroneously duplicated. in case inlinePerformIO (bucket_match delta_ls len ptr) of Nothing -> (new_fs:ls2, new_fs) Just fs -> (ls2,fs) where !(FastStringTable uid _arr) = string_table get_uid = atomicModifyIORef' uid $ \n -> (n+1,n) mkFastStringBytes :: Ptr Word8 -> Int -> FastString mkFastStringBytes !ptr !len = -- NB: Might as well use unsafeDupablePerformIO, since mkFastStringWith is -- idempotent. unsafeDupablePerformIO $ mkFastStringWith (copyNewFastString ptr len) ptr len -- | Create a 'FastString' from an existing 'ForeignPtr'; the difference -- between this and 'mkFastStringBytes' is that we don't have to copy -- the bytes if the string is new to the table. mkFastStringForeignPtr :: Ptr Word8 -> ForeignPtr Word8 -> Int -> IO FastString mkFastStringForeignPtr ptr !fp len = mkFastStringWith (mkNewFastString fp ptr len) ptr len -- | Create a 'FastString' from an existing 'ForeignPtr'; the difference -- between this and 'mkFastStringBytes' is that we don't have to copy -- the bytes if the string is new to the table. mkFastStringByteString :: ByteString -> FastString mkFastStringByteString bs = inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(ptr, len) -> do let ptr' = castPtr ptr mkFastStringWith (mkNewFastStringByteString bs ptr' len) ptr' len -- | Creates a UTF-8 encoded 'FastString' from a 'String' mkFastString :: String -> FastString mkFastString str = inlinePerformIO $ do let l = utf8EncodedLength str buf <- mallocForeignPtrBytes l withForeignPtr buf $ \ptr -> do utf8EncodeString ptr str mkFastStringForeignPtr ptr buf l -- | Creates a 'FastString' from a UTF-8 encoded @[Word8]@ mkFastStringByteList :: [Word8] -> FastString mkFastStringByteList str = inlinePerformIO $ do let l = Prelude.length str buf <- mallocForeignPtrBytes l withForeignPtr buf $ \ptr -> do pokeArray (castPtr ptr) str mkFastStringForeignPtr ptr buf l -- | Creates a Z-encoded 'FastString' from a 'String' mkZFastString :: String -> FastZString mkZFastString = mkFastZStringString bucket_match :: [FastString] -> Int -> Ptr Word8 -> IO (Maybe FastString) bucket_match [] _ _ = return Nothing bucket_match (v@(FastString _ _ bs _):ls) len ptr | len == BS.length bs = do b <- BS.unsafeUseAsCString bs $ \buf -> cmpStringPrefix ptr (castPtr buf) len if b then return (Just v) else bucket_match ls len ptr | otherwise = bucket_match ls len ptr mkNewFastString :: ForeignPtr Word8 -> Ptr Word8 -> Int -> Int -> IO FastString mkNewFastString fp ptr len uid = do ref <- newIORef Nothing n_chars <- countUTF8Chars ptr len return (FastString uid n_chars (BS.fromForeignPtr fp 0 len) ref) mkNewFastStringByteString :: ByteString -> Ptr Word8 -> Int -> Int -> IO FastString mkNewFastStringByteString bs ptr len uid = do ref <- newIORef Nothing n_chars <- countUTF8Chars ptr len return (FastString uid n_chars bs ref) copyNewFastString :: Ptr Word8 -> Int -> Int -> IO FastString copyNewFastString ptr len uid = do fp <- copyBytesToForeignPtr ptr len ref <- newIORef Nothing n_chars <- countUTF8Chars ptr len return (FastString uid n_chars (BS.fromForeignPtr fp 0 len) ref) copyBytesToForeignPtr :: Ptr Word8 -> Int -> IO (ForeignPtr Word8) copyBytesToForeignPtr ptr len = do fp <- mallocForeignPtrBytes len withForeignPtr fp $ \ptr' -> copyBytes ptr' ptr len return fp cmpStringPrefix :: Ptr Word8 -> Ptr Word8 -> Int -> IO Bool cmpStringPrefix ptr1 ptr2 len = do r <- memcmp ptr1 ptr2 len return (r == 0) hashStr :: Ptr Word8 -> Int -> Int -- use the Addr to produce a hash value between 0 & m (inclusive) hashStr (Ptr a#) (I# len#) = loop 0# 0# where loop h n | isTrue# (n ==# len#) = I# h | otherwise = loop h2 (n +# 1#) where !c = ord# (indexCharOffAddr# a# n) !h2 = (c +# (h *# 128#)) `remInt#` hASH_TBL_SIZE# -- ----------------------------------------------------------------------------- -- Operations -- | Returns the length of the 'FastString' in characters lengthFS :: FastString -> Int lengthFS f = n_chars f -- | Returns @True@ if this 'FastString' is not Z-encoded but already has -- a Z-encoding cached (used in producing stats). hasZEncoding :: FastString -> Bool hasZEncoding (FastString _ _ _ ref) = inlinePerformIO $ do m <- readIORef ref return (isJust m) -- | Returns @True@ if the 'FastString' is empty nullFS :: FastString -> Bool nullFS f = BS.null (fs_bs f) -- | Unpacks and decodes the FastString unpackFS :: FastString -> String unpackFS (FastString _ _ bs _) = inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(ptr, len) -> utf8DecodeString (castPtr ptr) len -- | Gives the UTF-8 encoded bytes corresponding to a 'FastString' bytesFS :: FastString -> [Word8] bytesFS fs = BS.unpack $ fastStringToByteString fs -- | Returns a Z-encoded version of a 'FastString'. This might be the -- original, if it was already Z-encoded. The first time this -- function is applied to a particular 'FastString', the results are -- memoized. -- zEncodeFS :: FastString -> FastZString zEncodeFS fs@(FastString _ _ _ ref) = inlinePerformIO $ do m <- readIORef ref case m of Just zfs -> return zfs Nothing -> do atomicModifyIORef' ref $ \m' -> case m' of Nothing -> let zfs = mkZFastString (zEncodeString (unpackFS fs)) in (Just zfs, zfs) Just zfs -> (m', zfs) appendFS :: FastString -> FastString -> FastString appendFS fs1 fs2 = mkFastStringByteString $ BS.append (fastStringToByteString fs1) (fastStringToByteString fs2) concatFS :: [FastString] -> FastString concatFS = mkFastStringByteString . BS.concat . map fs_bs headFS :: FastString -> Char headFS (FastString _ 0 _ _) = panic "headFS: Empty FastString" headFS (FastString _ _ bs _) = inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr -> return (fst (utf8DecodeChar (castPtr ptr))) tailFS :: FastString -> FastString tailFS (FastString _ 0 _ _) = panic "tailFS: Empty FastString" tailFS (FastString _ _ bs _) = inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr -> do let (_, n) = utf8DecodeChar (castPtr ptr) return $! mkFastStringByteString (BS.drop n bs) consFS :: Char -> FastString -> FastString consFS c fs = mkFastString (c : unpackFS fs) uniqueOfFS :: FastString -> Int uniqueOfFS (FastString u _ _ _) = u nilFS :: FastString nilFS = mkFastString "" -- ----------------------------------------------------------------------------- -- Stats getFastStringTable :: IO [[FastString]] getFastStringTable = do buckets <- forM [0.. hASH_TBL_SIZE-1] $ \idx -> do bucket <- lookupTbl string_table idx readIORef bucket return buckets -- ----------------------------------------------------------------------------- -- Outputting 'FastString's -- |Outputs a 'FastString' with /no decoding at all/, that is, you -- get the actual bytes in the 'FastString' written to the 'Handle'. hPutFS :: Handle -> FastString -> IO () hPutFS handle fs = BS.hPut handle $ fastStringToByteString fs -- ToDo: we'll probably want an hPutFSLocal, or something, to output -- in the current locale's encoding (for error messages and suchlike). -- ----------------------------------------------------------------------------- -- LitStrings, here for convenience only. -- | A 'LitString' is a pointer to some null-terminated array of bytes. type LitString = Ptr Word8 --Why do we recalculate length every time it's requested? --If it's commonly needed, we should perhaps have --data LitString = LitString {-#UNPACK#-}!Addr# {-#UNPACK#-}!Int# -- | Wrap an unboxed address into a 'LitString'. mkLitString# :: Addr# -> LitString mkLitString# a# = Ptr a# -- | Encode a 'String' into a newly allocated 'LitString' using Latin-1 -- encoding. The original string must not contain non-Latin-1 characters -- (above codepoint @0xff@). {-# INLINE mkLitString #-} mkLitString :: String -> LitString mkLitString s = unsafePerformIO (do p <- mallocBytes (length s + 1) let loop :: Int -> String -> IO () loop !n [] = pokeByteOff p n (0 :: Word8) loop n (c:cs) = do pokeByteOff p n (fromIntegral (ord c) :: Word8) loop (1+n) cs loop 0 s return p ) -- | Decode a 'LitString' back into a 'String' using Latin-1 encoding. -- This does not free the memory associated with 'LitString'. unpackLitString :: LitString -> String unpackLitString (Ptr p) = unpackCString# p -- | Compute the length of a 'LitString', which must necessarily be -- null-terminated. lengthLS :: LitString -> Int lengthLS = ptrStrLength -- ----------------------------------------------------------------------------- -- under the carpet foreign import ccall unsafe "ghc_strlen" ptrStrLength :: Ptr Word8 -> Int {-# NOINLINE sLit #-} sLit :: String -> LitString sLit x = mkLitString x {-# NOINLINE fsLit #-} fsLit :: String -> FastString fsLit x = mkFastString x {-# RULES "slit" forall x . sLit (unpackCString# x) = mkLitString# x #-} {-# RULES "fslit" forall x . fsLit (unpackCString# x) = mkFastString# x #-}
olsner/ghc
compiler/utils/FastString.hs
Haskell
bsd-3-clause
20,911
module Snap.App (module Snap.Core ,module Snap.App.Types ,module Snap.App.Controller ,module Snap.App.Model) where import Snap.Core import Snap.App.Types import Snap.App.Controller import Snap.App.Model
lwm/haskellnews
upstream/snap-app/src/Snap/App.hs
Haskell
bsd-3-clause
214
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE ExistentialQuantification, FlexibleContexts, FlexibleInstances, StandaloneDeriving #-} -------------------------------------------------------------------- -- | -- Module : XMonad.Util.NamedActions -- Copyright : 2009 Adam Vogt <vogt.adam@gmail.com> -- License : BSD3-style (see LICENSE) -- -- Maintainer : Adam Vogt <vogt.adam@gmail.com> -- Stability : unstable -- Portability : unportable -- -- A wrapper for keybinding configuration that can list the available -- keybindings. -- -- Note that xmonad>=0.11 has by default a list of the default keybindings -- bound to @M-S-/@ or @M-?@. -------------------------------------------------------------------- module XMonad.Util.NamedActions ( -- * Usage: -- $usage sendMessage', spawn', submapName, addDescrKeys, addDescrKeys', xMessage, showKmSimple, showKm, noName, oneName, addName, separator, subtitle, (^++^), NamedAction(..), HasName, defaultKeysDescr ) where import XMonad.Actions.Submap(submap) import XMonad import System.Posix.Process(executeFile) import Control.Arrow(Arrow((&&&), second, (***))) import Data.Bits(Bits((.&.), complement)) import Data.List (groupBy) import System.Exit(ExitCode(ExitSuccess), exitWith) import Control.Applicative ((<*>)) import qualified Data.Map as M import qualified XMonad.StackSet as W -- $usage -- Here is an example config that demonstrates the usage of 'sendMessage'', -- 'mkNamedKeymap', 'addDescrKeys', and '^++^' -- -- > import XMonad -- > import XMonad.Util.NamedActions -- > import XMonad.Util.EZConfig -- > -- > main = xmonad $ addDescrKeys ((mod4Mask, xK_F1), xMessage) myKeys -- > def { modMask = mod4Mask } -- > -- > myKeys c = (subtitle "Custom Keys":) $ mkNamedKeymap c $ -- > [("M-x a", addName "useless message" $ spawn "xmessage foo"), -- > ("M-c", sendMessage' Expand)] -- > ^++^ -- > [("<XF86AudioPlay>", spawn "mpc toggle" :: X ()), -- > ("<XF86AudioNext>", spawn "mpc next")] -- -- Using '^++^', you can combine bindings whose actions are @X ()@ -- as well as actions that have descriptions. However you cannot mix the two in -- a single list, unless each is prefixed with 'addName' or 'noName'. -- -- If you don't like EZConfig, you can still use '^++^' with the basic XMonad -- keybinding configuration too. -- -- Also note the unfortunate necessity of a type annotation, since 'spawn' is -- too general. -- TODO: squeeze titles that have no entries (consider titles containing \n) -- -- Output to Multiple columns -- -- Devin Mullin's suggestions: -- -- Reduce redundancy wrt mkNamedSubmaps, mkSubmaps and mkNamedKeymap to have a -- HasName context (and leave mkKeymap as a specific case of it?) -- Currently kept separate to aid error messages, common lines factored out -- -- Suggestions for UI: -- -- - An IO () -> IO () that wraps the main xmonad action and wrests control -- from it if the user asks for --keys. -- -- Just a separate binary: keep this as the only way to show keys for simplicity -- -- - An X () that toggles a cute little overlay like the ? window for gmail -- and reader. -- -- Add dzen binding deriving instance Show XMonad.Resize deriving instance Show XMonad.IncMasterN -- | 'sendMessage' but add a description that is @show message@. Note that not -- all messages have show instances. sendMessage' :: (Message a, Show a) => a -> NamedAction sendMessage' x = NamedAction $ (XMonad.sendMessage x,show x) -- | 'spawn' but the description is the string passed spawn' :: String -> NamedAction spawn' x = addName x $ spawn x class HasName a where showName :: a -> [String] showName = const [""] getAction :: a -> X () instance HasName (X ()) where getAction = id instance HasName (IO ()) where getAction = io instance HasName [Char] where getAction _ = return () showName = (:[]) instance HasName (X (),String) where showName = (:[]) . snd getAction = fst instance HasName (X (),[String]) where showName = snd getAction = fst -- show only the outermost description instance HasName (NamedAction,String) where showName = (:[]) . snd getAction = getAction . fst instance HasName NamedAction where showName (NamedAction x) = showName x getAction (NamedAction x) = getAction x -- | An existential wrapper so that different types can be combined in lists, -- and maps data NamedAction = forall a. HasName a => NamedAction a -- | 'submap', but propagate the descriptions of the actions. Does this belong -- in "XMonad.Actions.Submap"? submapName :: (HasName a) => [((KeyMask, KeySym), a)] -> NamedAction submapName = NamedAction . (submap . M.map getAction . M.fromList &&& showKm) . map (second NamedAction) -- | Combine keymap lists with actions that may or may not have names (^++^) :: (HasName b, HasName b1) => [(d, b)] -> [(d, b1)] -> [(d, NamedAction)] a ^++^ b = map (second NamedAction) a ++ map (second NamedAction) b -- | Or allow another lookup table? modToString :: KeyMask -> String modToString mask = concatMap (++"-") $ filter (not . null) $ map (uncurry pick) [(mod1Mask, "M1") ,(mod2Mask, "M2") ,(mod3Mask, "M3") ,(mod4Mask, "M4") ,(mod5Mask, "M5") ,(controlMask, "C") ,(shiftMask,"Shift")] where pick m str = if m .&. complement mask == 0 then str else "" keyToString :: (KeyMask, KeySym) -> [Char] keyToString = uncurry (++) . (modToString *** keysymToString) showKmSimple :: [((KeyMask, KeySym), NamedAction)] -> [[Char]] showKmSimple = concatMap (\(k,e) -> if snd k == 0 then "":showName e else map ((keyToString k ++) . smartSpace) $ showName e) smartSpace :: String -> String smartSpace [] = [] smartSpace xs = ' ':xs _test :: String _test = unlines $ showKm $ defaultKeysDescr XMonad.def { XMonad.layoutHook = XMonad.Layout $ XMonad.layoutHook XMonad.def } showKm :: [((KeyMask, KeySym), NamedAction)] -> [String] showKm keybindings = padding $ do (k,e) <- keybindings if snd k == 0 then map ((,) "") $ showName e else map ((,) (keyToString k) . smartSpace) $ showName e where padding = let pad n (k,e) = if null k then "\n>> "++e else take n (k++repeat ' ') ++ e expand xs n = map (pad n) xs getMax = map (maximum . map (length . fst)) in concat . (zipWith expand <*> getMax) . groupBy (const $ not . null . fst) -- | An action to send to 'addDescrKeys' for showing the keybindings. See also 'showKm' and 'showKmSimple' xMessage :: [((KeyMask, KeySym), NamedAction)] -> NamedAction xMessage x = addName "Show Keybindings" $ io $ do xfork $ executeFile "xmessage" True ["-default", "okay", unlines $ showKm x] Nothing return () -- | Merge the supplied keys with 'defaultKeysDescr', also adding a keybinding -- to run an action for showing the keybindings. addDescrKeys :: (HasName b1, HasName b) => ((KeyMask, KeySym),[((KeyMask, KeySym), NamedAction)] -> b) -> (XConfig Layout -> [((KeyMask, KeySym), b1)]) -> XConfig l -> XConfig l addDescrKeys k ks = addDescrKeys' k (\l -> defaultKeysDescr l ^++^ ks l) -- | Without merging with 'defaultKeysDescr' addDescrKeys' :: (HasName b) => ((KeyMask, KeySym),[((KeyMask, KeySym), NamedAction)] -> b) -> (XConfig Layout -> [((KeyMask, KeySym), NamedAction)]) -> XConfig l -> XConfig l addDescrKeys' (k,f) ks conf = let shk l = f $ [(k,f $ ks l)] ^++^ ks l keylist l = M.map getAction $ M.fromList $ ks l ^++^ [(k, shk l)] in conf { keys = keylist } -- | A version of the default keys from the default configuration, but with -- 'NamedAction' instead of @X ()@ defaultKeysDescr :: XConfig Layout -> [((KeyMask, KeySym), NamedAction)] defaultKeysDescr conf@(XConfig {XMonad.modMask = modm}) = [ subtitle "launching and killing programs" , ((modm .|. shiftMask, xK_Return), addName "Launch Terminal" $ spawn $ XMonad.terminal conf) -- %! Launch terminal , ((modm, xK_p ), addName "Launch dmenu" $ spawn "exe=`dmenu_path | dmenu` && eval \"exec $exe\"") -- %! Launch dmenu , ((modm .|. shiftMask, xK_p ), addName "Launch gmrun" $ spawn "gmrun") -- %! Launch gmrun , ((modm .|. shiftMask, xK_c ), addName "Close the focused window" kill) -- %! Close the focused window , subtitle "changing layouts" , ((modm, xK_space ), sendMessage' NextLayout) -- %! Rotate through the available layout algorithms , ((modm .|. shiftMask, xK_space ), addName "Reset the layout" $ setLayout $ XMonad.layoutHook conf) -- %! Reset the layouts on the current workspace to default , separator , ((modm, xK_n ), addName "Refresh" refresh) -- %! Resize viewed windows to the correct size , subtitle "move focus up or down the window stack" , ((modm, xK_Tab ), addName "Focus down" $ windows W.focusDown) -- %! Move focus to the next window , ((modm .|. shiftMask, xK_Tab ), addName "Focus up" $ windows W.focusUp ) -- %! Move focus to the previous window , ((modm, xK_j ), addName "Focus down" $ windows W.focusDown) -- %! Move focus to the next window , ((modm, xK_k ), addName "Focus up" $ windows W.focusUp ) -- %! Move focus to the previous window , ((modm, xK_m ), addName "Focus the master" $ windows W.focusMaster ) -- %! Move focus to the master window , subtitle "modifying the window order" , ((modm, xK_Return), addName "Swap with the master" $ windows W.swapMaster) -- %! Swap the focused window and the master window , ((modm .|. shiftMask, xK_j ), addName "Swap down" $ windows W.swapDown ) -- %! Swap the focused window with the next window , ((modm .|. shiftMask, xK_k ), addName "Swap up" $ windows W.swapUp ) -- %! Swap the focused window with the previous window , subtitle "resizing the master/slave ratio" , ((modm, xK_h ), sendMessage' Shrink) -- %! Shrink the master area , ((modm, xK_l ), sendMessage' Expand) -- %! Expand the master area , subtitle "floating layer support" , ((modm, xK_t ), addName "Push floating to tiled" $ withFocused $ windows . W.sink) -- %! Push window back into tiling , subtitle "change the number of windows in the master area" , ((modm , xK_comma ), sendMessage' (IncMasterN 1)) -- %! Increment the number of windows in the master area , ((modm , xK_period), sendMessage' (IncMasterN (-1))) -- %! Deincrement the number of windows in the master area , subtitle "quit, or restart" , ((modm .|. shiftMask, xK_q ), addName "Quit" $ io (exitWith ExitSuccess)) -- %! Quit xmonad , ((modm , xK_q ), addName "Restart" $ spawn "xmonad --recompile && xmonad --restart") -- %! Restart xmonad ] -- mod-[1..9] %! Switch to workspace N -- mod-shift-[1..9] %! Move client to workspace N ++ subtitle "switching workspaces": [((m .|. modm, k), addName (n ++ i) $ windows $ f i) | (f, m, n) <- [(W.greedyView, 0, "Switch to workspace "), (W.shift, shiftMask, "Move client to workspace ")] , (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9]] -- mod-{w,e,r} %! Switch to physical/Xinerama screens 1, 2, or 3 -- mod-shift-{w,e,r} %! Move client to screen 1, 2, or 3 ++ subtitle "switching screens" : [((m .|. modm, key), addName (n ++ show sc) $ screenWorkspace sc >>= flip whenJust (windows . f)) | (f, m, n) <- [(W.view, 0, "Switch to screen number "), (W.shift, shiftMask, "Move client to screen number ")] , (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]] -- | For a prettier presentation: keymask, keysym of 0 are reserved for this -- purpose: they do not happen, afaik, and keysymToString 0 would raise an -- error otherwise separator :: ((KeyMask,KeySym), NamedAction) separator = ((0,0), NamedAction (return () :: X (),[] :: [String])) subtitle :: String -> ((KeyMask, KeySym), NamedAction) subtitle x = ((0,0), NamedAction $ x ++ ":") -- | These are just the @NamedAction@ constructor but with a more specialized -- type, so that you don't have to supply any annotations, for ex coercing -- spawn to @X ()@ from the more general @MonadIO m => m ()@ noName :: X () -> NamedAction noName = NamedAction oneName :: (X (), String) -> NamedAction oneName = NamedAction addName :: String -> X () -> NamedAction addName = flip (curry NamedAction)
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Util/NamedActions.hs
Haskell
bsd-2-clause
12,707
module FVTests where import FVision import GraphicsZ import GeometryZ import qualified GeometryStatic as GS import qualified Graphics as G import FRP import FRPSignal import FRPTask import qualified NXVision2 as XV import IOExts (unsafePerformIO) dotAt c p = withColor c $ moveTo p $ stretch 10 $ circle testF p = runmpeg "test.mpg" "" (showPic p) test p = runmpeg "firewire" "" (showPic p) main = test emptyPic main1 = test (dotAt red (point2XY (50*timeB) (30*timeB))) main2 = test (dotAt red mouseB) main3 = test (dotAt (cycleColors [red, white, blue] lbpE) mouseB) main4 = test (dotAt (cycleColors [red, white, blue] rbpE) mouseB) --cycleColors colors e = cc1 (cycle colors) -- where cc1 (c:cs) = c `till` e -=> cc1 cs cycleColors colors e = switch (head colors) (tagE_ e (tail (cycle colors))) followMe :: VBehavior Picture followMe = emptyPic `till` lbpPosE ==> (\corner1 -> rectangle (lift0 corner1) mouseB `till` lbpPosE ==> (\corner2 -> fillRectangle (lift0 corner1) (lift0 corner2))) track :: VBehavior Picture track = emptyPic `till` lbpPosE ==> (\corner1 -> rectangle (lift0 corner1) mouseB `till` (lbpPosE `snapshotE` inputB) ==> (\(corner2,inp) -> let (x1,y1)=GS.point2XYCoords corner1 (x2,y2)=GS.point2XYCoords corner2 (x,y)=(round x1,round y1) (dx,dy)=(round (x2-x1), round (y2-y1)) im = XV.getRegion (viImage inp) x y dx dy c = XV.getColorSelector im f img = let (xc, yc, area) = XV.stepBlob (viImage img) c area' = (round (area*0.5)) :: Int (x,y)=(round xc,round yc) in ( ipoint2XY (x - area') (y - area'), ipoint2XY (x + area') (y + area') ) (corner1B, corner2B) = pairZSplit $ lift1 f inputB in rectangle corner1B corner2B)) capture :: Behavior inp XV.ImageRGB -> XV.ColorSelector -> Event inp XV.ImageRGB capture ims c = snapshotE_ (whenE (lift2 change posB pos2B <* close)) ims where posB = lift2 XV.stepBlob ims (lift0 c) pos2B = delayNB 10 posB close = lift0 (1,1,4) change (x1,y1,a1) (x2,y2,a2) = if (a1==0) || (a2==0) then (100,100,100) else (abs(x2-x1),abs(y2-y1),abs(a2-a1)) delayNB 1 b = delay1B b delayNB n b = delay1B $ delayNB (n-1) b gesture = emptyPic `till` lbpPosE ==> (\corner1 -> rectangle (lift0 corner1) mouseB `till` (lbpPosE `snapshotE` inputB) ==> (\(corner2,inp) -> let (x1,y1)=GS.point2XYCoords corner1 (x2,y2)=GS.point2XYCoords corner2 (x,y)=(round x1,round y1) (dx,dy)=(round (x2-x1), round (y2-y1)) im = XV.getRegion (viImage inp) x y dx dy c = XV.getColorSelector im subims x y x' y' = lift5 XV.getRegion imageB (lift0 x) (lift0 y) (lift0 (x'-x)) (lift0 (y'-y)) in rectangle (lift0 (ipoint2XY c1x c1y)) (lift0 (ipoint2XY c2x c2y)) `till` (capture (subims c1x c1y c2x c2y) c -=> emptyPic) )) where (c1x,c1y,c2x,c2y) = (400,250,600,400) imageB :: Behavior VideoInput XV.ImageRGB imageB = lift1 viImage inputB ipoint2XY :: Int -> Int -> Point2 ipoint2XY i1 i2 = GS.point2XY (fromInt i1) (fromInt i2) rectangle p1 p2 = withColor white $ polyline [p1, p3, p2, p4] where p3 = point2XY (point2XCoord p1) (point2YCoord p2) p4 = point2XY (point2XCoord p2) (point2YCoord p1) rectangle' p1 p2 = polyline [p1, p3, p2, p4] where p3 = point2XY (point2XCoord p1) (point2YCoord p2) p4 = point2XY (point2XCoord p2) (point2YCoord p1) rect' p1 p2 = G.polyline [p1, p3, p2, p4] where p3 = GS.point2XY (GS.point2XCoord p1) (GS.point2YCoord p2) p4 = GS.point2XY (GS.point2XCoord p2) (GS.point2YCoord p1) fillRectangle p1 p2 = withColor white $ polygon [p1, p3, p2, p4] where p3 = point2XY (point2XCoord p1) (point2YCoord p2) p4 = point2XY (point2XCoord p2) (point2YCoord p1) main5 = test followMe main6 = test track mainG = test gesture -- FVision Tasks type VisionTask e = SimpleTask VideoInput Picture e type IRegion = (Int,Int,Int,Int) runVisionTask t = test (runSimpleT_ t emptyPic) getImage :: IRegion -> VisionTask XV.ImageRGB getImage (c1x,c1y,c2x,c2y) = do mkTask (rectangle (lift0 (ipoint2XY c1x c1y)) (lift0 (ipoint2XY c2x c2y))) lbpE im0 <- snapshotNowT imageB return (XV.getRegion im0 c1x c1y (c2x-c1x) (c2y-c1y)) gesture' = do let reg1 = (400,250,520,400) reg2 = (400,100,520,250) reg = (400,100,600,400) im11 <- getImage reg1 im12 <- getImage reg1 im13 <- getImage reg1 im14 <- getImage reg2 im21 <- getImage reg1 im22 <- getImage reg1 im23 <- getImage reg1 im24 <- getImage reg2 liftT $ findG [im11,im12,im13,im21,im22,im23] reg1 -- `over` findG [im12,im14,im22,im24] reg2 findG' :: [XV.ImageRGB] -> IRegion -> XV.ImageRGB -> Color findG' temps reg im = let [f11,f12,f13,f21,f22,f23] = map XV.compareImageInt temps (c1x,c1y,c2x,c2y) = reg subim = XV.getRegion im c1x c1y (c2x-c1x) (c2y-c1y) err1 = f11 subim + f12 subim + f13 subim err2 = f21 subim + f22 subim + f23 subim b = unsafePerformIO $ do{ print (show err1 ++ " : " ++ show err2 ++ if (err1<err2) then " -> 1ST" else " -> 2ND"); return 5 } in if (b==5) then if (err1<err2) then Red else Blue else White {- findG' :: [XV.ImageRGB] -> IRegion -> XV.ImageRGB -> Color findG' temps reg im = let [ssd11,ssd12,ssd13,ssd21,ssd22,ssd23] = map XV.createSSDstepper temps (c1x,c1y,c2x,c2y) = reg subim = XV.getRegion im c1x c1y (c2x-c1x) (c2y-c1y) err1 = XV.compareSSD ssd11 subim + XV.compareSSD ssd12 subim + XV.compareSSD ssd13 subim err2 = XV.compareSSD ssd21 subim + XV.compareSSD ssd22 subim + XV.compareSSD ssd23 subim b = unsafePerformIO $ do{ print (show err1 ++ " : " ++ show err2 ++ if (err1<err2) then " -> 1ST" else " -> 2ND"); return 5 } in if (b==5) then if (err1<err2) then Red else Blue else White -} findG temps reg = let (c1x,c1y,c2x,c2y) = reg rect = rectangle' (lift0 (ipoint2XY c1x c1y)) (lift0 (ipoint2XY c2x c2y)) colorB = lift1 (findG' temps reg) imageB in withColor colorB rect main11 = runVisionTask gesture' type DRegion = (Double, Double, Double, Double) getCorner :: VisionTask Point2 getCorner = mkTask emptyPic lbpPosE getColor :: VisionTask (XV.ColorSelector, DRegion) getColor = do c1 <- mkTask emptyPic lbpPosE (c2,im) <- mkTask (rectangle (lift0 c1) mouseB) lbpPosE `snapshotT` imageB let (x1,y1)=GS.point2XYCoords c1 (x2,y2)=GS.point2XYCoords c2 (x,y)=(round x1,round y1) (dx,dy)=(round (x2-x1), round (y2-y1)) c = XV.getColorSelector (XV.getRegion im x y dx dy) return (c,(x1-10.0,y1-10.0,(x2-x1+10.0),(y2-y1+10.0))) getRegion :: XV.ImageRGB -> DRegion -> XV.ImageRGB getRegion im (x,y,w,h) = XV.getRegion im (round x) (round y) (round w) (round h) trackT = do (c,reg0) <- getColor let regB = delayB reg0 (lift2 (findRegion c) imageB regB) f reg = let (x,y,w,h) = reg in (GS.point2XY x y, GS.point2XY (x+w) (y+h)) (c1,c2) = pairZSplit $ lift1 f regB liftT $ rectangle c1 c2 findRegion :: XV.ColorSelector -> XV.ImageRGB -> DRegion -> DRegion findRegion c im reg = let (x,y,w,h) = reg dist = 5.0 subim = getRegion im reg (x2, y2, w2, h2) = toDouble $ XV.stepBlob2 subim c x' = if w2<=0 then x else x+x2-dist y' = if h2<=0 then y else y+y2-dist w' = if w2<=0 then w else w2+2*dist h' = if h2<=0 then h else h2+2*dist in (x',y',w',h') main12 = runVisionTask trackT toDouble :: (Float,Float,Float,Float) -> (Double,Double,Double,Double) toDouble (a,b,c,d) = (f a, f b, f c, f d) where f = fromInt . round trackT2 = do (c,reg0) <- getColor let regB = delayB reg0 (lift2 (findRegion c) imageB regB) f reg = let (x,y,w,h) = reg in (GS.point2XY x y, GS.point2XY (x+w) (y+h)) g reg im = let subim = getRegion im reg (x0,y0,w0,h0) = reg regs = map (\(x2,y2,w2,h2) -> (x0+x2,y0+y2,w2,h2)) (XV.blobRegions c subim) hck = unsafePerformIO $ do { print regs; return 5 } in -- map f regs if hck==5 then map f regs else error "debug" rects [] = G.emptyPic rects ((p1,p2):ps) = G.over (rect' p1 p2) (rects ps) liftT $ withColor red $ lift1 rects (lift2 g regB imageB) main14 = runVisionTask trackT2 main13 = test (dotAt red (fstZ pos_v) `over` dotAt blue mouseB) pos_v :: VBehavior (Point2,Vector2) pos_v = delayB center (lift2 f pos_v mouseB) where center = (GS.point2XY 320 240, GS.zeroVector) f (p,v) p2 = (p GS..+^ (speed GS.*^ GS.normalize newv), newv) where vec = p GS..-.p2 newv = if GS.magnitude vec < radius then vec GS.^+^ oldv else oldv oldv = friction GS.*^ v radius = GS.magnitude (GS.Vector2XY 20 20) speed = 5 friction = 0.5
jatinshah/autonomous_systems
project/fvision.hugs/fvtests.hs
Haskell
mit
10,742
main = print $ foldl1 (+) [i | i <- [0..(1000 - 1)], i `mod` 3 == 0 || i `mod` 5 == 0]
liuyang1/euler
001.hs
Haskell
mit
87
{-# LANGUAGE ScopedTypeVariables #-} -- | Effectful functions that create and convert disk image files. module B9.DiskImageBuilder ( materializeImageSource, substImageTarget, preferredDestImageTypes, preferredSourceImageTypes, resolveImageSource, createDestinationImage, resizeImage, importImage, exportImage, exportAndRemoveImage, convertImage, shareImage, ensureAbsoluteImageDirExists, getVirtualSizeForRawImage ) where import B9.Artifact.Content.StringTemplate import B9.B9Config import B9.B9Error import B9.B9Exec import B9.B9Logging import B9.B9Monad import B9.BuildInfo import B9.DiskImages import B9.Environment import qualified B9.PartitionTable as P import B9.RepositoryIO import Control.Eff import qualified Control.Exception as IO import Control.Lens (view, (^.)) import Control.Monad import Control.Monad.IO.Class import qualified Data.ByteString.Char8 as Strict import Data.Char (isDigit) import Data.Generics.Aliases import Data.Generics.Schemes import Data.List import Data.Maybe import qualified Foreign.C.Error as IO import qualified GHC.IO.Exception as IO import GHC.Stack import System.Directory import System.FilePath import System.IO.B9Extras ( ensureDir, prettyPrintToFile, ) import Text.Printf (printf) import Text.Show.Pretty (ppShow) -- -- | Convert relative file paths of images, sources and mounted host directories -- -- to absolute paths relative to '_projectRoot'. -- makeImagePathsAbsoluteToBuildDirRoot :: ImageTarget -> B9 ImageTarget -- makeImagePathsAbsoluteToBuildDirRoot img = -- getConfig >>= maybe (return img) (return . go) . _projectRoot -- where -- go rootDir = everywhere mkAbs img -- where mkAbs = mkT -- | Replace $... variables inside an 'ImageTarget' substImageTarget :: forall e. (HasCallStack, Member EnvironmentReader e, Member ExcB9 e) => ImageTarget -> Eff e ImageTarget substImageTarget = everywhereM gsubst where gsubst :: GenericM (Eff e) gsubst = mkM substMountPoint `extM` substImage `extM` substImageSource `extM` substDiskTarget substMountPoint NotMounted = pure NotMounted substMountPoint (MountPoint x) = MountPoint <$> substStr x substImage (Image fp t fs) = Image <$> substStr fp <*> pure t <*> pure fs substImageSource (From n s) = From <$> substStr n <*> pure s substImageSource (EmptyImage l f t s) = EmptyImage <$> substStr l <*> pure f <*> pure t <*> pure s substImageSource s = pure s substDiskTarget (Share n t s) = Share <$> substStr n <*> pure t <*> pure s substDiskTarget (LiveInstallerImage name outDir resize) = LiveInstallerImage <$> substStr name <*> substStr outDir <*> pure resize substDiskTarget s = pure s -- | Resolve an ImageSource to an 'Image'. The ImageSource might -- not exist, as is the case for 'EmptyImage'. resolveImageSource :: IsB9 e => ImageSource -> Eff e Image resolveImageSource src = case src of (EmptyImage fsLabel fsType imgType _size) -> let img = Image fsLabel imgType fsType in return (changeImageFormat imgType img) (SourceImage srcImg _part _resize) -> ensureAbsoluteImageDirExists srcImg (CopyOnWrite backingImg) -> ensureAbsoluteImageDirExists backingImg (From name _resize) -> getLatestImageByName (SharedImageName name) >>= maybe ( errorExitL (printf "Nothing found for %s." (show (SharedImageName name))) ) ensureAbsoluteImageDirExists -- | Return all valid image types sorted by preference. preferredDestImageTypes :: IsB9 e => ImageSource -> Eff e [ImageType] preferredDestImageTypes src = case src of (CopyOnWrite (Image _file fmt _fs)) -> return [fmt] (EmptyImage _label NoFileSystem fmt _size) -> return (nub [fmt, Raw, QCow2, Vmdk]) (EmptyImage _label _fs _fmt _size) -> return [Raw] (SourceImage _img (Partition _) _resize) -> return [Raw] (SourceImage (Image _file fmt _fs) _pt resize) -> return ( nub [fmt, Raw, QCow2, Vmdk] `intersect` allowedImageTypesForResize resize ) (From name resize) -> getLatestImageByName (SharedImageName name) >>= maybe ( errorExitL (printf "Nothing found for %s." (show (SharedImageName name))) ) ( \sharedImg -> preferredDestImageTypes (SourceImage sharedImg NoPT resize) ) -- | Return all supported source 'ImageType's compatible to a 'ImageDestinaion' -- in the preferred order. preferredSourceImageTypes :: HasCallStack => ImageDestination -> [ImageType] preferredSourceImageTypes dest = case dest of (Share _ fmt resize) -> nub [fmt, Raw, QCow2, Vmdk] `intersect` allowedImageTypesForResize resize (LocalFile (Image _ fmt _) resize) -> nub [fmt, Raw, QCow2, Vmdk] `intersect` allowedImageTypesForResize resize Transient -> [Raw, QCow2, Vmdk] (LiveInstallerImage _name _repo _imgResize) -> [Raw] allowedImageTypesForResize :: HasCallStack => ImageResize -> [ImageType] allowedImageTypesForResize r = case r of Resize _ -> [Raw] ShrinkToMinimumAndIncrease _ -> [Raw] ShrinkToMinimum -> [Raw] ResizeImage _ -> [Raw, QCow2, Vmdk] KeepSize -> [Raw, QCow2, Vmdk] -- | Create the parent directories for the file that contains the 'Image'. -- If the path to the image file is relative, prepend '_projectRoot' from -- the 'B9Config'. ensureAbsoluteImageDirExists :: IsB9 e => Image -> Eff e Image ensureAbsoluteImageDirExists img@(Image path _ _) = do b9cfg <- getConfig let dir = let dirRel = takeDirectory path in if isRelative dirRel then let prefix = fromMaybe "." (b9cfg ^. projectRoot) in prefix </> dirRel else dirRel liftIO $ do createDirectoryIfMissing True dir dirAbs <- canonicalizePath dir return $ changeImageDirectory dirAbs img -- | Create an image from an image source. The destination image must have a -- compatible image type and filesystem. The directory of the image MUST be -- present and the image file itself MUST NOT alredy exist. materializeImageSource :: IsB9 e => ImageSource -> Image -> Eff e () materializeImageSource src dest = case src of (EmptyImage fsLabel fsType _imgType size) -> let (Image _ imgType _) = dest in createEmptyImage fsLabel fsType imgType size dest (SourceImage srcImg part resize) -> createImageFromImage srcImg part resize dest (CopyOnWrite backingImg) -> createCOWImage backingImg dest (From name resize) -> getLatestImageByName (SharedImageName name) >>= maybe ( errorExitL (printf "Nothing found for %s." (show (SharedImageName name))) ) ( \sharedImg -> materializeImageSource (SourceImage sharedImg NoPT resize) dest ) createImageFromImage :: IsB9 e => Image -> Partition -> ImageResize -> Image -> Eff e () createImageFromImage src part size out = do importImage src out extractPartition part out resizeImage size out where extractPartition :: IsB9 e => Partition -> Image -> Eff e () extractPartition NoPT _ = return () extractPartition (Partition partIndex) (Image outFile Raw _) = do (start, len, blockSize) <- liftIO (P.getPartition partIndex outFile) let tmpFile = outFile <.> "extracted" dbgL (printf "Extracting partition %i from '%s'" partIndex outFile) cmd ( printf "dd if='%s' of='%s' bs=%i skip=%i count=%i &> /dev/null" outFile tmpFile blockSize start len ) cmd (printf "mv '%s' '%s'" tmpFile outFile) extractPartition (Partition partIndex) (Image outFile fmt _) = error ( printf "Extract partition %i from image '%s': Invalid format %s" partIndex outFile (imageFileExtension fmt) ) -- | Convert some 'Image', e.g. a temporary image used during the build phase -- to the final destination. createDestinationImage :: IsB9 e => Image -> ImageDestination -> Eff e () createDestinationImage buildImg dest = case dest of (Share name imgType imgResize) -> do resizeImage imgResize buildImg let shareableImg = changeImageFormat imgType buildImg exportAndRemoveImage buildImg shareableImg void (shareImage shareableImg (SharedImageName name)) (LocalFile destImg imgResize) -> do resizeImage imgResize buildImg exportAndRemoveImage buildImg destImg (LiveInstallerImage name repo imgResize) -> do resizeImage imgResize buildImg let destImg = Image destFile Raw buildImgFs (Image _ _ buildImgFs) = buildImg destFile = repo </> "machines" </> name </> "disks" </> "raw" </> "0.raw" sizeFile = repo </> "machines" </> name </> "disks" </> "raw" </> "0.size" versFile = repo </> "machines" </> name </> "disks" </> "raw" </> "VERSION" exportAndRemoveImage buildImg destImg eitherSize <- getVirtualSizeForRawImage destFile case eitherSize of Left err -> error err Right value -> liftIO (writeFile sizeFile (show value)) buildDate <- getBuildDate buildId <- getBuildId liftIO (writeFile versFile (buildId ++ "-" ++ buildDate)) Transient -> return () -- | Determine the virtual size of a raw image getVirtualSizeForRawImage :: (IsB9 e) => FilePath -> Eff e (Either String Integer) getVirtualSizeForRawImage file = do outPut <- cmdStdout (printf "qemu-img info -f raw '%s'" file) return (getVirtualSizeFromQemuImgInfoOutput outPut) getVirtualSizeFromQemuImgInfoOutput :: Strict.ByteString -> Either String Integer getVirtualSizeFromQemuImgInfoOutput qemuOutput = case filter (Strict.isPrefixOf (Strict.pack "virtual size")) (Strict.lines qemuOutput) of [] -> Left ("no line starting with 'virtual size' in output while parsing " <> Strict.unpack qemuOutput) (_ : _ : _) -> Left ("multiple lines starting with 'virtual size' in output" <> Strict.unpack qemuOutput) [x] -> let (digits, rest) = (Strict.span isDigit . Strict.drop 1 . Strict.dropWhile (/= '(')) x in if Strict.isPrefixOf (Strict.pack " bytes)") rest then Right (read (Strict.unpack digits)) else Left ("rest after digits didn't continue in ' bytes)'" <> Strict.unpack qemuOutput) createEmptyImage :: IsB9 e => String -> FileSystem -> ImageType -> ImageSize -> Image -> Eff e () createEmptyImage fsLabel fsType imgType imgSize dest@(Image _ imgType' fsType') | fsType /= fsType' = error ( printf "Conflicting createEmptyImage parameters. Requested is file system %s but the destination image has %s." (show fsType) (show fsType') ) | imgType /= imgType' = error ( printf "Conflicting createEmptyImage parameters. Requested is image type %s but the destination image has type %s." (show imgType) (show imgType') ) | otherwise = do let (Image imgFile imgFmt imgFs) = dest qemuImgOpts = conversionOptions imgFmt dbgL ( printf "Creating empty raw image '%s' with size %s and options %s" imgFile (toQemuSizeOptVal imgSize) qemuImgOpts ) cmd ( printf "qemu-img create -f %s %s '%s' '%s'" (imageFileExtension imgFmt) qemuImgOpts imgFile (toQemuSizeOptVal imgSize) ) case (imgFmt, imgFs) of (Raw, Ext4_64) -> do let fsCmd = "mkfs.ext4" dbgL (printf "Creating file system %s" (show imgFs)) cmd (printf "%s -F -L '%s' -O 64bit -q '%s'" fsCmd fsLabel imgFile) (Raw, Ext4) -> do ext4Options <- view ext4Attributes <$> getB9Config let fsOptions = "-O " <> intercalate "," ext4Options let fsCmd = "mkfs.ext4" dbgL (printf "Creating file system %s" (show imgFs)) cmd (printf "%s -F -L '%s' %s -q '%s'" fsCmd fsLabel fsOptions imgFile) (imageType, fs) -> error ( printf "Cannot create file system %s in image type %s" (show fs) (show imageType) ) createCOWImage :: IsB9 e => Image -> Image -> Eff e () createCOWImage (Image backingFile _ _) (Image imgOut imgFmt _) = do dbgL (printf "Creating COW image '%s' backed by '%s'" imgOut backingFile) cmd ( printf "qemu-img create -f %s -o backing_file='%s' '%s'" (imageFileExtension imgFmt) backingFile imgOut ) resizeExtFS :: (IsB9 e) => ImageSize -> FilePath -> Eff e () resizeExtFS newSize img = do let sizeOpt = toQemuSizeOptVal newSize dbgL (printf "Resizing ext4 filesystem on raw image to %s" sizeOpt) cmd (printf "e2fsck -p '%s'" img) cmd (printf "resize2fs -f '%s' %s" img sizeOpt) shrinkToMinimumExtFS :: (IsB9 e) => FilePath -> Eff e () shrinkToMinimumExtFS img = do dbgL "Shrinking image to minimum size" cmd (printf "e2fsck -p '%s'" img) cmd (printf "resize2fs -f -M '%s'" img) -- | Resize an image, including the file system inside the image. resizeImage :: IsB9 e => ImageResize -> Image -> Eff e () resizeImage KeepSize _ = return () resizeImage (Resize newSize) (Image img Raw fs) | fs == Ext4 || fs == Ext4_64 = resizeExtFS newSize img resizeImage (ShrinkToMinimumAndIncrease sizeIncrease) (Image img Raw fs) | fs == Ext4 || fs == Ext4_64 = do shrinkToMinimumExtFS img fileSize <- liftIO (getFileSize img) let newSize = addImageSize (bytesToKiloBytes (fromInteger fileSize)) sizeIncrease resizeExtFS newSize img resizeImage (ResizeImage newSize) (Image img _ _) = do let sizeOpt = toQemuSizeOptVal newSize dbgL (printf "Resizing image to %s" sizeOpt) cmd (printf "qemu-img resize -q '%s' %s" img sizeOpt) resizeImage ShrinkToMinimum (Image img Raw fs) | fs == Ext4 || fs == Ext4_64 = shrinkToMinimumExtFS img resizeImage _ img = error ( printf "Invalid image type or filesystem, cannot resize image: %s" (show img) ) -- | Import a disk image from some external source into the build directory -- if necessary convert the image. importImage :: IsB9 e => Image -> Image -> Eff e () importImage imgIn imgOut@(Image imgOutPath _ _) = do alreadyThere <- liftIO (doesFileExist imgOutPath) unless alreadyThere (convert False imgIn imgOut) -- | Export a disk image from the build directory; if necessary convert the image. exportImage :: IsB9 e => Image -> Image -> Eff e () exportImage = convert False -- | Export a disk image from the build directory; if necessary convert the image. exportAndRemoveImage :: IsB9 e => Image -> Image -> Eff e () exportAndRemoveImage = convert True -- | Convert an image in the build directory to another format and return the new image. convertImage :: IsB9 e => Image -> Image -> Eff e () convertImage imgIn imgOut@(Image imgOutPath _ _) = do alreadyThere <- liftIO (doesFileExist imgOutPath) unless alreadyThere (convert True imgIn imgOut) -- | Convert/Copy/Move images convert :: IsB9 e => Bool -> Image -> Image -> Eff e () convert doMove (Image imgIn fmtIn _) (Image imgOut fmtOut _) | imgIn == imgOut = do ensureDir imgOut dbgL (printf "No need to convert: '%s'" imgIn) | doMove && fmtIn == fmtOut = do ensureDir imgOut dbgL (printf "Moving '%s' to '%s'" imgIn imgOut) liftIO $ do let exdev e = if IO.ioe_errno e == Just ((\(IO.Errno a) -> a) IO.eXDEV) then copyFile imgIn imgOut >> removeFile imgIn else IO.throw e renameFile imgIn imgOut `IO.catch` exdev | otherwise = do ensureDir imgOut dbgL ( printf "Converting %s to %s: '%s' to '%s'" (imageFileExtension fmtIn) (imageFileExtension fmtOut) imgIn imgOut ) cmd ( printf "qemu-img convert -q -f %s -O %s %s '%s' '%s'" (imageFileExtension fmtIn) (imageFileExtension fmtOut) (conversionOptions fmtOut) imgIn imgOut ) when doMove $ do dbgL (printf "Removing '%s'" imgIn) liftIO (removeFile imgIn) conversionOptions :: ImageType -> String conversionOptions Vmdk = " -o adapter_type=lsilogic " conversionOptions QCow2 = " -o compat=1.1,lazy_refcounts=on " conversionOptions _ = " " toQemuSizeOptVal :: ImageSize -> String toQemuSizeOptVal (ImageSize amount u) = show amount ++ case u of GB -> "G" MB -> "M" KB -> "K" -- | Publish an sharedImage made from an image and image meta data to the -- configured repository shareImage :: IsB9 e => Image -> SharedImageName -> Eff e SharedImage shareImage buildImg sname@(SharedImageName name) = do sharedImage <- createSharedImageInCache buildImg sname infoL (printf "SHARED '%s'" name) pushToSelectedRepo sharedImage return sharedImage -- TODO Move the functions below to RepositoryIO??? -- | Return a 'SharedImage' with the current build data and build id from the -- name and disk image. getSharedImageFromImageInfo :: IsB9 e => SharedImageName -> Image -> Eff e SharedImage getSharedImageFromImageInfo name (Image _ imgType imgFS) = do buildId <- getBuildId date <- getBuildDate return ( SharedImage name (SharedImageDate date) (SharedImageBuildId buildId) imgType imgFS ) -- | Convert the disk image and serialize the base image data structure. -- If the 'maxLocalSharedImageRevisions' configuration is set to @Just n@ -- also delete all but the @n - 1@ newest images from the local cache. createSharedImageInCache :: IsB9 e => Image -> SharedImageName -> Eff e SharedImage createSharedImageInCache img sname@(SharedImageName name) = do dbgL (printf "CREATING SHARED IMAGE: '%s' '%s'" (ppShow img) name) sharedImg <- getSharedImageFromImageInfo sname img dir <- getSharedImagesCacheDir convertImage img (changeImageDirectory dir (sharedImageImage sharedImg)) prettyPrintToFile (dir </> sharedImageFileName sharedImg) sharedImg dbgL (printf "CREATED SHARED IMAGE IN CACHE '%s'" (ppShow sharedImg)) cleanOldSharedImageRevisionsFromCache sname return sharedImg -- -- -- -- -- -- -- imgDir <- getSharedImagesCacheDir -- let filesToDelete = (imgDir </>) <$> (infoFiles ++ imgFiles) -- infoFiles = sharedImageFileName <$> toDelete -- imgFiles = imageFileName . sharedImageImage <$> toDelete -- unless (null filesToDelete) $ do -- traceL -- ( printf -- "DELETING %d OBSOLETE REVISIONS OF: %s" -- (length filesToDelete) -- (show sn) -- ) -- mapM_ traceL filesToDelete -- mapM_ removeIfExists filesToDelete -- where -- newestSharedImages :: IsB9 e => Eff e [SharedImage] -- newestSharedImages = -- reverse . map snd -- <$> lookupSharedImages (== Cache) ((sn ==) . sharedImageName) -- removeIfExists fileName = liftIO $ removeFile fileName `catch` handleExists -- where -- handleExists e -- | isDoesNotExistError e = return () -- | otherwise = throwIO e --
sheyll/b9-vm-image-builder
src/lib/B9/DiskImageBuilder.hs
Haskell
mit
19,278
module Graphics.Urho3D.UI.Internal.FileSelector( FileSelector , fileSelectorCntx , sharedFileSelectorPtrCntx , weakFileSelectorPtrCntx , SharedFileSelector , WeakFileSelector , FileSelectorEntry(..) , HasName(..) , HasDirectory(..) ) where import Control.Lens import GHC.Generics import Graphics.Urho3D.Container.Ptr import qualified Data.Map as Map import qualified Language.C.Inline as C import qualified Language.C.Inline.Context as C import qualified Language.C.Types as C -- resolve lens fields import Graphics.Urho3D.Graphics.Internal.Skeleton -- | File selector dialog data FileSelector -- | File selector's list entry (file or directory.) data FileSelectorEntry = FileSelectorEntry { _fileSelectorEntryName :: !String -- ^ Name , _fileSelectorEntryDirectory :: !Bool -- ^ Directory flag } deriving (Generic) makeFields ''FileSelectorEntry fileSelectorCntx :: C.Context fileSelectorCntx = mempty { C.ctxTypesTable = Map.fromList [ (C.TypeName "FileSelector", [t| FileSelector |]) , (C.TypeName "FileSelectorEntry", [t| FileSelectorEntry |]) ] } sharedPtrImpl "FileSelector" sharedWeakPtrImpl "FileSelector"
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/UI/Internal/FileSelector.hs
Haskell
mit
1,165
module Main where import System.Environment import Lib main :: IO () main = do env <- getEnvironment let port = maybe 3000 read $ lookup "PORT" env startApp port
aaronshim/whenisbad
app/Main.hs
Haskell
mit
170
module System.AtomicWrite.Writer.Text.BinarySpec (spec) where import Test.Hspec (Spec, describe, it, shouldBe) import System.AtomicWrite.Writer.Text.Binary (atomicWriteFile, atomicWriteFileWithMode) import System.FilePath.Posix (joinPath) import System.IO.Temp (withSystemTempDirectory) import System.PosixCompat.Files (fileMode, getFileStatus, setFileCreationMask, setFileMode) import Data.Text (pack) spec :: Spec spec = do describe "atomicWriteFile" $ do it "writes contents to a file" $ withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do let path = joinPath [ tmpDir, "writeTest.tmp" ] atomicWriteFile path $ pack "just testing" contents <- readFile path contents `shouldBe` "just testing" it "preserves the permissions of original file, regardless of umask" $ withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do let filePath = joinPath [tmpDir, "testFile"] writeFile filePath "initial contents" setFileMode filePath 0o100644 newStat <- getFileStatus filePath fileMode newStat `shouldBe` 0o100644 -- New files are created with 100600 perms. _ <- setFileCreationMask 0o100066 -- Create a new file once different mask is set and make sure that mask -- is applied. writeFile (joinPath [tmpDir, "sanityCheck"]) "with sanity check mask" sanityCheckStat <- getFileStatus $ joinPath [tmpDir, "sanityCheck"] fileMode sanityCheckStat `shouldBe` 0o100600 -- Since we move, this makes the new file assume the filemask of 0600 atomicWriteFile filePath $ pack "new contents" resultStat <- getFileStatus filePath -- reset mask to not break subsequent specs _ <- setFileCreationMask 0o100022 -- Fails when using atomic mv command unless apply perms on initial file fileMode resultStat `shouldBe` 0o100644 it "creates a new file with permissions based on active umask" $ withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do let filePath = joinPath [tmpDir, "testFile"] sampleFilePath = joinPath [tmpDir, "sampleFile"] -- Set somewhat distinctive defaults for test _ <- setFileCreationMask 0o100171 -- We don't know what the default file permissions are, so create a -- file to sample them. writeFile sampleFilePath "I'm being written to sample permissions" newStat <- getFileStatus sampleFilePath fileMode newStat `shouldBe` 0o100606 atomicWriteFile filePath $ pack "new contents" resultStat <- getFileStatus filePath -- reset mask to not break subsequent specs _ <- setFileCreationMask 0o100022 -- The default tempfile permissions are 0600, so this fails unless we -- make sure that the default umask is relied on for creation of the -- tempfile. fileMode resultStat `shouldBe` 0o100606 describe "atomicWriteFileWithMode" $ do it "writes contents to a file" $ withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do let path = joinPath [ tmpDir, "writeTest.tmp" ] atomicWriteFileWithMode 0o100777 path $ pack "just testing" contents <- readFile path contents `shouldBe` "just testing" it "changes the permissions of a previously created file, regardless of umask" $ withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do let filePath = joinPath [tmpDir, "testFile"] writeFile filePath "initial contents" setFileMode filePath 0o100644 newStat <- getFileStatus filePath fileMode newStat `shouldBe` 0o100644 -- New files are created with 100600 perms. _ <- setFileCreationMask 0o100066 -- Create a new file once different mask is set and make sure that mask -- is applied. writeFile (joinPath [tmpDir, "sanityCheck"]) "with sanity check mask" sanityCheckStat <- getFileStatus $ joinPath [tmpDir, "sanityCheck"] fileMode sanityCheckStat `shouldBe` 0o100600 -- Since we move, this makes the new file assume the filemask of 0600 atomicWriteFileWithMode 0o100655 filePath $ pack "new contents" resultStat <- getFileStatus filePath -- reset mask to not break subsequent specs _ <- setFileCreationMask 0o100022 -- Fails when using atomic mv command unless apply perms on initial file fileMode resultStat `shouldBe` 0o100655 it "creates a new file with specified permissions" $ withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do let filePath = joinPath [tmpDir, "testFile"] atomicWriteFileWithMode 0o100606 filePath $ pack "new contents" resultStat <- getFileStatus filePath fileMode resultStat `shouldBe` 0o100606
stackbuilders/atomic-write
spec/System/AtomicWrite/Writer/Text/BinarySpec.hs
Haskell
mit
5,286
module Oracles.Flag ( Flag (..), flag, platformSupportsSharedLibs, ghcWithSMP, ghcWithNativeCodeGen, supportsSplitObjects ) where import Hadrian.Oracles.TextFile import Base import Oracles.Setting data Flag = ArSupportsAtFile | CrossCompiling | GccIsClang | GccLt44 | GccLt46 | GhcUnregisterised | LeadingUnderscore | SolarisBrokenShld | SplitObjectsBroken | SupportsThisUnitId | WithLibdw | UseSystemFfi -- Note, if a flag is set to empty string we treat it as set to NO. This seems -- fragile, but some flags do behave like this, e.g. GccIsClang. flag :: Flag -> Action Bool flag f = do let key = case f of ArSupportsAtFile -> "ar-supports-at-file" CrossCompiling -> "cross-compiling" GccIsClang -> "gcc-is-clang" GccLt44 -> "gcc-lt-44" GccLt46 -> "gcc-lt-46" GhcUnregisterised -> "ghc-unregisterised" LeadingUnderscore -> "leading-underscore" SolarisBrokenShld -> "solaris-broken-shld" SplitObjectsBroken -> "split-objects-broken" SupportsThisUnitId -> "supports-this-unit-id" WithLibdw -> "with-libdw" UseSystemFfi -> "use-system-ffi" value <- lookupValueOrError configFile key when (value `notElem` ["YES", "NO", ""]) . error $ "Configuration flag " ++ quote (key ++ " = " ++ value) ++ "cannot be parsed." return $ value == "YES" platformSupportsSharedLibs :: Action Bool platformSupportsSharedLibs = do badPlatform <- anyTargetPlatform [ "powerpc-unknown-linux" , "x86_64-unknown-mingw32" , "i386-unknown-mingw32" ] solaris <- anyTargetPlatform [ "i386-unknown-solaris2" ] solarisBroken <- flag SolarisBrokenShld return $ not (badPlatform || solaris && solarisBroken) ghcWithSMP :: Action Bool ghcWithSMP = do goodArch <- anyTargetArch ["i386", "x86_64", "sparc", "powerpc", "arm"] ghcUnreg <- flag GhcUnregisterised return $ goodArch && not ghcUnreg ghcWithNativeCodeGen :: Action Bool ghcWithNativeCodeGen = do goodArch <- anyTargetArch ["i386", "x86_64", "sparc", "powerpc"] badOs <- anyTargetOs ["ios", "aix"] ghcUnreg <- flag GhcUnregisterised return $ goodArch && not badOs && not ghcUnreg supportsSplitObjects :: Action Bool supportsSplitObjects = do broken <- flag SplitObjectsBroken ghcUnreg <- flag GhcUnregisterised goodArch <- anyTargetArch [ "i386", "x86_64", "powerpc", "sparc" ] goodOs <- anyTargetOs [ "mingw32", "cygwin32", "linux", "darwin", "solaris2" , "freebsd", "dragonfly", "netbsd", "openbsd" ] return $ not broken && not ghcUnreg && goodArch && goodOs
izgzhen/hadrian
src/Oracles/Flag.hs
Haskell
mit
2,920
module Language.Binal.StyleGuidance where import Control.Applicative import Control.Monad import Control.Monad.Trans import Control.Monad.State import qualified Text.Trifecta as T import qualified Text.Trifecta.Delta as D import Language.Binal.Types import qualified Language.Binal.Parser as P type StyleGuidance a = StateT [Where] T.Parser a isStyleError :: StyleError -> Bool isStyleError (UnexpectedEOFWhileReading _) = True isStyleError (ExtraCloseParenthesis _) = True isStyleError (BadToken _) = True isStyleError (MismatchIndent _ _) = False isStyleWarning :: StyleError -> Bool isStyleWarning (UnexpectedEOFWhileReading _) = False isStyleWarning (ExtraCloseParenthesis _) = False isStyleWarning (BadToken _) = False isStyleWarning (MismatchIndent _ _) = True styleErrors :: [StyleError] -> [StyleError] styleErrors = filter isStyleError examineStyleWithinProgram :: StyleGuidance [StyleError] examineStyleWithinProgram = do errs1 <- examineStyle errs2 <- concat <$> many (T.spaces *> examineExtraCloseParenthesis <* T.spaces) return (errs1 ++ errs2) examineStyle :: StyleGuidance [StyleError] examineStyle = concat <$> many (T.spaces *> examineStyle1 <* T.spaces) examineStyle1 :: StyleGuidance [StyleError] examineStyle1 = examineStyleAtom <|> examineStyleList <|> examineBadToken examineStyleAtom :: StyleGuidance [StyleError] examineStyleAtom = lift P.atom >> return [] examineExtraCloseParenthesis :: StyleGuidance [StyleError] examineExtraCloseParenthesis = do (pos, _) <- lift (P.withPosition (T.char ')')) return [ExtraCloseParenthesis pos] examineBadToken :: StyleGuidance [StyleError] examineBadToken = do (pos, _) <- lift (P.withPosition (some (T.noneOf " \n()"))) return [BadToken pos] examineStyleList :: StyleGuidance [StyleError] examineStyleList = do stack <- get let before = case stack of [] -> Nothing (x:_) -> Just x (begin, _) <- lift (P.withPosition (T.char '(')) let mkIndent = case (before, begin) of (Just (AtFile _ beforeL _ _ _ _), AtFile _ beginL _ _ _ _) | beforeL == beginL -> False | otherwise -> True (Just (AtLine beforeL _ _ _ _), AtLine beginL _ _ _ _) | beforeL == beginL -> False | otherwise -> True _ -> True when mkIndent $ do modify (begin:) mismatches1 <- examineStyle matchingParen <- lift (P.withPosition (optional (T.char ')'))) when mkIndent $ do modify tail let mismatches2 = case (before, begin) of (Just b@(AtFile _ beforeL beforeC _ _ _), AtFile _ beginL beginC _ _ _) | beforeL == beginL -> do [] | beforeC < beginC -> do [] | beforeC >= beginC -> do [MismatchIndent b begin] (Just b@(AtLine beforeL beforeC _ _ _), AtLine beginL beginC _ _ _) | beforeL == beginL -> do [] | beforeC < beginC -> do [] | beforeC >= beginC -> do [MismatchIndent b begin] _ -> [] let mismatches3 = case matchingParen of (_, Just _) -> [] (pos, Nothing) -> [UnexpectedEOFWhileReading pos] return (mismatches1 ++ mismatches2 ++ mismatches3) examineStyleFromFile :: FilePath -> IO (Maybe [StyleError]) examineStyleFromFile path = T.parseFromFile (evalStateT (examineStyleWithinProgram <* T.eof) []) path examineStyleString :: String -> IO (Maybe [StyleError]) examineStyleString str = do case T.parseString (evalStateT (examineStyleWithinProgram <* T.eof) []) (D.Columns 0 0) str of T.Success x -> return (Just x) T.Failure doc -> do putStrLn (show doc) return Nothing
pasberth/binal1
Language/Binal/StyleGuidance.hs
Haskell
mit
3,787
module Phb.Db ( module Phb.Db.Internal , module Phb.Db.Esqueleto , module Phb.Db.Event , module Phb.Db.Backlog , module Phb.Db.Customer , module Phb.Db.Action , module Phb.Db.Person , module Phb.Db.PersonLogin , module Phb.Db.Project , module Phb.Db.Heartbeat , module Phb.Db.Success , module Phb.Db.Standup , module Phb.Db.Task , module Phb.Db.TimeLog , module Phb.Db.WorkCategory , module Phb.Db.Enums ) where import Phb.Db.Action import Phb.Db.Backlog import Phb.Db.Customer import Phb.Db.Enums import Phb.Db.Esqueleto import Phb.Db.Event import Phb.Db.Heartbeat import Phb.Db.Internal import Phb.Db.Person import Phb.Db.PersonLogin import Phb.Db.Project import Phb.Db.Standup import Phb.Db.Success import Phb.Db.Task import Phb.Db.TimeLog import Phb.Db.WorkCategory
benkolera/phb
hs/Phb/Db.hs
Haskell
mit
965
{-# LANGUAGE OverloadedStrings #-} -- | Style attributes. -- -- See http://www.graphviz.org/doc/info/attrs.html#k:style for more info on graphviz styles module Text.Dot.Attributes.Styles where import Text.Dot.Types.Internal -- * Style attributes style :: AttributeName style = "style" -- * Style attribute values bold :: AttributeValue bold = "bold" striped :: AttributeValue striped = "striped" filled :: AttributeValue filled = "filled" solid :: AttributeValue solid = "solid" dashed :: AttributeValue dashed = "dashed" dotted :: AttributeValue dotted = "dotted" rounded :: AttributeValue rounded = "rounded" -- ** Styles only for nodes diagonals :: AttributeValue diagonals = "diagonals" wedged :: AttributeValue wedged = "wedged"
NorfairKing/haphviz
src/Text/Dot/Attributes/Styles.hs
Haskell
mit
760
module Main where import Control.Concurrent import Control.Monad import Network import System.IO main = do putStrLn "aclick client" forever $ do h <- connectTo "localhost" (PortNumber (fromIntegral 6666)) hGetLine h getLine >>= hPutStrLn h hGetLine h >>= putStrLn hClose h
ZerglingRush/aclick
src/Client.hs
Haskell
mit
299
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Main where import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BC import Data.FileEmbed (embedFile) import Data.Foldable (traverse_) import Data.List (transpose) import Data.List.Split (chunksOf) import Data.Maybe (fromJust) triple :: ByteString -> [Int] triple = map (fst . fromJust . BC.readInt) . filter (/= "") . BC.splitWith (== ' ') input :: ByteString input = $(embedFile "input.txt") triples :: [[Int]] triples = map triple . BC.lines $ input validTriangle :: [Int] -> Bool validTriangle xs = (a + b) > c && (a + c) > b && (b + c) > a where [a, b, c] = take 3 xs countValid :: [[Int]] -> Int countValid = length . filter validTriangle part1 :: Int part1 = countValid triples part2 :: Int part2 = countValid . concatMap (chunksOf 3) . transpose $ triples main :: IO () main = traverse_ print [part1, part2]
genos/online_problems
advent_of_code_2016/day3/src/Main.hs
Haskell
mit
1,041
{-# LANGUAGE ScopedTypeVariables #-} module TruthTable.Logic where import TruthTable.Types import TruthTable.Mapping import Data.List (nub) import qualified Data.Map.Strict as Map uniqueVariables :: Statement -> [Variable] uniqueVariables = nub . vars where vars (StatementResult _) = [] vars (NestedStatement s) = vars s vars (NegationStatement s) = vars s vars (VariableStatement v) = [v] vars (Statement s1 _ s2) = (vars s1) ++ (vars s2) getTruthSets :: Statement -> [TruthSet] getTruthSets = binaryToMap . uniqueVariables lookupEither :: Ord k => k -> Map.Map k v -> Either k v lookupEither k m = case Map.lookup k m of Just r -> Right r Nothing -> Left k -- | TODO: Better error handling: Change return type to -- Either (TruthSet, Variable) Bool so we have context for the bad input -- (can say "could not find Variable in TruthSet") evaluateStatement :: TruthSet -> Statement -> Either Variable Bool evaluateStatement vars s = let eval = evaluateStatement vars in -- ^ evaluate in the context of the current set of truth values case s of StatementResult b -> Right b NestedStatement stmt -> eval stmt VariableStatement thisVar -> lookupEither thisVar vars NegationStatement stmt -> fmap not $ eval stmt Statement s1 op s2 -> do let fOp = evaluateOperator op firstResult <- eval s1 secondResult <- eval s2 return $ fOp firstResult secondResult evaluateOperator :: Operator -> Bool -> Bool -> Bool evaluateOperator And a b = (a && b) evaluateOperator Or a b = (a || b) evaluateOperator Xor a b = (a || b) && (a /= b) catEithers :: [Either a b] -> Either [a] [b] catEithers = foldr f (Right []) where f (Left x) (Left cs) = Left $ x : cs f (Left x) (Right _) = Left [x] f (Right x) (Right ds) = Right $ x : ds f (Right _) cs = cs -- | TODO: should probably change Either [Variable] TruthTable to -- Either [TruthSet] TruthTable so we can see all of the problematic input -- instead of just getting a list of bad variables with no context genTruthTable :: Statement -> Either [Variable] TruthTable genTruthTable stmt = case genTruthTable' of Left vs -> Left vs Right res -> Right . (uncurry $ TruthTable vars) . unzip $ res where genTruthTable' :: Either [Variable] [(TruthSet, Bool)] genTruthTable' = catEithers allResults vars :: [Variable] vars = uniqueVariables stmt inputTruthSets :: [TruthSet] inputTruthSets = binaryToMap vars allResults :: [Either Variable (TruthSet, Bool)] allResults = map (\thisTruthSet -> evaluateStatement thisTruthSet stmt >>= \r -> return (thisTruthSet, r)) inputTruthSets
tjakway/truth-table-generator
src/TruthTable/Logic.hs
Haskell
mit
3,033
{-# LANGUAGE CPP #-} module GHCJS.DOM.SQLTransaction ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.SQLTransaction #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.SQLTransaction #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/SQLTransaction.hs
Haskell
mit
335
-- |Netrium is Copyright Anthony Waite, Dave Hewett, Shaun Laurens & Contributors 2009-2018, and files herein are licensed -- |under the MIT license, the text of which can be found in license.txt -- {-# LANGUAGE DeriveFunctor, GADTs, PatternGuards #-} module DecisionTreeSimplify ( decisionTreeSimple, decisionStepWithTime, simplifyWait ) where import Contract import Observable (Steps(..)) import qualified Observable as Obs import DecisionTree import Prelude hiding (product, until, and, id) import Data.List hiding (and) -- --------------------------------------------------------------------------- -- * Apply our knowledge of time -- --------------------------------------------------------------------------- decisionTreeSimple :: Time -> Contract -> DecisionTree decisionTreeSimple t c = unfoldDecisionTree decisionStepWithTime (initialProcessState t c) decisionStepWithTime :: ProcessState -> (DecisionStep ProcessState, Time) decisionStepWithTime st@(PSt time _ _) = case decisionStep st of Done -> (Done, time) Trade d sf t st1 -> (Trade d sf t st1, time) Choose p id st1 st2 -> (Choose p id st1 st2, time) ObserveCond o st1 st2 -> case Obs.eval time o of Result True -> decisionStepWithTime st1 Result False -> decisionStepWithTime st2 _ -> (ObserveCond o st1 st2, time) ObserveValue o k -> case Obs.eval time o of Result v -> decisionStepWithTime (k v) _ -> (ObserveValue o k, time) Wait conds opts -> case simplifyWait time conds (not (null opts)) of Left st' -> decisionStepWithTime st' Right [] -> (Done, time) Right conds' -> (Wait conds' opts, time) -- The Wait action is the complicated one -- simplifyWait :: Time -> [(Obs Bool, Time -> ProcessState)] -> Bool -> Either ProcessState [(Obs Bool, Time -> ProcessState)] simplifyWait time conds opts = -- Check if any conditions are currently true, case checkCondTrue time conds of -- if so we can run one rather than waiting. Left k -> Left (k time) -- If all the conditions are evermore false... Right [] | opts -> Right [(konst False, \time' -> PSt time' [] [])] | otherwise -> Right [] -- Otherwise, all conditions are either false or are unknown. Right otherConds -> -- We look at the remaining conditions and check if there is -- a time at which one of the conditions will become true. case Obs.earliestTimeHorizon time otherConds of -- Of course, there may be no such time, in which case we -- simply return a new Wait using the remaining conditions Nothing -> Right otherConds -- but if this time does exists (call it the time horizon) -- then we can use it to simplify or eliminate the -- remaining conditions. -- Note that we also get the continuation step associated -- with the condition that becomes true at the horizon. Just (horizon, k) -> -- For each remaining condition we try to simplify it -- based on the knowledge that the time falls in the -- range between now and the time horizon (exclusive). -- If a condition will be false for the whole of this -- time range then it can be eliminated. let simplifiedConds = [ (obs', k') | (obs, k') <- otherConds , let obs' = Obs.simplifyWithinHorizon time horizon obs , not (Obs.isFalse time obs') ] -- It is possible that all the conditions are false -- in the time period from now up to (but not -- including) the horizon. in if null simplifiedConds -- In that case the condition associated with the -- time horizon will become true first, and we -- can advance time to the horizon and follow its -- associated continuation. then if opts then Right [(at horizon, k)] else Left (k horizon) -- Otherwise, we return a new Wait, using the -- simplified conditions else Right ((at horizon, k) : simplifiedConds) checkCondTrue :: Time -> [(Obs Bool, a)] -> Either a [(Obs Bool, a)] checkCondTrue time conds | ((_,k) :_) <- trueConds = Left k | otherwise = Right otherConds' where (trueConds, otherConds) = partition (Obs.isTrue time . fst) conds otherConds' = filter (not . Obs.evermoreFalse time . fst) otherConds
netrium/Netrium
src/DecisionTreeSimplify.hs
Haskell
mit
5,104
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -O0 -fno-warn-missing-signatures -fno-warn-partial-type-signatures #-} module Example.Extras where name = "plugin"
sboosali/simple-plugins
executables/Example/Extras.hs
Haskell
mit
165
module Jhc.ForeignPtr( ForeignPtr(), newPlainForeignPtr_, newForeignPtr_, mallocPlainForeignPtrAlignBytes, mallocForeignPtrAlignBytes, unsafeForeignPtrToPtr, castForeignPtr, touchForeignPtr ) where import Jhc.Addr import Jhc.IO import Jhc.Prim.Rts import Jhc.Basics type FinalizerPtr a = FunPtr (Ptr a -> IO ()) -- not Addr_ because we need to make sure it is allocated in a real heap -- location. The actual ForeignPtr heap location may contain more than the -- single BitsPtr_ argument. data ForeignPtr a = FP BitsPtr_ -- | This function creates a plain ForeignPtr from a Ptr, a plain foreignptr -- may not have finalizers associated with it, hence this function may be pure. newPlainForeignPtr_ :: Ptr a -> ForeignPtr a newPlainForeignPtr_ (Ptr (Addr_ addr)) = FP addr newForeignPtr_ :: Ptr a -> IO (ForeignPtr a) newForeignPtr_ ptr = fromUIO $ \w -> case gc_new_foreignptr ptr w of (# w', bp #) -> (# w', fromBang_ bp #) -- | This function is similar to 'mallocForeignPtrAlignBytes', except that the -- internally an optimised ForeignPtr representation with no finalizer is used. -- Attempts to add a finalizer will cause the program to abort. mallocPlainForeignPtrAlignBytes :: Int -- ^ alignment in bytes, must be power of 2. May be zero. -> Int -- ^ size to allocate in bytes. -> IO (ForeignPtr a) mallocPlainForeignPtrAlignBytes align size = fromUIO $ \w -> case gc_malloc_foreignptr (int2word align) (int2word size) False w of (# w', bp #) -> (# w', fromBang_ bp #) -- | Allocate memory of the given size and alignment that will automatically be -- reclaimed. Any Finalizers that are attached to this will run before the -- memory is freed. mallocForeignPtrAlignBytes :: Int -- ^ alignment in bytes, must be power of 2. May be zero. -> Int -- ^ size to allocate in bytes. -> IO (ForeignPtr a) mallocForeignPtrAlignBytes align size = fromUIO $ \w -> case gc_malloc_foreignptr (int2word align) (int2word size) True w of (# w', bp #) -> (# w', fromBang_ bp #) foreign import safe ccall gc_malloc_foreignptr :: Word -- alignment in words -> Word -- size in words -> Bool -- false for plain foreignptrs, true for ones with finalizers. -> UIO (Bang_ (ForeignPtr a)) foreign import safe ccall gc_new_foreignptr :: Ptr a -> UIO (Bang_ (ForeignPtr a)) foreign import unsafe ccall gc_add_foreignptr_finalizer :: Bang_ (ForeignPtr a) -> FinalizerPtr a -> IO () unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a unsafeForeignPtrToPtr (FP x) = Ptr (Addr_ x) touchForeignPtr :: ForeignPtr a -> IO () touchForeignPtr x = fromUIO_ (touch_ x) castForeignPtr :: ForeignPtr a -> ForeignPtr b castForeignPtr x = unsafeCoerce x foreign import primitive touch_ :: ForeignPtr a -> UIO_ foreign import primitive "B2B" int2word :: Int -> Word foreign import primitive unsafeCoerce :: a -> b
m-alvarez/jhc
lib/jhc/Jhc/ForeignPtr.hs
Haskell
mit
2,928
module Main where import Control.Monad import Control.Concurrent import Control.Concurrent.STM import Data.List import System.Random fromYear :: Integer fromYear = 1900 toYear :: Integer toYear = 1920 supportedYears :: [Integer] supportedYears = [fromYear .. toYear] randomYear :: IO Integer randomYear = do g <- newStdGen return $ fst $ randomR (fromYear, toYear) g forkDelay :: Int -> IO ()-> IO () forkDelay n f = replicateM_ n $ forkIO (randomDelay >> f) main :: IO () main = do ys <- replicateM 10 randomYear print $ nub ys stYs <- newTVarIO $ nub ys forkDelay 10 $ randomYear >>= \y -> atomically $ sim stYs y `orElse` return () randomDelay :: IO () randomDelay = do r <- randomRIO (3, 15) threadDelay (r * 100000) canTravel1 :: TVar Integer -> STM Bool canTravel1 clientNum = do num <- readTVar clientNum if num > 8 then return False else return True canTravel2 :: Integer -> TVar [Integer] -> STM Bool canTravel2 y years = do ys <- readTVar years return $ y `notElem` ys sim :: TVar [Integer] -> Integer -> STM () sim ys y = do --cond1 <- canTravel1 y cond2 <- canTravel2 y ys if not cond2 --if not cond1 || not cond2 then retry else return ()
hnfmr/beginning_haskell
ex8.2/src/Main.hs
Haskell
mit
1,268
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} module Text.Inflections.UnderscoreSpec (spec) where import Test.Hspec import Text.Inflections #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif spec :: Spec spec = describe "underscore" $ it "converts a word list to snake case" $ do test <- SomeWord <$> mkWord "test" this <- SomeWord <$> mkWord "this" underscore [test, this] `shouldBe` "test_this"
stackbuilders/inflections-hs
test/Text/Inflections/UnderscoreSpec.hs
Haskell
mit
451
module Example.Sorting where import Control.Category hiding ((>>>),(<<<)) import Control.Applicative import Prelude hiding ((.), id) import Melchior.Control import Melchior.Data.String import Melchior.Dom import Melchior.Dom.Events import Melchior.Dom.Html import Melchior.Dom.Selectors import Melchior.EventSources.Mouse import Melchior.Remote.Internal.ParserUtils --maybe more useful than an internal import Melchior.Time main :: IO Element main = runDom setupSorting setupSorting :: [Element] -> Dom Element setupSorting html = do inp <- Dom $ select (byId "inp" . from) html >>= \m -> return $ ensures m ordering <- Dom $ select (byId "numbers" . from) html >>= \m -> return $ ensures m input <- return $ createEventedSignal (Of "string") inp (ElementEvt InputEvt) put ordering ((\_ -> qsort $ parseToNumbers $ value $ toInput inp) <$> input) return $ UHC.Base.head html stringListToNumbers :: String -> [Int] stringListToNumbers s = case parse numbers s of [] -> [] (x:xs) -> map (\x -> (read x :: Int)) (fst x) numbers = many1 numberAndDelim numberAndDelim = do { n <- many1 digit; space; symb "," +++ return []; return n } parseToNumbers :: JSString -> [Int] parseToNumbers s = stringListToNumbers $ jsStringToString s qsort :: Ord a => [a] -> [a] qsort [] = [] qsort (pivot:rest) = (qsort lesser) ++ [pivot] ++ (qsort greater) where lesser = filter (< pivot) rest greater = filter (>= pivot) rest put :: (Renderable a) => Element -> Signal (a) -> Dom () put el s = terminate s (\x -> return $ set el "innerHTML" $ render x)
kjgorman/melchior
example/assets/hs/sorting.hs
Haskell
mit
1,565
{-# htermination ($!) :: (a -> b) -> a -> b #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_DOLLARBANG_1.hs
Haskell
mit
48
module JobReport.Insert where import Control.Monad import Database.HDBC import Database.HDBC.Sqlite3 import JobReport.Database newtype InsertOptions = InsertOptions Working deriving (Read, Show) data Job = Job { jobName :: String } deriving (Read, Show) data Payment = Payment { paymentJob :: Job , paymentYear :: Int , paymentMonth :: Int } deriving (Read, Show) data Working = Working { workingPayment :: Payment , workingYear :: Int , workingMonth :: Int , workingDay :: Int , workingStartHour :: Int , workingStartMinute :: Int , workingEndHour :: Int , workingEndMinute :: Int } deriving (Read, Show) insertAction :: InsertOptions -> IO () insertAction (InsertOptions w) = withDatabase (flip withTransaction f) where f c = do insertPayment c (workingPayment w) insertWorking c w insertPayment :: Connection -> Payment -> IO () insertPayment c (Payment j y m) = void $ run c stm [toSql (jobName j), toSql y, toSql m] where stm = unlines [ "INSERT OR IGNORE INTO Payment (job, year, month)" , " SELECT id, ?2, ?3" , " FROM Job" , " WHERE name = ?1" ] insertWorking :: Connection -> Working -> IO () insertWorking c w = void $ run c stm args where args = [ toSql $ jobName $ paymentJob $ workingPayment w , toSql $ paymentYear $ workingPayment w , toSql $ paymentMonth $ workingPayment w , toSql $ workingYear w , toSql $ workingMonth w , toSql $ workingDay w , toSql $ workingStartHour w , toSql $ workingStartMinute w , toSql $ workingEndHour w , toSql $ workingEndMinute w ] stm = unlines [ "INSERT INTO Working (payment, year, month, day, startHour, startMinute, endHour, endMinute)" , " SELECT Payment.id, ?4, ?5, ?6, ?7, ?8, ?9, ?10" , " FROM Payment" , " INNER JOIN Job ON Job.id = Payment.job" , " WHERE Job.name = ?1" , " AND Payment.year = ?2" , " AND Payment.month = ?3" ]
haliner/jobreport
src/JobReport/Insert.hs
Haskell
mit
2,126
import Data.List import Data.Char vowels = "aeiou" doubles = [ [c, c] | i <- [0..25], let c = chr (ord 'a' + i) ] bad = ["ab", "cd", "pq", "xy"] good s = hasVowels && hasDoubles && notBad where hasVowels = length (filter (`elem` vowels) s) >= 3 hasDoubles = any (`isInfixOf` s) doubles notBad = not $ any (`isInfixOf` s) bad answer f = interact $ (++"\n") . show . f main = answer $ length . filter good . lines
msullivan/advent-of-code
2015/A5a.hs
Haskell
mit
434
module Main where -- • How many different ways can you find to write allEven? allEvenComprehension :: [Integer] -> [Integer] allEvenComprehension list = [x | x <- list, even x] allEvenFilter :: [Integer] -> [Integer] allEvenFilter list = filter even list -- • Write a function that takes a list and returns the same list in reverse. reverseList [] = [] reverseList (h:t) = reverseList(t) ++ [h] -- • Write a function that builds two-tuples with all possible combinations of two of the colors black, white, blue, yellow, and red. Note that you should include only one of (black, blue) and (blue, black). colorCombinations = do let colors = ["black", "white", "yellow", "red"] [(a, b) | a <- colors, b <- colors, a <= b] -- • Write a list comprehension to build a childhood multiplication table. The table would be a list of three-tuples where the first two are integers from 1–12 and the third is the product of the first two. multiplicationTable = [(a, b, a * b) | a <- [1..12], b <- [1..12] ] -- • Solve the map-coloring problem (Map Coloring,on page 101) using Haskell. mapColoring = do let colors = ["red", "green", "blue"] [("Alabama", a, "Mississippi", m, "Georgia", g, "Tennessee", t, "Florida", f) | a <- colors, m <- colors, g <- colors, t <- colors, f <- colors, m /= t, m /= a, a /= t, a /= m, a /= g, a /= f, g /= f, g /= t ]
hemslo/seven-in-seven
haskell/day1/day1.hs
Haskell
mit
1,400
-- From a blog post: http://www.jonmsterling.com/posts/2012-01-12-unifying-monoids-and-monads-with-polymorphic-kinds.html {-# LANGUAGE PolyKinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances, FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE TypeFamilies #-} module Main where import Data.Kind import Control.Monad (Monad(..), join, ap, liftM) import Data.Monoid (Monoid(..)) import Data.Semigroup (Semigroup(..)) -- First we define the type class Monoidy: class Monoidy (to :: k0 -> k1 -> Type) (m :: k1) where type MComp to m :: k1 -> k1 -> k0 type MId to m :: k0 munit :: MId to m `to` m mjoin :: MComp to m m m `to` m -- We use functional dependencies to help the typechecker understand that -- m and ~> uniquely determine comp (times) and id. -- This kind of type class would not have been possible in previous -- versions of GHC; with the new kind system, however, we can abstract -- over kinds!2 Now, let’s create types for the additive and -- multiplicative monoids over the natural numbers: newtype Sum a = Sum a deriving Show newtype Product a = Product a deriving Show instance Num a ⇒ Monoidy (→) (Sum a) where type MComp (→) (Sum a) = (,) type MId (→) (Sum a) = () munit _ = Sum 0 mjoin (Sum x, Sum y) = Sum $ x + y instance Num a ⇒ Monoidy (→) (Product a) where type MComp (→) (Product a) = (,) type MId (→) (Product a) = () munit _ = Product 1 mjoin (Product x, Product y) = Product $ x * y -- It will be slightly more complicated to make a monadic instance with -- Monoidy. First, we need to define the identity functor, a type for -- natural transformations, and a type for functor composition: data Id α = Id { runId :: α } deriving Functor -- A natural transformation (Λ f g α. (f α) → (g α)) may be encoded in Haskell as follows: data NT f g = NT { runNT :: ∀ α. f α → g α } -- Functor composition (Λ f g α. f (g α)) is encoded as follows: data FC f g α = FC { runFC :: f (g α) } -- Now, let us define some type T which should be a monad: data Wrapper a = Wrapper { runWrapper :: a } deriving (Show, Functor) instance Monoidy NT Wrapper where type MComp NT Wrapper = FC type MId NT Wrapper = Id munit = NT $ Wrapper . runId mjoin = NT $ runWrapper . runFC -- With these defined, we can use them as follows: test1 = do { print (mjoin (munit (), Sum 2)) -- Sum 2 ; print (mjoin (Product 2, Product 3)) -- Product 6 ; print (runNT mjoin $ FC $ Wrapper (Wrapper "hello, world")) -- Wrapper {runWrapper = "hello, world" } } -- We can even provide a special binary operator for the appropriate monoids as follows: (<+>) :: (Monoidy (→) m, MId (→) m ~ (), MComp (→) m ~ (,)) ⇒ m → m → m (<+>) = curry mjoin test2 = print (Sum 1 <+> Sum 2 <+> Sum 4) -- Sum 7 -- Now, all the extra wrapping that Haskell requires for encoding this is -- rather cumbersome in actual use. So, we can give traditional Monad and -- Monoid instances for instances of Monoidy: instance (MId (→) m ~ (), MComp (→) m ~ (,), Monoidy (→) m) ⇒ Semigroup m where (<>) = curry mjoin instance (MId (→) m ~ (), MComp (→) m ~ (,), Monoidy (→) m) ⇒ Monoid m where mempty = munit () instance Applicative Wrapper where pure = return (<*>) = ap instance Monad Wrapper where return x = runNT munit $ Id x x >>= f = runNT mjoin $ FC (f `fmap` x) -- And so the following works: test3 = do { print (mappend mempty (Sum 2)) -- Sum 2 ; print (mappend (Product 2) (Product 3)) -- Product 6 ; print (join $ Wrapper $ Wrapper "hello") -- Wrapper {runWrapper = "hello" } ; print (Wrapper "hello, world" >>= return) -- Wrapper {runWrapper = "hello, world" } } main = test1 >> test2 >> test3
ghcjs/ghcjs
test/ghc/polykinds/monoidsTF.hs
Haskell
mit
4,111
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} -- Type definitions to avoid circular imports. module Language.K3.Codegen.CPP.Materialization.Hints where import Control.DeepSeq import Data.Binary import Data.Hashable import Data.Serialize import Data.Typeable import GHC.Generics (Generic) data Method = ConstReferenced | Referenced | Moved | Copied | Forwarded deriving (Eq, Ord, Read, Show, Typeable, Generic) defaultMethod :: Method defaultMethod = Copied data Direction = In | Ex deriving (Eq, Ord, Read, Show, Typeable, Generic) {- Typeclass Instances -} instance NFData Method instance NFData Direction instance Binary Method instance Binary Direction instance Serialize Method instance Serialize Direction instance Hashable Method instance Hashable Direction
DaMSL/K3
src/Language/K3/Codegen/CPP/Materialization/Hints.hs
Haskell
apache-2.0
805
module Str.String where import Prelude hiding (null) import qualified Prelude as P type Str = String null :: Str -> Bool null = P.null singleton :: Char -> Str singleton c = [c] splits :: Str -> [(Str, Str)] splits [] = [([], [])] splits (c:cs) = ([], c:cs):[(c:s1,s2) | (s1,s2) <- splits cs] parts :: Str -> [[Str]] parts [] = [[]] parts [c] = [[[c]]] parts (c:cs) = concat [[(c:p):ps, [c]:p:ps] | p:ps <- parts cs]
DanielG/cabal-helper
tests/bkpregex/str-impls/Str/String.hs
Haskell
apache-2.0
423
module IndentInBracesAgain where f = r{ render = do make return f }
Atsky/haskell-idea-plugin
data/indentTests/IndentInBracesAgain.hs
Haskell
apache-2.0
87
-- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings ( widgetFile , PersistConfig , staticRoot , staticDir , Extra (..) , parseExtra ) where import Prelude import Text.Shakespeare.Text (st) import Language.Haskell.TH.Syntax import Database.Persist.Sqlite (SqliteConf) import Yesod.Default.Config import qualified Yesod.Default.Util import Data.Text (Text) import Data.Yaml import Control.Applicative import Settings.Development import Network.HTTP.Types (Ascii) -- | Which Persistent backend this site is using. type PersistConfig = SqliteConf -- Static setting below. Changing these requires a recompile -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticDir :: FilePath staticDir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in Foundation.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in Foundation.hs staticRoot :: AppConfig DefaultEnv x -> Text staticRoot conf = [st|#{appRoot conf}/static|] -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = if development then Yesod.Default.Util.widgetFileReload else Yesod.Default.Util.widgetFileNoReload data Extra = Extra { extraCopyright :: Text , extraAnalytics :: Maybe Text -- ^ Google Analytics , extraFacebookAppName :: Ascii , extraFacebookAppId :: Integer , extraFacebookSecret :: Ascii } deriving Show parseExtra :: DefaultEnv -> Object -> Parser Extra parseExtra _ o = Extra <$> o .: "copyright" <*> o .:? "analytics" <*> o .: "facebookAppName" <*> o .: "facebookAppId" <*> o .: "facebookSecret"
tmiw/4peas
Settings.hs
Haskell
bsd-2-clause
2,645
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QGraphicsSceneHelpEvent.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QGraphicsSceneHelpEvent ( qGraphicsSceneHelpEvent_delete ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.QEvent import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QscenePos (QGraphicsSceneHelpEvent a) (()) where scenePos x0 () = withPointFResult $ \cpointf_ret_x cpointf_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_scenePos_qth cobj_x0 cpointf_ret_x cpointf_ret_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_scenePos_qth" qtc_QGraphicsSceneHelpEvent_scenePos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr CDouble -> Ptr CDouble -> IO () instance QqscenePos (QGraphicsSceneHelpEvent a) (()) where qscenePos x0 () = withQPointFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_scenePos cobj_x0 foreign import ccall "qtc_QGraphicsSceneHelpEvent_scenePos" qtc_QGraphicsSceneHelpEvent_scenePos :: Ptr (TQGraphicsSceneHelpEvent a) -> IO (Ptr (TQPointF ())) instance QscreenPos (QGraphicsSceneHelpEvent a) (()) where screenPos x0 () = withPointResult $ \cpoint_ret_x cpoint_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_screenPos_qth cobj_x0 cpoint_ret_x cpoint_ret_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_screenPos_qth" qtc_QGraphicsSceneHelpEvent_screenPos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr CInt -> Ptr CInt -> IO () instance QqscreenPos (QGraphicsSceneHelpEvent a) (()) where qscreenPos x0 () = withQPointResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_screenPos cobj_x0 foreign import ccall "qtc_QGraphicsSceneHelpEvent_screenPos" qtc_QGraphicsSceneHelpEvent_screenPos :: Ptr (TQGraphicsSceneHelpEvent a) -> IO (Ptr (TQPoint ())) instance QsetScenePos (QGraphicsSceneHelpEvent a) ((PointF)) where setScenePos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QGraphicsSceneHelpEvent_setScenePos_qth cobj_x0 cpointf_x1_x cpointf_x1_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScenePos_qth" qtc_QGraphicsSceneHelpEvent_setScenePos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> CDouble -> CDouble -> IO () instance QqsetScenePos (QGraphicsSceneHelpEvent a) ((QPointF t1)) where qsetScenePos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsSceneHelpEvent_setScenePos cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScenePos" qtc_QGraphicsSceneHelpEvent_setScenePos :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr (TQPointF t1) -> IO () instance QsetScreenPos (QGraphicsSceneHelpEvent a) ((Point)) where setScreenPos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QGraphicsSceneHelpEvent_setScreenPos_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScreenPos_qth" qtc_QGraphicsSceneHelpEvent_setScreenPos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> CInt -> CInt -> IO () instance QqsetScreenPos (QGraphicsSceneHelpEvent a) ((QPoint t1)) where qsetScreenPos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsSceneHelpEvent_setScreenPos cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScreenPos" qtc_QGraphicsSceneHelpEvent_setScreenPos :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr (TQPoint t1) -> IO () qGraphicsSceneHelpEvent_delete :: QGraphicsSceneHelpEvent a -> IO () qGraphicsSceneHelpEvent_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_delete cobj_x0 foreign import ccall "qtc_QGraphicsSceneHelpEvent_delete" qtc_QGraphicsSceneHelpEvent_delete :: Ptr (TQGraphicsSceneHelpEvent a) -> IO ()
keera-studios/hsQt
Qtc/Gui/QGraphicsSceneHelpEvent.hs
Haskell
bsd-2-clause
4,319
{-# LANGUAGE TupleSections #-} {-| Auto-repair tool for Ganeti. -} {- Copyright (C) 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.HTools.Program.Harep ( main , arguments , options) where import Control.Exception (bracket) import Control.Monad import Data.Function import Data.List import Data.Maybe import Data.Ord import System.Time import qualified Data.Map as Map import Ganeti.BasicTypes import Ganeti.Common import Ganeti.Errors import Ganeti.Jobs import Ganeti.OpCodes import Ganeti.OpParams import Ganeti.Types import Ganeti.Utils import qualified Ganeti.Constants as C import qualified Ganeti.Luxi as L import qualified Ganeti.Path as Path import Ganeti.HTools.CLI import Ganeti.HTools.Loader import Ganeti.HTools.ExtLoader import Ganeti.HTools.Types import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Node as Node -- | Options list and functions. options :: IO [OptType] options = do luxi <- oLuxiSocket return [ luxi , oJobDelay ] arguments :: [ArgCompletion] arguments = [] data InstanceData = InstanceData { arInstance :: Instance.Instance , arState :: AutoRepairStatus , tagsToRemove :: [String] } deriving (Eq, Show) -- | Parse a tag into an 'AutoRepairData' record. -- -- @Nothing@ is returned if the tag is not an auto-repair tag, or if it's -- malformed. parseInitTag :: String -> Maybe AutoRepairData parseInitTag tag = let parsePending = do subtag <- chompPrefix C.autoRepairTagPending tag case sepSplit ':' subtag of [rtype, uuid, ts, jobs] -> makeArData rtype uuid ts jobs _ -> fail ("Invalid tag: " ++ show tag) parseResult = do subtag <- chompPrefix C.autoRepairTagResult tag case sepSplit ':' subtag of [rtype, uuid, ts, result, jobs] -> do arData <- makeArData rtype uuid ts jobs result' <- autoRepairResultFromRaw result return arData { arResult = Just result' } _ -> fail ("Invalid tag: " ++ show tag) makeArData rtype uuid ts jobs = do rtype' <- autoRepairTypeFromRaw rtype ts' <- tryRead "auto-repair time" ts jobs' <- mapM makeJobIdS $ sepSplit '+' jobs return AutoRepairData { arType = rtype' , arUuid = uuid , arTime = TOD ts' 0 , arJobs = jobs' , arResult = Nothing , arTag = tag } in parsePending `mplus` parseResult -- | Return the 'AutoRepairData' element of an 'AutoRepairStatus' type. getArData :: AutoRepairStatus -> Maybe AutoRepairData getArData status = case status of ArHealthy (Just d) -> Just d ArFailedRepair d -> Just d ArPendingRepair d -> Just d ArNeedsRepair d -> Just d _ -> Nothing -- | Return a short name for each auto-repair status. -- -- This is a more concise representation of the status, because the default -- "Show" formatting includes all the accompanying auto-repair data. arStateName :: AutoRepairStatus -> String arStateName status = case status of ArHealthy _ -> "Healthy" ArFailedRepair _ -> "Failure" ArPendingRepair _ -> "Pending repair" ArNeedsRepair _ -> "Needs repair" -- | Return a new list of tags to remove that includes @arTag@ if present. delCurTag :: InstanceData -> [String] delCurTag instData = let arData = getArData $ arState instData rmTags = tagsToRemove instData in case arData of Just d -> arTag d : rmTags Nothing -> rmTags -- | Set the initial auto-repair state of an instance from its auto-repair tags. -- -- The rules when there are multiple tags is: -- -- * the earliest failure result always wins -- -- * two or more pending repairs results in a fatal error -- -- * a pending result from id X and a success result from id Y result in error -- if Y is newer than X -- -- * if there are no pending repairs, the newest success result wins, -- otherwise the pending result is used. setInitialState :: Instance.Instance -> Result InstanceData setInitialState inst = let arData = mapMaybe parseInitTag $ Instance.allTags inst -- Group all the AutoRepairData records by id (i.e. by repair task), and -- present them from oldest to newest. arData' = sortBy (comparing arUuid) arData arGroups = groupBy ((==) `on` arUuid) arData' arGroups' = sortBy (comparing $ minimum . map arTime) arGroups in foldM arStatusCmp (InstanceData inst (ArHealthy Nothing) []) arGroups' -- | Update the initial status of an instance with new repair task tags. -- -- This function gets called once per repair group in an instance's tag, and it -- determines whether to set the status of the instance according to this new -- group, or to keep the existing state. See the documentation for -- 'setInitialState' for the rules to be followed when determining this. arStatusCmp :: InstanceData -> [AutoRepairData] -> Result InstanceData arStatusCmp instData arData = let curSt = arState instData arData' = sortBy (comparing keyfn) arData keyfn d = (arResult d, arTime d) newData = last arData' newSt = case arResult newData of Just ArSuccess -> ArHealthy $ Just newData Just ArEnoperm -> ArHealthy $ Just newData Just ArFailure -> ArFailedRepair newData Nothing -> ArPendingRepair newData in case curSt of ArFailedRepair _ -> Ok instData -- Always keep the earliest failure. ArHealthy _ -> Ok instData { arState = newSt , tagsToRemove = delCurTag instData } ArPendingRepair d -> Bad ( "An unfinished repair was found in instance " ++ Instance.name (arInstance instData) ++ ": found tag " ++ show (arTag newData) ++ ", but older pending tag " ++ show (arTag d) ++ "exists.") ArNeedsRepair _ -> Bad "programming error: ArNeedsRepair found as an initial state" -- | Query jobs of a pending repair, returning the new instance data. processPending :: L.Client -> InstanceData -> IO InstanceData processPending client instData = case arState instData of (ArPendingRepair arData) -> do sts <- L.queryJobsStatus client $ arJobs arData time <- getClockTime case sts of Bad e -> exitErr $ "could not check job status: " ++ formatError e Ok sts' -> if any (<= JOB_STATUS_RUNNING) sts' then return instData -- (no change) else do let iname = Instance.name $ arInstance instData srcSt = arStateName $ arState instData destSt = arStateName arState' putStrLn ("Moving " ++ iname ++ " from " ++ show srcSt ++ " to " ++ show destSt) commitChange client instData' where instData' = instData { arState = arState' , tagsToRemove = delCurTag instData } arState' = if all (== JOB_STATUS_SUCCESS) sts' then ArHealthy $ Just (updateTag $ arData { arResult = Just ArSuccess , arTime = time }) else ArFailedRepair (updateTag $ arData { arResult = Just ArFailure , arTime = time }) _ -> return instData -- | Update the tag of an 'AutoRepairData' record to match all the other fields. updateTag :: AutoRepairData -> AutoRepairData updateTag arData = let ini = [autoRepairTypeToRaw $ arType arData, arUuid arData, clockTimeToString $ arTime arData] end = [intercalate "+" . map (show . fromJobId) $ arJobs arData] (pfx, middle) = case arResult arData of Nothing -> (C.autoRepairTagPending, []) Just rs -> (C.autoRepairTagResult, [autoRepairResultToRaw rs]) in arData { arTag = pfx ++ intercalate ":" (ini ++ middle ++ end) } -- | Apply and remove tags from an instance as indicated by 'InstanceData'. -- -- If the /arState/ of the /InstanceData/ record has an associated -- 'AutoRepairData', add its tag to the instance object. Additionally, if -- /tagsToRemove/ is not empty, remove those tags from the instance object. The -- returned /InstanceData/ object always has an empty /tagsToRemove/. commitChange :: L.Client -> InstanceData -> IO InstanceData commitChange client instData = do let iname = Instance.name $ arInstance instData arData = getArData $ arState instData rmTags = tagsToRemove instData execJobsWaitOk' opcodes = do res <- execJobsWaitOk [map wrapOpCode opcodes] client case res of Ok _ -> return () Bad e -> exitErr e when (isJust arData) $ do let tag = arTag $ fromJust arData putStrLn (">>> Adding the following tag to " ++ iname ++ ":\n" ++ show tag) execJobsWaitOk' [OpTagsSet TagKindInstance [tag] (Just iname)] unless (null rmTags) $ do putStr (">>> Removing the following tags from " ++ iname ++ ":\n" ++ unlines (map show rmTags)) execJobsWaitOk' [OpTagsDel TagKindInstance rmTags (Just iname)] return instData { tagsToRemove = [] } -- | Detect brokenness with an instance and suggest repair type and jobs to run. detectBroken :: Node.List -> Instance.Instance -> Maybe (AutoRepairType, [OpCode]) detectBroken nl inst = let disk = Instance.diskTemplate inst iname = Instance.name inst offPri = Node.offline $ Container.find (Instance.pNode inst) nl offSec = Node.offline $ Container.find (Instance.sNode inst) nl in case disk of DTDrbd8 | offPri && offSec -> Just ( ArReinstall, [ OpInstanceRecreateDisks { opInstanceName = iname , opInstanceUuid = Nothing , opRecreateDisksInfo = RecreateDisksAll , opNodes = [] -- FIXME: there should be a better way to -- specify opcode parameters than abusing -- mkNonEmpty in this way (using the fact -- that Maybe is used both for optional -- fields, and to express failure). , opNodeUuids = Nothing , opIallocator = mkNonEmpty "hail" } , OpInstanceReinstall { opInstanceName = iname , opInstanceUuid = Nothing , opOsType = Nothing , opTempOsParams = Nothing , opForceVariant = False } ]) | offPri -> Just ( ArFailover, [ OpInstanceFailover { opInstanceName = iname , opInstanceUuid = Nothing -- FIXME: ditto, see above. , opShutdownTimeout = fromJust $ mkNonNegative C.defaultShutdownTimeout , opIgnoreConsistency = False , opTargetNode = Nothing , opTargetNodeUuid = Nothing , opIgnoreIpolicy = False , opIallocator = Nothing , opMigrationCleanup = False } ]) | offSec -> Just ( ArFixStorage, [ OpInstanceReplaceDisks { opInstanceName = iname , opInstanceUuid = Nothing , opReplaceDisksMode = ReplaceNewSecondary , opReplaceDisksList = [] , opRemoteNode = Nothing -- FIXME: ditto, see above. , opRemoteNodeUuid = Nothing , opIallocator = mkNonEmpty "hail" , opEarlyRelease = False , opIgnoreIpolicy = False } ]) | otherwise -> Nothing DTPlain | offPri -> Just ( ArReinstall, [ OpInstanceRecreateDisks { opInstanceName = iname , opInstanceUuid = Nothing , opRecreateDisksInfo = RecreateDisksAll , opNodes = [] -- FIXME: ditto, see above. , opNodeUuids = Nothing , opIallocator = mkNonEmpty "hail" } , OpInstanceReinstall { opInstanceName = iname , opInstanceUuid = Nothing , opOsType = Nothing , opTempOsParams = Nothing , opForceVariant = False } ]) | otherwise -> Nothing _ -> Nothing -- Other cases are unimplemented for now: DTDiskless, -- DTFile, DTSharedFile, DTBlock, DTRbd, DTExt. -- | Perform the suggested repair on an instance if its policy allows it. doRepair :: L.Client -- ^ The Luxi client -> Double -- ^ Delay to insert before the first repair opcode -> InstanceData -- ^ The instance data -> (AutoRepairType, [OpCode]) -- ^ The repair job to perform -> IO InstanceData -- ^ The updated instance data doRepair client delay instData (rtype, opcodes) = let inst = arInstance instData ipol = Instance.arPolicy inst iname = Instance.name inst in case ipol of ArEnabled maxtype -> if rtype > maxtype then do uuid <- newUUID time <- getClockTime let arState' = ArNeedsRepair ( updateTag $ AutoRepairData rtype uuid time [] (Just ArEnoperm) "") instData' = instData { arState = arState' , tagsToRemove = delCurTag instData } putStrLn ("Not performing a repair of type " ++ show rtype ++ " on " ++ iname ++ " because only repairs up to " ++ show maxtype ++ " are allowed") commitChange client instData' -- Adds "enoperm" result label. else do putStrLn ("Executing " ++ show rtype ++ " repair on " ++ iname) -- After submitting the job, we must write an autorepair:pending tag, -- that includes the repair job IDs so that they can be checked later. -- One problem we run into is that the repair job immediately grabs -- locks for the affected instance, and the subsequent TAGS_SET job is -- blocked, introducing an unnecessary delay for the end-user. One -- alternative would be not to wait for the completion of the TAGS_SET -- job, contrary to what commitChange normally does; but we insist on -- waiting for the tag to be set so as to abort in case of failure, -- because the cluster is left in an invalid state in that case. -- -- The proper solution (in 2.9+) would be not to use tags for storing -- autorepair data, or make the TAGS_SET opcode not grab an instance's -- locks (if that's deemed safe). In the meantime, we introduce an -- artificial delay in the repair job (via a TestDelay opcode) so that -- once we have the job ID, the TAGS_SET job can complete before the -- repair job actually grabs the locks. (Please note that this is not -- about synchronization, but merely about speeding up the execution of -- the harep tool. If this TestDelay opcode is removed, the program is -- still correct.) let opcodes' = if delay > 0 then OpTestDelay { opDelayDuration = delay , opDelayOnMaster = True , opDelayOnNodes = [] , opDelayOnNodeUuids = Nothing , opDelayRepeat = fromJust $ mkNonNegative 0 , opDelayNoLocks = False } : opcodes else opcodes uuid <- newUUID time <- getClockTime jids <- submitJobs [map wrapOpCode opcodes'] client case jids of Bad e -> exitErr e Ok jids' -> let arState' = ArPendingRepair ( updateTag $ AutoRepairData rtype uuid time jids' Nothing "") instData' = instData { arState = arState' , tagsToRemove = delCurTag instData } in commitChange client instData' -- Adds "pending" label. otherSt -> do putStrLn ("Not repairing " ++ iname ++ " because it's in state " ++ show otherSt) return instData -- | Main function. main :: Options -> [String] -> IO () main opts args = do unless (null args) $ exitErr "this program doesn't take any arguments." luxiDef <- Path.defaultLuxiSocket let master = fromMaybe luxiDef $ optLuxi opts opts' = opts { optLuxi = Just master } (ClusterData _ nl il _ _) <- loadExternalData opts' let iniDataRes = mapM setInitialState $ Container.elems il iniData <- exitIfBad "when parsing auto-repair tags" iniDataRes -- First step: check all pending repairs, see if they are completed. iniData' <- bracket (L.getClient master) L.closeClient $ forM iniData . processPending -- Second step: detect any problems. let repairs = map (detectBroken nl . arInstance) iniData' -- Third step: create repair jobs for broken instances that are in ArHealthy. let maybeRepair c (i, r) = maybe (return i) (repairHealthy c i) r jobDelay = optJobDelay opts repairHealthy c i = case arState i of ArHealthy _ -> doRepair c jobDelay i _ -> const (return i) repairDone <- bracket (L.getClient master) L.closeClient $ forM (zip iniData' repairs) . maybeRepair -- Print some stats and exit. let states = map ((, 1 :: Int) . arStateName . arState) repairDone counts = Map.fromListWith (+) states putStrLn "---------------------" putStrLn "Instance status count" putStrLn "---------------------" putStr . unlines . Map.elems $ Map.mapWithKey (\k v -> k ++ ": " ++ show v) counts
apyrgio/snf-ganeti
src/Ganeti/HTools/Program/Harep.hs
Haskell
bsd-2-clause
20,587
{-# LANGUAGE OverloadedStrings #-} module CurrentCmd where import Data.Text (Text) import qualified Data.Text as T import Text.Printf -- friends import Time import Record import RecordSet -- This command doesn't actually use any command line arguments -- but still respects the spec. currentCmd :: ZonedTime -> [String] -> IO () currentCmd zt _ = do mbRecord <- readCurrentRecord case mbRecord of Just r -> printf "Description: %s\nStarted: %s\n" (T.unpack $ crecDescr r) (prettyTime (zonedTimeZone zt) (crecStart r)) Nothing -> printf "There is no current record.\n"
sseefried/task
src/CurrentCmd.hs
Haskell
bsd-3-clause
627
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Myo.WebSockets.Types ( EventType(..) , MyoID , Version(..) , EMG(..) , Pose(..) , Orientation(..) , Accelerometer(..) , Gyroscope(..) , Arm(..) , Direction(..) , Frame(..) , Event(..) , Command , CommandData(..) , Vibration(..) , StreamEMGStatus(..) , UnlockMode(..) , UserAction(..) , LockingPolicy(..) -- * Lenses , mye_type , mye_timestamp , mye_myo , mye_arm , mye_x_direction , mye_version , mye_warmup_result , mye_rssi , mye_pose , mye_emg , mye_orientation , mye_accelerometer , mye_gyroscope , myv_major , myv_minor , myv_patch , myv_hardware -- * Smart constructors , newCommand ) where import Data.Aeson.TH import Data.Int import Data.Monoid import Data.Scientific import Data.Aeson.Types hiding (Result) import Data.Char import Control.Monad import Control.Applicative import Lens.Family2.TH import qualified Data.Vector as V import qualified Data.Text as T import qualified Data.HashMap.Strict as HM ------------------------------------------------------------------------------- data EventType = EVT_Paired | EVT_Battery_Level | EVT_Locked | EVT_Unlocked | EVT_Warmup_Completed | EVT_Connected | EVT_Disconnected | EVT_Arm_Synced | EVT_Arm_Unsynced | EVT_Orientation | EVT_Pose | EVT_RSSI | EVT_EMG deriving (Show, Eq) ------------------------------------------------------------------------------- newtype MyoID = MyoID Integer deriving (Show, Eq) ------------------------------------------------------------------------------- data Version = Version { _myv_major :: !Integer , _myv_minor :: !Integer , _myv_patch :: !Integer , _myv_hardware :: !Integer } deriving (Show, Eq) ------------------------------------------------------------------------------- -- It's an 8 bit integer data EMG = EMG Int8 deriving (Show, Eq) ------------------------------------------------------------------------------- data Pose = Rest | Fist | Wave_In | Wave_Out | Fingers_Spread | Double_Tap | Unknown deriving (Show, Eq) data Orientation = Orientation { _ori_x :: !Double , _ori_y :: !Double , _ori_z :: !Double , _ori_w :: !Double } deriving (Show, Eq) data Accelerometer = Accelerometer { _acc_x :: !Double , _acc_y :: !Double , _acc_z :: !Double } deriving (Show, Eq) data Gyroscope = Gyroscope { _gyr_x :: !Double , _gyr_y :: !Double , _gyr_z :: !Double } deriving (Show, Eq) ------------------------------------------------------------------------------- data Arm = Arm_Left | Arm_Right deriving (Show, Eq) ------------------------------------------------------------------------------- data Direction = Toward_wrist | Toward_elbow deriving (Show, Eq) ------------------------------------------------------------------------------- data Frame = Evt Event | Cmd Command | Ack Acknowledgement deriving (Show, Eq) instance FromJSON Frame where parseJSON a@(Array v) = case V.toList v of [String "event", o@(Object _)] -> Evt <$> parseJSON o [String "acknowledgement", o@(Object _)] -> Ack <$> parseJSON o [String "command", o@(Object b)] -> case HM.lookup "result" b of Nothing -> Cmd <$> parseJSON o Just _ -> Ack <$> parseJSON o _ -> typeMismatch "Frame: Unexpected payload in Array." a parseJSON v = typeMismatch "Frame: Expecting an Array of frames." v ------------------------------------------------------------------------------- -- TODO: Break down this `Event` type into a mandatory section (type, timestamp, myo) -- and a payload specific field, so that we do not have all this proliferation of -- Maybe. The `FromJSON` instance will need to be written manually, but it's not -- too bad. data Event = Event { _mye_type :: !EventType , _mye_timestamp :: !T.Text , _mye_myo :: !MyoID , _mye_arm :: !(Maybe Arm) , _mye_x_direction :: !(Maybe Direction) , _mye_version :: !(Maybe Version) , _mye_warmup_result :: !(Maybe Result) , _mye_rssi :: !(Maybe Int) , _mye_pose :: !(Maybe Pose) , _mye_emg :: !(Maybe EMG) , _mye_orientation :: !(Maybe Orientation) , _mye_accelerometer :: !(Maybe Accelerometer) , _mye_gyroscope :: !(Maybe Gyroscope) } deriving (Show, Eq) data Acknowledgement = Acknowledgement { _ack_command :: AcknowledgedCommand , _ack_result :: Result } deriving (Show, Eq) data AcknowledgedCommand = ACC_set_locking_policy | ACC_set_stream_emg deriving (Show, Eq) ------------------------------------------------------------------------------- data Result = Success | Fail deriving (Show, Eq) ------------------------------------------------------------------------------- data CommandData = Vibrate Vibration | Set_Stream_EMG StreamEMGStatus | Unlock UnlockMode | Notify_User_Action UserAction | Set_Locking_Policy LockingPolicy | Request_RSSI | Lock deriving (Show, Eq) instance ToJSON CommandData where toJSON cd = case cd of Vibrate v -> object ["command" .= String "vibrate", "type" .= toJSON v] Set_Stream_EMG v -> object ["command" .= String "set_stream_emg", "type" .= toJSON v] Unlock v -> object ["command" .= String "unlock", "type" .= toJSON v] Notify_User_Action v -> object ["command" .= String "notify_user_action", "type" .= toJSON v] Set_Locking_Policy v -> object ["command" .= String "set_locking_policy", "type" .= toJSON v] Lock -> object ["command" .= String "lock"] Request_RSSI -> object ["command" .= String "request_rssi"] instance FromJSON CommandData where parseJSON (Object o) = do (cmd :: T.Text) <- o .: "command" typ <- o .: "type" case cmd of "vibrate" -> Vibrate <$> parseJSON typ "request_rssi" -> pure Request_RSSI "set_stream_emg" -> Set_Stream_EMG <$> parseJSON typ "set_locking_policy" -> Set_Locking_Policy <$> parseJSON typ "unlock" -> Unlock <$> parseJSON typ "lock" -> pure Lock "notify_user_action" -> Notify_User_Action <$> parseJSON typ t -> fail $ "FromJSON CommandData: invalid 'command' found: " <> show t parseJSON t = typeMismatch ("CommandData, expected Object, found " <> show t) t ------------------------------------------------------------------------------- data Vibration = VIB_short | VIB_medium | VIB_long deriving (Show, Eq) ------------------------------------------------------------------------------- data UserAction = UAC_single deriving (Show, Eq) ------------------------------------------------------------------------------- data LockingPolicy = LKP_standard | LKP_none deriving (Show, Eq) ------------------------------------------------------------------------------- data UnlockMode = UMD_timed | UMD_hold deriving (Show, Eq) ------------------------------------------------------------------------------- data StreamEMGStatus = SES_enabled | SES_disabled deriving (Show, Eq) ------------------------------------------------------------------------------- data Command = Command { _myc_myo :: !MyoID , _myc_info :: CommandData } deriving (Show, Eq) instance FromJSON Command where parseJSON v@(Object o) = Command <$> o .: "myo" <*> parseJSON v parseJSON v = fail $ "FromJSON Command, expected Object, found " <> show v instance ToJSON Command where toJSON (Command mid cd) = case toJSON cd of Object b -> object $ ["myo" .= mid] <> HM.toList b v -> error $ "Command: toJSON of CommandData failed, found " <> show v -------------------------------------------------------------------------------- -- | Creates a new `Command`, to be sent to the Myo armband. newCommand :: MyoID -> CommandData -> Command newCommand mid cd = Command mid cd ------------------------------------------------------------------------------- instance FromJSON Version where parseJSON (Array v) = do let lst = V.toList v case liftM2 (,) (Just $ length lst) (mapM toNumber lst) of Just (4, x) -> case mapM floatingOrInteger x of Right [ma, mi, pa, ha] -> return $ Version ma mi pa ha _ -> mzero _ -> mzero parseJSON v = typeMismatch "Version: Expecting an Array like [major, minor, patch, hardware]" v ------------------------------------------------------------------------------- toNumber :: Value -> Maybe Scientific toNumber (Number v) = Just v toNumber _ = Nothing ------------------------------------------------------------------------------- -- TODO: Create an Int8 in a better way than this one! instance FromJSON EMG where parseJSON (Array v) = do let lst = V.toList v case liftM2 (,) (Just $ length lst) (mapM toNumber lst) of Just (8, x) -> case mapM floatingOrInteger x of Right res -> return . EMG . read $ concatMap show res _ -> mzero _ -> mzero parseJSON v = typeMismatch "EMG: Expecting an Array of size 8." v instance FromJSON Gyroscope where parseJSON (Array v) = case V.toList v of [Number x, Number y, Number z] -> return $ Gyroscope (toRealFloat x) (toRealFloat y) (toRealFloat z) _ -> mzero parseJSON v = typeMismatch "Gyroscope: Expecting an Array of Double like [x,y,z]" v instance FromJSON Accelerometer where parseJSON (Array v) = case V.toList v of [Number x, Number y, Number z] -> return $ Accelerometer (toRealFloat x) (toRealFloat y) (toRealFloat z) _ -> mzero parseJSON v = typeMismatch "Accelerometer: Expecting an Array of Double like [x,y,z]" v ------------------------------------------------------------------------------- -- -- JSON instances -- deriveJSON defaultOptions ''MyoID deriveFromJSON defaultOptions { fieldLabelModifier = drop 5 } ''Event deriveFromJSON defaultOptions { constructorTagModifier = map toLower } ''Result deriveJSON defaultOptions { constructorTagModifier = drop 4 . map toLower } ''Vibration deriveJSON defaultOptions { constructorTagModifier = drop 4 . map toLower } ''StreamEMGStatus deriveJSON defaultOptions { constructorTagModifier = drop 4 . map toLower } ''LockingPolicy deriveJSON defaultOptions { constructorTagModifier = map toLower } ''UserAction deriveJSON defaultOptions { constructorTagModifier = map toLower } ''UnlockMode deriveFromJSON defaultOptions { fieldLabelModifier = drop 5 } ''Orientation deriveFromJSON defaultOptions { constructorTagModifier = map toLower . drop 4 } ''EventType deriveFromJSON defaultOptions { constructorTagModifier = map toLower } ''Pose deriveFromJSON defaultOptions { constructorTagModifier = map toLower } ''Direction deriveFromJSON defaultOptions { constructorTagModifier = map toLower . drop 4 } ''Arm deriveFromJSON defaultOptions { fieldLabelModifier = drop 5 } ''Acknowledgement deriveFromJSON defaultOptions { constructorTagModifier = drop 4 } ''AcknowledgedCommand ------------------------------------------------------------------------------- -- -- Lenses -- makeLenses ''Event makeLenses ''Version
adinapoli/myo
src/Myo/WebSockets/Types.hs
Haskell
bsd-3-clause
11,449
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} module Test.Tasty.Hspec ( -- * Test testSpec -- * Options -- | === Re-exported from <https://hackage.haskell.org/package/tasty-smallcheck tasty-smallcheck> , SmallCheckDepth(..) -- | === Re-exported from <https://hackage.haskell.org/package/tasty-quickcheck tasty-quickcheck> , QuickCheckMaxRatio(..) , QuickCheckMaxSize(..) , QuickCheckReplay(..) , QuickCheckTests(..) -- * Hspec re-export , module Test.Hspec ) where import Control.Applicative ((<$>)) import Data.Proxy import Data.Typeable (Typeable) import qualified Test.Hspec as H import qualified Test.Hspec.Core.Spec as H import qualified Test.QuickCheck as QC import qualified Test.Tasty as T import qualified Test.Tasty.SmallCheck as TSC import qualified Test.Tasty.Options as T import qualified Test.Tasty.Providers as T import qualified Test.Tasty.QuickCheck as TQC import qualified Test.Tasty.Runners as T -- For re-export. import Test.Hspec import Test.Tasty.SmallCheck (SmallCheckDepth(..)) import Test.Tasty.QuickCheck (QuickCheckMaxRatio(..), QuickCheckMaxSize(..) , QuickCheckReplay(..), QuickCheckTests(..)) -- | Create a <https://hackage.haskell.org/package/tasty tasty> 'T.TestTree' from an -- <https://hackage.haskell.org/package/hspec Hspec> 'H.Spec'. testSpec :: T.TestName -> H.Spec -> IO T.TestTree testSpec name spec = T.testGroup name . map specTreeToTestTree <$> H.runSpecM spec specTreeToTestTree :: H.SpecTree () -> T.TestTree specTreeToTestTree (H.Node name spec_trees) = T.testGroup name (map specTreeToTestTree spec_trees) specTreeToTestTree (H.NodeWithCleanup cleanup spec_trees) = let test_tree = specTreeToTestTree (H.Node "(unnamed)" spec_trees) in T.WithResource (T.ResourceSpec (return ()) cleanup) (const test_tree) specTreeToTestTree (H.Leaf item) = T.singleTest (H.itemRequirement item) (Item item) hspecResultToTastyResult :: H.Result -> T.Result hspecResultToTastyResult H.Success = T.testPassed "" hspecResultToTastyResult (H.Pending mstr) = T.testFailed ("test pending" ++ maybe "" (": " ++) mstr) hspecResultToTastyResult (H.Fail str) = T.testFailed str newtype Item = Item (H.Item ()) deriving Typeable instance T.IsTest Item where run opts (Item (H.Item _ _ _ ex)) progress = hspecResultToTastyResult <$> ex params ($ ()) hprogress where params :: H.Params params = H.Params { H.paramsQuickCheckArgs = qc_args , H.paramsSmallCheckDepth = sc_depth } where qc_args :: QC.Args qc_args = let TQC.QuickCheckTests num_tests = T.lookupOption opts TQC.QuickCheckReplay replay = T.lookupOption opts TQC.QuickCheckMaxSize max_size = T.lookupOption opts TQC.QuickCheckMaxRatio max_ratio = T.lookupOption opts in QC.stdArgs { QC.chatty = False , QC.maxDiscardRatio = max_ratio , QC.maxSize = max_size , QC.maxSuccess = num_tests , QC.replay = replay } sc_depth :: Int sc_depth = let TSC.SmallCheckDepth depth = T.lookupOption opts in depth hprogress :: H.Progress -> IO () hprogress (x,y) = progress $ T.Progress { T.progressText = "" , T.progressPercent = fromIntegral x / fromIntegral y } testOptions = return [ T.Option (Proxy :: Proxy TQC.QuickCheckTests) , T.Option (Proxy :: Proxy TQC.QuickCheckReplay) , T.Option (Proxy :: Proxy TQC.QuickCheckMaxSize) , T.Option (Proxy :: Proxy TQC.QuickCheckMaxRatio) , T.Option (Proxy :: Proxy TSC.SmallCheckDepth) ]
markus1189/tasty-hspec
Test/Tasty/Hspec.hs
Haskell
bsd-3-clause
3,986
{- - Claq (c) 2013 NEC Laboratories America, Inc. All rights reserved. - - This file is part of Claq. - Claq is distributed under the 3-clause BSD license. - See the LICENSE file for more details. -} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} module Data.ClassicalCircuit (ClaGate(..), ClaCircuit(..)) where import Data.Foldable (Foldable) import Data.Traversable (Traversable) import Data.DAG (DAG) import qualified Data.DAG as DAG import Data.ExitF data ClaGate a = GConst Bool | GNot a | GAnd a a | GOr a a | GXor a a deriving (Eq, Show, Functor, Foldable, Traversable) newtype ClaCircuit inp = ClaCircuit (DAG (ExitF inp ClaGate)) instance Functor ClaCircuit where fmap f (ClaCircuit g) = ClaCircuit $ DAG.mapDAG (mapExitF f) g
ti1024/claq
src/Data/ClassicalCircuit.hs
Haskell
bsd-3-clause
805
module Graphics.UI.SDL.Basic ( -- * Initialization and Shutdown init, initSubSystem, quit, quitSubSystem, setMainReady, wasInit, -- * Configuration Variables addHintCallback, clearHints, delHintCallback, getHint, setHint, setHintWithPriority, -- * Error Handling clearError, getError, setError, -- * Log Handling log, logCritical, logDebug, logError, logGetOutputFunction, logGetPriority, logInfo, logMessage, logResetPriorities, logSetAllPriority, logSetOutputFunction, logSetPriority, logVerbose, logWarn, -- * Assertions -- | Use Haskell's own assertion primitives rather than SDL's. -- * Querying SDL Version getRevision, getRevisionNumber, getVersion ) where import Data.Word import Foreign.C.String import Foreign.C.Types import Foreign.Ptr import Graphics.UI.SDL.Enum import Graphics.UI.SDL.Types import Prelude hiding (init, log) foreign import ccall "SDL.h SDL_Init" init :: InitFlag -> IO CInt foreign import ccall "SDL.h SDL_InitSubSystem" initSubSystem :: InitFlag -> IO CInt foreign import ccall "SDL.h SDL_Quit" quit :: IO () foreign import ccall "SDL.h SDL_QuitSubSystem" quitSubSystem :: InitFlag -> IO () foreign import ccall "SDL.h SDL_SetMainReady" setMainReady :: IO () foreign import ccall "SDL.h SDL_WasInit" wasInit :: InitFlag -> IO Word32 foreign import ccall "SDL.h SDL_AddHintCallback" addHintCallback :: CString -> HintCallback -> Ptr () -> IO () foreign import ccall "SDL.h SDL_ClearHints" clearHints :: IO () foreign import ccall "SDL.h SDL_DelHintCallback" delHintCallback :: CString -> HintCallback -> Ptr () -> IO () foreign import ccall "SDL.h SDL_GetHint" getHint :: CString -> IO CString foreign import ccall "SDL.h SDL_SetHint" setHint :: CString -> CString -> IO Bool foreign import ccall "SDL.h SDL_SetHintWithPriority" setHintWithPriority :: CString -> CString -> HintPriority -> IO Bool foreign import ccall "SDL.h SDL_ClearError" clearError :: IO () foreign import ccall "SDL.h SDL_GetError" getError :: IO CString foreign import ccall "sdlhelper.c SDLHelper_SetError" setError :: CString -> IO CInt foreign import ccall "SDL.h SDL_LogGetOutputFunction" logGetOutputFunction :: Ptr LogOutputFunction -> Ptr (Ptr ()) -> IO () foreign import ccall "SDL.h SDL_LogGetPriority" logGetPriority :: CInt -> IO LogPriority foreign import ccall "sdlhelper.c SDLHelper_LogMessage" logMessage :: CInt -> LogPriority -> CString -> IO () foreign import ccall "SDL.h SDL_LogResetPriorities" logResetPriorities :: IO () foreign import ccall "SDL.h SDL_LogSetAllPriority" logSetAllPriority :: LogPriority -> IO () foreign import ccall "SDL.h SDL_LogSetOutputFunction" logSetOutputFunction :: LogOutputFunction -> Ptr () -> IO () foreign import ccall "SDL.h SDL_LogSetPriority" logSetPriority :: CInt -> LogPriority -> IO () foreign import ccall "SDL.h SDL_GetRevision" getRevision :: IO CString foreign import ccall "SDL.h SDL_GetRevisionNumber" getRevisionNumber :: IO CInt foreign import ccall "SDL.h SDL_GetVersion" getVersion :: Ptr Version -> IO () log :: CString -> IO () log = logMessage SDL_LOG_CATEGORY_APPLICATION SDL_LOG_PRIORITY_INFO logCritical :: CInt -> CString -> IO () logCritical category = logMessage category SDL_LOG_PRIORITY_CRITICAL logDebug :: CInt -> CString -> IO () logDebug category = logMessage category SDL_LOG_PRIORITY_DEBUG logError :: CInt -> CString -> IO () logError category = logMessage category SDL_LOG_PRIORITY_ERROR logInfo :: CInt -> CString -> IO () logInfo category = logMessage category SDL_LOG_PRIORITY_INFO logVerbose :: CInt -> CString -> IO () logVerbose category = logMessage category SDL_LOG_PRIORITY_VERBOSE logWarn :: CInt -> CString -> IO () logWarn category = logMessage category SDL_LOG_PRIORITY_WARN
ekmett/sdl2
Graphics/UI/SDL/Basic.hs
Haskell
bsd-3-clause
3,737
module EarleyExampleSpec where import EarleyExample (grammar, NumberWord, Expected) import qualified Text.Earley as E import qualified Data.List.NonEmpty as NonEmpty import Test.Hspec (Spec, hspec, describe, it, shouldMatchList) -- | Required for auto-discovery. spec :: Spec spec = describe "EarleyExample" $ do it "returns all possible parses of number words" $ do let (result, _) = parseNumberWord 1234 map NonEmpty.toList result `shouldMatchList` ["ABCD", "AWD", "LCD"] parseNumberWord :: Integer -> ([NumberWord], E.Report Expected String) parseNumberWord = E.fullParses (E.parser grammar) . show main :: IO () main = hspec spec
FranklinChen/twenty-four-days2015-of-hackage
test/EarleyExampleSpec.hs
Haskell
bsd-3-clause
665
module Consts where import Data.Text -- | TODO: move to SDL module type WindowName = Text mainWindowName :: WindowName mainWindowName = "mainWindow"
Teaspot-Studio/gore-and-ash-game
src/client/Consts.hs
Haskell
bsd-3-clause
153
{-# LANGUAGE TypeFamilies, ExistentialQuantification, FlexibleInstances, UndecidableInstances, FlexibleContexts, ScopedTypeVariables, MultiParamTypeClasses #-} -- | The Signal module serves as a representation for the combined shallow and -- deep embeddings of sequential circuits. The shallow portion is reprented as a -- stream, the deep portion as a (typed) entity. To allow for multiple clock -- domains, the Signal type includes an extra type parameter. The type alias 'Seq' -- is for sequential logic in some implicit global clock domain. module Language.KansasLava.Signal where import Control.Applicative import Control.Monad (liftM, liftM2, liftM3) import Data.List as List import Data.Bits import Data.Sized.Ix import Data.Sized.Matrix as M -- import Language.KansasLava.Comb import Language.KansasLava.Rep --import Language.KansasLava.Signal import qualified Language.KansasLava.Stream as S import Language.KansasLava.Types ----------------------------------------------------------------------------------------------- -- | These are sequences of values over time. -- We assume edge triggered logic (checked at (typically) rising edge of clock) -- This clock is assumed known, based on who is consuming the list. -- Right now, it is global, but we think we can support multiple clocks with a bit of work. data Signal (c :: *) a = Signal (S.Stream (X a)) (D a) -- | Signal in some implicit clock domain. type Seq a = Signal CLK a -- | Extract the shallow portion of a 'Signal'. shallowS :: Signal c a -> S.Stream (X a) shallowS (Signal a _) = a -- | Extract the deep portion of a 'Signal'. deepS :: Signal c a -> D a deepS (Signal _ d) = d deepMapS :: (D a -> D a) -> Signal c a -> Signal c a deepMapS f (Signal a d) = (Signal a (f d)) shallowMapS :: (S.Stream (X a) -> S.Stream (X a)) -> Signal c a -> Signal c a shallowMapS f (Signal a d) = (Signal (f a) d) -- | A pure 'Signal'. pureS :: (Rep a) => a -> Signal i a pureS a = Signal (pure (pureX a)) (D $ Lit $ toRep $ pureX a) -- | A 'Signal' witness identity function. Useful when typing things. witnessS :: (Rep a) => Witness a -> Signal i a -> Signal i a witnessS (Witness) = id -- | Inject a deep value into a Signal. The shallow portion of the Signal will be an -- error, if it is every used. mkDeepS :: D a -> Signal c a mkDeepS = Signal (error "incorrect use of shallow Signal") -- | Inject a shallow value into a Signal. The deep portion of the Signal will be an -- Error if it is ever used. mkShallowS :: (Clock c) => S.Stream (X a) -> Signal c a mkShallowS s = Signal s (D $ Error "incorrect use of deep Signal") -- | Create a Signal with undefined for both the deep and shallow elements. undefinedS :: forall a sig clk . (Rep a, sig ~ Signal clk) => sig a undefinedS = Signal (pure $ (unknownX :: X a)) (D $ Lit $ toRep (unknownX :: X a)) -- | Attach a comment to a 'Signal'. commentS :: forall a sig clk . (Rep a, sig ~ Signal clk) => String -> sig a -> sig a commentS msg = idS (Comment [msg]) ----------------------------------------------------------------------- -- primitive builders -- | 'idS' create an identity function, with a given 'Id' tag. idS :: forall a sig clk . (Rep a, sig ~ Signal clk) => Id -> sig a -> sig a idS id' (Signal a ae) = Signal a $ D $ Port "o0" $ E $ Entity id' [("o0",repType (Witness :: Witness a))] [("i0",repType (Witness :: Witness a),unD $ ae)] -- | create a zero-arity Signal value from an 'X' value. primXS :: (Rep a) => X a -> String -> Signal i a primXS a nm = Signal (pure a) (entityD nm) -- | create an arity-1 Signal function from an 'X' function. primXS1 :: forall a b i . (Rep a, Rep b) => (X a -> X b) -> String -> Signal i a -> Signal i b primXS1 f nm (Signal a1 ae1) = Signal (fmap f a1) (entityD1 nm ae1) -- | create an arity-2 Signal function from an 'X' function. primXS2 :: forall a b c i . (Rep a, Rep b, Rep c) => (X a -> X b -> X c) -> String -> Signal i a -> Signal i b -> Signal i c primXS2 f nm (Signal a1 ae1) (Signal a2 ae2) = Signal (S.zipWith f a1 a2) (entityD2 nm ae1 ae2) -- | create an arity-3 Signal function from an 'X' function. primXS3 :: forall a b c d i . (Rep a, Rep b, Rep c, Rep d) => (X a -> X b -> X c -> X d) -> String -> Signal i a -> Signal i b -> Signal i c -> Signal i d primXS3 f nm (Signal a1 ae1) (Signal a2 ae2) (Signal a3 ae3) = Signal (S.zipWith3 f a1 a2 a3) (entityD3 nm ae1 ae2 ae3) -- | create a zero-arity Signal value from a value. primS :: (Rep a) => a -> String -> Signal i a primS a nm = primXS (pureX a) nm -- | create an arity-1 Signal function from a function. primS1 :: (Rep a, Rep b) => (a -> b) -> String -> Signal i a -> Signal i b primS1 f nm = primXS1 (\ a -> optX $ liftM f (unX a)) nm -- | create an arity-2 Signal function from a function. primS2 :: (Rep a, Rep b, Rep c) => (a -> b -> c) -> String -> Signal i a -> Signal i b -> Signal i c primS2 f nm = primXS2 (\ a b -> optX $ liftM2 f (unX a) (unX b)) nm -- | create an arity-3 Signal function from a function. primS3 :: (Rep a, Rep b, Rep c, Rep d) => (a -> b -> c -> d) -> String -> Signal i a -> Signal i b -> Signal i c -> Signal i d primS3 f nm = primXS3 (\ a b c -> optX $ liftM3 f (unX a) (unX b) (unX c)) nm --------------------------------------------------------------------------------- instance (Rep a, Show a) => Show (Signal c a) where show (Signal vs _) = concat [ showRep x ++ " " | x <- take 20 $ S.toList vs ] ++ "..." instance (Rep a, Eq a) => Eq (Signal c a) where -- Silly question; never True; can be False. (Signal _ _) == (Signal _ _) = error "undefined: Eq over a Signal" instance (Num a, Rep a) => Num (Signal i a) where s1 + s2 = primS2 (+) "+" s1 s2 s1 - s2 = primS2 (-) "-" s1 s2 s1 * s2 = primS2 (*) "*" s1 s2 negate s1 = primS1 (negate) "negate" s1 abs s1 = primS1 (abs) "abs" s1 signum s1 = primS1 (signum) "signum" s1 fromInteger n = pureS (fromInteger n) instance (Bounded a, Rep a) => Bounded (Signal i a) where minBound = pureS $ minBound maxBound = pureS $ maxBound instance (Show a, Bits a, Rep a) => Bits (Signal i a) where s1 .&. s2 = primS2 (.&.) ".&." s1 s2 s1 .|. s2 = primS2 (.|.) ".|." s1 s2 s1 `xor` s2 = primS2 (xor) ".^." s1 s2 s1 `shiftL` n = primS2 (shiftL) "shiftL" s1 (pureS n) s1 `shiftR` n = primS2 (shiftR) "shiftR" s1 (pureS n) s1 `rotateL` n = primS2 (rotateL) "rotateL" s1 (pureS n) s1 `rotateR` n = primS2 (rotateR) "rotateR" s1 (pureS n) complement s = primS1 (complement) "complement" s bitSize s = typeWidth (typeOfS s) isSigned s = isTypeSigned (typeOfS s) instance (Eq a, Show a, Fractional a, Rep a) => Fractional (Signal i a) where s1 / s2 = primS2 (/) "/" s1 s2 recip s1 = primS1 (recip) "recip" s1 -- This should just fold down to the raw bits. fromRational r = pureS (fromRational r :: a) instance (Rep a, Enum a) => Enum (Signal i a) where toEnum = error "toEnum not supported" fromEnum = error "fromEnum not supported" instance (Ord a, Rep a) => Ord (Signal i a) where compare _ _ = error "compare not supported for Comb" (<) _ _ = error "(<) not supported for Comb" (>=) _ _ = error "(>=) not supported for Comb" (>) _ _ = error "(>) not supported for Comb" (<=)_ _ = error "(<=) not supported for Comb" s1 `max` s2 = primS2 max "max" s1 s2 s1 `min` s2 = primS2 max "min" s1 s2 instance (Rep a, Real a) => Real (Signal i a) where toRational = error "toRational not supported for Comb" instance (Rep a, Integral a) => Integral (Signal i a) where quot num dom = primS2 quot "quot" num dom rem num dom = primS2 rem "rem" num dom div num dom = primS2 div "div" num dom mod num dom = primS2 mod "mod" num dom quotRem num dom = (quot num dom, rem num dom) divMod num dom = (div num dom, mod num dom) toInteger = error "toInteger (Signal {})" ---------------------------------------------------------------------------------------------------- -- Small DSL's for declaring signals -- | Convert a list of values into a Signal. The shallow portion of the resulting -- Signal will begin with the input list, then an infinite stream of X unknowns. toS :: (Clock c, Rep a) => [a] -> Signal c a toS xs = mkShallowS (S.fromList (map optX (map Just xs ++ repeat Nothing))) -- | Convert a list of values into a Signal. The input list is wrapped with a -- Maybe, and any Nothing elements are mapped to X's unknowns. toS' :: (Clock c, Rep a) => [Maybe a] -> Signal c a toS' xs = mkShallowS (S.fromList (map optX (xs ++ repeat Nothing))) -- | Convert a list of X values to a Signal. Pad the end with an infinite list of X unknowns. toSX :: forall a c . (Clock c, Rep a) => [X a] -> Signal c a toSX xs = mkShallowS (S.fromList (xs ++ map (optX :: Maybe a -> X a) (repeat Nothing))) -- | Convert a Signal of values into a list of Maybe values. fromS :: (Rep a) => Signal c a -> [Maybe a] fromS = fmap unX . S.toList . shallowS -- | Convret a Signal of values into a list of representable values. fromSX :: (Rep a) => Signal c a -> [X a] fromSX = S.toList . shallowS -- | Compare the first depth elements of two Signals. cmpSignalRep :: forall a c . (Rep a) => Int -> Signal c a -> Signal c a -> Bool cmpSignalRep depth s1 s2 = and $ take depth $ S.toList $ S.zipWith cmpRep (shallowS s1) (shallowS s2) ----------------------------------------------------------------------------------- instance Dual (Signal c a) where dual c d = Signal (shallowS c) (deepS d) -- | Return the Lava type of a representable signal. typeOfS :: forall w clk sig . (Rep w, sig ~ Signal clk) => sig w -> Type typeOfS _ = repType (Witness :: Witness w) -- | The Pack class allows us to move between signals containing compound data -- and signals containing the elements of the compound data. This is done by -- commuting the signal type constructor with the type constructor representing -- the compound data. For example, if we have a value x :: Signal sig => sig -- (a,b), then 'unpack x' converts this to a (sig a, sig b). Dually, pack takes -- (sig a,sig b) to sig (a,b). class Pack clk a where type Unpacked clk a -- ^ Pull the sig type *out* of the compound data type. pack :: Unpacked clk a -> Signal clk a -- ^ Push the sign type *into* the compound data type. unpack :: Signal clk a -> Unpacked clk a -- | Given a function over unpacked (composite) signals, turn it into a function -- over packed signals. mapPacked :: (Pack i a, Pack i b, sig ~ Signal i) => (Unpacked i a -> Unpacked i b) -> sig a -> sig b mapPacked f = pack . f . unpack -- | Lift a binary function operating over unpacked signals into a function over a pair of packed signals. zipPacked :: (Pack i a, Pack i b, Pack i c, sig ~ Signal i) => (Unpacked i a -> Unpacked i b -> Unpacked i c) -> sig a -> sig b -> sig c zipPacked f x y = pack $ f (unpack x) (unpack y) instance (Rep a, Rep b) => Pack i (a,b) where type Unpacked i (a,b) = (Signal i a,Signal i b) pack (a,b) = primS2 (,) "pair" a b unpack ab = ( primS1 (fst) "fst" ab , primS1 (snd) "snd" ab ) instance (Rep a, Rep b, Rep c) => Pack i (a,b,c) where type Unpacked i (a,b,c) = (Signal i a,Signal i b, Signal i c) pack (a,b,c) = primS3 (,,) "triple" a b c unpack abc = ( primS1 (\(x,_,_) -> x) "fst3" abc , primS1 (\(_,x,_) -> x) "snd3" abc , primS1 (\(_,_,x) -> x) "thd3" abc ) instance (Rep a) => Pack i (Maybe a) where type Unpacked i (Maybe a) = (Signal i Bool, Signal i a) pack (a,b) = primXS2 (\ a' b' -> case unX a' of Nothing -> optX Nothing Just False -> optX $ Just Nothing Just True -> optX (Just (unX b'))) "pair" a b unpack ma = ( primXS1 (\ a -> case unX a of Nothing -> optX Nothing Just Nothing -> optX (Just False) Just (Just _) -> optX (Just True)) "fst" ma , primXS1 (\ a -> case unX a of Nothing -> optX Nothing Just Nothing -> optX Nothing Just (Just v) -> optX (Just v)) "snd" ma ) {- instance (Rep a, Rep b, Rep c, Signal sig) => Pack sig (a,b,c) where type Unpacked sig (a,b,c) = (sig a, sig b,sig c) pack (a,b,c) = liftS3 (\ (Comb a' ae) (Comb b' be) (Comb c' ce) -> Comb (XTriple (a',b',c')) (entity3 (Prim "triple") ae be ce)) a b c unpack abc = ( liftS1 (\ (Comb (XTriple (a,_b,_)) abce) -> Comb a (entity1 (Prim "fst3") abce)) abc , liftS1 (\ (Comb (XTriple (_,b,_)) abce) -> Comb b (entity1 (Prim "snd3") abce)) abc , liftS1 (\ (Comb (XTriple (_,_,c)) abce) -> Comb c (entity1 (Prim "thd3") abce)) abc ) -} unpackMatrix :: (Rep a, Size x, sig ~ Signal clk) => sig (M.Matrix x a) -> M.Matrix x (sig a) unpackMatrix a = unpack a packMatrix :: (Rep a, Size x, sig ~ Signal clk) => M.Matrix x (sig a) -> sig (M.Matrix x a) packMatrix a = pack a instance (Rep a, Size ix) => Pack clk (Matrix ix a) where type Unpacked clk (Matrix ix a) = Matrix ix (Signal clk a) pack m = Signal shallow deep where shallow :: (S.Stream (X (Matrix ix a))) shallow = id $ S.fromList -- Stream (X (Matrix ix a)) $ fmap XMatrix -- [(X (Matrix ix a))] $ fmap M.fromList -- [Matrix ix (X a)] $ List.transpose -- [[X a]] $ fmap S.toList -- [[X a]] $ fmap shallowS -- [Stream (X a)] $ M.toList -- [sig a] $ m -- Matrix ix (sig a) deep :: D (Matrix ix a) deep = D $ Port "o0" $ E $ Entity (Prim "concat") [("o0",repType (Witness :: Witness (Matrix ix a)))] [ ("i" ++ show i,repType (Witness :: Witness a),unD $ deepS $ x) | (x,i) <- zip (M.toList m) ([0..] :: [Int]) ] unpack ms = forAll $ \ i -> Signal (shallow i) (deep i) where mx :: (Size ix) => Matrix ix Integer mx = matrix (Prelude.zipWith (\ _ b -> b) (M.indices mx) [0..]) deep i = D $ Port "o0" $ E $ Entity (Prim "index") [("o0",repType (Witness :: Witness a))] [("i0",GenericTy,Generic (mx ! i)) ,("i1",repType (Witness :: Witness (Matrix ix a)),unD $ deepS ms) ] shallow i = fmap (liftX (M.! i)) (shallowS ms) ---------------------------------------------------------------- -- | a delay is a register with no defined default / initial value. delay :: forall a clk . (Rep a, Clock clk) => Signal clk a -> Signal clk a delay ~(Signal line eline) = res where def = optX $ Nothing -- rep = toRep def res = Signal sres1 (D $ Port ("o0") $ E $ entity) sres0 = line sres1 = S.Cons def sres0 entity = Entity (Prim "delay") [("o0", typeOfS res)] [("i0", typeOfS res, unD eline), ("clk",ClkTy, Pad "clk"), ("rst",B, Pad "rst") ] -- | delays generates a serial sequence of n delays. delays :: forall a clk . (Rep a, Clock clk) => Int -> Signal clk a -> Signal clk a delays n ss = iterate delay ss !! n -- | A register is a state element with a reset. The reset is supplied by the clock domain in the Signal. register :: forall a clk . (Rep a, Clock clk) => a -> Signal clk a -> Signal clk a register first ~(Signal line eline) = res where def = optX $ Just first rep = toRep def res = Signal sres1 (D $ Port ("o0") $ E $ entity) sres0 = line sres1 = S.Cons def sres0 entity = Entity (Prim "register") [("o0", typeOfS res)] [("i0", typeOfS res, unD eline), ("def",GenericTy,Generic (fromRepToInteger rep)), ("clk",ClkTy, Pad "clk"), ("rst",B, Pad "rst") ] -- | registers generates a serial sequence of n registers, all with the same initial value. registers :: forall a clk . (Rep a, Clock clk) => Int -> a -> Signal clk a -> Signal clk a registers n def ss = iterate (register def) ss !! n ----------------------------------------------------------------------------------- -- The 'deep' combinators, used to build the deep part of a signal. entityD :: forall a . (Rep a) => String -> D a entityD nm = D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))] [] entityD1 :: forall a1 a . (Rep a, Rep a1) => String -> D a1 -> D a entityD1 nm (D a1) = D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))] [("i0",repType (Witness :: Witness a1),a1)] entityD2 :: forall a1 a2 a . (Rep a, Rep a1, Rep a2) => String -> D a1 -> D a2 -> D a entityD2 nm (D a1) (D a2) = D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))] [("i0",repType (Witness :: Witness a1),a1) ,("i1",repType (Witness :: Witness a2),a2)] entityD3 :: forall a1 a2 a3 a . (Rep a, Rep a1, Rep a2, Rep a3) => String -> D a1 -> D a2 -> D a3 -> D a entityD3 nm (D a1) (D a2) (D a3) = D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))] [("i0",repType (Witness :: Witness a1),a1) ,("i1",repType (Witness :: Witness a2),a2) ,("i2",repType (Witness :: Witness a3),a3)] pureD :: (Rep a) => a -> D a pureD a = pureXD (pureX a) pureXD :: (Rep a) => X a -> D a pureXD a = D $ Lit $ toRep a
andygill/kansas-lava
Language/KansasLava/Signal.hs
Haskell
bsd-3-clause
18,502
{-# LANGUAGE MultiParamTypeClasses #-} -- Standard modules. import Control.Monad import Control.Monad.Trans import Data.List import qualified Data.Map as M import Data.Maybe import System.Random -- Modules provided by this library. import Control.Monad.Dist import Control.Monad.Maybe import Control.Monad.Perhaps import Data.Prob -- ======================================================================== -- Spam Filtering -- -- Inspired by <http://www.paulgraham.com/spam.html> and -- <http://www.mathpages.com/home/kmath267.htm>. -- Each message is spam (junk mail) or "ham" (good mail). data MsgType = Spam | Ham deriving (Show, Eq, Enum, Bounded) hasWord :: String -> FDist' MsgType -> FDist' MsgType hasWord word prior = do msgType <- prior wordPresent <- wordPresentIn msgType word condition wordPresent return msgType -- > bayes msgTypePrior -- [Perhaps Spam 64.2%,Perhaps Ham 35.8%] -- > bayes (hasWord "free" msgTypePrior) -- [Perhaps Spam 90.5%,Perhaps Ham 9.5%] wordPresentIn msgType word = boolDist (Prob (n/total)) where wordCounts = findWordCounts word n = entryFor msgType wordCounts total = entryFor msgType msgCounts boolDist :: Prob -> FDist' Bool boolDist (Prob p) = weighted [(True, p), (False, 1-p)] msgCounts = [102, 57] wordCountTable = M.fromList [("free", [57, 6]), -- Lots of words... ("bayes", [1, 10]), ("monad", [0, 22])] entryFor :: Enum a => a -> [b] -> b entryFor x ys = ys !! fromEnum x findWordCounts word = M.findWithDefault [0,0] word wordCountTable msgTypePrior :: Dist d => d MsgType msgTypePrior = weighted (zipWith (,) [Spam,Ham] msgCounts) -- > bayes (hasWord "bayes" msgTypePrior) -- [Perhaps Spam 9.1%,Perhaps Ham 90.9%] hasWords [] prior = prior hasWords (w:ws) prior = do hasWord w (hasWords ws prior) -- > bayes (hasWords ["free","bayes"] msgTypePrior) -- [Perhaps Spam 34.7%,Perhaps Ham 65.3%] uniformAll :: (Dist d,Enum a,Bounded a) => d a uniformAll = uniform allValues allValues :: (Enum a,Bounded a) => [a] allValues = enumFromTo minBound maxBound -- > bayes (uniformAll :: FDist' MsgType) -- [Perhaps Spam 50.0%,Perhaps Ham 50.0%] characteristic f = f uniformAll -- > bayes (characteristic (hasWord "free")) -- [Perhaps Spam 84.1%,Perhaps Ham 15.9%] score f = distance (characteristic f) uniformAll distance :: (Eq a, Enum a, Bounded a) => FDist' a -> FDist' a -> Double distance dist1 dist2 = sum (map (^2) (zipWith (-) ps1 ps2)) where ps1 = vectorFromDist dist1 ps2 = vectorFromDist dist2 vectorFromDist dist = map doubleFromProb (probsFromDist dist) probsFromDist dist = map (\x -> (sumProbs . matching x) (bayes dist)) allValues where matching x = filter ((==x) . perhapsValue) sumProbs = sum . map perhapsProb adjustMinimums xs = map (/ total) adjusted where adjusted = map (max 0.01) xs total = sum adjusted adjustedProbsFromDist dist = adjustMinimums (probsFromDist dist) classifierProbs f = adjustedProbsFromDist (characteristic f) --applyProbs :: (Enum a) => [Prob] -> FDist' a -> FDist' a applyProbs probs prior = do msgType <- prior applyProb (entryFor msgType probs) return msgType -- Will need LaTeX PNG to explain. applyProb :: Prob -> FDist' () applyProb p = do b <- boolDist p condition b -- > bayes (hasWord "free" msgTypePrior) -- [Perhaps Spam 90.5%,Perhaps Ham 9.5%] -- > let probs = classifierProbs (hasWord "free") -- > bayes (applyProbs probs msgTypePrior) -- [Perhaps Spam 90.5%,Perhaps Ham 9.5%] data Classifier = Classifier Double [Prob] deriving Show classifier f = Classifier (score f) (classifierProbs f) applyClassifier (Classifier _ probs) = applyProbs probs instance Eq Classifier where (Classifier s1 _) == (Classifier s2 _) = s1 == s2 instance Ord Classifier where compare (Classifier s1 _) (Classifier s2 _) = compare s2 s1 -- > classifier (hasWord "free") -- Classifier 0.23 [84.1%,15.9%] classifiers :: M.Map String Classifier classifiers = M.mapWithKey toClassifier wordCountTable where toClassifier w _ = classifier (hasWord w) findClassifier :: String -> Maybe Classifier findClassifier w = M.lookup w classifiers findClassifiers n ws = take n (sort classifiers) where classifiers = catMaybes (map findClassifier ws) hasTokens ws prior = foldr applyClassifier prior (findClassifiers 15 ws) -- > bayes (hasTokens ["bayes", "free"] -- msgTypePrior) -- [Perhaps Spam 34.7%,Perhaps Ham 65.3%] -- ======================================================================== -- Robot localization -- -- Example based on "Bayesian Filters for Location Estimation", Fox et al., -- 2005. Available online at: -- -- http://seattle.intel-research.net/people/jhightower/pubs/fox2003bayesian/fox2003bayesian.pdf -- The hallway extends from 0 to 299, and -- it contains three doors. doorAtPosition :: Int -> Bool doorAtPosition pos -- Doors 1, 2 and 3. | 26 <= pos && pos < 58 = True | 82 <= pos && pos < 114 = True | 192 <= pos && pos < 224 = True | otherwise = False localizeRobot :: WPS Int localizeRobot = do -- Pick a random starting location -- to use as a hypothesis. pos1 <- uniform [0..299] -- We know we're at a door. Hypotheses -- which agree with this fact get a -- weight of 1, others get 0. if doorAtPosition pos1 then weight 1 else weight 0 -- Drive forward a bit. let pos2 = pos1 + 28 -- We know we're not at a door. if not (doorAtPosition pos2) then weight 1 else weight 0 -- Drive forward some more. let pos3 = pos2 + 28 if doorAtPosition pos3 then weight 1 else weight 0 -- Our final hypothesis. return pos3 -- > runRand (runWPS localizeRobot 10) -- [Perhaps 106 100.0%, -- never,never,never,never,never, -- Perhaps 93 100.0%, -- never,never,never] -- > runWPS' localizeRobot 10 -- [97,109,93] -- ======================================================================== -- Random sampling -- -- Heavily inspired by Sungwoo Park and colleagues' $\lambda_{\bigcirc}$ -- caculus <http://citeseer.ist.psu.edu/752237.html>. -- -- See <http://www.randomhacks.net/articles/2007/02/21/randomly-sampled-distributions>. histogram :: Ord a => [a] -> [Int] histogram = map length . group . sort -- ======================================================================== -- Particle System newtype PS a = PS { runPS :: Int -> Rand [a] } liftRand :: Rand a -> PS a liftRand r = PS (sample r) instance Functor PS where fmap f ps = PS mapped where mapped n = liftM (map f) (runPS ps n) instance Monad PS where return = liftRand . return ps >>= f = joinPS (fmap f ps) joinPS :: PS (PS a) -> PS a joinPS psps = PS (joinPS' psps) joinPS' :: PS (PS a) -> Int -> Rand [a] joinPS' psps n = do pss <- (runPS psps n) xs <- sequence (map sample1 pss) return (concat xs) -- TODO: Can we base on Rand's join? where sample1 ps = runPS ps 1 instance Dist PS where weighted = liftRand . weighted type WPS = PerhapsT PS instance Dist (PerhapsT PS) where weighted = PerhapsT . weighted . map liftWeighted where liftWeighted (x,w) = (Perhaps x 1,w) weight :: Prob -> WPS () weight p = PerhapsT (return (Perhaps () p)) runWPS wps n = runPS (runPerhapsT wps) n runWPS' wps n = (runRand . liftM catPossible) (runWPS wps n) catPossible (ph:phs) | impossible ph = catPossible phs catPossible (Perhaps x p:phs) = x:(catPossible phs) catPossible [] = []
emk/haskell-probability-monads
examples/Probability.hs
Haskell
bsd-3-clause
7,598
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module DB.Schema where import Database.Persist import Data.Time import Data.Aeson (FromJSON, ToJSON) import GHC.Generics (Generic) import Database.Persist.TH import Database.Persist.Postgresql import Control.Monad.IO.Class (liftIO) import Control.Monad.Reader import DB.Config share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| User json email String UniqueEmail email username String UniqueUsername username passwordHash String deriving Show Generic SessionToken json userId UserId token String UniqueToken token expiration UTCTime deriving Show Generic |] doMigrations :: SqlPersistT IO () doMigrations = runMigration migrateAll runDb :: (MonadReader Config m, MonadIO m) => SqlPersistT IO b -> m b runDb query = do pool <- asks getPool liftIO $ runSqlPool query pool
AlexaDeWit/haskellsandboxserver
src/db/Schema.hs
Haskell
bsd-3-clause
1,356
{-# LANGUAGE CPP, DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Language.Python.Common.SrcLocation -- Copyright : (c) 2009 Bernie Pope -- License : BSD-style -- Maintainer : bjpop@csse.unimelb.edu.au -- Stability : experimental -- Portability : ghc -- -- Source location information for the Python lexer and parser. This module -- provides single-point locations and spans, and conversions between them. ----------------------------------------------------------------------------- module Language.JavaScript.Parser.SrcLocation ( -- * Construction AlexPosn (..), AlexSpan, alexStartPos, alexSpanEmpty, SrcLocation (..), SrcSpan (..), Span (..), toSrcSpan, spanning, mkSrcSpan, combineSrcSpans, initialSrcLocation, spanStartPoint, -- * Modification incColumn, decColumn, incLine, incTab, -- endCol, -- * Projection of components of a span -- endRow, -- startCol, -- startRow ) where import Data.Data import Prelude hiding (span) -- | `Posn' records the location of a token in the input text. It has three -- fields: the address (number of characters preceding the token), line number -- and column of a token within the file. `start_pos' gives the position of the -- start of the file and `eof_pos' a standard encoding for the end of file. -- `move_pos' calculates the new position after traversing a given character, -- assuming the usual eight character tab stops. data AlexPosn = AlexPn !Int -- address (number of characters preceding the token) !Int -- line number !Int -- column deriving (Eq,Show) alexStartPos :: AlexPosn alexStartPos = AlexPn 0 1 1 -- AZ bringing this in as SrcSpan replacement. type AlexSpan = (AlexPosn, Char, String) alexSpanEmpty :: AlexSpan alexSpanEmpty = (alexStartPos, '\n', "") -- | A location for a syntactic entity from the source code. -- The location is specified by its filename, and starting row -- and column. data SrcLocation = Sloc { sloc_filename :: !String , sloc_address :: {-# UNPACK #-} !Int -- address (number of characters preceding the token) , sloc_row :: {-# UNPACK #-} !Int , sloc_column :: {-# UNPACK #-} !Int } | NoLocation deriving (Eq,Ord,Show,Typeable,Data) {- instance Pretty SrcLocation where pretty = pretty . getSpan -} -- | Types which have a span. class Span a where getSpan :: a -> SrcSpan getSpan _x = SpanEmpty -- | Create a new span which encloses two spanned things. spanning :: (Span a, Span b) => a -> b -> SrcSpan spanning x y = combineSrcSpans (getSpan x) (getSpan y) instance Span a => Span [a] where getSpan [] = SpanEmpty getSpan [x] = getSpan x getSpan list@(x:_xs) = combineSrcSpans (getSpan x) (getSpan (last list)) instance Span a => Span (Maybe a) where getSpan Nothing = SpanEmpty getSpan (Just x) = getSpan x instance (Span a, Span b) => Span (Either a b) where getSpan (Left x) = getSpan x getSpan (Right x) = getSpan x instance (Span a, Span b) => Span (a, b) where getSpan (x,y) = spanning x y instance Span SrcSpan where getSpan = id -- ++AZ++ adding this instance Span AlexPosn where getSpan ap = toSrcSpan (ap,'\n',"") toSrcSpan :: AlexSpan -> SrcSpan toSrcSpan ((AlexPn _addr line col),_,_) = SpanPoint { span_filename = "", span_row = line, span_column = col} -- ++AZ++ end -- | Construct the initial source location for a file. initialSrcLocation :: String -> SrcLocation initialSrcLocation filename = Sloc { sloc_filename = filename , sloc_address = 1 , sloc_row = 1 , sloc_column = 1 } -- | Decrement the column of a location, only if they are on the same row. decColumn :: Int -> SrcLocation -> SrcLocation decColumn n loc | n < col = loc { sloc_column = col - n } | otherwise = loc where col = sloc_column loc -- | Increment the column of a location. incColumn :: Int -> SrcLocation -> SrcLocation incColumn n loc@(Sloc { sloc_column = col }) = loc { sloc_column = col + n } incColumn _ NoLocation = NoLocation -- | Increment the column of a location by one tab stop. incTab :: SrcLocation -> SrcLocation incTab loc@(Sloc { sloc_column = col }) = loc { sloc_column = newCol } where newCol = col + 8 - (col - 1) `mod` 8 incTab NoLocation = NoLocation -- | Increment the line number (row) of a location by one. incLine :: Int -> SrcLocation -> SrcLocation incLine n loc@(Sloc { sloc_row = row }) = loc { sloc_column = 1, sloc_row = row + n } incLine _ NoLocation = NoLocation {- Inspired heavily by compiler/basicTypes/SrcLoc.lhs A SrcSpan delimits a portion of a text file. -} -- | Source location spanning a contiguous section of a file. data SrcSpan -- | A span which starts and ends on the same line. = SpanCoLinear { span_filename :: !String , span_row :: {-# UNPACK #-} !Int , span_start_column :: {-# UNPACK #-} !Int , span_end_column :: {-# UNPACK #-} !Int } -- | A span which starts and ends on different lines. | SpanMultiLine { span_filename :: !String , span_start_row :: {-# UNPACK #-} !Int , span_start_column :: {-# UNPACK #-} !Int , span_end_row :: {-# UNPACK #-} !Int , span_end_column :: {-# UNPACK #-} !Int } -- | A span which is actually just one point in the file. | SpanPoint { span_filename :: !String , span_row :: {-# UNPACK #-} !Int , span_column :: {-# UNPACK #-} !Int } -- | No span information. | SpanEmpty deriving (Eq,Ord,Show,Read,Typeable,Data) {- instance Show SrcSpan where show (s@(SpanCoLinear filename row start end)) = -- showChar '('.showString filename.shows row.shows start.shows end.showChar ')' -- ("foo.txt" 12 4 5) showChar '(' . showChar ')' -- ("foo.txt" 12 4 5) show (s@(SpanMultiLine filename sr sc er ec)) = showChar '('.showString filename.shows sr.shows sc.shows er.shows ec.showChar ')' -- ("foo.txt" 12 4 13 5) show (s@(SpanPoint filename r c)) = showChar '('.showString filename.shows r.shows c.showChar ')' -- ("foo.txt" 12 4) show (SpanEmpty) = showString "()" -- () -} --instance Read SrcSpan where -- readsPrec _ str = [ {- instance Read a => Read Tree a where readsPrec _ str = [(Leave x, t’) | ("Leave", t) <- reads str, (x, t’) <- reads t] ++ [((Node i r d), t’’’) | ("Node", t) <- reads str, (i, t’) <- reads t, (r, t’’) <- reads t’, (d, t’’’) <- reads t’’] -} instance Span SrcLocation where getSpan loc@(Sloc {}) = SpanPoint { span_filename = sloc_filename loc , span_row = sloc_row loc , span_column = sloc_column loc } getSpan NoLocation = SpanEmpty -- | Make a point span from the start of a span spanStartPoint :: SrcSpan -> SrcSpan spanStartPoint SpanEmpty = SpanEmpty spanStartPoint span = SpanPoint { span_filename = span_filename span , span_row = startRow span , span_column = startCol span } -- | Make a span from two locations. Assumption: either the -- arguments are the same, or the left one preceeds the right one. mkSrcSpan :: SrcLocation -> SrcLocation -> SrcSpan mkSrcSpan NoLocation _ = SpanEmpty mkSrcSpan _ NoLocation = SpanEmpty mkSrcSpan loc1 loc2 | line1 == line2 = if col2 <= col1 then SpanPoint file line1 col1 else SpanCoLinear file line1 col1 col2 | otherwise = SpanMultiLine file line1 col1 line2 col2 where line1 = sloc_row loc1 line2 = sloc_row loc2 col1 = sloc_column loc1 col2 = sloc_column loc2 file = sloc_filename loc1 -- | Combines two 'SrcSpan' into one that spans at least all the characters -- within both spans. Assumes the "file" part is the same in both inputs combineSrcSpans :: SrcSpan -> SrcSpan -> SrcSpan combineSrcSpans SpanEmpty r = r -- this seems more useful combineSrcSpans l SpanEmpty = l combineSrcSpans start end = case row1 `compare` row2 of EQ -> case col1 `compare` col2 of EQ -> SpanPoint file row1 col1 LT -> SpanCoLinear file row1 col1 col2 GT -> SpanCoLinear file row1 col2 col1 LT -> SpanMultiLine file row1 col1 row2 col2 GT -> SpanMultiLine file row2 col2 row1 col1 where row1 = startRow start col1 = startCol start row2 = endRow end col2 = endCol end file = span_filename start -- | Get the row of the start of a span. startRow :: SrcSpan -> Int startRow (SpanCoLinear { span_row = row }) = row startRow (SpanMultiLine { span_start_row = row }) = row startRow (SpanPoint { span_row = row }) = row startRow SpanEmpty = error "startRow called on empty span" -- | Get the row of the end of a span. endRow :: SrcSpan -> Int endRow (SpanCoLinear { span_row = row }) = row endRow (SpanMultiLine { span_end_row = row }) = row endRow (SpanPoint { span_row = row }) = row endRow SpanEmpty = error "endRow called on empty span" -- | Get the column of the start of a span. startCol :: SrcSpan -> Int startCol (SpanCoLinear { span_start_column = col }) = col startCol (SpanMultiLine { span_start_column = col }) = col startCol (SpanPoint { span_column = col }) = col startCol SpanEmpty = error "startCol called on empty span" -- | Get the column of the end of a span. endCol :: SrcSpan -> Int endCol (SpanCoLinear { span_end_column = col }) = col endCol (SpanMultiLine { span_end_column = col }) = col endCol (SpanPoint { span_column = col }) = col endCol SpanEmpty = error "endCol called on empty span"
jb55/language-javascript
src/Language/JavaScript/Parser/SrcLocation.hs
Haskell
bsd-3-clause
9,900
module Data.Name.Iso where import Data.Name import Control.Lens import qualified Language.Haskell.TH as TH nameIso :: Iso String String (Maybe Name) Name nameIso = iso nameMay unName -- | unsafe -- >>> "hello" ^. nameIso' -- hello nameIso' :: Iso' String Name nameIso' = iso toName unName -- | there are lack of info a little thNameIso :: Iso' Name TH.Name thNameIso = iso (TH.mkName . unName) (toName . show)
kmyk/proof-haskell
Data/Name/Iso.hs
Haskell
mit
414
{- Copyright 2019 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-| Snap helper functions -} module CodeWorld.Auth.Util ( getRequiredParam , hoistEither , hoistMaybe , m , withSnapExcept ) where import CodeWorld.Auth.Http import CodeWorld.Auth.Types import Control.Monad.Trans.Except (ExceptT(..), runExceptT, throwE) import Data.ByteString (ByteString) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap (fromList) import Snap.Core (Snap, finishWith, getParam) getRequiredParam :: ByteString -> Snap ByteString getRequiredParam name = do mbValue <- getParam name case mbValue of Nothing -> finishWith badRequest400 Just value -> return value m :: [(String, String)] -> HashMap String String m = HashMap.fromList hoistMaybe :: Monad m => e -> Maybe a -> ExceptT e m a hoistMaybe e mb = maybe (throwE e) return mb hoistEither :: Monad m => Either e a -> ExceptT e m a hoistEither = ExceptT . return withSnapExcept :: SnapExcept a withSnapExcept action = runExceptT action >>= either id return
alphalambda/codeworld
codeworld-auth/src/CodeWorld/Auth/Util.hs
Haskell
apache-2.0
1,685
{-| Module : Base Description : Base/radix module for the MPL DSL Copyright : (c) Rohit Jha, 2015 License : BSD2 Maintainer : rohit305jha@gmail.com Stability : Stable Functionality for: * Converting decimal numbers to binary, octal, hexadecimal or any other base/radix * Converting numbers from binary, octal, hexadecimal or any other base/radix to decimal base/radix -} module Base ( toBase, toBin, toOct, toDec, toHex, fromBase, fromBin, fromOct, fromDec, fromHex, toAlpha, fromAlpha ) where import Data.List import Data.Char {-| The 'toBase' function converts a number from decimal base to a specified base in the form of digits. The function takes two arguments, both of type Integer. Below are a few examples: >>> toBase 8 37 [4,5] >>> toBase 100 233243 [23,32,43] >>> toBase 9 233243 [3,8,4,8,4,8] >>> toBase 35 233243 [5,15,14,3] -} toBase :: Integer -> Integer -> [Integer] toBase b v = toBase' [] v where toBase' a 0 = a toBase' a v = toBase' (r:a) q where (q,r) = v `divMod` b {-| The 'toBin' function converts a decimal number to its binary equivalent. The function takes one argument of type Integer, which is the decimal number. Below are a few examples: >>> toBin 11 [1,0,1,1] >>> toBin 32 [1,0,0,0,0,0] >>> toBin (3^(-1)) *** Exception: Negative exponent -} toBin :: Integer -> [Integer] toBin = toBase 2 {-| The 'toOct' function converts a decimal number to its octal equivalent. The function takes one argument of type Integer, which is the decimal number. Below are a few examples: >>> toOct 11 [1,3] >>> toOct 100 [1,4,4] -} toOct :: Integer -> [Integer] toOct = toBase 8 {-| The 'toDec' function converts a decimal number to its decimal equivalent. The function returns a list of digits of the decimal number. The function takes one argument of type Integer, which is the decimal number. Below are a few examples: >>> toDec 15 [1,5] >>> toDec 123 [1,2,3] -} toDec :: Integer -> [Integer] toDec = toBase 10 {-| The 'toHex' function converts a decimal number to its hexadecimal equivalent. The function takes one argument of type Integer, which is the decimal number. Below are a few examples: >>> toHex 15 [15] >>> toHex 1200 [4,11,0] -} toHex :: Integer -> [Integer] toHex = toBase 16 {-| The 'fromBase' function converts a number from a specified base to decimal in the form of a list of digits. The function takes two arguments, the first of type Integer and the second of type [Integer]. Below are a few examples: >>> fromBase 16 [15,15,15] 4095 >>> fromBase 100 [21,12,1] 211201 >>> fromBase 2 [1,0,1] 5 -} fromBase :: Integer -> [Integer] -> Integer fromBase b ds = foldl' (\n k -> n * b + k) 0 ds {-| The 'fromBin' function converts a number from binary (in the form of a list of digits) to decimal. The function takes two arguments, the first of type Integer and the second of type [Integer]. Below are a few examples: >>> fromBin [1,0,1,0] 10 >>> fromBin (toBin 12345) 12345 -} fromBin :: [Integer] -> Integer fromBin = fromBase 2 {-| The 'fromOct' function converts a number from octal (in the form of a list of digits) to decimal. The function takes two arguments, the first of type Integer and the second of type [Integer]. Below are a few examples: >>> fromOct [6,3,7] 415 >>> fromOct (toOct 1234) 1234 -} fromOct :: [Integer] -> Integer fromOct = fromBase 8 {-| The 'fromDec' function converts a number from decimal (in the form of a list of digits) to decimal. The function takes two arguments, the first of type Integer and the second of type [Integer]. Below are a few examples: >>> fromDec [1,5,8,2,2] 15822 >>> fromDec (toDec 635465) 635465 -} fromDec :: [Integer] -> Integer fromDec = fromBase 10 {-| The 'fromHex' function converts a number from hexadecimal (in the form of a list of digits) to decimal. The function takes two arguments, the first of type Integer and the second of type [Integer]. Below are a few examples: >>> fromHex [14,15,8,2,0] 981024 >>> fromHex (toHex 0234) 234 -} fromHex :: [Integer] -> Integer fromHex = fromBase 16 {-| The 'toAlpha' function converts a number from a list of Integer to corresponding String representation. The function takes one argument of type [Integer], which contains the list of digits. Below are a few examples: >>> toAlpha $ toBase 16 23432 "5b88" >>> toAlpha $ toBase 16 255 "ff" >>> toAlpha [38,12,1] "}c1" >>> toAlpha [21,12,1] "lc1" -} toAlpha :: [Integer] -> String toAlpha = map convert where convert n | n < 10 = chr (fromInteger n + ord '0') | otherwise = chr (fromInteger n + ord 'a' - 10) {-| The 'from AlphaDigits' function converts a String to list of Integer digits. The function takes only one argument of type String. Below are a few examples: >>> fromAlpha "j43hbrh" [19,4,3,17,11,27,17] >>> fromAlpha "ffff" [15,15,15,15] -} fromAlpha :: String -> [Integer] fromAlpha = map convert where convert c | isDigit c = toInteger (ord c - ord '0') | isUpper c = toInteger (ord c - ord 'A' + 10) | isLower c = toInteger (ord c - ord 'a' + 10)
rohitjha/DiMPL
src/Base.hs
Haskell
bsd-2-clause
5,416
{-# LANGUAGE ScopedTypeVariables #-} module Properties.Layout.Tall where import Test.QuickCheck import Instances import Utils import XMonad.StackSet hiding (filter) import XMonad.Core import XMonad.Layout import Graphics.X11.Xlib.Types (Rectangle(..)) import Data.Maybe import Data.List (sort) import Data.Ratio ------------------------------------------------------------------------ -- The Tall layout -- 1 window should always be tiled fullscreen prop_tile_fullscreen rect = tile pct rect 1 1 == [rect] where pct = 1/2 -- multiple windows prop_tile_non_overlap rect windows nmaster = noOverlaps (tile pct rect nmaster windows) where _ = rect :: Rectangle pct = 3 % 100 -- splitting horizontally yields sensible results prop_split_horizontal (NonNegative n) x = (noOverflows (+) (rect_x x) (rect_width x)) ==> sum (map rect_width xs) == rect_width x && all (== rect_height x) (map rect_height xs) && (map rect_x xs) == (sort $ map rect_x xs) where xs = splitHorizontally n x -- splitting vertically yields sensible results prop_split_vertical (r :: Rational) x = rect_x x == rect_x a && rect_x x == rect_x b && rect_width x == rect_width a && rect_width x == rect_width b where (a,b) = splitVerticallyBy r x -- pureLayout works. prop_purelayout_tall n r1 r2 rect = do x <- (arbitrary :: Gen T) `suchThat` (isJust . peek) let layout = Tall n r1 r2 st = fromJust . stack . workspace . current $ x ts = pureLayout layout rect st return $ length ts == length (index x) && noOverlaps (map snd ts) && description layout == "Tall" -- Test message handling of Tall -- what happens when we send a Shrink message to Tall prop_shrink_tall (NonNegative n) (NonZero (NonNegative delta)) (NonNegative frac) = n == n' && delta == delta' -- these state components are unchanged && frac' <= frac && (if frac' < frac then frac' == 0 || frac' == frac - delta else frac == 0 ) -- remaining fraction should shrink where l1 = Tall n delta frac Just l2@(Tall n' delta' frac') = l1 `pureMessage` (SomeMessage Shrink) -- pureMessage :: layout a -> SomeMessage -> Maybe (layout a) -- what happens when we send a Shrink message to Tall prop_expand_tall (NonNegative n) (NonZero (NonNegative delta)) (NonNegative n1) (NonZero (NonNegative d1)) = n == n' && delta == delta' -- these state components are unchanged && frac' >= frac && (if frac' > frac then frac' == 1 || frac' == frac + delta else frac == 1 ) -- remaining fraction should shrink where frac = min 1 (n1 % d1) l1 = Tall n delta frac Just l2@(Tall n' delta' frac') = l1 `pureMessage` (SomeMessage Expand) -- pureMessage :: layout a -> SomeMessage -> Maybe (layout a) -- what happens when we send an IncMaster message to Tall prop_incmaster_tall (NonNegative n) (NonZero (NonNegative delta)) (NonNegative frac) (NonNegative k) = delta == delta' && frac == frac' && n' == n + k where l1 = Tall n delta frac Just l2@(Tall n' delta' frac') = l1 `pureMessage` (SomeMessage (IncMasterN k)) -- pureMessage :: layout a -> SomeMessage -> Maybe (layout a) -- toMessage LT = SomeMessage Shrink -- toMessage EQ = SomeMessage Expand -- toMessage GT = SomeMessage (IncMasterN 1) prop_desc_mirror n r1 r2 = description (Mirror $! t) == "Mirror Tall" where t = Tall n r1 r2
Happy-Ferret/xmonad
tests/Properties/Layout/Tall.hs
Haskell
bsd-3-clause
3,761
{-| Module : Fit Copyright : Copyright 2014-2015, Matt Giles License : Modified BSD License Maintainer : matt.w.giles@gmail.com Stability : experimental -} module Fit ( -- * Messages API -- $messages readMessages, readFileMessages, parseMessages, Messages(..), Message(..), Field(..), Value(..), SingletonValue(..), ArrayValue(..), -- ** Lenses for the Messages API messages, message, messageNumber, fields, field, fieldNumber, fieldValue, int, real, text, byte, ints, reals, bytestring ) where import Fit.Messages import Fit.Messages.Lens -- $messages -- A high-level view of a FIT file as a sequence of data messages. This is the -- recommended API for pulling information out of a FIT file, but if you need -- access to the exact structure of the file you can use the API in "Fit.Internal.FitFile" and "Fit.Internal.Parse". -- -- Some basic lenses are also provided for working with the Messages API. These -- can make it much easier to extract information from a FIT file, especially -- since you usually know what sort of data you're expecting to find. -- -- For example, from the FIT global profile we can find that the global message -- number for 'record' messages is 20, and within a `record` message the 'speed' -- field has field number 6. The following code gets the `speed` field from all -- 'record' messages in the file: -- -- @ -- Right fit <- readFileMessages "file.fit" -- let speeds = fit ^.. message 20 . field 6 . int -- -- speeds :: [Int] -- @ -- -- Note that this package doesn't provide any lens combinators (like @(^..)@), -- so you'll need to use ones from a lens package.
bitemyapp/fit
src/Fit.hs
Haskell
bsd-3-clause
1,671
module Data.Tiled ( module X , module Data.Tiled ) where import Data.Tiled.Load as X import Data.Tiled.Types as X import Data.Vector (Vector, force, slice) -- | Yield a slice of the tile vectors without copying it. -- -- The vectors must be at least x+w wide and y+h tall. sliceTileVectors :: Int -- ^ X -> Int -- ^ Y -> Int -- ^ Width -> Int -- ^ Height -> Vector (Vector (Maybe TileIndex)) -> Vector (Vector (Maybe TileIndex)) sliceTileVectors x y w h = (slice x w <$>) . slice y h -- | Yield the argument but force it not to retain any extra memory, -- possibly by copying it. -- -- Useful after slicing huge tile vectors. forceTileVectors :: Vector (Vector (Maybe TileIndex)) -> Vector (Vector (Maybe TileIndex)) forceTileVectors = force . fmap force
chrra/htiled
src/Data/Tiled.hs
Haskell
bsd-3-clause
822
{-# LANGUAGE FlexibleInstances #-} module Kalium.Nucleus.Vector.Show where import Kalium.Prelude import Kalium.Nucleus.Vector.Program deriving instance Show NameSpecial deriving instance Show Literal instance Show Name where show = \case NameSpecial op -> show op NameGen n -> "_" ++ show n instance Show Expression where show = \case AppOp2 OpPair x y -> "(" ++ show x ++ "," ++ show y ++ ")" Access name -> show name Primary lit -> show lit Lambda p a -> "(λ" ++ show p ++ "." ++ show a ++ ")" Beta a b -> show a ++ "(" ++ show b ++ ")" Ext ext -> absurd ext instance Show Pattern where show = \case PUnit -> "()" PWildCard -> "_" PAccess name _ -> show name PTuple p1 p2 -> "(" ++ show p1 ++ "," ++ show p2 ++ ")" PExt pext -> absurd pext deriving instance Show Type deriving instance Show Func deriving instance Show Program
rscprof/kalium
src/Kalium/Nucleus/Vector/Show.hs
Haskell
bsd-3-clause
952
module Data.IP.Op where import Data.Bits import Data.IP.Addr import Data.IP.Mask import Data.IP.Range ---------------------------------------------------------------- {-| >>> toIPv4 [127,0,2,1] `masked` intToMask 7 126.0.0.0 -} class Eq a => Addr a where {-| The 'masked' function takes an 'Addr' and a contiguous mask and returned a masked 'Addr'. -} masked :: a -> a -> a {-| The 'intToMask' function takes an 'Int' representing the number of bits to be set in the returned contiguous mask. When this integer is positive the bits will be starting from the MSB and from the LSB otherwise. >>> intToMask 16 :: IPv4 255.255.0.0 >>> intToMask (-16) :: IPv4 0.0.255.255 >>> intToMask 16 :: IPv6 ffff:: >>> intToMask (-16) :: IPv6 ::ffff -} intToMask :: Int -> a instance Addr IPv4 where masked = maskedIPv4 intToMask = maskIPv4 instance Addr IPv6 where masked = maskedIPv6 intToMask = maskIPv6 ---------------------------------------------------------------- {-| The >:> operator takes two 'AddrRange'. It returns 'True' if the first 'AddrRange' contains the second 'AddrRange'. Otherwise, it returns 'False'. >>> makeAddrRange ("127.0.2.1" :: IPv4) 8 >:> makeAddrRange "127.0.2.1" 24 True >>> makeAddrRange ("127.0.2.1" :: IPv4) 24 >:> makeAddrRange "127.0.2.1" 8 False >>> makeAddrRange ("2001:DB8::1" :: IPv6) 16 >:> makeAddrRange "2001:DB8::1" 32 True >>> makeAddrRange ("2001:DB8::1" :: IPv6) 32 >:> makeAddrRange "2001:DB8::1" 16 False -} (>:>) :: Addr a => AddrRange a -> AddrRange a -> Bool a >:> b = mlen a <= mlen b && (addr b `masked` mask a) == addr a {-| The 'toMatchedTo' function take an 'Addr' address and an 'AddrRange', and returns 'True' if the range contains the address. >>> ("127.0.2.0" :: IPv4) `isMatchedTo` makeAddrRange "127.0.2.1" 24 True >>> ("127.0.2.0" :: IPv4) `isMatchedTo` makeAddrRange "127.0.2.1" 32 False >>> ("2001:DB8::1" :: IPv6) `isMatchedTo` makeAddrRange "2001:DB8::1" 32 True >>> ("2001:DB8::" :: IPv6) `isMatchedTo` makeAddrRange "2001:DB8::1" 128 False -} isMatchedTo :: Addr a => a -> AddrRange a -> Bool isMatchedTo a r = a `masked` mask r == addr r {-| The 'makeAddrRange' functions takes an 'Addr' address and a mask length. It creates a bit mask from the mask length and masks the 'Addr' address, then returns 'AddrRange' made of them. >>> makeAddrRange (toIPv4 [127,0,2,1]) 8 127.0.0.0/8 >>> makeAddrRange (toIPv6 [0x2001,0xDB8,0,0,0,0,0,1]) 8 2000::/8 -} makeAddrRange :: Addr a => a -> Int -> AddrRange a makeAddrRange ad len = AddrRange adr msk len where msk = intToMask len adr = ad `masked` msk -- | Convert IPv4 range to IPV4-embedded-in-IPV6 range ipv4RangeToIPv6 :: AddrRange IPv4 -> AddrRange IPv6 ipv4RangeToIPv6 range = makeAddrRange (toIPv6 [0,0,0,0,0,0xffff, (i1 `shift` 8) .|. i2, (i3 `shift` 8) .|. i4]) (masklen + 96) where (ip, masklen) = addrRangePair range [i1,i2,i3,i4] = fromIPv4 ip {-| The 'unmakeAddrRange' functions take a 'AddrRange' and returns the network address and a mask length. >>> addrRangePair ("127.0.0.0/8" :: AddrRange IPv4) (127.0.0.0,8) >>> addrRangePair ("2000::/8" :: AddrRange IPv6) (2000::,8) -} addrRangePair :: Addr a => AddrRange a -> (a, Int) addrRangePair (AddrRange adr _ len) = (adr, len)
greydot/iproute
Data/IP/Op.hs
Haskell
bsd-3-clause
3,378
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "Control/Concurrent/STM/TBQueue.hs" #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# LANGUAGE CPP, DeriveDataTypeable #-} {-# LANGUAGE Trustworthy #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent.STM.TBQueue -- Copyright : (c) The University of Glasgow 2012 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (requires STM) -- -- 'TBQueue' is a bounded version of 'TQueue'. The queue has a maximum -- capacity set when it is created. If the queue already contains the -- maximum number of elements, then 'writeTBQueue' blocks until an -- element is removed from the queue. -- -- The implementation is based on the traditional purely-functional -- queue representation that uses two lists to obtain amortised /O(1)/ -- enqueue and dequeue operations. -- -- @since 2.4 ----------------------------------------------------------------------------- module Control.Concurrent.STM.TBQueue ( -- * TBQueue TBQueue, newTBQueue, newTBQueueIO, readTBQueue, tryReadTBQueue, peekTBQueue, tryPeekTBQueue, writeTBQueue, unGetTBQueue, isEmptyTBQueue, isFullTBQueue, ) where import Data.Typeable import GHC.Conc -- | 'TBQueue' is an abstract type representing a bounded FIFO channel. -- -- @since 2.4 data TBQueue a = TBQueue {-# UNPACK #-} !(TVar Int) -- CR: read capacity {-# UNPACK #-} !(TVar [a]) -- R: elements waiting to be read {-# UNPACK #-} !(TVar Int) -- CW: write capacity {-# UNPACK #-} !(TVar [a]) -- W: elements written (head is most recent) deriving Typeable instance Eq (TBQueue a) where TBQueue a _ _ _ == TBQueue b _ _ _ = a == b -- Total channel capacity remaining is CR + CW. Reads only need to -- access CR, writes usually need to access only CW but sometimes need -- CR. So in the common case we avoid contention between CR and CW. -- -- - when removing an element from R: -- CR := CR + 1 -- -- - when adding an element to W: -- if CW is non-zero -- then CW := CW - 1 -- then if CR is non-zero -- then CW := CR - 1; CR := 0 -- else **FULL** -- |Build and returns a new instance of 'TBQueue' newTBQueue :: Int -- ^ maximum number of elements the queue can hold -> STM (TBQueue a) newTBQueue size = do read <- newTVar [] write <- newTVar [] rsize <- newTVar 0 wsize <- newTVar size return (TBQueue rsize read wsize write) -- |@IO@ version of 'newTBQueue'. This is useful for creating top-level -- 'TBQueue's using 'System.IO.Unsafe.unsafePerformIO', because using -- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't -- possible. newTBQueueIO :: Int -> IO (TBQueue a) newTBQueueIO size = do read <- newTVarIO [] write <- newTVarIO [] rsize <- newTVarIO 0 wsize <- newTVarIO size return (TBQueue rsize read wsize write) -- |Write a value to a 'TBQueue'; blocks if the queue is full. writeTBQueue :: TBQueue a -> a -> STM () writeTBQueue (TBQueue rsize _read wsize write) a = do w <- readTVar wsize if (w /= 0) then do writeTVar wsize (w - 1) else do r <- readTVar rsize if (r /= 0) then do writeTVar rsize 0 writeTVar wsize (r - 1) else retry listend <- readTVar write writeTVar write (a:listend) -- |Read the next value from the 'TBQueue'. readTBQueue :: TBQueue a -> STM a readTBQueue (TBQueue rsize read _wsize write) = do xs <- readTVar read r <- readTVar rsize writeTVar rsize (r + 1) case xs of (x:xs') -> do writeTVar read xs' return x [] -> do ys <- readTVar write case ys of [] -> retry _ -> do let (z:zs) = reverse ys -- NB. lazy: we want the transaction to be -- short, otherwise it will conflict writeTVar write [] writeTVar read zs return z -- | A version of 'readTBQueue' which does not retry. Instead it -- returns @Nothing@ if no value is available. tryReadTBQueue :: TBQueue a -> STM (Maybe a) tryReadTBQueue c = fmap Just (readTBQueue c) `orElse` return Nothing -- | Get the next value from the @TBQueue@ without removing it, -- retrying if the channel is empty. peekTBQueue :: TBQueue a -> STM a peekTBQueue c = do x <- readTBQueue c unGetTBQueue c x return x -- | A version of 'peekTBQueue' which does not retry. Instead it -- returns @Nothing@ if no value is available. tryPeekTBQueue :: TBQueue a -> STM (Maybe a) tryPeekTBQueue c = do m <- tryReadTBQueue c case m of Nothing -> return Nothing Just x -> do unGetTBQueue c x return m -- |Put a data item back onto a channel, where it will be the next item read. -- Blocks if the queue is full. unGetTBQueue :: TBQueue a -> a -> STM () unGetTBQueue (TBQueue rsize read wsize _write) a = do r <- readTVar rsize if (r > 0) then do writeTVar rsize (r - 1) else do w <- readTVar wsize if (w > 0) then writeTVar wsize (w - 1) else retry xs <- readTVar read writeTVar read (a:xs) -- |Returns 'True' if the supplied 'TBQueue' is empty. isEmptyTBQueue :: TBQueue a -> STM Bool isEmptyTBQueue (TBQueue _rsize read _wsize write) = do xs <- readTVar read case xs of (_:_) -> return False [] -> do ys <- readTVar write case ys of [] -> return True _ -> return False -- |Returns 'True' if the supplied 'TBQueue' is full. -- -- @since 2.4.3 isFullTBQueue :: TBQueue a -> STM Bool isFullTBQueue (TBQueue rsize _read wsize _write) = do w <- readTVar wsize if (w > 0) then return False else do r <- readTVar rsize if (r > 0) then return False else return True
phischu/fragnix
tests/packages/scotty/Control.Concurrent.STM.TBQueue.hs
Haskell
bsd-3-clause
6,106
{-# LANGUAGE CPP #-} -- | Groups black-box tests of cabal-install and configures them to test -- the correct binary. -- -- This file should do nothing but import tests from other modules and run -- them with the path to the correct cabal-install binary. module Main where -- Modules from Cabal. import Distribution.Compat.CreatePipe (createPipe) import Distribution.Compat.Environment (setEnv) import Distribution.Compat.Internal.TempFile (createTempDirectory) import Distribution.Simple.Configure (findDistPrefOrDefault) import Distribution.Simple.Program.Builtin (ghcPkgProgram) import Distribution.Simple.Program.Db (defaultProgramDb, requireProgram, setProgramSearchPath) import Distribution.Simple.Program.Find (ProgramSearchPathEntry(ProgramSearchPathDir), defaultProgramSearchPath) import Distribution.Simple.Program.Types ( Program(..), simpleProgram, programPath) import Distribution.Simple.Setup ( Flag(..) ) import Distribution.Simple.Utils ( findProgramVersion, copyDirectoryRecursive ) import Distribution.Verbosity (normal) -- Third party modules. import Control.Concurrent.Async (withAsync, wait) import Control.Exception (bracket) import Data.Maybe (fromMaybe) import System.Directory ( canonicalizePath , findExecutable , getDirectoryContents , getTemporaryDirectory , doesDirectoryExist , removeDirectoryRecursive , doesFileExist ) import System.FilePath import Test.Tasty (TestTree, defaultMain, testGroup) import Test.Tasty.HUnit (testCase, Assertion, assertFailure) import Control.Monad ( filterM, forM, unless, when ) import Data.List (isPrefixOf, isSuffixOf, sort) import Data.IORef (newIORef, writeIORef, readIORef) import System.Exit (ExitCode(..)) import System.IO (withBinaryFile, IOMode(ReadMode)) import System.Process (runProcess, waitForProcess) import Text.Regex.Posix ((=~)) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C8 import Data.ByteString (ByteString) #if MIN_VERSION_base(4,6,0) import System.Environment ( getExecutablePath ) #endif -- | Test case. data TestCase = TestCase { tcName :: String -- ^ Name of the shell script , tcBaseDirectory :: FilePath , tcCategory :: String , tcShouldX :: String , tcStdOutPath :: Maybe FilePath -- ^ File path of "golden standard output" , tcStdErrPath :: Maybe FilePath -- ^ File path of "golden standard error" } -- | Test result. data TestResult = TestResult { trExitCode :: ExitCode , trStdOut :: ByteString , trStdErr :: ByteString , trWorkingDirectory :: FilePath } -- | Cabal executable cabalProgram :: Program cabalProgram = (simpleProgram "cabal") { programFindVersion = findProgramVersion "--numeric-version" id } -- | Convert test result to string. testResultToString :: TestResult -> String testResultToString testResult = exitStatus ++ "\n" ++ workingDirectory ++ "\n\n" ++ stdOut ++ "\n\n" ++ stdErr where exitStatus = "Exit status: " ++ show (trExitCode testResult) workingDirectory = "Working directory: " ++ (trWorkingDirectory testResult) stdOut = "<stdout> was:\n" ++ C8.unpack (trStdOut testResult) stdErr = "<stderr> was:\n" ++ C8.unpack (trStdErr testResult) -- | Returns the command that was issued, the return code, and the output text run :: FilePath -> String -> [String] -> IO TestResult run cwd path args = do -- path is relative to the current directory; canonicalizePath makes it -- absolute, so that runProcess will find it even when changing directory. path' <- canonicalizePath path (pid, hReadStdOut, hReadStdErr) <- do -- Create pipes for StdOut and StdErr (hReadStdOut, hWriteStdOut) <- createPipe (hReadStdErr, hWriteStdErr) <- createPipe -- Run the process pid <- runProcess path' args (Just cwd) Nothing Nothing (Just hWriteStdOut) (Just hWriteStdErr) -- Return the pid and read ends of the pipes return (pid, hReadStdOut, hReadStdErr) -- Read subprocess output using asynchronous threads; we need to -- do this aynchronously to avoid deadlocks due to buffers filling -- up. withAsync (B.hGetContents hReadStdOut) $ \stdOutAsync -> do withAsync (B.hGetContents hReadStdErr) $ \stdErrAsync -> do -- Wait for the subprocess to terminate exitcode <- waitForProcess pid -- We can now be sure that no further output is going to arrive, -- so we wait for the results of the asynchronous reads. stdOut <- wait stdOutAsync stdErr <- wait stdErrAsync -- Done return $ TestResult exitcode stdOut stdErr cwd -- | Get a list of all names in a directory, excluding all hidden or -- system files/directories such as '.', '..' or any files/directories -- starting with a '.'. listDirectory :: FilePath -> IO [String] listDirectory directory = do fmap (filter notHidden) $ getDirectoryContents directory where notHidden = not . isHidden isHidden name = "." `isPrefixOf` name -- | List a directory as per 'listDirectory', but return an empty list -- in case the directory does not exist. listDirectoryLax :: FilePath -> IO [String] listDirectoryLax directory = do d <- doesDirectoryExist directory if d then listDirectory directory else return [ ] pathIfExists :: FilePath -> IO (Maybe FilePath) pathIfExists p = do e <- doesFileExist p if e then return $ Just p else return Nothing fileMatchesString :: FilePath -> ByteString -> IO Bool fileMatchesString p s = do withBinaryFile p ReadMode $ \h -> do expected <- (C8.lines . normalizeLinebreaks) `fmap` B.hGetContents h -- Strict let actual = C8.lines $ normalizeLinebreaks s return $ length expected == length actual && and (zipWith matches expected actual) where matches :: ByteString -> ByteString -> Bool matches pattern line | C8.pack "RE:" `B.isPrefixOf` pattern = line =~ C8.drop 3 pattern | otherwise = line == pattern -- This is a bit of a hack, but since we're comparing -- *text* output, we should be OK. normalizeLinebreaks = B.filter (not . ((==) 13)) mustMatch :: TestResult -> String -> ByteString -> Maybe FilePath -> Assertion mustMatch _ _ _ Nothing = return () mustMatch testResult handleName actual (Just expected) = do m <- fileMatchesString expected actual unless m $ assertFailure $ "<" ++ handleName ++ "> did not match file '" ++ expected ++ "'.\n" ++ testResultToString testResult discoverTestCategories :: FilePath -> IO [String] discoverTestCategories directory = do names <- listDirectory directory fmap sort $ filterM (\name -> doesDirectoryExist $ directory </> name) names discoverTestCases :: FilePath -> String -> String -> IO [TestCase] discoverTestCases baseDirectory category shouldX = do -- Find the names of the shell scripts names <- fmap (filter isTestCase) $ listDirectoryLax directory -- Fill in TestCase for each script forM (sort names) $ \name -> do stdOutPath <- pathIfExists $ directory </> name `replaceExtension` ".out" stdErrPath <- pathIfExists $ directory </> name `replaceExtension` ".err" return $ TestCase { tcName = name , tcBaseDirectory = baseDirectory , tcCategory = category , tcShouldX = shouldX , tcStdOutPath = stdOutPath , tcStdErrPath = stdErrPath } where directory = baseDirectory </> category </> shouldX isTestCase name = ".sh" `isSuffixOf` name createTestCases :: [TestCase] -> (TestCase -> Assertion) -> IO [TestTree] createTestCases testCases mk = return $ (flip map) testCases $ \tc -> testCase (tcName tc ++ suffix tc) $ mk tc where suffix tc = case (tcStdOutPath tc, tcStdErrPath tc) of (Nothing, Nothing) -> " (ignoring stdout+stderr)" (Just _ , Nothing) -> " (ignoring stderr)" (Nothing, Just _ ) -> " (ignoring stdout)" (Just _ , Just _ ) -> "" runTestCase :: (TestResult -> Assertion) -> TestCase -> IO () runTestCase assertResult tc = do doRemove <- newIORef False bracket createWorkDirectory (removeWorkDirectory doRemove) $ \workDirectory -> do -- Run let scriptDirectory = workDirectory </> tcShouldX tc sh <- fmap (fromMaybe $ error "Cannot find 'sh' executable") $ findExecutable "sh" testResult <- run scriptDirectory sh [ "-e", tcName tc] -- Assert that we got what we expected assertResult testResult mustMatch testResult "stdout" (trStdOut testResult) (tcStdOutPath tc) mustMatch testResult "stderr" (trStdErr testResult) (tcStdErrPath tc) -- Only remove working directory if test succeeded writeIORef doRemove True where createWorkDirectory = do -- Create the temporary directory tempDirectory <- getTemporaryDirectory workDirectory <- createTempDirectory tempDirectory "cabal-install-test" -- Copy all the files from the category into the working directory. copyDirectoryRecursive normal (tcBaseDirectory tc </> tcCategory tc) workDirectory -- Done return workDirectory removeWorkDirectory doRemove workDirectory = do remove <- readIORef doRemove when remove $ removeDirectoryRecursive workDirectory makeShouldXTests :: FilePath -> String -> String -> (TestResult -> Assertion) -> IO [TestTree] makeShouldXTests baseDirectory category shouldX assertResult = do testCases <- discoverTestCases baseDirectory category shouldX createTestCases testCases $ \tc -> runTestCase assertResult tc makeShouldRunTests :: FilePath -> String -> IO [TestTree] makeShouldRunTests baseDirectory category = do makeShouldXTests baseDirectory category "should_run" $ \testResult -> do case trExitCode testResult of ExitSuccess -> return () -- We're good ExitFailure _ -> assertFailure $ "Unexpected exit status.\n\n" ++ testResultToString testResult makeShouldFailTests :: FilePath -> String -> IO [TestTree] makeShouldFailTests baseDirectory category = do makeShouldXTests baseDirectory category "should_fail" $ \testResult -> do case trExitCode testResult of ExitSuccess -> assertFailure $ "Unexpected exit status.\n\n" ++ testResultToString testResult ExitFailure _ -> return () -- We're good discoverCategoryTests :: FilePath -> String -> IO [TestTree] discoverCategoryTests baseDirectory category = do srTests <- makeShouldRunTests baseDirectory category sfTests <- makeShouldFailTests baseDirectory category return [ testGroup "should_run" srTests , testGroup "should_fail" sfTests ] main :: IO () main = do -- Find executables and build directories, etc. distPref <- guessDistDir buildDir <- canonicalizePath (distPref </> "build/cabal") let programSearchPath = ProgramSearchPathDir buildDir : defaultProgramSearchPath (cabal, _) <- requireProgram normal cabalProgram (setProgramSearchPath programSearchPath defaultProgramDb) (ghcPkg, _) <- requireProgram normal ghcPkgProgram defaultProgramDb baseDirectory <- canonicalizePath $ "tests" </> "IntegrationTests" -- Set up environment variables for test scripts setEnv "GHC_PKG" $ programPath ghcPkg setEnv "CABAL" $ programPath cabal -- Define default arguments setEnv "CABAL_ARGS" $ "--config-file=config-file" setEnv "CABAL_ARGS_NO_CONFIG_FILE" " " -- Discover all the test caregories categories <- discoverTestCategories baseDirectory -- Discover tests in each category tests <- forM categories $ \category -> do categoryTests <- discoverCategoryTests baseDirectory category return (category, categoryTests) -- Map into a test tree let testTree = map (\(category, categoryTests) -> testGroup category categoryTests) tests -- Run the tests defaultMain $ testGroup "Integration Tests" $ testTree -- See this function in Cabal's PackageTests. If you update this, -- update its copy in cabal-install. (Why a copy here? I wanted -- to try moving this into the Cabal library, but to do this properly -- I'd have to BC'ify getExecutablePath, and then it got hairy, so -- I aborted and did something simple.) guessDistDir :: IO FilePath guessDistDir = do #if MIN_VERSION_base(4,6,0) exe_path <- canonicalizePath =<< getExecutablePath let dist0 = dropFileName exe_path </> ".." </> ".." b <- doesFileExist (dist0 </> "setup-config") #else let dist0 = error "no path" b = False #endif -- Method (2) if b then canonicalizePath dist0 else findDistPrefOrDefault NoFlag >>= canonicalizePath
garetxe/cabal
cabal-install/tests/IntegrationTests.hs
Haskell
bsd-3-clause
12,691
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module: Web.Twitter.Conduit -- Copyright: (c) 2014 Takahiro Himura -- License: BSD -- Maintainer: Takahiro Himura <taka@himura.jp> -- Stability: experimental -- Portability: portable -- -- A client library for Twitter APIs (see <https://dev.twitter.com/>). module Web.Twitter.Conduit ( -- * How to use this library -- $howto -- * Re-exports module Web.Twitter.Conduit.Api , module Web.Twitter.Conduit.Cursor , module Web.Twitter.Conduit.Parameters , module Web.Twitter.Conduit.Request , module Web.Twitter.Conduit.Response , module Web.Twitter.Conduit.Status , module Web.Twitter.Conduit.Stream , module Web.Twitter.Conduit.Types -- * 'Web.Twitter.Conduit.Base' , TwitterBaseM , call , call' , callWithResponse , callWithResponse' , sourceWithMaxId , sourceWithMaxId' , sourceWithCursor , sourceWithCursor' , sourceWithSearchResult , sourceWithSearchResult' -- * Backward compatibility -- $backward ) where import Web.Twitter.Conduit.Api import Web.Twitter.Conduit.Base import Web.Twitter.Conduit.Cursor import Web.Twitter.Conduit.Parameters import Web.Twitter.Conduit.Request import Web.Twitter.Conduit.Response import Web.Twitter.Conduit.Status import Web.Twitter.Conduit.Stream import Web.Twitter.Conduit.Types -- for haddock import Web.Authenticate.OAuth import Data.Conduit import qualified Data.Conduit.List as CL import qualified Data.Text as T import qualified Data.Text.IO as T import Control.Monad.IO.Class import Control.Lens #ifdef HLINT {-# ANN module "HLint: ignore Use import/export shortcut" #-} #endif -- $howto -- -- The main module of twitter-conduit is "Web.Twitter.Conduit". -- This library cooperate with <http://hackage.haskell.org/package/twitter-types twitter-types>, -- <http://hackage.haskell.org/package/authenticate-oauth authenticate-oauth>, -- and <http://hackage.haskell.org/package/conduit conduit>. -- All of following examples import modules as below: -- -- > {-# LANGUAGE OverloadedStrings #-} -- > -- > import Web.Twitter.Conduit -- > import Web.Twitter.Types.Lens -- > import Web.Authenticate.OAuth -- > import Network.HTTP.Conduit -- > import Data.Conduit -- > import qualified Data.Conduit.List as CL -- > import qualified Data.Text as T -- > import qualified Data.Text.IO as T -- > import Control.Monad.IO.Class -- > import Control.Lens -- -- First, you should obtain consumer token and secret from <https://apps.twitter.com/ Twitter>, -- and prepare 'OAuth' variables as follows: -- -- @ -- tokens :: 'OAuth' -- tokens = 'twitterOAuth' -- { 'oauthConsumerKey' = \"YOUR CONSUMER KEY\" -- , 'oauthConsumerSecret' = \"YOUR CONSUMER SECRET\" -- } -- @ -- -- Second, you should obtain access token and secret. -- You can find examples obtaining those tokens in -- <https://github.com/himura/twitter-conduit/blob/master/sample sample directry>, -- for instance, -- <https://github.com/himura/twitter-conduit/blob/master/sample/oauth_pin.hs oauth_pin.hs>, and -- <https://github.com/himura/twitter-conduit/blob/master/sample/oauth_callback.hs oauth_callback.hs>. -- If you need more information, see <https://dev.twitter.com/docs/auth/obtaining-access-tokens>. -- -- You should set an access token to 'Credential' variable: -- -- @ -- credential :: 'Credential' -- credential = 'Credential' -- [ (\"oauth_token\", \"YOUR ACCESS TOKEN\") -- , (\"oauth_token_secret\", \"YOUR ACCESS TOKEN SECRET\") -- ] -- @ -- -- You should also set up the 'TWToken' and 'TWInfo' variables as below: -- -- @ -- twInfo :: 'TWInfo' -- twInfo = 'def' -- { 'twToken' = 'def' { 'twOAuth' = tokens, 'twCredential' = credential } -- , 'twProxy' = Nothing -- } -- @ -- -- Or, simply as follows: -- -- > twInfo = setCredential tokens credential def -- -- Twitter API requests are performed by 'call' function. -- For example, <https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline GET statuses/home_timeline> -- could be obtained by: -- -- @ -- timeline \<- 'withManager' $ \\mgr -\> 'call' twInfo mgr 'homeTimeline' -- @ -- -- The response of 'call' function is wrapped by the suitable type of -- <http://hackage.haskell.org/package/twitter-types twitter-types>. -- In this case, /timeline/ has a type of ['Status']. -- If you need /raw/ JSON Value which is parsed by <http://hackage.haskell.org/package/aeson aeson>, -- use 'call'' to obtain it. -- -- By default, the response of <https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline GET statuses/home_timeline> -- includes 20 tweets, and you can change the number of tweets by the /count/ parameter. -- -- @ -- timeline \<- 'withManager' $ \\mgr -\> 'call' twInfo mgr '$' 'homeTimeline' '&' 'count' '?~' 200 -- @ -- -- If you need more statuses, you can obtain those with multiple API requests. -- This library provides the wrapper for multiple requests with conduit interfaces. -- For example, if you intend to fetch the all friends information, -- you may perform multiple API requests with changing cursor parameter, -- or use the conduit wrapper 'sourceWithCursor' as below: -- -- @ -- friends \<- 'withManager' $ \\mgr -\> 'sourceWithCursor' twInfo mgr ('friendsList' ('ScreenNameParam' \"thimura\") '&' 'count' '?~' 200) '$$' 'CL.consume' -- @ -- -- Statuses APIs, for instance, 'homeTimeline', are also wrapped by 'sourceWithMaxId'. -- -- For example, you can print 1000 tweets from your home timeline, as below: -- -- @ -- main :: IO () -- main = withManager $ \mgr -> do -- 'sourceWithMaxId' twInfo mgr 'homeTimeline' -- $= CL.isolate 60 -- $$ CL.mapM_ $ \status -> liftIO $ do -- T.putStrLn $ T.concat [ T.pack . show $ status ^. statusId -- , \": \" -- , status ^. statusUser . userScreenName -- , \": \" -- , status ^. statusText -- ] -- @ -- $backward -- -- In the version below 0.1.0, twitter-conduit provides the TW monad, -- and every Twitter API functions are run in the TW monad. -- -- For backward compatibility, TW monad and the functions are provided in the Web.Twitter.Conduit.Monad module.
johan--/twitter-conduit
Web/Twitter/Conduit.hs
Haskell
bsd-2-clause
6,423
module Test.Tests where import Test.Framework import Test.AddDays import Test.ClipDates import Test.ConvertBack import Test.LongWeekYears import Test.TestCalendars import Test.TestEaster import Test.TestFormat import Test.TestMonthDay import Test.TestParseDAT import Test.TestParseTime import Test.TestTime import Test.TestTimeZone tests :: [Test] tests = [ addDaysTest , clipDates , convertBack , longWeekYears , testCalendars , testEaster , testFormat , testMonthDay , testParseDAT , testParseTime , testTime , testTimeZone ]
bergmark/time
test/Test/Tests.hs
Haskell
bsd-3-clause
619
module RmOneParameter.D2 where {-remove parameter 'ys' from function 'sumSquares'. This refactoring affects module 'D1', and 'A1'. This aims to test removing a parameter from a recursion function-} sumSquares (x:xs) = sq x + sumSquares xs sumSquares [] = 0 sq x = x ^ pow pow =2
RefactoringTools/HaRe
test/testdata/RmOneParameter/D2.expected.hs
Haskell
bsd-3-clause
289
-- | This is mostly dummy, JHC does not support inexact exceptions. module Control.Exception where import Prelude hiding(catch) import qualified Prelude as P type IOException = IOError data Exception = IOException IOException -- throw :: Exception -> a assert :: Bool -> a -> a assert True x = x assert False _ = error "assertion failure" throwIO :: Exception -> IO a throwIO (IOException ioe) = ioError ioe catch :: IO a -> (Exception -> IO a) -> IO a catch c h = P.catch c (h . IOException) catchJust :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a catchJust et c h = catch c $ \e -> maybe (throwIO e) h (et e) handle :: (Exception -> IO a) -> IO a -> IO a handle = flip catch handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a handleJust et h c = catchJust et c h try :: IO a -> IO (Either Exception a) try c = catch (fmap Right c) (return . Left) tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a) tryJust et c = catchJust et (fmap Right c) (return . Left) -- FIXME this is wrong! evaluate :: a -> IO a evaluate = return -- mapException ioErrors (IOException _) = True block, unblock :: IO a -> IO a block = id unblock = id bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c bracket before after m = do x <- before rs <- try (m x) after x case rs of Right r -> return r Left e -> throwIO e bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c bracket_ before after m = bracket before after (const m) finally :: IO a -> IO b -> IO a finally cmd end = bracket_ (return ()) (const end) cmd
m-alvarez/jhc
lib/haskell-extras/Control/Exception.hs
Haskell
mit
1,617
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..)) import Accumulate (accumulate) import System.Exit (ExitCode(..), exitWith) import Data.Char (toUpper) exitProperly :: IO Counts -> IO () exitProperly m = do counts <- m exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess testCase :: String -> Assertion -> Test testCase label assertion = TestLabel label (TestCase assertion) main :: IO () main = exitProperly $ runTestTT $ TestList [ TestList accumulateTests ] square :: Int -> Int square x = x * x accumulateTests :: [Test] accumulateTests = [ testCase "empty accumulation" $ [] @=? accumulate square [] , testCase "accumulate squares" $ [1, 4, 9] @=? accumulate square [1, 2, 3] , testCase "accumulate upcases" $ ["HELLO", "WORLD"] @=? accumulate (map toUpper) ["hello", "world"] , testCase "accumulate reversed strings" $ ["eht", "kciuq", "nworb", "xof", "cte"] @=? accumulate reverse ["the", "quick", "brown", "fox", "etc"] , testCase "accumulate recursively" $ [["a1", "a2", "a3"], ["b1", "b2", "b3"], ["c1", "c2", "c3"]] @=? accumulate (\c -> accumulate ((c:) . show) ([1, 2, 3] :: [Int])) "abc" , testCase "accumulate non-strict" $ ["nice work!"] @=? take 1 (accumulate id ("nice work!" : error "accumulate should be even lazier, don't use reverse!")) ]
ullet/exercism
haskell/accumulate/accumulate_test.hs
Haskell
mit
1,400
import Map import P import Q main = do x <- foo print (mymember 5 x)
mfine/ghc
testsuite/tests/cabal/sigcabal02/Main.hs
Haskell
bsd-3-clause
78
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module T13674 where import Data.Proxy import Data.Kind (Constraint, Type) import GHC.TypeLits import Unsafe.Coerce (unsafeCoerce) data Dict :: Constraint -> Type where Dict :: a => Dict a infixr 9 :- newtype a :- b = Sub (a => Dict b) -- | Given that @a :- b@, derive something that needs a context @b@, using the context @a@ (\\) :: a => (b => r) -> (a :- b) -> r r \\ Sub Dict = r newtype Magic n = Magic (KnownNat n => Dict (KnownNat n)) magic :: forall n m o. (Integer -> Integer -> Integer) -> (KnownNat n, KnownNat m) :- KnownNat o magic f = Sub $ unsafeCoerce (Magic Dict) (natVal (Proxy :: Proxy n) `f` natVal (Proxy :: Proxy m)) type family Lcm :: Nat -> Nat -> Nat where axiom :: forall a b. Dict (a ~ b) axiom = unsafeCoerce (Dict :: Dict (a ~ a)) lcmNat :: forall n m. (KnownNat n, KnownNat m) :- KnownNat (Lcm n m) lcmNat = magic lcm lcmIsIdempotent :: forall n. Dict (n ~ Lcm n n) lcmIsIdempotent = axiom newtype GF (n :: Nat) = GF Integer x :: GF 5 x = GF 3 y :: GF 5 y = GF 4 foo :: (KnownNat m, KnownNat n) => GF m -> GF n -> GF (Lcm m n) foo m@(GF x) n@(GF y) = GF $ (x*y) `mod` (lcm (natVal m) (natVal n)) bar :: (KnownNat m) => GF m -> GF m -> GF m bar (x :: GF m) y = foo x y - foo y x \\ lcmNat @m @m \\ Sub @() (lcmIsIdempotent @m)
sdiehl/ghc
testsuite/tests/indexed-types/should_fail/T13674.hs
Haskell
bsd-3-clause
1,544
{-# LANGUAGE TemplateHaskell, StandaloneDeriving, GeneralizedNewtypeDeriving, DeriveDataTypeable, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, BangPatterns #-} module Distribution.Server.Features.DownloadCount.State where import Data.Time.Calendar (Day(..)) import Data.Version (Version) import Data.Typeable (Typeable) import Data.Foldable (forM_) import Control.Arrow (first) import Control.Monad (liftM) import Data.List (foldl', groupBy) import Data.Function (on) import Control.Monad.Reader (ask, asks) import Control.Monad.State (get, put) import qualified Data.Map.Lazy as Map import System.FilePath ((</>)) import System.Directory ( getDirectoryContents , createDirectoryIfMissing ) import Control.Applicative ((<$>)) import qualified Data.ByteString.Lazy as BSL import System.IO (withFile, IOMode (..), hPutStr) import System.IO.Unsafe (unsafeInterleaveIO) import Text.CSV (printCSV) import Control.Exception (evaluate) import Data.Acid (Update, Query, makeAcidic) import Data.SafeCopy (base, deriveSafeCopy, safeGet, safePut) import Data.Serialize.Get (runGetLazy) import Data.Serialize.Put (runPutLazy) import Distribution.Package ( PackageId , PackageName , packageName , packageVersion ) import Distribution.Text (simpleParse, display) import Distribution.Simple.Utils (writeFileAtomic) import Distribution.Server.Framework.Instances () import Distribution.Server.Framework.MemSize import Distribution.Server.Util.CountingMap {------------------------------------------------------------------------------ Data types ------------------------------------------------------------------------------} data InMemStats = InMemStats { inMemToday :: !Day , inMemCounts :: !(SimpleCountingMap PackageId) } deriving (Show, Eq, Typeable) newtype OnDiskStats = OnDiskStats { onDiskStats :: NestedCountingMap PackageName OnDiskPerPkg } deriving (Show, Eq, MemSize) instance CountingMap (PackageName, (Day, Version)) OnDiskStats where cmEmpty = OnDiskStats $ cmEmpty cmTotal (OnDiskStats ncm) = cmTotal ncm cmInsert kl n (OnDiskStats ncm) = OnDiskStats $ cmInsert kl n ncm cmFind k (OnDiskStats ncm) = cmFind k ncm cmUnion (OnDiskStats a) (OnDiskStats b) = OnDiskStats (cmUnion a b) cmToList (OnDiskStats ncm) = cmToList ncm cmToCSV (OnDiskStats ncm) = cmToCSV ncm cmInsertRecord r (OnDiskStats ncm) = first OnDiskStats `liftM` cmInsertRecord r ncm newtype OnDiskPerPkg = OnDiskPerPkg { onDiskPerPkgCounts :: NestedCountingMap Day (SimpleCountingMap Version) } deriving (Show, Eq, Ord, MemSize) instance CountingMap (Day, Version) OnDiskPerPkg where cmEmpty = OnDiskPerPkg $ cmEmpty cmTotal (OnDiskPerPkg ncm) = cmTotal ncm cmInsert kl n (OnDiskPerPkg ncm) = OnDiskPerPkg $ cmInsert kl n ncm cmFind k (OnDiskPerPkg ncm) = cmFind k ncm cmUnion (OnDiskPerPkg a) (OnDiskPerPkg b) = OnDiskPerPkg (cmUnion a b) cmToList (OnDiskPerPkg ncm) = cmToList ncm cmToCSV (OnDiskPerPkg ncm) = cmToCSV ncm cmInsertRecord r (OnDiskPerPkg ncm) = first OnDiskPerPkg `liftM` cmInsertRecord r ncm newtype RecentDownloads = RecentDownloads { recentDownloads :: SimpleCountingMap PackageName } deriving (Show, Eq, MemSize) instance CountingMap PackageName RecentDownloads where cmEmpty = RecentDownloads $ cmEmpty cmTotal (RecentDownloads ncm) = cmTotal ncm cmInsert kl n (RecentDownloads ncm) = RecentDownloads $ cmInsert kl n ncm cmFind k (RecentDownloads ncm) = cmFind k ncm cmUnion (RecentDownloads a) (RecentDownloads b) = RecentDownloads (cmUnion a b) cmToList (RecentDownloads ncm) = cmToList ncm cmToCSV (RecentDownloads ncm) = cmToCSV ncm cmInsertRecord r (RecentDownloads ncm) = first RecentDownloads `liftM` cmInsertRecord r ncm newtype TotalDownloads = TotalDownloads { totalDownloads :: SimpleCountingMap PackageName } deriving (Show, Eq, MemSize) instance CountingMap PackageName TotalDownloads where cmEmpty = TotalDownloads $ cmEmpty cmTotal (TotalDownloads ncm) = cmTotal ncm cmInsert kl n (TotalDownloads ncm) = TotalDownloads $ cmInsert kl n ncm cmFind k (TotalDownloads ncm) = cmFind k ncm cmUnion (TotalDownloads a) (TotalDownloads b) = TotalDownloads (cmUnion a b) cmToList (TotalDownloads ncm) = cmToList ncm cmToCSV (TotalDownloads ncm) = cmToCSV ncm cmInsertRecord r (TotalDownloads ncm) = first TotalDownloads `liftM` cmInsertRecord r ncm {------------------------------------------------------------------------------ Initial instances ------------------------------------------------------------------------------} initInMemStats :: Day -> InMemStats initInMemStats day = InMemStats { inMemToday = day , inMemCounts = cmEmpty } type DayRange = (Day, Day) initRecentAndTotalDownloads :: DayRange -> OnDiskStats -> (RecentDownloads, TotalDownloads) initRecentAndTotalDownloads dayRange (OnDiskStats (NCM _ m)) = foldl' (\(recent, total) (pname, pstats) -> let !recent' = accumRecentDownloads dayRange pname pstats recent !total' = accumTotalDownloads pname pstats total in (recent', total')) (emptyRecentDownloads, emptyTotalDownloads) (Map.toList m) emptyRecentDownloads :: RecentDownloads emptyRecentDownloads = RecentDownloads cmEmpty accumRecentDownloads :: DayRange -> PackageName -> OnDiskPerPkg -> RecentDownloads -> RecentDownloads accumRecentDownloads dayRange pkgName (OnDiskPerPkg (NCM _ perDay)) | let rangeTotal = sum (map cmTotal (lookupRange dayRange perDay)) , rangeTotal > 0 = cmInsert pkgName rangeTotal | otherwise = id lookupRange :: Ord k => (k,k) -> Map.Map k a -> [a] lookupRange (l,u) m = let (_,ml,above) = Map.splitLookup l m (middle,mu,_) = Map.splitLookup u above in maybe [] (\x->[x]) ml ++ Map.elems middle ++ maybe [] (\x->[x]) mu emptyTotalDownloads :: TotalDownloads emptyTotalDownloads = TotalDownloads cmEmpty accumTotalDownloads :: PackageName -> OnDiskPerPkg -> TotalDownloads -> TotalDownloads accumTotalDownloads pkgName (OnDiskPerPkg perPkg) = cmInsert pkgName (cmTotal perPkg) {------------------------------------------------------------------------------ Pure updates/queries ------------------------------------------------------------------------------} updateHistory :: InMemStats -> OnDiskStats -> OnDiskStats updateHistory (InMemStats day perPkg) (OnDiskStats (NCM _ m)) = OnDiskStats (NCM 0 (Map.unionWith cmUnion m updatesMap)) where updatesMap :: Map.Map PackageName OnDiskPerPkg updatesMap = Map.fromList [ (pkgname, applyUpdates pkgs) | pkgs <- groupBy ((==) `on` (packageName . fst)) (cmToList perPkg :: [(PackageId, Int)]) , let pkgname = packageName (fst (head pkgs)) ] applyUpdates :: [(PackageId, Int)] -> OnDiskPerPkg applyUpdates pkgs = foldr (.) id [ cmInsert (day, packageVersion pkgId) count | (pkgId, count) <- pkgs ] cmEmpty {------------------------------------------------------------------------------ MemSize ------------------------------------------------------------------------------} instance MemSize InMemStats where memSize (InMemStats a b) = memSize2 a b {------------------------------------------------------------------------------ Serializing on-disk stats ------------------------------------------------------------------------------} readOnDiskStats :: FilePath -> IO OnDiskStats readOnDiskStats stateDir = do createDirectoryIfMissing True stateDir pkgStrs <- getDirectoryContents stateDir OnDiskStats . NCM 0 . Map.fromList <$> sequence [ do onDiskPerPkg <- unsafeInterleaveIO $ either (const cmEmpty) id <$> readOnDiskPerPkg pkgFile return (pkgName, onDiskPerPkg) | Just pkgName <- map simpleParse pkgStrs , let pkgFile = stateDir </> display pkgName ] readOnDiskPerPkg :: FilePath -> IO (Either String OnDiskPerPkg) readOnDiskPerPkg pkgFile = withFile pkgFile ReadMode $ \h -> -- By evaluating the Either result from the parser we force -- all contents to be read evaluate =<< (runGetLazy safeGet <$> BSL.hGetContents h) writeOnDiskStats :: FilePath -> OnDiskStats -> IO () writeOnDiskStats stateDir (OnDiskStats (NCM _ onDisk)) = do createDirectoryIfMissing True stateDir forM_ (Map.toList onDisk) $ \(pkgName, perPkg) -> do let pkgFile = stateDir </> display pkgName writeFileAtomic pkgFile $ runPutLazy (safePut perPkg) {------------------------------------------------------------------------------ The append-only all-time log ------------------------------------------------------------------------------} appendToLog :: FilePath -> InMemStats -> IO () appendToLog stateDir (InMemStats _ inMemStats) = withFile (stateDir </> "log") AppendMode $ \h -> hPutStr h $ printCSV (cmToCSV inMemStats) reconstructLog :: FilePath -> OnDiskStats -> IO () reconstructLog stateDir onDisk = withFile (stateDir </> "log") WriteMode $ \h -> hPutStr h $ printCSV (cmToCSV onDisk) {------------------------------------------------------------------------------ ACID stuff ------------------------------------------------------------------------------} deriveSafeCopy 0 'base ''InMemStats deriveSafeCopy 0 'base ''OnDiskPerPkg getInMemStats :: Query InMemStats InMemStats getInMemStats = ask replaceInMemStats :: InMemStats -> Update InMemStats () replaceInMemStats = put recordedToday :: Query InMemStats Day recordedToday = asks inMemToday registerDownload :: PackageId -> Update InMemStats () registerDownload pkgId = do InMemStats day counts <- get put $ InMemStats day (cmInsert pkgId 1 counts) makeAcidic ''InMemStats [ 'getInMemStats , 'replaceInMemStats , 'recordedToday , 'registerDownload ]
ocharles/hackage-server
Distribution/Server/Features/DownloadCount/State.hs
Haskell
bsd-3-clause
10,210
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Program.Strip -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This module provides an library interface to the @strip@ program. module Distribution.Simple.Program.Strip (stripLib, stripExe) where import Distribution.Simple.Program import Distribution.Simple.Utils import Distribution.System import Distribution.Verbosity import Distribution.Version import Control.Monad (unless) import System.FilePath (takeBaseName) runStrip :: Verbosity -> ProgramConfiguration -> FilePath -> [String] -> IO () runStrip verbosity progConf path args = case lookupProgram stripProgram progConf of Just strip -> rawSystemProgram verbosity strip (path:args) Nothing -> unless (buildOS == Windows) $ -- Don't bother warning on windows, we don't expect them to -- have the strip program anyway. warn verbosity $ "Unable to strip executable or library '" ++ (takeBaseName path) ++ "' (missing the 'strip' program)" stripExe :: Verbosity -> Platform -> ProgramConfiguration -> FilePath -> IO () stripExe verbosity (Platform _arch os) conf path = runStrip verbosity conf path args where args = case os of OSX -> ["-x"] -- By default, stripping the ghc binary on at least -- some OS X installations causes: -- HSbase-3.0.o: unknown symbol `_environ'" -- The -x flag fixes that. _ -> [] stripLib :: Verbosity -> Platform -> ProgramConfiguration -> FilePath -> IO () stripLib verbosity (Platform arch os) conf path = do case os of OSX -> -- '--strip-unneeded' is not supported on OS X, iOS, AIX, or -- Solaris. See #1630. return () IOS -> return () AIX -> return () Solaris -> return () Windows -> -- Stripping triggers a bug in 'strip.exe' for -- libraries with lots identically named modules. See -- #1784. return() Linux | arch == I386 -> -- Versions of 'strip' on 32-bit Linux older than 2.18 are -- broken. See #2339. let okVersion = orLaterVersion (Version [2,18] []) in case programVersion =<< lookupProgram stripProgram conf of Just v | withinRange v okVersion -> runStrip verbosity conf path args _ -> warn verbosity $ "Unable to strip library '" ++ (takeBaseName path) ++ "' (version of 'strip' too old; " ++ "requires >= 2.18 on 32-bit Linux)" _ -> runStrip verbosity conf path args where args = ["--strip-unneeded"]
tolysz/prepare-ghcjs
spec-lts8/cabal/Cabal/Distribution/Simple/Program/Strip.hs
Haskell
bsd-3-clause
2,876
{-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.DynamicWorkspaceOrder -- Copyright : (c) Brent Yorgey 2009 -- License : BSD-style (see LICENSE) -- -- Maintainer : <byorgey@gmail.com> -- Stability : experimental -- Portability : unportable -- -- Remember a dynamically updateable ordering on workspaces, together -- with tools for using this ordering with "XMonad.Actions.CycleWS" -- and "XMonad.Hooks.DynamicLog". -- ----------------------------------------------------------------------------- module XMonad.Actions.DynamicWorkspaceOrder ( -- * Usage -- $usage getWsCompareByOrder , getSortByOrder , swapWith , moveTo , moveToGreedy , shiftTo , withNthWorkspace ) where import XMonad import qualified XMonad.StackSet as W import qualified XMonad.Util.ExtensibleState as XS import XMonad.Util.WorkspaceCompare (WorkspaceCompare, WorkspaceSort, mkWsSort) import XMonad.Actions.CycleWS (findWorkspace, WSType(..), Direction1D(..), doTo) import qualified Data.Map as M import qualified Data.Set as S import Data.Maybe (fromJust, fromMaybe) import Data.Ord (comparing) -- $usage -- You can use this module by importing it into your ~\/.xmonad\/xmonad.hs file: -- -- > import qualified XMonad.Actions.DynamicWorkspaceOrder as DO -- -- Then add keybindings to swap the order of workspaces (these -- examples use "XMonad.Util.EZConfig" emacs-style keybindings): -- -- > , ("M-C-<R>", DO.swapWith Next NonEmptyWS) -- > , ("M-C-<L>", DO.swapWith Prev NonEmptyWS) -- -- See "XMonad.Actions.CycleWS" for information on the possible -- arguments to 'swapWith'. -- -- However, by itself this will do nothing; 'swapWith' does not change -- the actual workspaces in any way. It simply keeps track of an -- auxiliary ordering on workspaces. Anything which cares about the -- order of workspaces must be updated to use the auxiliary ordering. -- -- To change the order in which workspaces are displayed by -- "XMonad.Hooks.DynamicLog", use 'getSortByOrder' in your -- 'XMonad.Hooks.DynamicLog.ppSort' field, for example: -- -- > ... dynamicLogWithPP $ byorgeyPP { -- > ... -- > , ppSort = DO.getSortByOrder -- > ... -- > } -- -- To use workspace cycling commands like those from -- "XMonad.Actions.CycleWS", use the versions of 'moveTo', -- 'moveToGreedy', and 'shiftTo' exported by this module. For example: -- -- > , ("M-S-<R>", DO.shiftTo Next HiddenNonEmptyWS) -- > , ("M-S-<L>", DO.shiftTo Prev HiddenNonEmptyWS) -- > , ("M-<R>", DO.moveTo Next HiddenNonEmptyWS) -- > , ("M-<L>", DO.moveTo Prev HiddenNonEmptyWS) -- -- For slight variations on these, use the source for examples and -- tweak as desired. -- | Extensible state storage for the workspace order. data WSOrderStorage = WSO { unWSO :: Maybe (M.Map WorkspaceId Int) } deriving (Typeable, Read, Show) instance ExtensionClass WSOrderStorage where initialValue = WSO Nothing extensionType = PersistentExtension -- | Lift a Map function to a function on WSOrderStorage. withWSO :: (M.Map WorkspaceId Int -> M.Map WorkspaceId Int) -> (WSOrderStorage -> WSOrderStorage) withWSO f = WSO . fmap f . unWSO -- | Update the ordering storage: initialize if it doesn't yet exist; -- add newly created workspaces at the end as necessary. updateOrder :: X () updateOrder = do WSO mm <- XS.get case mm of Nothing -> do -- initialize using ordering of workspaces from the user's config ws <- asks (workspaces . config) XS.put . WSO . Just . M.fromList $ zip ws [0..] Just m -> do -- check for new workspaces and add them at the end curWs <- gets (S.fromList . map W.tag . W.workspaces . windowset) let mappedWs = M.keysSet m newWs = curWs `S.difference` mappedWs nextIndex = 1 + maximum (-1 : M.elems m) newWsIxs = zip (S.toAscList newWs) [nextIndex..] XS.modify . withWSO . M.union . M.fromList $ newWsIxs -- | A comparison function which orders workspaces according to the -- stored dynamic ordering. getWsCompareByOrder :: X WorkspaceCompare getWsCompareByOrder = do updateOrder -- after the call to updateOrder we are guaranteed that the dynamic -- workspace order is initialized and contains all existing -- workspaces. WSO (Just m) <- XS.get return $ comparing (fromMaybe 1000 . flip M.lookup m) -- | Sort workspaces according to the stored dynamic ordering. getSortByOrder :: X WorkspaceSort getSortByOrder = mkWsSort getWsCompareByOrder -- | Swap the current workspace with another workspace in the stored -- dynamic order. swapWith :: Direction1D -> WSType -> X () swapWith dir which = findWorkspace getSortByOrder dir which 1 >>= swapWithCurrent -- | Swap the given workspace with the current one. swapWithCurrent :: WorkspaceId -> X () swapWithCurrent w = do cur <- gets (W.currentTag . windowset) swapOrder w cur -- | Swap the two given workspaces in the dynamic order. swapOrder :: WorkspaceId -> WorkspaceId -> X () swapOrder w1 w2 = do io $ print (w1,w2) WSO (Just m) <- XS.get let [i1,i2] = map (fromJust . flip M.lookup m) [w1,w2] XS.modify (withWSO (M.insert w1 i2 . M.insert w2 i1)) windows id -- force a status bar update -- | View the next workspace of the given type in the given direction, -- where \"next\" is determined using the dynamic workspace order. moveTo :: Direction1D -> WSType -> X () moveTo dir t = doTo dir t getSortByOrder (windows . W.view) -- | Same as 'moveTo', but using 'greedyView' instead of 'view'. moveToGreedy :: Direction1D -> WSType -> X () moveToGreedy dir t = doTo dir t getSortByOrder (windows . W.greedyView) -- | Shift the currently focused window to the next workspace of the -- given type in the given direction, using the dynamic workspace order. shiftTo :: Direction1D -> WSType -> X () shiftTo dir t = doTo dir t getSortByOrder (windows . W.shift) -- | Do something with the nth workspace in the dynamic order. The -- callback is given the workspace's tag as well as the 'WindowSet' -- of the workspace itself. withNthWorkspace :: (String -> WindowSet -> WindowSet) -> Int -> X () withNthWorkspace job wnum = do sort <- getSortByOrder ws <- gets (map W.tag . sort . W.workspaces . windowset) case drop wnum ws of (w:_) -> windows $ job w [] -> return ()
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Actions/DynamicWorkspaceOrder.hs
Haskell
bsd-2-clause
6,450
{- Haskell version of ... ! Text of rule base for Boyer benchmark ! ! Started by Tony Kitto on 6th April 1988 ! ! Changes Log ! ! 07-04-88 ADK Corrected errors in rules ! 08-04-88 ADK Modified "or" rule to remove extra final (f) of book definition Haskell version: 23-06-93 JSM initial version -} module Rulebasetext (rules) where rules :: [String] -- Rule base extracted from Gabriel pages 118 to 126 rules = [ "(equal (compile form)\ \(reverse (codegen (optimize form) (nil) ) ) )", "(equal (eqp x y)\ \(equal (fix x)\ \(fix y) ) )", "(equal (greaterp x y)\ \(lessp y x) )", "(equal (lesseqp x y)\ \(not (lessp y x) ) )", "(equal (greatereqp x y)\ \(not (lessp y x) ) )", "(equal (boolean x)\ \(or (equal x (t) )\ \(equal x (f) ) )", "(equal (iff x y)\ \(and (implies x y)\ \(implies y x) ) )", "(equal (even1 x)\ \(if (zerop x)\ \(t)\ \(odd (1- x) ) ) )", "(equal (countps- l pred)\ \(countps-loop l pred (zero) ) )", "(equal (fact- i)\ \(fact-loop i 1) )", "(equal (reverse- x)\ \(reverse-loop x (nil) ) )", "(equal (divides x y)\ \(zerop (remainder y x) ) )", "(equal (assume-true var alist)\ \(cons (cons var (t) )\ \alist) )", "(equal (assume-false var alist)\ \(cons (cons var (f) )\ \alist) )", "(equal (tautology-checker x)\ \(tautologyp (normalize x)\ \(nil) ) )", "(equal (falsify x)\ \(falsify1 (normalize x)\ \(nil) ) )", "(equal (prime x)\ \(and (not (zerop x))\ \(not (equal x (add1 (zero) ) ) )\ \(prime1 x (1- x) ) ) )", "(equal (and p q)\ \(if p (if q (t) (f) ) (f) ) )", "(equal (or p q)\ \(if p (t) (if q (t) (f) ) ) )", -- book has extra (f) "(equal (not p)\ \(if p (f) (t) ) )", "(equal (implies p q)\ \(if p (if q (t) (f) ) (t) ) )", "(equal (fix x)\ \(if (numberp x) x (zero) ) )", "(equal (if (if a b c) d e)\ \(if a (if b d e) (if c d e) ) )", "(equal (zerop x)\ \(or (equal x (zero) )\ \(not (numberp x) ) ) )", "(equal (plus (plus x y) z )\ \(plus x (plus y z) ) )", "(equal (equal (plus a b) (zero ) )\ \(and (zerop a) (zerop b) ) )", "(equal (difference x x)\ \(zero) )", "(equal (equal (plus a b) (plus a c) )\ \(equal (fix b) (fix c) ) )", "(equal (equal (zero) (difference x y) )\ \(not (lessp y x) ) )", "(equal (equal x (difference x y) )\ \(and (numberp x)\ \(or (equal x (zero) )\ \(zerop y) ) ) )", "(equal (meaning (plus-tree (append x y) ) a)\ \(plus (meaning (plus-tree x) a)\ \(meaning (plus-tree y) a) ) )", "(equal (meaning (plus-tree (plus-fringe x) ) a)\ \(fix (meaning x a) ) )", "(equal (append (append x y) z)\ \(append x (append y z) ) )", "(equal (reverse (append a b) )\ \(append (reverse b) (reverse a) ) )", "(equal (times x (plus y z) )\ \(plus (times x y)\ \(times x z) ) )", "(equal (times (times x y) z)\ \(times x (times y z) ) )", "(equal (equal (times x y) (zero) )\ \(or (zerop x)\ \(zerop y) ) )", "(equal (exec (append x y)\ \pds envrn)\ \(exec y (exec x pds envrn)\ \envrn) )", "(equal (mc-flatten x y)\ \(append (flatten x)\ \y) )", "(equal (member x (append a b) )\ \(or (member x a)\ \(member x b) ) )", "(equal (member x (reverse y) )\ \(member x y) )", "(equal (length (reverse x) )\ \(length x) )", "(equal (member a (intersect b c) )\ \(and (member a b)\ \(member a c) ) )", "(equal (nth (zero)\ \i)\ \(zero) )", "(equal (exp i (plus j k) )\ \(times (exp i j)\ \(exp i k) ) )", "(equal (exp i (times j k) )\ \(exp (exp i j)\ \k) )", "(equal (reverse-loop x y)\ \(append (reverse x)\ \y) )", "(equal (reverse-loop x (nil) )\ \(reverse x) )", "(equal (count-list z (sort-lp x y) )\ \(plus (count-list z x)\ \(count-list z y) ) )", "(equal (equal (append a b)\ \(append a c) )\ \(equal b c) )", "(equal (plus (remainder x y)\ \(times y (quotient x y) ) )\ \(fix x) )", "(equal (power-eval (big-plus1 l i base)\ \base)\ \(plus (power-eval l base)\ \i) )", "(equal (power-eval (big-plus x y i base)\ \base)\ \(plus i (plus (power-eval x base)\ \(power-eval y base) ) ) )", "(equal (remainder y 1)\ \(zero) )", "(equal (lessp (remainder x y)\ \y)\ \(not (zerop y) ) )", "(equal (remainder x x)\ \(zero) )", "(equal (lessp (quotient i j)\ \i)\ \(and (not (zerop i) )\ \(or (zerop j)\ \(not (equal j 1) ) ) ) )", "(equal (lessp (remainder x y)\ \x)\ \(and (not (zerop y) )\ \(not (zerop x) )\ \(not (lessp x y) ) ) )", "(equal (power-eval (power-rep i base)\ \base)\ \(fix i) )", "(equal (power-eval (big-plus (power-rep i base)\ \(power-rep j base)\ \(zero)\ \base)\ \base)\ \(plus i j) )", "(equal (gcd x y)\ \(gcd y x) )", "(equal (nth (append a b)\ \i)\ \(append (nth a i)\ \(nth b (difference i (length a) ) ) ) )", "(equal (difference (plus x y)\ \x)\ \(fix y) )", "(equal (difference (plus y x)\ \x)\ \(fix y) )", "(equal (difference (plus x y)\ \(plus x z) )\ \(difference y z) )", "(equal (times x (difference c w) )\ \(difference (times c x)\ \(times w x) ) )", "(equal (remainder (times x z)\ \z)\ \(zero) )", "(equal (difference (plus b (plus a c) )\ \a)\ \(plus b c) )", "(equal (difference (add1 (plus y z)\ \z)\ \(add1 y) )", "(equal (lessp (plus x y)\ \(plus x z ) )\ \(lessp y z) )", "(equal (lessp (times x z)\ \(times y z) )\ \(and (not (zerop z) )\ \(lessp x y) ) )", "(equal (lessp y (plus x y) )\ \(not (zerop x) ) )", "(equal (gcd (times x z)\ \(times y z) )\ \(times z (gcd x y) ) )", "(equal (value (normalize x)\ \a)\ \(value x a) )", "(equal (equal (flatten x)\ \(cons y (nil) ) )\ \(and (nlistp x)\ \(equal x y) ) )", "(equal (listp (gopher x) )\ \(listp x) )", "(equal (samefringe x y)\ \(equal (flatten x)\ \(flatten y) ) )", "(equal (equal (greatest-factor x y)\ \(zero) )\ \(and (or (zerop y)\ \(equal y 1) )\ \(equal x (zero) ) ) )", "(equal (equal (greatest-factor x y)\ \1)\ \(equal x 1) )", "(equal (numberp (greatest-factor x y) )\ \(not (and (or (zerop y)\ \(equal y 1) )\ \(not (numberp x) ) ) ) )", "(equal (times-list (append x y) )\ \(times (times-list x)\ \(times-list y) ) )", "(equal (prime-list (append x y) )\ \(and (prime-list x)\ \(prime-list y) ) )", "(equal (equal z (times w z) )\ \(and (numberp z)\ \(or (equal z (zero) )\ \(equal w 1) ) ) )", "(equal (greatereqpr x y)\ \(not (lessp x y) ) )", "(equal (equal x (times x y) )\ \(or (equal x (zero) )\ \(and (numberp x)\ \(equal y 1) ) ) )", "(equal (remainder (times y x)\ \y)\ \(zero) )", "(equal (equal (times a b)\ \1)\ \(and (not (equal a (zero) ) )\ \(not (equal b (zero) ) )\ \(numberp a)\ \(numberp b)\ \(equal (1- a)\ \(zero) )\ \(equal (1- b)\ \(zero) ) ) )", "(equal (lessp (length (delete x l) )\ \(length l) )\ \(member x l) )", "(equal (sort2 (delete x l) )\ \(delete x (sort2 l) ) )", "(equal (dsort x)\ \(sort2 x) )", "(equal (length\ \(cons \ \x1\ \(cons \ \x2\ \(cons \ \x3\ \(cons \ \x4\ \(cons \ \x5\ \(cons x6 x7) ) ) ) ) ) )\ \(plus 6 (length x7) ) )", "(equal (difference (add1 (add1 x) )\ \2)\ \(fix x) )", "(equal (quotient (plus x (plus x y) )\ \2)\ \(plus x (quotient y 2) ) )", "(equal (sigma (zero)\ \i)\ \(quotient (times i (add1 i) )\ \2) )", "(equal (plus x (add1 y) )\ \(if (numberp y)\ \(add1 (plus x y) )\ \(add1 x) ) )", "(equal (equal (difference x y)\ \(difference z y) )\ \(if (lessp x y)\ \(not (lessp y z) )\ \(if (lessp z y)\ \(not (lessp y x) )\ \(equal (fix x)\ \(fix z) ) ) ) )", "(equal (meaning (plus-tree (delete x y) )\ \a)\ \(if (member x y)\ \(difference (meaning (plus-tree y)\ \a)\ \(meaning x a) )\ \(meaning (plus-tree y)\ \a) ) )", "(equal (times x (add1 y) )\ \(if (numberp y)\ \(plus x (times x y) )\ \(fix x) ) )", "(equal (nth (nil)\ \i)\ \(if (zerop i)\ \(nil)\ \(zero) ) )", "(equal (last (append a b) )\ \(if (listp b)\ \(last b)\ \(if (listp a)\ \(cons (car (last a) )\ \b)\ \b) ) )", "(equal (equal (lessp x y)\ \z)\ \(if (lessp x y)\ \(equal t z)\ \(equal f z) ) )", "(equal (assignment x (append a b) )\ \(if (assignedp x a)\ \(assignment x a)\ \(assignment x b) ) )", "(equal (car (gopher x) )\ \(if (listp x)\ \(car (flatten x) )\ \(zero) ) )", "(equal (flatten (cdr (gopher x) ) )\ \(if (listp x)\ \(cdr (flatten x) )\ \(cons (zero)\ \(nil) ) ) )", "(equal (quotient (times y x)\ \y)\ \(if (zerop y)\ \(zero)\ \(fix x) ) )", "(equal (get j (set i val mem) )\ \(if (eqp j i)\ \val\ \(get j mem) ) )"]
philderbeast/ghcjs
test/nofib/spectral/boyer2/Rulebasetext.hs
Haskell
mit
15,416
module A where data A = A other :: Int other = 2 -- | Doc for test2 test2 :: Bool test2 = False -- | Should show up on the page for both modules A and B data X = X -- ^ Doc for consructor -- | Should show up on the page for both modules A and B reExport :: Int reExport = 1
DavidAlphaFox/ghc
utils/haddock/html-test/src/A.hs
Haskell
bsd-3-clause
279
module Main where import Control.Concurrent main = do c <- newChan let writer = writeList2Chan c "Hello World\n" forkIO writer let reader = do char <- readChan c if (char == '\n') then return () else do putChar char; reader reader
urbanslug/ghc
testsuite/tests/concurrent/should_run/conc002.hs
Haskell
bsd-3-clause
262
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE TupleSections #-} module Stutter.Parser where import Control.Applicative import Control.Monad import Text.Read (readMaybe) import Data.Attoparsec.Text ((<?>)) import qualified Data.Attoparsec.Text as Atto import qualified Data.Text as T import Stutter.Producer hiding (ProducerGroup) type ProducerGroup = ProducerGroup_ () ------------------------------------------------------------------------------- -- Text ------------------------------------------------------------------------------- parseText :: Atto.Parser T.Text parseText = (<?> "text") $ T.pack <$> Atto.many1 parseSimpleChar parseSimpleChar :: Atto.Parser Char parseSimpleChar = (<?> "simple char or escaped char") $ -- A non-special char Atto.satisfy (`notElem` specialChars) <|> -- An escaped special char Atto.char '\\' *> Atto.anyChar specialChars :: [Char] specialChars = [ -- Used for sum '|' -- Used for product , '#' -- Used for zip , '$' -- Used for Kleene plus , '+' -- Used for Kleene start , '*' -- Used for optional , '?' -- Used to delimit ranges , '[', ']' -- Used to scope groups , '(', ')' -- Used to replicate groups , '{', '}' -- Used for escaping , '\\' -- Used for files , '@' ] parseGroup :: Atto.Parser ProducerGroup parseGroup = (<?> "producer group") $ (parseUnit' <**> parseSquasher' <*> parseGroup) <|> (PProduct <$> parseUnit' <*> parseGroup) <|> parseUnit' where parseUnit' = parseReplicatedUnit <|> parseUnit -- Default binary function to product (@#@) parseSquasher' = parseSquasher <|> pure PProduct parseReplicatedUnit :: Atto.Parser ProducerGroup parseReplicatedUnit = (<?> "replicated unary producer") $ -- This the logic for the replication shouldn't be in the parser parseUnit <**> parseReplicator type Squasher = ProducerGroup -> ProducerGroup -> ProducerGroup type Replicator = ProducerGroup -> ProducerGroup parseReplicator :: Atto.Parser Replicator parseReplicator = parseKleenePlus <|> parseKleeneStar <|> parseOptional <|> parseFoldApp parseKleenePlus :: Atto.Parser Replicator parseKleenePlus = Atto.char '+' *> pure (PRepeat) parseKleeneStar :: Atto.Parser Replicator parseKleeneStar = Atto.char '*' *> pure (PSum (PText T.empty) . PRepeat) parseOptional :: Atto.Parser Replicator parseOptional = Atto.char '?' *> pure (PSum (PText T.empty) ) parseFoldApp :: Atto.Parser Replicator parseFoldApp = bracketed '{' '}' ( flip (,) <$> parseSquasher <* Atto.char '|' <*> parseInt <|> (,PSum) <$> parseInt ) <**> (pure (\(n, f) -> foldr1 f . replicate n)) where parseInt :: Atto.Parser Int parseInt = (readMaybe <$> Atto.many1 Atto.digit) >>= \case Nothing -> mzero Just x -> return x parseSquasher :: Atto.Parser Squasher parseSquasher = Atto.anyChar >>= \case '|' -> return PSum '$' -> return PZip '#' -> return PProduct _ -> mzero parseUnit :: Atto.Parser ProducerGroup parseUnit = (<?> "unary producer") $ PRanges <$> parseRanges <|> parseHandle <|> PText <$> parseText <|> bracketed '(' ')' parseGroup bracketed :: Char -> Char -> Atto.Parser a -> Atto.Parser a bracketed cl cr p = Atto.char cl *> p <* Atto.char cr -- | Parse a Handle-like reference, preceded by an @\@@ sign. A single dash -- (@-@) is interpreted as @stdin@, any other string is used as a file path. parseHandle :: Atto.Parser ProducerGroup parseHandle = (<?> "handle reference") $ (flip fmap) parseFile $ \case "-" -> PStdin () fp -> PFile fp ------------------------------------------------------------------------------- -- File ------------------------------------------------------------------------------- parseFile :: Atto.Parser FilePath parseFile = (<?> "file reference") $ T.unpack <$> (Atto.char '@' *> parseText) ------------------------------------------------------------------------------- -- Ranges ------------------------------------------------------------------------------- -- | Parse several ranges -- -- Example: -- @[a-zA-Z0-6]@ parseRanges :: Atto.Parser [Range] parseRanges = (<?> "ranges") $ Atto.char '[' *> Atto.many1 parseRange <* Atto.char ']' -- | Parse a range of the form 'a-z' (int or char) parseRange :: Atto.Parser Range parseRange = (<?> "range") $ parseIntRange <|> parseCharRange -- | Parse a range in the format "<start>-<end>", consuming exactly 3 -- characters parseIntRange :: Atto.Parser Range parseIntRange = (<?> "int range") $ IntRange <$> ((,) <$> parseInt <* Atto.char '-' <*> parseInt) where parseInt :: Atto.Parser Int parseInt = (readMaybe . (:[]) <$> Atto.anyChar) >>= \case Nothing -> mzero Just x -> return x -- | Parse a range in the format "<start>-<end>", consuming exactly 3 -- characters parseCharRange :: Atto.Parser Range parseCharRange = (<?> "char range") $ CharRange <$> ((,) <$> Atto.anyChar <* Atto.char '-' <*> Atto.anyChar)
nmattia/stutter
src/Stutter/Parser.hs
Haskell
mit
5,112
-- This source code is distributed under the terms of a MIT license, -- Copyright (c) 2016-present, SoundCloud Ltd. -- All rights reserved. -- -- This source code is distributed under the terms of a MIT license, -- found in the LICENSE file. {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} module Main where import Kubernetes.Apis import Servant import Servant.Mock import qualified Network.Wai.Handler.Warp as Warp main :: IO () main = Warp.run 8080 $ serve api (mock api)
soundcloud/haskell-kubernetes
server/Main.hs
Haskell
mit
519
module Euler008 (euler8) where import Common import Data.Char euler8 :: Int euler8 = maximum [product adjacents | adjacents <- sliding 13 num] num :: [Int] num = map digitToInt "\ \73167176531330624919225119674426574742355349194934\ \96983520312774506326239578318016984801869478851843\ \85861560789112949495459501737958331952853208805511\ \12540698747158523863050715693290963295227443043557\ \66896648950445244523161731856403098711121722383113\ \62229893423380308135336276614282806444486645238749\ \30358907296290491560440772390713810515859307960866\ \70172427121883998797908792274921901699720888093776\ \65727333001053367881220235421809751254540594752243\ \52584907711670556013604839586446706324415722155397\ \53697817977846174064955149290862569321978468622482\ \83972241375657056057490261407972968652414535100474\ \82166370484403199890008895243450658541227588666881\ \16427171479924442928230863465674813919123162824586\ \17866458359124566529476545682848912883142607690042\ \24219022671055626321111109370544217506941658960408\ \07198403850962455444362981230987879927244284909188\ \84580156166097919133875499200524063689912560717606\ \05886116467109405077541002256983155200055935729725\ \71636269561882670428252483600823257530420752963450"
TrustNoOne/Euler
haskell/src/Euler008.hs
Haskell
mit
1,324
module Types( Matrix(..), Point(..), Point3d(..), IntPoint, IntPoint3d, GLPoint, GLPoint3d, Line(..), Line3d(..), Viewport(..), Axis, mkViewport, translateMatrix, scaleMatrix, rotationMatrix, translate3d, scale3d, rotate3d ) where import Graphics.Rendering.OpenGL.Raw.Core31 data Matrix a = Matrix{ w :: Int, h :: Int, mdata :: [[a]] } deriving (Show, Eq) type Point a = (a, a) type Point3d a = (a, a, a) type IntPoint = Point Int type GLPoint = Point GLfloat type IntPoint3d = Point3d Int type GLPoint3d = Point3d GLfloat data Line a = Line {p_x :: Point a, p_y :: Point a} deriving (Show, Eq) data Line3d a = Line3d { p :: Point3d a, q :: Point3d a} deriving (Show, Eq) data Viewport = Viewport {minX :: Int, minY :: Int, maxX :: Int, maxY :: Int} deriving (Show, Eq) data Axis = X | Y | Z deriving (Show, Eq) --Safe making viewport mkViewport :: Int -> Int -> Int -> Int -> Maybe Viewport mkViewport minx miny maxx maxy | minx < maxx && miny < maxy = Just (Viewport minx miny maxx maxy) | otherwise = Nothing translateMatrix tx ty = Matrix 3 3 [[1, 0, tx], [0, 1, ty], [0, 0, 1]] scaleMatrix sx sy = Matrix 3 3 [[sx, 0, 0], [0, sy, 0], [0, 0, 1]] rotationMatrix theta = Matrix 3 3 [[cos t, -(sin t), 0], [sin t, cos t, 0], [0, 0, 1]] where t = - (theta * pi / 180) -- to change to clockwise rotation and map to rads translate3d tx ty tz = Matrix 4 4 [[1, 0, 0, tx], [0, 1, 0, ty], [0, 0, 0, tz], [0, 0, 0, 1]] scale3d sx sy sz = Matrix 4 4 [[sx, 0, 0, 0], [0, sy, 0, 0], [0, 0, sz, 0], [0, 0, 0, 1]] rotate3d a theta = let t = - (theta * pi / 180) c = cos t s = sin t in Matrix 4 4 $ case a of X -> [[1, 0, 0, 0], [0, c, s, 0], [0, (-s), c, 0], [0, 0, 0, 1]] Y -> [[c, 0, (-s), 0], [0, 1, 0, 0], [s, 0, c, 0], [0, 0, 0, 1]] Z -> [[c, s, 0, 0], [(-s), c, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
5outh/Haskell-Graphics-Projects
Project3/Types.hs
Haskell
mit
1,881
module Y2017.M07.D04.Exercise where {-- Another Mensa-puzzler from the Genius Mensa Quiz-a-Day Book by Dr. Abbie F. Salny. July 2 problem: Jemima has the same number of brothers as she has sisters, but her brother, Roland, has twice as many sisters as he has brothers. How many boys and girls are there in this family? --} data Name = Jemima | Roland deriving (Eq, Show) data Sex = Male | Female deriving (Eq, Show) data Person = Pers Name Sex deriving (Eq, Show) type Boys = Int type Girls = Int type Multiplier = Int -- to equate girls to boys data Statement = Has Person Multiplier deriving (Eq, Show) jemima, roland :: Statement jemima = Pers Jemima Female `Has` 1 roland = Pers Roland Male `Has` 2 familySize :: [Statement] -> [(Boys, Girls)] familySize statements = undefined
geophf/1HaskellADay
exercises/HAD/Y2017/M07/D04/Exercise.hs
Haskell
mit
805
{-# LANGUAGE FlexibleContexts #-} module Metropolis (arb) where import Data.Random arb :: (Distribution Uniform a, Distribution Uniform b, Ord a, Num b, Ord b) => (a->b) -> (a,a) -> b -> RVar a arb f (low, high) top = do site <- uniform low high test <- uniform 0 top if f site > test then return site else arb f (low, high) top
rprospero/NeutronPipe
Metropolis.hs
Haskell
mit
341
ans s [] = if s == 0 then "YES" else "NO" ans s (l:ls) = case l of "A" -> ans (s+1) ls "Un" -> if s == 0 then "NO" else ans (s-1) ls main = do _ <- getLine c <- getContents let i = lines c o = ans 0 i putStrLn o
a143753/AOJ
2738.hs
Haskell
apache-2.0
241
{-# LANGUAGE ForeignFunctionInterface #-} {-# OPTIONS_GHC -O2 #-} -- | * Author: Jefferson Heard (jefferson.r.heard at gmail.com) -- -- * Copyright 2008 Renaissance Computing Institute < http://www.renci.org > -- -- * License: GNU LGPL -- -- * Compatibility GHC (I could change the data declarations to not be empty and that would make it more generally compatible, I believe) -- -- * Description: -- -- Use FreeType 2 Fonts in OpenGL. Requires the FTGL library and FreeType libraries. -- available at < http://ftgl.wiki.sourceforge.net/ > . The most important functions for -- everyday use are renderFont and the create*Font family of functions. To render a -- simple string inside OpenGL, assuming you have OpenGL initialized and a current -- pen color, all you need is: -- -- > do font <- createTextureFont "Font.ttf" -- > setFontFaceSize font 24 72 -- > renderFont font "Hello world!" -- -- Fonts are rendered so that a single point is an OpenGL unit, and a point is 1:72 of -- an inch. module Graphics.Rendering.FTGL where import System.IO.Unsafe (unsafePerformIO) import Foreign.C import Foreign.Ptr import Foreign.Marshal.Alloc import Foreign.Marshal.Array import Data.Bits import Data.Char (ord) import Data.Word import qualified Graphics.Rendering.OpenGL.GL as GL import Control.Applicative ((<$>)) foreign import ccall unsafe "ftglCreateBitmapFont" fcreateBitmapFont :: CString -> IO Font -- | Create a bitmapped version of a TrueType font. Bitmapped versions will not -- | respond to matrix transformations, but rather must be transformed using the -- | raster positioning functions in OpenGL createBitmapFont :: String -> IO Font createBitmapFont file = withCString file $ \p -> fcreateBitmapFont p foreign import ccall unsafe "ftglCreateBufferFont" fcreateBufferFont :: CString -> IO Font -- | Create a buffered version of a TrueType font. This stores the entirety of -- | a string in a texture, "buffering" it before rendering. Very fast if you -- | will be repeatedly rendering the same strings over and over. createBufferFont :: String -> IO Font createBufferFont file = withCString file $ \p -> fcreateBufferFont p {- foreign import ccall unsafe "ftglCreateOutlineFont" fcreateOutlineFont :: CString -> IO Font -- | Create an outline version of a TrueType font. This uses actual geometry -- | and will scale independently without loss of quality. Faster than polygons -- | but slower than texture or buffer fonts. createOutlineFont :: String -> IO Font createOutlineFont file = withCString file $ \p -> fcreateOutlineFont p -} foreign import ccall unsafe "ftglCreatePixmapFont" fcreatePixmapFont :: CString -> IO Font -- | Create a pixmap version of a TrueType font. Higher quality than the bitmap -- | font without losing any performance. Use this if you don't mind using -- | set and get RasterPosition. createPixmapFont :: String -> IO Font createPixmapFont file = withCString file $ \p -> fcreatePixmapFont p foreign import ccall unsafe "ftglCreatePolygonFont" fcreatePolygonFont :: CString -> IO Font -- | Create polygonal display list fonts. These scale independently without -- | losing quality, unlike texture or buffer fonts, but can be impractical -- | for large amounts of text because of the high number of polygons needed. -- | Additionally, they do not, unlike the textured fonts, create artifacts -- | within the square formed at the edge of each character. createPolygonFont :: String -> IO Font createPolygonFont file = withCString file $ \p -> fcreatePolygonFont p foreign import ccall unsafe "ftglCreateTextureFont" fcreateTextureFont :: CString -> IO Font -- | Create textured display list fonts. These can scale somewhat well, -- | but lose quality quickly. They are much faster than polygonal fonts, -- | though, so are suitable for large quantities of text. Especially suited -- | well to text that changes with most frames, because it doesn't incur the -- | (normally helpful) overhead of buffering. createTextureFont :: String -> IO Font createTextureFont file = withCString file $ \p -> fcreateTextureFont p {- foreign import ccall unsafe "ftglCreateExtrudeFont" fcreateExtrudeFont :: CString -> IO Font -- | Create a 3D extruded font. This is the only way of creating 3D fonts -- | within FTGL. Could be fun to use a geometry shader to get different -- | effects by warping the otherwise square nature of the font. Polygonal. -- | Scales without losing quality. Slower than all other fonts. createExtrudeFont :: String -> IO Font createExtrudeFont file = withCString file $ \p -> fcreateExtrudeFont p -} -- | Create a simple layout foreign import ccall unsafe "ftglCreateSimpleLayout" createSimpleLayout :: IO Layout -- | Set the layout's font. foreign import ccall unsafe "ftglSetLayoutFont" setLayoutFont :: Layout -> Font -> IO () foreign import ccall unsafe "ftglGetLayoutFont" fgetLayoutFont :: Layout -> IO Font -- | Get the embedded font from the Layout getLayoutFont f = fgetLayoutFont f -- | Set the line length, I believe in OpenGL units, although I'm not sure. foreign import ccall unsafe "ftglSetLayoutLineLength" setLayoutLineLength :: Layout -> CFloat -> IO () foreign import ccall unsafe "ftglGetLayoutLineLength" fgetLayoutLineLength :: Layout -> IO CFloat -- | Get the line length in points (1:72in) of lines in the layout getLayoutLineLength :: Layout -> IO Float getLayoutLineLength f = realToFrac <$> fgetLayoutLineLength f foreign import ccall unsafe "ftglSetLayoutAlignment" fsetLayoutAlignment :: Layout -> CInt -> IO () -- | Set the layout alignment setLayoutAlignment layout alignment = fsetLayoutAlignment layout (marshalTextAlignment alignment) foreign import ccall unsafe "ftglGetLayoutAlignement" fgetLayoutAlignment :: Layout -> IO CInt -- | Get the alignment of text in this layout. getLayoutAlignment f = readTextAlignment <$> fgetLayoutAlignment f foreign import ccall unsafe "ftglSetLayoutLineSpacing" fsetLayoutLineSpacing :: Layout -> CFloat -> IO () -- | Set layout line spacing in OpenGL units. setLayoutLineSpacing :: Layout -> Float -> IO () setLayoutLineSpacing layout spacing = setLayoutLineSpacing layout (realToFrac spacing) -- | Destroy a font foreign import ccall unsafe "ftglDestroyFont" destroyFont :: Font -> IO () foreign import ccall unsafe "ftglAttachFile" fattachFile :: Font -> CString -> IO () -- | Attach a metadata file to a font. attachFile :: Font -> String -> IO () attachFile font str = withCString str $ \p -> fattachFile font p -- | Attach some external data (often kerning) to the font foreign import ccall unsafe "ftglAttachData" attachData :: Font -> Ptr () -> IO () -- | Set the font's character map foreign import ccall unsafe "ftglSetFontCharMap" fsetFontCharMap :: Font -> CInt -> IO () setCharMap :: Font -> CharMap -> IO () setCharMap font charmap = fsetFontCharMap font (marshalCharMap charmap) foreign import ccall unsafe "ftglGetFontCharMapCount" fgetFontCharMapCount :: Font -> IO CInt -- | Get the number of characters loaded into the current charmap for the font. getFontCharMapCount :: Font -> Int getFontCharMapCount f = fromIntegral . unsafePerformIO $ fgetFontCharMapCount f foreign import ccall unsafe "ftglGetFontCharMapList" fgetFontCharMapList :: Font -> IO (Ptr CInt) -- | Get the different character mappings available in this font. getFontCharMapList f = unsafePerformIO $ fgetFontCharMapList f foreign import ccall unsafe "ftglSetFontFaceSize" fsetFontFaceSize :: Font -> CInt -> CInt -> IO CInt setFontFaceSize :: Font -> Int -> Int -> IO CInt setFontFaceSize f s x = fsetFontFaceSize f (fromIntegral s) (fromIntegral x) foreign import ccall unsafe "ftglGetFontFaceSize" fgetFontFaceSize :: Font -> IO CInt -- | Get the current font face size in points. getFontFaceSize :: Font -> IO Int getFontFaceSize f = fromIntegral <$> fgetFontFaceSize f foreign import ccall unsafe "ftglSetFontDepth" fsetFontDepth :: Font -> CFloat -> IO () setFontDepth :: Font -> Float -> IO () setFontDepth font depth = fsetFontDepth font (realToFrac depth) foreign import ccall unsafe "ftglSetFontOutset" fsetFontOutset :: Font -> CFloat -> CFloat -> IO () setFontOutset :: Font -> Float -> Float -> IO () setFontOutset font d o = fsetFontOutset font (realToFrac d) (realToFrac o) foreign import ccall unsafe "ftglGetFontBBoxW" fgetFontBBoxW :: Font -> Ptr Word32 -> Int -> Ptr CFloat -> IO () -- | Get the text extents of a string as a list of (llx,lly,lly,urx,ury,urz) getFontBBox :: Font -> String -> IO [Float] getFontBBox f str = allocaBytes 24 $ \pf -> allocaArray (length str + 1) $ \ps -> do pokeArray0 0 ps (map (fromIntegral . ord) str) fgetFontBBoxW f ps (-1) pf map realToFrac <$> peekArray 6 pf foreign import ccall unsafe "ftglGetFontAscender" fgetFontAscender :: Font -> CFloat -- | Get the global ascender height for the face. getFontAscender :: Font -> Float getFontAscender = realToFrac . fgetFontAscender foreign import ccall unsafe "ftglGetFontDescender" fgetFontDescender :: Font -> CFloat -- | Gets the global descender height for the face. getFontDescender :: Font -> Float getFontDescender = realToFrac . fgetFontDescender foreign import ccall unsafe "ftglGetFontLineHeight" fgetFontLineHeight :: Font -> CFloat -- | Gets the global line spacing for the face. getFontLineHeight :: Font -> Float getFontLineHeight = realToFrac . fgetFontLineHeight foreign import ccall unsafe "ftglGetFontAdvanceW" fgetFontAdvanceW :: Font -> Ptr Word32 -> IO CFloat -- | Get the horizontal span of a string of text using the current font. Input as the xcoord -- | in any translate operation getFontAdvance :: Font -> String -> IO Float getFontAdvance font str = allocaArray (length str + 1) $ \p -> do pokeArray0 0 p (map (fromIntegral . ord) str) realToFrac <$> fgetFontAdvanceW font p foreign import ccall unsafe "ftglRenderFontW" frenderFontW :: Font -> Ptr Word32 -> CInt -> IO () -- | Render a string of text in the current font. renderFont :: Font -> String -> RenderMode -> IO () renderFont font str mode = allocaArray (length str + 1) $ \p -> do pokeArray0 0 p (map (fromIntegral . ord) str) frenderFontW font p (marshalRenderMode mode) foreign import ccall unsafe "ftglGetFontError" fgetFontError :: Font -> IO CInt -- | Get any errors associated with loading a font. FIXME return should be a type, not an Int. getFontError :: Font -> IO Int getFontError f = fromIntegral <$> fgetFontError f foreign import ccall unsafe "ftglDestroyLayout" destroyLayout :: Layout -> IO () foreign import ccall unsafe "ftglRenderLayout" frenderLayout :: Layout -> CString -> IO () -- | Render a string of text within a layout. renderLayout layout str = withCString str $ \strPtr -> do frenderLayout layout strPtr foreign import ccall unsafe "ftglGetLayoutError" fgetLayoutError :: Layout -> IO CInt -- | Get any errors associated with a layout. getLayoutError f = fgetLayoutError f -- | Whether or not in polygonal or extrusion mode, the font will render equally front and back data RenderMode = Front | Back | Side | All -- | In a Layout directed render, the layout mode of the text data TextAlignment = AlignLeft | AlignCenter | AlignRight | Justify marshalRenderMode :: RenderMode -> CInt marshalRenderMode Front = 0x0001 marshalRenderMode Back = 0x0002 marshalRenderMode Side = 0x004 marshalRenderMode All = 0xffff marshalTextAlignment :: TextAlignment -> CInt marshalTextAlignment AlignLeft = 0 marshalTextAlignment AlignCenter = 1 marshalTextAlignment AlignRight = 2 marshalTextAlignment Justify = 3 readTextAlignment :: CInt -> TextAlignment readTextAlignment 0 = AlignLeft readTextAlignment 1 = AlignCenter readTextAlignment 2 = AlignRight readTextAlignment 3 = Justify -- | An opaque type encapsulating a glyph in C. Currently the glyph functions are unimplemented in Haskell. data Glyph_Opaque -- | An opaque type encapsulating a font in C. data Font_Opaque -- | An opaque type encapsulating a layout in C data Layout_Opaque type Glyph = Ptr Glyph_Opaque type Font = Ptr Font_Opaque type Layout = Ptr Layout_Opaque data CharMap = EncodingNone | EncodingMSSymbol | EncodingUnicode | EncodingSJIS | EncodingGB2312 | EncodingBig5 | EncodingWanSung | EncodingJohab | EncodingAdobeStandard | EncodingAdobeExpert | EncodingAdobeCustom | EncodingAdobeLatin1 | EncodingOldLatin2 | EncodingAppleRoman encodeTag :: Char -> Char -> Char -> Char -> CInt encodeTag a b c d = (fromIntegral (ord a) `shift` 24) .|. (fromIntegral (ord b) `shift` 16) .|. (fromIntegral (ord c) `shift` 8) .|. (fromIntegral (ord d)) marshalCharMap EncodingNone = 0 marshalCharMap EncodingMSSymbol = encodeTag 's' 'y' 'm' 'b' marshalCharMap EncodingUnicode =encodeTag 'u' 'n' 'i' 'c' marshalCharMap EncodingSJIS = encodeTag 's' 'j' 'i' 's' marshalCharMap EncodingGB2312 = encodeTag 'g' 'b' ' ' ' ' marshalCharMap EncodingBig5= encodeTag 'b' 'i' 'g' '5' marshalCharMap EncodingWanSung= encodeTag 'w' 'a' 'n' 's' marshalCharMap EncodingJohab= encodeTag 'j' 'o' 'h' 'a' marshalCharMap EncodingAdobeStandard= encodeTag 'A' 'D' 'O' 'B' marshalCharMap EncodingAdobeExpert= encodeTag 'A' 'D' 'B' 'E' marshalCharMap EncodingAdobeCustom= encodeTag 'A' 'D' 'B' 'C' marshalCharMap EncodingAdobeLatin1= encodeTag 'l' 'a' 't' '1' marshalCharMap EncodingOldLatin2= encodeTag 'l' 'a' 't' '2' marshalCharMap EncodingAppleRoman= encodeTag 'a' 'r' 'm' 'n'
ghc-ios/FTGLES
Graphics/Rendering/FTGL.hs
Haskell
bsd-2-clause
13,564
{-# LANGUAGE OverloadedStrings #-} module Scoutess.Service.Source.Dir (fetchDir, fetchVersionsDir) where import Control.Monad.Trans (MonadIO, liftIO) import Data.Monoid ((<>)) import Data.Set (singleton) import Data.Text (pack) import Data.Version (showVersion) import Distribution.PackageDescription.Parse (readPackageDescription) import Distribution.Simple.Utils (installDirectoryContents) import Distribution.Verbosity (silent) import System.FilePath ((</>)) import Scoutess.Core import Scoutess.Types fetchDir :: MonadIO m => SourceConfig -> VersionInfo -> m (Either SourceException SourceInfo) fetchDir sourceConfig versionInfo = do let Dir oldPath = viSourceLocation versionInfo nameVersion = viName versionInfo <> "-" <> showVersion (viVersion versionInfo) newPath = srcCacheDir sourceConfig </> nameVersion liftIO $ installDirectoryContents silent oldPath newPath return . Right $ SourceInfo newPath versionInfo fetchVersionsDir :: MonadIO m => SourceLocation -> m (Either SourceException VersionSpec) fetchVersionsDir sourceLocation = do let Dir filePath = sourceLocation mCabalFile <- liftIO $ findCabalFile filePath case mCabalFile of Nothing -> do return . Left . SourceErrorOther $ "Could not find .cabal file in " <> pack filePath Just cabalFile -> do gpd <- liftIO $ readPackageDescription silent cabalFile let versionInfo = createVersionInfo sourceLocation cabalFile gpd return . Right $ VersionSpec (singleton versionInfo) Nothing
cartazio/scoutess
Scoutess/Service/Source/Dir.hs
Haskell
bsd-3-clause
1,631
{-#LANGUAGE ScopedTypeVariables, QuasiQuotes, OverloadedStrings #-} module Web.Horse.Forms.Basic where import Control.Arrow import Data.Monoid textField :: String -> Maybe String -> String -> String -> String textField label err val name = mconcat $ [ maybe "" (\x -> mconcat ["<span class=\"error\">", x, "</span><br/>"]) err, "<label>", label, "<br/><input type=\"text\" value=\"", val, "\" name=\"", name, "\"><br/></label>" ] link :: String -> String -> String link linkName name = mconcat ["<a href=\"?", name, "=1\">", linkName, "</a><br/>"] select :: String -> [String] -> Int -> String -> String select label options val name = mconcat [ "<label>", label, "<br/>", "<select name=\"", name, "\">", opts, "</select>", "<br/>", "</label>" ] where opts = mconcat $ map renderOpt (zip [0..] options) renderOpt (n, opt) = mconcat $ [ "<option ", if n == val then "selected=\"selected\"" else "", " value=\"", show n, "\">", opt, "</option>" ] wrapForm :: String -> String wrapForm f = mconcat ["<form method='POST' action=''>", f, "<input type='submit'></input></form>"]
jhp/on-a-horse
Web/Horse/Forms/Basic.hs
Haskell
bsd-3-clause
1,334
import Control.Concurrent import Control.Concurrent.STM.TChan import Control.Monad import Control.Monad.STM import Quant.MatchingEngine.BasicTypes import Quant.MatchingEngine.Book import Quant.MatchingEngine.Feed import Quant.MatchingEngine.Protocol import System.Directory import System.Environment import System.Exit import System.FilePath import System.IO import Quant.MatchingEngine.Tests main :: IO () main = getArgs >>= parseArgs where parseArgs :: [String] -> IO () parseArgs [rootdir, port] = mif (doesDirectoryExist rootdir) (startServer rootdir port) (putStrLn ("Directory "++ rootdir ++ " not found")) parseArgs [arg] | arg == "test" = runTests parseArgs _ = usage >> exitWith (ExitFailure 2) mif :: Monad m => m Bool -> m () -> m () -> m () mif test actionTrue actionFalse = test >>= \t -> if t then actionTrue else actionFalse usage :: IO () usage = putStrLn "exec <root directory> <port>" type FeedChannel = TChan FeedMessage type TradeChannel = TChan TradeMessage type TradeResponseChannel = TChan TradeResponseMessage startServer :: FilePath -> String -> IO () startServer rootDir port = do marketFeed <- newTChanIO tradingInterface <- newTChanIO tradingResponses <- newTChanIO _ <- forkIO $ algo (ClientID 1) marketFeed tradingInterface tradingResponses exchange emptyBook marketFeed tradingInterface tradingResponses print "yada" -- read config file to get list of securities to create books for -- configuration also specifices number and type of algos to create -- and has algo-specific config (root directory for each algo instance) -- create control channel and control module (sends market open, auction, close, timer events) -- create books -- create client trade interface channels -- create client feed interface channels -- create clients and connect channels -- algo :: ClientID -> FeedChannel -> TradeChannel -> TradeResponseChannel -> IO () algo clientID feed tradeChannel tradeResponses = do atomically $ writeTChan tradeChannel (NewOrder clientID Buy (Price 100) (ShareCount 50) (ClientOrderID 1)) tradeResponseMessage <- atomically $ readTChan tradeResponses print ("received trade response " ++ show tradeResponseMessage) algo clientID feed tradeChannel tradeResponses exchange :: Book -> FeedChannel -> TradeChannel -> TradeResponseChannel -> IO () exchange book feedChannel tradeChannel tradeResponseChannel = do tradeMessage <- atomically $ readTChan tradeChannel let tradeResponseMessage = validateAndAckTradeMessage book tradeMessage atomically $ writeTChan tradeResponseChannel tradeResponseMessage let (newBook, feedMessages, tradeResponseMessages) = processTradeMessage book tradeMessage print ("new book:" ++ show newBook) let r1 = map (writeTChan feedChannel) feedMessages let r2 = map (writeTChan tradeResponseChannel) tradeResponseMessages exchange newBook feedChannel tradeChannel tradeResponseChannel validateAndAckTradeMessage :: Book -> TradeMessage -> TradeResponseMessage validateAndAckTradeMessage book (NewOrder clientID _ _ _ clientOrderID) = NewOrderAck clientID clientOrderID orderID where orderID = OrderID 1101 validateAndAckTradeMessage book (CancelOrder clientID orderID) = if okToCancel then CancelOrderAck clientID orderID else CancelOrderNack clientID orderID where okToCancel = orderExists book clientID orderID processTradeMessage :: Book -> TradeMessage -> (Book, [FeedMessage], [TradeResponseMessage]) processTradeMessage book (NewOrder clientID Buy price shareCount clientOrderID) = (newBook, feedMessages, tradeResponseMessages) where (newBook, trades) = processBuy book (OrderBuy price time shareCount clientID orderID) feedMessages = map (\(Trade tprice tshareCount _ _ _ _) -> FeedMessageTrade tshareCount tprice) trades tradeResponseMessages = map genFill1 trades ++ map genFill2 trades time = Time 0 orderID = OrderID 400 genFill1 :: Trade -> TradeResponseMessage genFill1 (Trade price shareCount orderID clientID _ _) = OrderFill clientID orderID price shareCount genFill2 :: Trade -> TradeResponseMessage genFill2 (Trade price shareCount _ _ orderID clientID) = OrderFill clientID orderID price shareCount
tdoris/StockExchange
Main.hs
Haskell
bsd-3-clause
4,420
----------------------------------------------------------------------------- -- -- Module : Language.Haskell.Parser.ParsePostProcess -- Copyright : -- License : AllRightsReserved -- -- Maintainer : -- Stability : -- Portability : -- -- Description: Post processing for the Haskell Parser suite. -- -- The HsParser places each HsMatch equation in -- a seperate HsFunbind, even when multiple -- HsMatchs should appear in the same HsFunbind. -- -- This code is intended as a post-processor of the -- output from the parser, that re-groups -- associated HsMatch equations into the same -- HsFunBind. It has no semantic effect on the code. -- -- It requires a single pass over the entire parse -- tree, some applications might find this expensive. -- -- Associated matches are determined by the string -- name of the variable that is being bound, in -- _unqualified_ form. This means that: -- -- Foo.f w x = ... -- f y z = ... -- -- are treated as matches for the same variable, -- even though I don't think this is possible in -- Haskell 98, the parser does allow it, and thus so -- does this code. -- -- There is plenty of room for static analysis of the -- parsed code, but that is not the intention of this -- module. -- -- In time, other post-processing tasks may be -- placed in this module. -- ----------------------------------------------------------------------------- module Haskell.Parser.ParsePostProcess (fixFunBindsInModule, fixFunBinds) where import Haskell.Syntax.Syntax -- applies fixFunBinds to all decls in a Module fixFunBindsInModule :: HsModule -> HsModule fixFunBindsInModule (HsModule loc modName exports imports decls) = HsModule loc modName exports imports $ fixFunBinds decls -- collect associated funbind equations (matches) into a single funbind -- intended as a post-processer for the parser output fixFunBinds :: [HsDecl] -> [HsDecl] fixFunBinds [] = [] fixFunBinds (d:ds) = case d of HsClassDecl sloc ctx n tvs decls -> HsClassDecl sloc ctx n tvs (fixFunBinds decls) : fixFunBinds ds HsInstDecl sloc ctx qn tys decls -> HsInstDecl sloc ctx qn tys (fixFunBinds decls) : fixFunBinds ds HsFunBind matches@(_:_) -> let funName = matchName $ head matches (same, different) = span (sameFun funName) (d:ds) newMatches = map fixFunBindsInMatch $ collectMatches same in (HsFunBind newMatches) : fixFunBinds different HsPatBind sloc pat rhs decls -> HsPatBind sloc pat (fixFunBindsInRhs rhs) (fixFunBinds decls) : fixFunBinds ds _anythingElse -> d : fixFunBinds ds -- get the variable name bound by a match matchName :: HsMatch -> String matchName (HsMatch _sloc name _pats _rhs _whereDecls) = unHsName name -- selects the string identifier from a (possibly) -- qualified name (ie drops the module name when possible) unQualName :: HsQName -> String unQualName name = case name of (Qual _mod ident) -> unHsName ident (UnQual ident) -> unHsName ident (Special s) -> specialName s unHsName (HsIdent s) = s unHsName (HsSymbol s) = s specialName HsUnitCon = "()" specialName HsListCon = "[]" specialName HsFunCon = "->" specialName (HsTupleCon n) = "(" ++ (replicate (n - 1) ',') ++ ")" specialName HsCons = ":" -- True if the decl is a HsFunBind and binds the same name as the -- first argument, False otherwise sameFun :: String -> HsDecl -> Bool sameFun name (HsFunBind matches@(_:_)) | name == (matchName $ head matches) = True | otherwise = False sameFun _name _decl = False -- collects all the HsMatch equations from any FunBinds -- from a list of HsDecls collectMatches :: [HsDecl] -> [HsMatch] collectMatches [] = [] collectMatches (d:ds) = case d of (HsFunBind matches) -> matches ++ collectMatches ds _anythingElse -> collectMatches ds -- the rest of the code just crawls tediously over the syntax tree -- recursively fixing up any decls where they occur fixFunBindsInMatch :: HsMatch -> HsMatch fixFunBindsInMatch (HsMatch sloc name pats rhs wheres) = HsMatch sloc name pats (fixFunBindsInRhs rhs) $ fixFunBinds wheres fixFunBindsInRhs :: HsRhs -> HsRhs fixFunBindsInRhs (HsUnGuardedRhs e) = HsUnGuardedRhs $ fixFunBindsInExp e fixFunBindsInRhs (HsGuardedRhss rhss) = HsGuardedRhss $ map fixFunBindsInGuardedRhs rhss fixFunBindsInGuardedRhs :: HsGuardedRhs -> HsGuardedRhs fixFunBindsInGuardedRhs (HsGuardedRhs sloc e1 e2) = HsGuardedRhs sloc (fixFunBindsInExp e1) (fixFunBindsInExp e2) fixFunBindsInExp :: HsExp -> HsExp fixFunBindsInExp e@(HsVar _) = e fixFunBindsInExp e@(HsCon _) = e fixFunBindsInExp e@(HsLit _) = e fixFunBindsInExp (HsInfixApp e1 e2 e3) = HsInfixApp (fixFunBindsInExp e1) e2 (fixFunBindsInExp e3) fixFunBindsInExp (HsApp e1 e2) = HsApp (fixFunBindsInExp e1) (fixFunBindsInExp e2) fixFunBindsInExp (HsNegApp e) = HsNegApp $ fixFunBindsInExp e fixFunBindsInExp (HsLambda sloc pats e) = HsLambda sloc pats $ fixFunBindsInExp e fixFunBindsInExp (HsLet decls e) = HsLet (fixFunBinds decls) $ fixFunBindsInExp e fixFunBindsInExp (HsIf e1 e2 e3) = HsIf (fixFunBindsInExp e1) (fixFunBindsInExp e2) (fixFunBindsInExp e3) fixFunBindsInExp (HsCase e alts) = HsCase (fixFunBindsInExp e) $ map fixFunBindsInAlt alts fixFunBindsInExp (HsDo stmts) = HsDo $ map fixFunBindsInStmt stmts fixFunBindsInExp (HsTuple exps) = HsTuple $ map fixFunBindsInExp exps fixFunBindsInExp (HsList exps) = HsList $ map fixFunBindsInExp exps fixFunBindsInExp (HsParen e) = HsParen $ fixFunBindsInExp e fixFunBindsInExp (HsLeftSection e1 e2) = HsLeftSection (fixFunBindsInExp e1) e2 fixFunBindsInExp (HsRightSection e1 e2) = HsRightSection e1 (fixFunBindsInExp e2) fixFunBindsInExp e@(HsRecConstr qname fieldUpdates) = e fixFunBindsInExp (HsRecUpdate e fieldUpdates) = HsRecUpdate (fixFunBindsInExp e) fieldUpdates fixFunBindsInExp (HsEnumFrom e) = HsEnumFrom $ fixFunBindsInExp e fixFunBindsInExp (HsEnumFromTo e1 e2) = HsEnumFromTo (fixFunBindsInExp e1) (fixFunBindsInExp e2) fixFunBindsInExp (HsEnumFromThen e1 e2) = HsEnumFromThen (fixFunBindsInExp e1) (fixFunBindsInExp e2) fixFunBindsInExp (HsEnumFromThenTo e1 e2 e3) = HsEnumFromThenTo (fixFunBindsInExp e1) (fixFunBindsInExp e2) (fixFunBindsInExp e3) fixFunBindsInExp (HsListComp e stmts) = HsListComp (fixFunBindsInExp e) $ map fixFunBindsInStmt stmts fixFunBindsInExp (HsExpTypeSig sloc e qtype) = HsExpTypeSig sloc (fixFunBindsInExp e) qtype fixFunBindsInExp (HsAsPat name e) = HsAsPat name $ fixFunBindsInExp e fixFunBindsInExp e@HsWildCard = e fixFunBindsInExp (HsIrrPat e) = HsIrrPat $ fixFunBindsInExp e fixFunBindsInAlt :: HsAlt -> HsAlt fixFunBindsInAlt (HsAlt sloc pat (HsUnGuardedAlt e) decls) = HsAlt sloc pat (HsUnGuardedAlt (fixFunBindsInExp e)) $ fixFunBinds decls fixFunBindsInAlt (HsAlt sloc pat (HsGuardedAlts alts) decls) = HsAlt sloc pat (HsGuardedAlts $ map fixFunBindsInGuardedAlt alts) $ fixFunBinds decls fixFunBindsInGuardedAlt :: HsGuardedAlt -> HsGuardedAlt fixFunBindsInGuardedAlt (HsGuardedAlt sloc e1 e2) = HsGuardedAlt sloc (fixFunBindsInExp e1) (fixFunBindsInExp e2) fixFunBindsInStmt :: HsStmt -> HsStmt fixFunBindsInStmt (HsGenerator sloc pat e) = HsGenerator sloc pat $ fixFunBindsInExp e fixFunBindsInStmt (HsQualifier e) = HsQualifier $ fixFunBindsInExp e fixFunBindsInStmt (HsLetStmt decls) = HsLetStmt $ fixFunBinds decls --------------------------------------------------------------------------------
emcardoso/CTi
src/Haskell/Parser/ParsePostProcess.hs
Haskell
bsd-3-clause
8,149
{-# LANGUAGE BangPatterns, CPP, OverloadedStrings #-} -- | -- Module: Data.Aeson.Parser.Internal -- Copyright: (c) 2011, 2012 Bryan O'Sullivan -- (c) 2011 MailRank, Inc. -- License: Apache -- Maintainer: Bryan O'Sullivan <bos@serpentine.com> -- Stability: experimental -- Portability: portable -- -- Efficiently and correctly parse a JSON string. The string must be -- encoded as UTF-8. module Data.Aeson.Parser.Internal ( -- * Lazy parsers json, jsonEOF , value , jstring -- * Strict parsers , json', jsonEOF' , value' -- * Helpers , decodeWith , decodeStrictWith , eitherDecodeWith , eitherDecodeStrictWith ) where import Control.Applicative ((*>), (<$>), (<*), liftA2, pure) import Control.Monad.IO.Class (liftIO) import Data.Aeson.Types (Result(..), Value(..)) import Data.Attoparsec.ByteString.Char8 (Parser, char, endOfInput, scientific, skipSpace, string) import Data.Bits ((.|.), shiftL) import Data.ByteString.Internal (ByteString(..)) import Data.Char (chr) import Data.Text (Text) import Data.Text.Encoding (decodeUtf8') import Data.Text.Internal.Encoding.Utf8 (ord2, ord3, ord4) import Data.Text.Internal.Unsafe.Char (ord) import Data.Vector as Vector (Vector, fromList) import Data.Word (Word8) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Ptr (minusPtr) import Foreign.Ptr (Ptr, plusPtr) import Foreign.Storable (poke) import System.IO.Unsafe (unsafePerformIO) import qualified Data.Attoparsec.ByteString as A import qualified Data.Attoparsec.Lazy as L import qualified Data.Attoparsec.Zepto as Z import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Internal as B import qualified Data.ByteString.Unsafe as B import qualified Data.HashMap.Strict as H #define BACKSLASH 92 #define CLOSE_CURLY 125 #define CLOSE_SQUARE 93 #define COMMA 44 #define DOUBLE_QUOTE 34 #define OPEN_CURLY 123 #define OPEN_SQUARE 91 #define C_0 48 #define C_9 57 #define C_A 65 #define C_F 70 #define C_a 97 #define C_f 102 #define C_n 110 #define C_t 116 -- | Parse a top-level JSON value. -- -- The conversion of a parsed value to a Haskell value is deferred -- until the Haskell value is needed. This may improve performance if -- only a subset of the results of conversions are needed, but at a -- cost in thunk allocation. -- -- This function is an alias for 'value'. In aeson 0.8 and earlier, it -- parsed only object or array types, in conformance with the -- now-obsolete RFC 4627. json :: Parser Value json = value -- | Parse a top-level JSON value. -- -- This is a strict version of 'json' which avoids building up thunks -- during parsing; it performs all conversions immediately. Prefer -- this version if most of the JSON data needs to be accessed. -- -- This function is an alias for 'value''. In aeson 0.8 and earlier, it -- parsed only object or array types, in conformance with the -- now-obsolete RFC 4627. json' :: Parser Value json' = value' object_ :: Parser Value object_ = {-# SCC "object_" #-} Object <$> objectValues jstring value object_' :: Parser Value object_' = {-# SCC "object_'" #-} do !vals <- objectValues jstring' value' return (Object vals) where jstring' = do !s <- jstring return s objectValues :: Parser Text -> Parser Value -> Parser (H.HashMap Text Value) objectValues str val = do skipSpace let pair = liftA2 (,) (str <* skipSpace) (char ':' *> val) H.fromList <$> commaSeparated pair CLOSE_CURLY {-# INLINE objectValues #-} array_ :: Parser Value array_ = {-# SCC "array_" #-} Array <$> arrayValues value array_' :: Parser Value array_' = {-# SCC "array_'" #-} do !vals <- arrayValues value' return (Array vals) commaSeparated :: Parser a -> Word8 -> Parser [a] commaSeparated item endByte = do w <- A.peekWord8' if w == endByte then A.anyWord8 >> return [] else loop where loop = do v <- item <* skipSpace ch <- A.satisfy $ \w -> w == COMMA || w == endByte if ch == COMMA then skipSpace >> (v:) <$> loop else return [v] {-# INLINE commaSeparated #-} arrayValues :: Parser Value -> Parser (Vector Value) arrayValues val = do skipSpace Vector.fromList <$> commaSeparated val CLOSE_SQUARE {-# INLINE arrayValues #-} -- | Parse any JSON value. You should usually 'json' in preference to -- this function, as this function relaxes the object-or-array -- requirement of RFC 4627. -- -- In particular, be careful in using this function if you think your -- code might interoperate with Javascript. A na&#xef;ve Javascript -- library that parses JSON data using @eval@ is vulnerable to attack -- unless the encoded data represents an object or an array. JSON -- implementations in other languages conform to that same restriction -- to preserve interoperability and security. value :: Parser Value value = do skipSpace w <- A.peekWord8' case w of DOUBLE_QUOTE -> A.anyWord8 *> (String <$> jstring_) OPEN_CURLY -> A.anyWord8 *> object_ OPEN_SQUARE -> A.anyWord8 *> array_ C_f -> string "false" *> pure (Bool False) C_t -> string "true" *> pure (Bool True) C_n -> string "null" *> pure Null _ | w >= 48 && w <= 57 || w == 45 -> Number <$> scientific | otherwise -> fail "not a valid json value" -- | Strict version of 'value'. See also 'json''. value' :: Parser Value value' = do skipSpace w <- A.peekWord8' case w of DOUBLE_QUOTE -> do !s <- A.anyWord8 *> jstring_ return (String s) OPEN_CURLY -> A.anyWord8 *> object_' OPEN_SQUARE -> A.anyWord8 *> array_' C_f -> string "false" *> pure (Bool False) C_t -> string "true" *> pure (Bool True) C_n -> string "null" *> pure Null _ | w >= 48 && w <= 57 || w == 45 -> do !n <- scientific return (Number n) | otherwise -> fail "not a valid json value" -- | Parse a quoted JSON string. jstring :: Parser Text jstring = A.word8 DOUBLE_QUOTE *> jstring_ -- | Parse a string without a leading quote. jstring_ :: Parser Text jstring_ = {-# SCC "jstring_" #-} do s <- A.scan False $ \s c -> if s then Just False else if c == DOUBLE_QUOTE then Nothing else Just (c == BACKSLASH) _ <- A.word8 DOUBLE_QUOTE s1 <- if BACKSLASH `B.elem` s then case unescape s of Right r -> return r Left err -> fail err else return s case decodeUtf8' s1 of Right r -> return r Left err -> fail $ show err {-# INLINE jstring_ #-} unescape :: ByteString -> Either String ByteString unescape s = unsafePerformIO $ do let len = B.length s fp <- B.mallocByteString len -- We perform no bounds checking when writing to the destination -- string, as unescaping always makes it shorter than the source. withForeignPtr fp $ \ptr -> do ret <- Z.parseT (go ptr) s case ret of Left err -> return (Left err) Right p -> do let newlen = p `minusPtr` ptr slop = len - newlen Right <$> if slop >= 128 && slop >= len `quot` 4 then B.create newlen $ \np -> B.memcpy np ptr newlen else return (PS fp 0 newlen) where go ptr = do h <- Z.takeWhile (/=BACKSLASH) let rest = do start <- Z.take 2 let !slash = B.unsafeHead start !t = B.unsafeIndex start 1 escape = case B.elemIndex t "\"\\/ntbrfu" of Just i -> i _ -> 255 if slash /= BACKSLASH || escape == 255 then fail "invalid JSON escape sequence" else if t /= 117 -- 'u' then copy h ptr >>= word8 (B.unsafeIndex mapping escape) >>= go else do a <- hexQuad if a < 0xd800 || a > 0xdfff then copy h ptr >>= charUtf8 (chr a) >>= go else do b <- Z.string "\\u" *> hexQuad if a <= 0xdbff && b >= 0xdc00 && b <= 0xdfff then let !c = ((a - 0xd800) `shiftL` 10) + (b - 0xdc00) + 0x10000 in copy h ptr >>= charUtf8 (chr c) >>= go else fail "invalid UTF-16 surrogates" done <- Z.atEnd if done then copy h ptr else rest mapping = "\"\\/\n\t\b\r\f" hexQuad :: Z.ZeptoT IO Int hexQuad = do s <- Z.take 4 let hex n | w >= C_0 && w <= C_9 = w - C_0 | w >= C_a && w <= C_f = w - 87 | w >= C_A && w <= C_F = w - 55 | otherwise = 255 where w = fromIntegral $ B.unsafeIndex s n a = hex 0; b = hex 1; c = hex 2; d = hex 3 if (a .|. b .|. c .|. d) /= 255 then return $! d .|. (c `shiftL` 4) .|. (b `shiftL` 8) .|. (a `shiftL` 12) else fail "invalid hex escape" decodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Maybe a decodeWith p to s = case L.parse p s of L.Done _ v -> case to v of Success a -> Just a _ -> Nothing _ -> Nothing {-# INLINE decodeWith #-} decodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString -> Maybe a decodeStrictWith p to s = case either Error to (A.parseOnly p s) of Success a -> Just a Error _ -> Nothing {-# INLINE decodeStrictWith #-} eitherDecodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Either String a eitherDecodeWith p to s = case L.parse p s of L.Done _ v -> case to v of Success a -> Right a Error msg -> Left msg L.Fail _ _ msg -> Left msg {-# INLINE eitherDecodeWith #-} eitherDecodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString -> Either String a eitherDecodeStrictWith p to s = case either Error to (A.parseOnly p s) of Success a -> Right a Error msg -> Left msg {-# INLINE eitherDecodeStrictWith #-} -- $lazy -- -- The 'json' and 'value' parsers decouple identification from -- conversion. Identification occurs immediately (so that an invalid -- JSON document can be rejected as early as possible), but conversion -- to a Haskell value is deferred until that value is needed. -- -- This decoupling can be time-efficient if only a smallish subset of -- elements in a JSON value need to be inspected, since the cost of -- conversion is zero for uninspected elements. The trade off is an -- increase in memory usage, due to allocation of thunks for values -- that have not yet been converted. -- $strict -- -- The 'json'' and 'value'' parsers combine identification with -- conversion. They consume more CPU cycles up front, but have a -- smaller memory footprint. -- | Parse a top-level JSON value followed by optional whitespace and -- end-of-input. See also: 'json'. jsonEOF :: Parser Value jsonEOF = json <* skipSpace <* endOfInput -- | Parse a top-level JSON value followed by optional whitespace and -- end-of-input. See also: 'json''. jsonEOF' :: Parser Value jsonEOF' = json' <* skipSpace <* endOfInput word8 :: Word8 -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) word8 w ptr = do liftIO $ poke ptr w return $! ptr `plusPtr` 1 copy :: ByteString -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) copy (PS fp off len) ptr = liftIO . withForeignPtr fp $ \src -> do B.memcpy ptr (src `plusPtr` off) len return $! ptr `plusPtr` len charUtf8 :: Char -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) charUtf8 ch ptr | ch < '\x80' = liftIO $ do poke ptr (fromIntegral (ord ch)) return $! ptr `plusPtr` 1 | ch < '\x800' = liftIO $ do let (a,b) = ord2 ch poke ptr a poke (ptr `plusPtr` 1) b return $! ptr `plusPtr` 2 | ch < '\xffff' = liftIO $ do let (a,b,c) = ord3 ch poke ptr a poke (ptr `plusPtr` 1) b poke (ptr `plusPtr` 2) c return $! ptr `plusPtr` 3 | otherwise = liftIO $ do let (a,b,c,d) = ord4 ch poke ptr a poke (ptr `plusPtr` 1) b poke (ptr `plusPtr` 2) c poke (ptr `plusPtr` 3) d return $! ptr `plusPtr` 4
beni55/aeson
Data/Aeson/Parser/Internal.hs
Haskell
bsd-3-clause
12,821
module Language.SOS.Data.Rule where newtype Rule = Rule Name [Premiss] Conclusion [CompileTimeCondition] [RuntimeCondidtion] deriving (Eq, Ord, Show) type Name = String type Premiss = Transformation type Conclusion = Transformation newtype CompileTimeCondition = CTC newtype RuntimeCondition = RTC
JanBessai/hsos
src/Language/SOS/Data/Rule.hs
Haskell
bsd-3-clause
309
module Math.Probably.Student where import Numeric.LinearAlgebra import Math.Probably.FoldingStats import Text.Printf --http://www.haskell.org/haskellwiki/Gamma_and_Beta_function --cof :: [Double] cof = [76.18009172947146,-86.50532032941677,24.01409824083091, -1.231739572450155,0.001208650973866179,-0.000005395239384953] --ser :: Double ser = 1.000000000190015 --gammaln :: Double -> Double gammaln xx = let tmp' = (xx+5.5) - (xx+0.5)*log(xx+5.5) ser' = foldl (+) ser $ map (\(y,c) -> c/(xx+y)) $ zip [1..] cof in -tmp' + log(2.5066282746310005 * ser' / xx) beta z w = exp (gammaln z + gammaln w - gammaln (z+w)) fac :: (Enum a, Num a) => a -> a fac n = product [1..n] ixbeta :: (Enum a, Floating a) => a -> a -> a -> a ixbeta x a b = let top = fac $ a+b-1 down j = fac j * fac (a+b-1-j) in sum $ map (\j->(top/down j)*(x**j)*(1-x)**(a+b-1-j)) [a..a+b-1] studentIntegral :: (Enum a, Floating a) => a -> a -> a studentIntegral t v = 1-ixbeta (v/(v+t*t)) (v/2) (1/2) tTerms :: Vector Double tTerms = fromList $ map tTermUnmemo [1..100] tTermUnmemo :: Int -> Double tTermUnmemo nu = gammaln ((realToFrac nu+1)/2) - log(realToFrac nu*pi)/2 - gammaln (realToFrac nu/2) tTerm1 :: Int -> Double tTerm1 df | df <= 100 = tTerms@>df | otherwise = tTermUnmemo df tDist :: Int -> Double -> Double tDist df t = tTerm1 df - (realToFrac df +1/2) * log (1+(t*t)/(realToFrac df)) tDist3 :: Double -> Double -> Int -> Double -> Double tDist3 mean prec df x = tTerm1 df + log(prec)/2 - (realToFrac df +1/2) * log (1+(prec*xMinusMu*xMinusMu)/(realToFrac df)) where xMinusMu = x-mean oneSampleT :: Floating b => b -> Fold b b oneSampleT v0 = fmap (\(mean,sd,n)-> (mean - v0)/(sd/(sqrt n))) meanSDNF pairedSampleT :: Fold (Double, Double) Double pairedSampleT = before (fmap (\(mean,sd,n)-> (mean)/(sd/(sqrt n))) meanSDNF) (uncurry (-)) data TTestResult = TTestResult { degFreedom :: Int, tValue :: Double, pValue :: Double } ppTTestRes :: TTestResult -> String ppTTestRes (TTestResult df tval pval) = printf "paired t(%d)=%.3g, p=%.3g" df tval pval pairedTTest :: [(Double,Double)] -> TTestResult pairedTTest vls = let tval = runStat pairedSampleT vls df = length vls - 1 pval = (1-) $ studentIntegral (tval) (realToFrac df) in TTestResult df tval pval oneSampleTTest :: [Double] -> TTestResult oneSampleTTest vls = let tval = runStat (oneSampleT 0) vls df = length vls - 1 pval = (1-) $ studentIntegral (tval) (realToFrac df) in TTestResult df tval pval
glutamate/probably-baysig
src/Math/Probably/Student.hs
Haskell
bsd-3-clause
2,739
{-# LANGUAGE TemplateHaskell #-} module Gifter.Giveaway.Internal where import Control.Lens import qualified Data.Text as T type Points = Integer data GiveawayStatus = Open Points | Closed | ContributorsOnly | AlreadyOwn | NoLogin | Entered | MissingBaseGame | ComingSoon | NotEnoughPoints deriving (Show, Eq) data Giveaway = Giveaway { _url :: T.Text , _status :: GiveawayStatus , _entries :: Integer , _formKey :: Maybe T.Text , _accPoints :: Integer } deriving (Show, Eq) makeLenses ''Giveaway
arjantop/gifter
src/Gifter/Giveaway/Internal.hs
Haskell
bsd-3-clause
674
{- This file is part of the Haskell package cassava-streams. It is subject to the license terms in the LICENSE file found in the top-level directory of this distribution and at git://pmade.com/cassava-streams/LICENSE. No part of cassava-streams package, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the LICENSE file. -} -------------------------------------------------------------------------------- module Main (main) where -------------------------------------------------------------------------------- import System.Environment import System.IO import System.IO.Streams.Csv.Tutorial -------------------------------------------------------------------------------- main :: IO () main = do args <- getArgs case args of ["todo"] -> onlyTodo stdin stdout ["done", x] -> markDone x stdin stdout _ -> fail "give one of todo or done"
pjones/cassava-streams
bin/tutorial.hs
Haskell
bsd-3-clause
938
{- Lets.RoseTree A Rose Tree (or multi-way tree) is a tree structure with a variable and unbounded number of branches at each node. This implementation allows for an empty tree. References [1] Wikipedia, "Rose Tree", http://en.wikipedia.org/wiki/Rose_tree [2] Jeremy Gibbons, "Origami Programming", appears in The Fun of Programming edited by J. Gibbons and O. de Moor, Palgrave McMillan, 2003, pages 41-60. PDF available at: http://www.staff.science.uu.nl/~3860418/msc/11_infomtpt/papers/origami-programming_Gibbons.pdf -} module Lets.RoseTree ( RoseTree -- constructors , node , singleton -- properties , value , children , forest , size , depth -- operations , insert , toList , flatten ) where -- -- definitions -- data RoseTree a = Empty | Node a (Forest a) deriving (Show, Eq) type Forest a = [RoseTree a] -- -- constructors -- node :: a -> [RoseTree a] -> RoseTree a node v t = Node v t singleton :: a -> RoseTree a singleton v = Node v [] -- -- operations -- value :: RoseTree a -> Maybe a value (Empty) = Nothing value (Node v _) = Just v children :: RoseTree a -> [RoseTree a] children (Empty) = [] children (Node _ t) = t -- [] or [...] -- also called forest forest = children size :: RoseTree a -> Int size (Empty) = 0 size (Node v ts) = 1 + sum (map size ts) depth :: RoseTree a -> Int depth (Empty) = 0 depth (Node _ []) = 1 depth (Node v ts) = 1 + maximum (map depth ts) toList :: RoseTree a -> [a] toList Empty = [] toList (Node v t) = v : concatMap toList t -- also called flatten flatten = toList -- -- a simple insert operation that places tree q at the head of the children -- of tree r insert :: RoseTree a -> RoseTree a -> RoseTree a insert Empty r = r insert q Empty = q insert q r@(Node v t) = Node v (q:t) -- -- sample -- rt1 = singleton 1 rt2 = singleton 2 rt3 = node 3 [rt1, rt2] rt4 = node 8 [node 3 [], node 4 []] rt5 = node 12 [rt4, rt3]
peterson/lets-tree
src/Lets/RoseTree.hs
Haskell
bsd-3-clause
1,983