code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Main (main) where
import Rendering
import Interface
import ClientSide
import Control.Monad.Trans.Except
import Control.Concurrent (forkIO)
import Control.Concurrent.STM
import Graphics.Gloss.Interface.IO.Game
import qualified Network.WebSockets as WS
import System.Environment
background :: Color
background = makeColorI 25 25 112 0
fps :: Int
fps = 60
main :: IO ()
main = do
argv <- getArgs
let ip = head argv
let http_port = (read . head . tail) argv :: Int
WS.runClient ip http_port "/service/open_socket" $ \socket -> do
putStrLn "Connection successful"
c <- mkClientWithManager ip http_port
response <- runExceptT (new c)
new_game <- getServerResponse response
shared <- newTVarIO new_game
let new_state = (ClientState shared socket c)
_ <- forkIO (handleUpdates new_state)
playIO window background fps new_state renderPicIO handleKeys getUpdatedGameState
putStrLn "Finished"
where
|
cmc-haskell-2016/asteroids
|
client/Main.hs
|
bsd-3-clause
| 995 | 0 | 15 | 220 | 286 | 146 | 140 | 30 | 1 |
{-# LANGUAGE UndecidableInstances #-}
-- | Classifying spaces for discrete groups
-- Wbar : Grp -> 0-reduced sSet_*
-- Much easier than the case of general simplicial groups
-- See also https://dl.acm.org/doi/10.1145/1576702.1576744
module Math.Topology.SGrp.WbarDiscrete where
import Math.Algebra.Group
import qualified Math.Topology.SGrp as S
import Math.Topology.SSet
-- If a is a discrete group, things get much easier.
newtype WbarDiscrete a = WbarDiscrete a
normalise :: (Group a, Eq (Element a)) => a -> [Element a] -> Simplex (WbarDiscrete a)
normalise a [] = NonDegen []
normalise a (e : es)
| e == unit a = degen (normalise a es) 0
| otherwise = fmap (e :) (downshift (normalise a es))
unnormalise :: (Group a, Eq (Element a)) => a -> Simplex (WbarDiscrete a) -> [Element a]
unnormalise a (NonDegen g) = g
unnormalise a (Degen i g) =
let (before, after) = splitAt i (unnormalise a g)
in before ++ [unit a] ++ after
instance (Group a, Eq (Element a)) => SSet (WbarDiscrete a) where
-- A non-degenerate n-simplex is a list of n non-identity elements
-- of `a`
type GeomSimplex (WbarDiscrete a) = [Element a]
isGeomSimplex (WbarDiscrete a) ss = unit a `notElem` ss
geomSimplexDim _ ss = length ss
geomFace _ [] _ = undefined
geomFace (WbarDiscrete a) ss i = normalise a (underlying ss i)
where
underlying ss 0 = tail ss
underlying [s] 1 = []
underlying (s : s' : ss) 1 = prod a s s' : ss
underlying (s : ss) i = s : underlying ss (i - 1)
underlying _ _ = undefined -- can't happen
instance (Group a, Eq (Element a)) => Pointed (WbarDiscrete a) where
basepoint (WbarDiscrete a) = []
instance (Group a, Eq (Element a)) => ZeroReduced (WbarDiscrete a)
instance (FiniteGroup a, Eq (Element a)) => FiniteType (WbarDiscrete a) where
geomBasis (WbarDiscrete a) i = sequence (replicate i nonident)
where nonident = filter (\x -> x /= unit a) (elements a)
instance (Abelian a, Eq (Element a)) => S.SGrp (WbarDiscrete a) where
prodMor (WbarDiscrete a) = Morphism $ \(s, t) -> normalise a $ fmap (uncurry (prod a)) (zip (unnormalise a s) (unnormalise a t))
invMor (WbarDiscrete a) = Morphism $ \s -> NonDegen $ fmap (inv a) s
instance (Abelian a, Eq (Element a)) => S.SAb (WbarDiscrete a)
|
mvr/at
|
src/Math/Topology/SGrp/WbarDiscrete.hs
|
bsd-3-clause
| 2,267 | 0 | 13 | 462 | 928 | 478 | 450 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
module GraphBuilder (
shortDistMat,
shortestDists,
joinContext,
EContext(..),
EShortDists(..),
theContextsAndDists,
) where
import Control.DeepSeq (NFData (..))
import Control.Monad (ap, join, liftM2)
import Control.Monad.ST
import Control.Parallel.Strategies
import Data.Graph.Inductive hiding (ap)
import qualified Data.Graph.Inductive.PatriciaTree as GP
import Data.List (sortOn)
import qualified Data.Strict.Tuple as T hiding (uncurry)
import Foreign.C (CInt)
import GHC.Generics
import Numeric.LinearAlgebra
import Numeric.LinearAlgebra.Devel
data EContext =
EContext
{ vertex :: {-# UNPACK #-} !Int
, dstToCtr :: {-# UNPACK #-} !Double
, dists :: {-# UNPACK #-} !(Vector Double)
, ns :: {-# UNPACK #-} !(Vector Int)
}
deriving (Show, Generic)
instance NFData EContext
data EShortDists =
EShortDists
{ vertex' :: {-# UNPACK #-} !Int
, dists' :: {-# UNPACK #-} !(Vector Double)
}
deriving (Show, Generic)
instance NFData EShortDists
shortDistMat :: Int -> [EShortDists] -> Matrix Double
shortDistMat size' !sdists =
let mat = konst 0 (length', size') :: Matrix Double
length' = length sdists
in runST $ do
m <- unsafeThawMatrix mat
mapM_ (`setRow` m) $ zip sdists [0 ..]
unsafeFreezeMatrix m
where
setRow (e, pt) mat = setMatrix mat pt 0 . asRow . dists' $ e
joinContext :: EContext -> GP.Gr Double Double -> GP.Gr Double Double
joinContext (EContext pt dstCtr edists vs) graph =
let zipped = zip (toList edists) (toList vs)
in (zipped, pt, dstCtr, zipped) & graph
matD2 :: Matrix Double -> Matrix Double
matD2 = join pairwiseD2
theContextsAndDists :: (Int, Int) -- ^ Graph neighborhood size and PCA neighborhood size
-> Int
-> Matrix Double
-> ([EContext], Matrix Double, [Int])
theContextsAndDists (n1, n2) bpt mat =
(makeContexts . theNearest n1 $ mat', extract' . idxs $ idxs'', idxs''')
where
makeContexts = zipWith makeContext [0 :: Int ..] . map unzip
makeContext a (b, c) = EContext a (mat' `atIndex` (a, bpt)) (fromList b) (fromList c)
mat' = matD2 mat
idxs'' = map (toEnum . snd) idxs'
idxs' = (!! bpt) . theNearest n2 $ mat'
idxs''' = map snd idxs'
extract' a = mat ?? (Pos a, All)
theNearest :: Int -> Matrix Double -> [[(Double, Int)]]
theNearest n = filterKNearest . findNearestWithInd
where
findNearestWithInd = helper1 . helper2
filterKNearest = map (take n . filter ((/= 0.0) . fst) . uncurry zip)
helper1 in' = uncurry zip (map toList (T.fst in'), map (map fromEnum . toList) (T.snd in'))
helper2 = strUnzip . map (liftM2 (T.:!:) sortVector sortIndex) . toRows
shortestDists :: [Int] -> GP.Gr Double Double -> [EShortDists]
shortestDists inds g = parMap rseq (clean `ap` (sortIndDumpDist . makeList)) inds
where
clean x' a = EShortDists x' $ fromList a
sortIndDumpDist = map T.snd . sortOn T.fst
makeList = map (Prelude.uncurry (T.:!:)) . join . map (take 1 . unLPath) . flip spTree g
-- UTILITY FUNCTION(S) --
strUnzip :: [T.Pair (Vector Double) (Vector CInt)] -> T.Pair [Vector Double] [Vector CInt]
strUnzip = foldr (\((T.:!:) a b) acc -> ((T.:!:) (a : T.fst acc) (b : T.snd acc))) ((T.:!:) [] [])
-- -- For debugging!
-- remember to import Control.Arrow ((&&&)) when using this function.
-- checkSymRowsCols :: (Container Vector a, Eq a, S.Storable a)
-- => Matrix a
-- -> Bool
-- checkSymRowsCols = uncurry (==) . (map sumElements . toColumns &&& map sumElements . toRows)
|
emmanueldenloye/manifoldRNC
|
src/GraphBuilder.hs
|
bsd-3-clause
| 3,918 | 0 | 14 | 1,090 | 1,245 | 679 | 566 | 76 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ordinal.GA.Rules
( rules ) where
import qualified Data.Text as Text
import Prelude
import Data.String
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers (parseInt)
import Duckling.Ordinal.Helpers
import Duckling.Regex.Types
import Duckling.Types
ruleOrdinalsChadDaraEtc :: Rule
ruleOrdinalsChadDaraEtc = Rule
{ name = "ordinals (chéad, dara, etc.)"
, pattern =
[ regex "(ch(é|e)ad|aon(ú|u)|t-aon(ú|u)|dara|tr(í|i)(ú|u)|ceathr(ú|u)|c(ú|u)igi(ú|u)|s(é|e)(ú|u)|seacht(ú|u)|ocht(ú|u)|t-ocht(ú|u)|nao(ú|u)|deichi(ú|u)|fichi(ú|u)|tr(í|i)ochad(ú|u)|daichead(ú|u)|caogad(ú|u)|seascad(ú|u)|seacht(ó|o)d(ú|u)|ocht(ó|o)d(ú|u)|t-ocht(ó|o)d(ú|u)|n(ó|o)chad(ú|u)|c(é|e)ad(ú|u)|mili(ú|u)|milli(ú|u)n(ú|u))"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"t-aonu" -> Just $ ordinal 1
"aonu" -> Just $ ordinal 1
"aonú" -> Just $ ordinal 1
"chéad" -> Just $ ordinal 1
"chead" -> Just $ ordinal 1
"t-aonú" -> Just $ ordinal 1
"dara" -> Just $ ordinal 2
"triú" -> Just $ ordinal 3
"tríu" -> Just $ ordinal 3
"tríú" -> Just $ ordinal 3
"triu" -> Just $ ordinal 3
"ceathrú" -> Just $ ordinal 4
"ceathru" -> Just $ ordinal 4
"cúigiu" -> Just $ ordinal 5
"cúigiú" -> Just $ ordinal 5
"cuigiu" -> Just $ ordinal 5
"cuigiú" -> Just $ ordinal 5
"séu" -> Just $ ordinal 6
"séú" -> Just $ ordinal 6
"seu" -> Just $ ordinal 6
"seú" -> Just $ ordinal 6
"seachtu" -> Just $ ordinal 7
"seachtú" -> Just $ ordinal 7
"t-ochtú" -> Just $ ordinal 8
"ochtu" -> Just $ ordinal 8
"t-ochtu" -> Just $ ordinal 8
"ochtú" -> Just $ ordinal 8
"naou" -> Just $ ordinal 9
"naoú" -> Just $ ordinal 9
"deichiu" -> Just $ ordinal 10
"deichiú" -> Just $ ordinal 10
"fichiu" -> Just $ ordinal 20
"fichiú" -> Just $ ordinal 20
"tríochadu" -> Just $ ordinal 30
"triochadu" -> Just $ ordinal 30
"tríochadú" -> Just $ ordinal 30
"triochadú" -> Just $ ordinal 30
"daicheadú" -> Just $ ordinal 40
"daicheadu" -> Just $ ordinal 40
"caogadu" -> Just $ ordinal 50
"caogadú" -> Just $ ordinal 50
"seascadu" -> Just $ ordinal 60
"seascadú" -> Just $ ordinal 60
"seachtodu" -> Just $ ordinal 70
"seachtodú" -> Just $ ordinal 70
"seachtódú" -> Just $ ordinal 70
"seachtódu" -> Just $ ordinal 70
"ochtódu" -> Just $ ordinal 80
"ochtodu" -> Just $ ordinal 80
"t-ochtodu" -> Just $ ordinal 80
"t-ochtódú" -> Just $ ordinal 80
"t-ochtodú" -> Just $ ordinal 80
"ochtódú" -> Just $ ordinal 80
"t-ochtódu" -> Just $ ordinal 80
"ochtodú" -> Just $ ordinal 80
"nóchadú" -> Just $ ordinal 90
"nóchadu" -> Just $ ordinal 90
"nochadú" -> Just $ ordinal 90
"nochadu" -> Just $ ordinal 90
"céadú" -> Just $ ordinal 100
"ceadú" -> Just $ ordinal 100
"ceadu" -> Just $ ordinal 100
"céadu" -> Just $ ordinal 100
"miliu" -> Just $ ordinal 1000
"miliú" -> Just $ ordinal 1000
"milliunú" -> Just $ ordinal 1000000
"milliunu" -> Just $ ordinal 1000000
"milliúnu" -> Just $ ordinal 1000000
"milliúnú" -> Just $ ordinal 1000000
_ -> Nothing
_ -> Nothing
}
ruleOrdinalDigits :: Rule
ruleOrdinalDigits = Rule
{ name = "ordinal (digits)"
, pattern =
[ regex "0*(\\d+) ?(adh|a|d|ú|u)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> ordinal <$> parseInt match
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleOrdinalDigits
, ruleOrdinalsChadDaraEtc
]
|
facebookincubator/duckling
|
Duckling/Ordinal/GA/Rules.hs
|
bsd-3-clause
| 4,270 | 0 | 17 | 1,209 | 1,172 | 577 | 595 | 102 | 71 |
module Trace(
module Debug.Trace,
) where
import Debug.Trace
|
OS2World/DEV-UTIL-HUGS
|
oldlib/Trace.hs
|
bsd-3-clause
| 67 | 2 | 5 | 14 | 20 | 13 | 7 | 3 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : GHC.LanguageExtensions.Type
-- Copyright : (c) The GHC Team
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- A data type defining the language extensions supported by GHC.
--
{-# LANGUAGE DeriveGeneric #-}
module GHC.LanguageExtensions.Type ( Extension(..) ) where
import GHC.Generics
-- | The language extensions known to GHC.
--
-- Note that there is an orphan 'Binary' instance for this type supplied by
-- the "GHC.LanguageExtensions" module provided by @ghc-boot@. We can't provide
-- here as this would require adding transitive dependencies to the
-- @template-haskell@ package, which must have a minimal dependency set.
data Extension
-- See Note [Updating flag description in the User's Guide] in DynFlags
= Cpp
| OverlappingInstances
| UndecidableInstances
| IncoherentInstances
| UndecidableSuperClasses
| MonomorphismRestriction
| MonoPatBinds
| MonoLocalBinds
| RelaxedPolyRec -- Deprecated
| ExtendedDefaultRules -- Use GHC's extended rules for defaulting
| ForeignFunctionInterface
| UnliftedFFITypes
| InterruptibleFFI
| CApiFFI
| GHCForeignImportPrim
| JavaScriptFFI
| ParallelArrays -- Syntactic support for parallel arrays
| Arrows -- Arrow-notation syntax
| TemplateHaskell
| TemplateHaskellQuotes -- subset of TH supported by stage1, no splice
| QuasiQuotes
| ImplicitParams
| ImplicitPrelude
| ScopedTypeVariables
| AllowAmbiguousTypes
| UnboxedTuples
| UnboxedSums
| BangPatterns
| TypeFamilies
| TypeFamilyDependencies
| TypeInType
| OverloadedStrings
| OverloadedLists
| NumDecimals
| DisambiguateRecordFields
| RecordWildCards
| RecordPuns
| ViewPatterns
| GADTs
| GADTSyntax
| NPlusKPatterns
| DoAndIfThenElse
| RebindableSyntax
| ConstraintKinds
| PolyKinds -- Kind polymorphism
| DataKinds -- Datatype promotion
| InstanceSigs
| ApplicativeDo
| StandaloneDeriving
| DeriveDataTypeable
| AutoDeriveTypeable -- Automatic derivation of Typeable
| DeriveFunctor
| DeriveTraversable
| DeriveFoldable
| DeriveGeneric -- Allow deriving Generic/1
| DefaultSignatures -- Allow extra signatures for defmeths
| DeriveAnyClass -- Allow deriving any class
| DeriveLift -- Allow deriving Lift
| DerivingStrategies
| TypeSynonymInstances
| FlexibleContexts
| FlexibleInstances
| ConstrainedClassMethods
| MultiParamTypeClasses
| NullaryTypeClasses
| FunctionalDependencies
| UnicodeSyntax
| ExistentialQuantification
| MagicHash
| EmptyDataDecls
| KindSignatures
| RoleAnnotations
| ParallelListComp
| TransformListComp
| MonadComprehensions
| GeneralizedNewtypeDeriving
| RecursiveDo
| PostfixOperators
| TupleSections
| PatternGuards
| LiberalTypeSynonyms
| RankNTypes
| ImpredicativeTypes
| TypeOperators
| ExplicitNamespaces
| PackageImports
| ExplicitForAll
| AlternativeLayoutRule
| AlternativeLayoutRuleTransitional
| DatatypeContexts
| NondecreasingIndentation
| RelaxedLayout
| TraditionalRecordSyntax
| LambdaCase
| MultiWayIf
| BinaryLiterals
| NegativeLiterals
| HexFloatLiterals
| DuplicateRecordFields
| OverloadedLabels
| EmptyCase
| PatternSynonyms
| PartialTypeSignatures
| NamedWildCards
| StaticPointers
| TypeApplications
| Strict
| StrictData
| MonadFailDesugaring
| EmptyDataDeriving
deriving (Eq, Enum, Show, Generic)
|
ezyang/ghc
|
libraries/ghc-boot-th/GHC/LanguageExtensions/Type.hs
|
bsd-3-clause
| 3,745 | 0 | 6 | 870 | 404 | 276 | 128 | 115 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Math.Probably.Datasets where
import Data.Csv
import GHC.Generics
import qualified Data.Vector as V
import qualified Data.ByteString.Lazy as BL
--http://www.stephendiehl.com/what/#csv
data Plant = Plant
{ sepal_length :: Double
, sepal_width :: Double
, petal_length :: Double
, petal_width :: Double
, species :: String
} deriving (Generic, Show)
instance FromNamedRecord Plant
instance ToNamedRecord Plant
type CsvData = (Header, V.Vector Plant)
plantToVector (Plant x y z w _) = [x,y,z,w]
parseCSV :: FilePath -> IO (Either String CsvData)
parseCSV fname = do
contents <- BL.readFile fname
return $ decodeByName contents
--e.g. https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv
iris :: FilePath -> IO (Either String [Plant])
iris = fmap (fmap (V.toList . snd)) . parseCSV
|
glutamate/probably-baysig
|
src/Math/Probably/Datasets.hs
|
bsd-3-clause
| 904 | 0 | 11 | 145 | 253 | 143 | 110 | 24 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Ivory.Tower.HAL.Bus.SPI where
import Ivory.Language
import Ivory.Tower.HAL.Bus.SPI.DeviceHandle
[ivory|
struct spi_transaction_request
{ tx_device :: Stored SPIDeviceHandle
; tx_buf :: Array 128 (Stored Uint8)
; tx_len :: Stored (Ix 128)
}
struct spi_transaction_result
{ resultcode :: Stored Uint8
; rx_buf :: Array 128 (Stored Uint8)
; rx_idx :: Stored (Ix 128)
}
|]
spiDriverTypes :: Module
spiDriverTypes = package "spiDriverTypes" $ do
defStruct (Proxy :: Proxy "spi_transaction_request")
defStruct (Proxy :: Proxy "spi_transaction_result")
|
GaloisInc/tower
|
tower-hal/src/Ivory/Tower/HAL/Bus/SPI.hs
|
bsd-3-clause
| 749 | 0 | 10 | 130 | 82 | 50 | 32 | 13 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverlappingInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Distributed.Process.Supervisor
-- Copyright : (c) Tim Watson 2012 - 2013
-- License : BSD3 (see the file LICENSE)
--
-- Maintainer : Tim Watson <[email protected]>
-- Stability : experimental
-- Portability : non-portable (requires concurrency)
--
-- This module implements a process which supervises a set of other
-- processes, referred to as its children. These /child processes/ can be
-- either workers (i.e., processes that do something useful in your application)
-- or other supervisors. In this way, supervisors may be used to build a
-- hierarchical process structure called a supervision tree, which provides
-- a convenient structure for building fault tolerant software.
--
-- Unless otherwise stated, all functions in this module will cause the calling
-- process to exit unless the specified supervisor process exists.
--
-- [Supervision Principles]
--
-- A supervisor is responsible for starting, stopping and monitoring its child
-- processes so as to keep them alive by restarting them when necessary.
--
-- The supervisors children are defined as a list of child specifications
-- (see 'ChildSpec'). When a supervisor is started, its children are started
-- in left-to-right (insertion order) according to this list. When a supervisor
-- stops (or exits for any reason), it will terminate its children in reverse
-- (i.e., from right-to-left of insertion) order. Child specs can be added to
-- the supervisor after it has started, either on the left or right of the
-- existing list of children.
--
-- When the supervisor spawns its child processes, they are always linked to
-- their parent (i.e., the supervisor), therefore even if the supervisor is
-- terminated abruptly by an asynchronous exception, the children will still be
-- taken down with it, though somewhat less ceremoniously in that case.
--
-- [Restart Strategies]
--
-- Supervisors are initialised with a 'RestartStrategy', which describes how
-- the supervisor should respond to a child that exits and should be restarted
-- (see below for the rules governing child restart eligibility). Each restart
-- strategy comprises a 'RestartMode' and 'RestartLimit', which govern how
-- the restart should be handled, and the point at which the supervisor
-- should give up and terminate itself respectively.
--
-- With the exception of the @RestartOne@ strategy, which indicates that the
-- supervisor will restart /only/ the one individual failing child, each
-- strategy describes a way to select the set of children that should be
-- restarted if /any/ child fails. The @RestartAll@ strategy, as its name
-- suggests, selects /all/ children, whilst the @RestartLeft@ and @RestartRight@
-- strategies select /all/ children to the left or right of the failed child,
-- in insertion (i.e., startup) order.
--
-- Note that a /branch/ restart will only occur if the child that exited is
-- meant to be restarted. Since @Temporary@ children are never restarted and
-- @Transient@ children are /not/ restarted if they exit normally, in both these
-- circumstances we leave the remaining supervised children alone. Otherwise,
-- the failing child is /always/ included in the /branch/ to be restarted.
--
-- For a hypothetical set of children @a@ through @d@, the following pseudocode
-- demonstrates how the restart strategies work.
--
-- > let children = [a..d]
-- > let failure = c
-- > restartsFor RestartOne children failure = [c]
-- > restartsFor RestartAll children failure = [a,b,c,d]
-- > restartsFor RestartLeft children failure = [a,b,c]
-- > restartsFor RestartRight children failure = [c,d]
--
-- [Branch Restarts]
--
-- We refer to a restart (strategy) that involves a set of children as a
-- /branch restart/ from now on. The behaviour of branch restarts can be further
-- refined by the 'RestartMode' with which a 'RestartStrategy' is parameterised.
-- The @RestartEach@ mode treats each child sequentially, first stopping the
-- respective child process and then restarting it. Each child is stopped and
-- started fully before moving on to the next, as the following imaginary
-- example demonstrates for children @[a,b,c]@:
--
-- > stop a
-- > start a
-- > stop b
-- > start b
-- > stop c
-- > start c
--
-- By contrast, @RestartInOrder@ will first run through the selected list of
-- children, stopping them. Then, once all the children have been stopped, it
-- will make a second pass, to handle (re)starting them. No child is started
-- until all children have been stopped, as the following imaginary example
-- demonstrates:
--
-- > stop a
-- > stop b
-- > stop c
-- > start a
-- > start b
-- > start c
--
-- Both the previous examples have shown children being stopped and started
-- from left to right, but that is up to the user. The 'RestartMode' data
-- type's constructors take a 'RestartOrder', which determines whether the
-- selected children will be processed from @LeftToRight@ or @RightToLeft@.
--
-- Sometimes it is desireable to stop children in one order and start them
-- in the opposite. This is typically the case when children are in some
-- way dependent on one another, such that restarting them in the wrong order
-- might cause the system to misbehave. For this scenarios, there is another
-- 'RestartMode' that will shut children down in the given order, but then
-- restarts them in the reverse. Using @RestartRevOrder@ mode, if we have
-- children @[a,b,c]@ such that @b@ depends on @a@ and @c@ on @b@, we can stop
-- them in the reverse of their startup order, but restart them the other way
-- around like so:
--
-- > RestartRevOrder RightToLeft
--
-- The effect will be thus:
--
-- > stop c
-- > stop b
-- > stop a
-- > start a
-- > start b
-- > start c
--
-- [Restart Intensity Limits]
--
-- If a child process repeatedly crashes during (or shortly after) starting,
-- it is possible for the supervisor to get stuck in an endless loop of
-- restarts. In order prevent this, each restart strategy is parameterised
-- with a 'RestartLimit' that caps the number of restarts allowed within a
-- specific time period. If the supervisor exceeds this limit, it will stop,
-- terminating all its children (in left-to-right order) and exit with the
-- reason @ExitOther "ReachedMaxRestartIntensity"@.
--
-- The 'MaxRestarts' type is a positive integer, and together with a specified
-- @TimeInterval@ forms the 'RestartLimit' to which the supervisor will adhere.
-- Since a great many children can be restarted in close succession when
-- a /branch restart/ occurs (as a result of @RestartAll@, @RestartLeft@ or
-- @RestartRight@ being triggered), the supervisor will track the operation
-- as a single restart attempt, since otherwise it would likely exceed its
-- maximum restart intensity too quickly.
--
-- [Child Restart and Termination Policies]
--
-- When the supervisor detects that a child has died, the 'RestartPolicy'
-- configured in the child specification is used to determin what to do. If
-- the this is set to @Permanent@, then the child is always restarted.
-- If it is @Temporary@, then the child is never restarted and the child
-- specification is removed from the supervisor. A @Transient@ child will
-- be restarted only if it terminates /abnormally/, otherwise it is left
-- inactive (but its specification is left in place). Finally, an @Intrinsic@
-- child is treated like a @Transient@ one, except that if /this/ kind of child
-- exits /normally/, then the supervisor will also exit normally.
--
-- When the supervisor does terminate a child, the 'ChildTerminationPolicy'
-- provided with the 'ChildSpec' determines how the supervisor should go
-- about doing so. If this is @TerminateImmediately@, then the child will
-- be killed without further notice, which means the child will /not/ have
-- an opportunity to clean up any internal state and/or release any held
-- resources. If the policy is @TerminateTimeout delay@ however, the child
-- will be sent an /exit signal/ instead, i.e., the supervisor will cause
-- the child to exit via @exit childPid ExitShutdown@, and then will wait
-- until the given @delay@ for the child to exit normally. If this does not
-- happen within the given delay, the supervisor will revert to the more
-- aggressive @TerminateImmediately@ policy and try again. Any errors that
-- occur during a timed-out shutdown will be logged, however exit reasons
-- resulting from @TerminateImmediately@ are ignored.
--
-- [Creating Child Specs]
--
-- The 'ToChildStart' typeclass simplifies the process of defining a 'ChildStart'
-- providing three default instances from which a 'ChildStart' datum can be
-- generated. The first, takes a @Closure (Process ())@, where the enclosed
-- action (in the @Process@ monad) is the actual (long running) code that we
-- wish to supervise. In the case of a /managed process/, this is usually the
-- server loop, constructed by evaluating some variant of @ManagedProcess.serve@.
--
-- The other two instances provide a means for starting children without having
-- to provide a @Closure@. Both instances wrap the supplied @Process@ action in
-- some necessary boilerplate code, which handles spawning a new process and
-- communicating its @ProcessId@ to the supervisor. The instance for
-- @Addressable a => SupervisorPid -> Process a@ is special however, since this
-- API is intended for uses where the typical interactions with a process take
-- place via an opaque handle, for which an instance of the @Addressable@
-- typeclass is provided. This latter approach requires the expression which is
-- responsible for yielding the @Addressable@ handle to handling linking the
-- target process with the supervisor, since we have delegated responsibility
-- for spawning the new process and cannot perform the link oepration ourselves.
--
-- [Supervision Trees & Supervisor Termination]
--
-- To create a supervision tree, one simply adds supervisors below one another
-- as children, setting the @childType@ field of their 'ChildSpec' to
-- @Supervisor@ instead of @Worker@. Supervision tree can be arbitrarilly
-- deep, and it is for this reason that we recommend giving a @Supervisor@ child
-- an arbitrary length of time to stop, by setting the delay to @Infinity@
-- or a very large @TimeInterval@.
--
-----------------------------------------------------------------------------
module Control.Distributed.Process.Supervisor
( -- * Defining and Running a Supervisor
ChildSpec(..)
, ChildKey
, ChildType(..)
, ChildTerminationPolicy(..)
, ChildStart(..)
, RegisteredName(LocalName, CustomRegister)
, RestartPolicy(..)
-- , ChildRestart(..)
, ChildRef(..)
, isRunning
, isRestarting
, Child
, StaticLabel
, SupervisorPid
, ChildPid
, StarterPid
, ToChildStart(..)
, start
, run
-- * Limits and Defaults
, MaxRestarts
, maxRestarts
, RestartLimit(..)
, limit
, defaultLimits
, RestartMode(..)
, RestartOrder(..)
, RestartStrategy(..)
, ShutdownMode(..)
, restartOne
, restartAll
, restartLeft
, restartRight
-- * Adding and Removing Children
, addChild
, AddChildResult(..)
, StartChildResult(..)
, startChild
, startNewChild
, terminateChild
, TerminateChildResult(..)
, deleteChild
, DeleteChildResult(..)
, restartChild
, RestartChildResult(..)
-- * Normative Shutdown
, shutdown
, shutdownAndWait
-- * Queries and Statistics
, lookupChild
, listChildren
, SupervisorStats(..)
, statistics
-- * Additional (Misc) Types
, StartFailure(..)
, ChildInitFailure(..)
) where
import Control.DeepSeq (NFData)
import Control.Distributed.Process.Supervisor.Types
import Control.Distributed.Process hiding (call)
import Control.Distributed.Process.Serializable()
import Control.Distributed.Process.Extras.Internal.Primitives hiding (monitor)
import Control.Distributed.Process.Extras.Internal.Types
( ExitReason(..)
)
import Control.Distributed.Process.ManagedProcess
( handleCall
, handleInfo
, reply
, continue
, stop
, stopWith
, input
, defaultProcess
, prioritised
, InitHandler
, InitResult(..)
, ProcessAction
, ProcessReply
, ProcessDefinition(..)
, PrioritisedProcessDefinition(..)
, Priority(..)
, DispatchPriority
, UnhandledMessagePolicy(Drop)
)
import qualified Control.Distributed.Process.ManagedProcess.UnsafeClient as Unsafe
( call
, cast
)
import qualified Control.Distributed.Process.ManagedProcess as MP
( pserve
)
import Control.Distributed.Process.ManagedProcess.Server.Priority
( prioritiseCast_
, prioritiseCall_
, prioritiseInfo_
, setPriority
)
import Control.Distributed.Process.ManagedProcess.Server.Restricted
( RestrictedProcess
, Result
, RestrictedAction
, getState
, putState
)
import qualified Control.Distributed.Process.ManagedProcess.Server.Restricted as Restricted
( handleCallIf
, handleCall
, handleCast
, reply
, continue
)
import Control.Distributed.Process.Extras.SystemLog
( LogClient
, LogChan
, LogText
, Logger(..)
)
import qualified Control.Distributed.Process.Extras.SystemLog as Log
import Control.Distributed.Process.Extras.Time
import Control.Exception (SomeException, throwIO)
import Control.Monad.Error
import Data.Accessor
( Accessor
, accessor
, (^:)
, (.>)
, (^=)
, (^.)
)
import Data.Binary
import Data.Foldable (find, foldlM, toList)
import Data.List (foldl')
import qualified Data.List as List (delete)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Sequence
( Seq
, ViewL(EmptyL, (:<))
, ViewR(EmptyR, (:>))
, (<|)
, (|>)
, (><)
, filter)
import qualified Data.Sequence as Seq
import Data.Time.Clock
( NominalDiffTime
, UTCTime
, getCurrentTime
, diffUTCTime
)
import Data.Typeable (Typeable)
#if ! MIN_VERSION_base(4,6,0)
import Prelude hiding (catch, filter, init, rem)
#else
import Prelude hiding (filter, init, rem)
#endif
import GHC.Generics
--------------------------------------------------------------------------------
-- Types --
--------------------------------------------------------------------------------
-- TODO: ToChildStart belongs with rest of types in
-- Control.Distributed.Process.Supervisor.Types
-- | A type that can be converted to a 'ChildStart'.
class ToChildStart a where
toChildStart :: a -> Process ChildStart
instance ToChildStart (Closure (Process ())) where
toChildStart = return . RunClosure
instance ToChildStart (Closure (SupervisorPid -> Process (ChildPid, Message))) where
toChildStart = return . CreateHandle
-- StarterProcess variants of ChildStart
expectTriple :: Process (SupervisorPid, ChildKey, SendPort ChildPid)
expectTriple = expect
instance ToChildStart (Process ()) where
toChildStart proc = do
starterPid <- spawnLocal $ do
-- note [linking]: the first time we see the supervisor's pid,
-- we must link to it, but only once, otherwise we simply waste
-- time and resources creating duplicate links
(supervisor, _, sendPidPort) <- expectTriple
link supervisor
spawnIt proc supervisor sendPidPort
tcsProcLoop proc
return (StarterProcess starterPid)
where
tcsProcLoop :: Process () -> Process ()
tcsProcLoop p = forever' $ do
(supervisor, _, sendPidPort) <- expectTriple
spawnIt p supervisor sendPidPort
spawnIt :: Process ()
-> SupervisorPid
-> SendPort ChildPid
-> Process ()
spawnIt proc' supervisor sendPidPort = do
supervisedPid <- spawnLocal $ do
link supervisor
self <- getSelfPid
(proc' `catches` [ Handler $ filterInitFailures supervisor self
, Handler $ logFailure supervisor self ])
`catchesExit` [\_ m -> handleMessageIf m (== ExitShutdown)
(\_ -> return ())]
sendChan sendPidPort supervisedPid
instance (Resolvable a) => ToChildStart (SupervisorPid -> Process a) where
toChildStart proc = do
starterPid <- spawnLocal $ do
-- see note [linking] in the previous instance (above)
(supervisor, _, sendPidPort) <- expectTriple
link supervisor
injectIt proc supervisor sendPidPort >> injectorLoop proc
return $ StarterProcess starterPid
where
injectorLoop :: Resolvable a
=> (SupervisorPid -> Process a)
-> Process ()
injectorLoop p = forever' $ do
(supervisor, _, sendPidPort) <- expectTriple
injectIt p supervisor sendPidPort
injectIt :: Resolvable a
=> (SupervisorPid -> Process a)
-> SupervisorPid
-> SendPort ChildPid
-> Process ()
injectIt proc' supervisor sendPidPort = do
addr <- proc' supervisor
mPid <- resolve addr
case mPid of
Nothing -> die "UnresolvableAddress in startChild instance"
Just p -> sendChan sendPidPort p
-- internal APIs. The corresponding XxxResult types are in
-- Control.Distributed.Process.Supervisor.Types
data DeleteChild = DeleteChild !ChildKey
deriving (Typeable, Generic)
instance Binary DeleteChild where
instance NFData DeleteChild where
data FindReq = FindReq ChildKey
deriving (Typeable, Generic)
instance Binary FindReq where
instance NFData FindReq where
data StatsReq = StatsReq
deriving (Typeable, Generic)
instance Binary StatsReq where
instance NFData StatsReq where
data ListReq = ListReq
deriving (Typeable, Generic)
instance Binary ListReq where
instance NFData ListReq where
type ImmediateStart = Bool
data AddChildReq = AddChild !ImmediateStart !ChildSpec
deriving (Typeable, Generic, Show)
instance Binary AddChildReq where
instance NFData AddChildReq where
data AddChildRes = Exists ChildRef | Added State
data StartChildReq = StartChild !ChildKey
deriving (Typeable, Generic)
instance Binary StartChildReq where
instance NFData StartChildReq where
data RestartChildReq = RestartChildReq !ChildKey
deriving (Typeable, Generic, Show, Eq)
instance Binary RestartChildReq where
instance NFData RestartChildReq where
{-
data DelayedRestartReq = DelayedRestartReq !ChildKey !DiedReason
deriving (Typeable, Generic, Show, Eq)
instance Binary DelayedRestartReq where
-}
data TerminateChildReq = TerminateChildReq !ChildKey
deriving (Typeable, Generic, Show, Eq)
instance Binary TerminateChildReq where
instance NFData TerminateChildReq where
data IgnoreChildReq = IgnoreChildReq !ChildPid
deriving (Typeable, Generic)
instance Binary IgnoreChildReq where
instance NFData IgnoreChildReq where
type ChildSpecs = Seq Child
type Prefix = ChildSpecs
type Suffix = ChildSpecs
data StatsType = Active | Specified
data LogSink = LogProcess !LogClient | LogChan
instance Logger LogSink where
logMessage LogChan = logMessage Log.logChannel
logMessage (LogProcess client') = logMessage client'
data State = State {
_specs :: ChildSpecs
, _active :: Map ChildPid ChildKey
, _strategy :: RestartStrategy
, _restartPeriod :: NominalDiffTime
, _restarts :: [UTCTime]
, _stats :: SupervisorStats
, _logger :: LogSink
, shutdownStrategy :: ShutdownMode
}
--------------------------------------------------------------------------------
-- Starting/Running Supervisor --
--------------------------------------------------------------------------------
-- | Start a supervisor (process), running the supplied children and restart
-- strategy.
--
-- > start = spawnLocal . run
--
start :: RestartStrategy -> ShutdownMode -> [ChildSpec] -> Process SupervisorPid
start rs ss cs = spawnLocal $ run rs ss cs
-- | Run the supplied children using the provided restart strategy.
--
run :: RestartStrategy -> ShutdownMode -> [ChildSpec] -> Process ()
run rs ss specs' = MP.pserve (rs, ss, specs') supInit serverDefinition
--------------------------------------------------------------------------------
-- Client Facing API --
--------------------------------------------------------------------------------
-- | Obtain statistics about a running supervisor.
--
statistics :: Addressable a => a -> Process (SupervisorStats)
statistics = (flip Unsafe.call) StatsReq
-- | Lookup a possibly supervised child, given its 'ChildKey'.
--
lookupChild :: Addressable a => a -> ChildKey -> Process (Maybe (ChildRef, ChildSpec))
lookupChild addr key = Unsafe.call addr $ FindReq key
-- | List all know (i.e., configured) children.
--
listChildren :: Addressable a => a -> Process [Child]
listChildren addr = Unsafe.call addr ListReq
-- | Add a new child.
--
addChild :: Addressable a => a -> ChildSpec -> Process AddChildResult
addChild addr spec = Unsafe.call addr $ AddChild False spec
-- | Start an existing (configured) child. The 'ChildSpec' must already be
-- present (see 'addChild'), otherwise the operation will fail.
--
startChild :: Addressable a => a -> ChildKey -> Process StartChildResult
startChild addr key = Unsafe.call addr $ StartChild key
-- | Atomically add and start a new child spec. Will fail if a child with
-- the given key is already present.
--
startNewChild :: Addressable a
=> a
-> ChildSpec
-> Process AddChildResult
startNewChild addr spec = Unsafe.call addr $ AddChild True spec
-- | Delete a supervised child. The child must already be stopped (see
-- 'terminateChild').
--
deleteChild :: Addressable a => a -> ChildKey -> Process DeleteChildResult
deleteChild sid childKey = Unsafe.call sid $ DeleteChild childKey
-- | Terminate a running child.
--
terminateChild :: Addressable a
=> a
-> ChildKey
-> Process TerminateChildResult
terminateChild sid = Unsafe.call sid . TerminateChildReq
-- | Forcibly restart a running child.
--
restartChild :: Addressable a
=> a
-> ChildKey
-> Process RestartChildResult
restartChild sid = Unsafe.call sid . RestartChildReq
-- | Gracefully terminate a running supervisor. Returns immediately if the
-- /address/ cannot be resolved.
--
shutdown :: Resolvable a => a -> Process ()
shutdown sid = do
mPid <- resolve sid
case mPid of
Nothing -> return ()
Just p -> exit p ExitShutdown
-- | As 'shutdown', but waits until the supervisor process has exited, at which
-- point the caller can be sure that all children have also stopped. Returns
-- immediately if the /address/ cannot be resolved.
--
shutdownAndWait :: Resolvable a => a -> Process ()
shutdownAndWait sid = do
mPid <- resolve sid
case mPid of
Nothing -> return ()
Just p -> withMonitor p $ do
shutdown p
receiveWait [ matchIf (\(ProcessMonitorNotification _ p' _) -> p' == p)
(\_ -> return ())
]
--------------------------------------------------------------------------------
-- Server Initialisation/Startup --
--------------------------------------------------------------------------------
supInit :: InitHandler (RestartStrategy, ShutdownMode, [ChildSpec]) State
supInit (strategy', shutdown', specs') = do
logClient <- Log.client
let client' = case logClient of
Nothing -> LogChan
Just c -> LogProcess c
let initState = ( ( -- as a NominalDiffTime (in seconds)
restartPeriod ^= configuredRestartPeriod
)
. (strategy ^= strategy')
. (logger ^= client')
$ emptyState shutdown'
)
-- TODO: should we return Ignore, as per OTP's supervisor, if no child starts?
catch (foldlM initChild initState specs' >>= return . (flip InitOk) Infinity)
(\(e :: SomeException) -> do
sup <- getSelfPid
logEntry Log.error $
mkReport "Could not init supervisor " sup "noproc" (show e)
return $ InitStop (show e))
where
initChild :: State -> ChildSpec -> Process State
initChild st ch =
case (findChild (childKey ch) st) of
Just (ref, _) -> die $ StartFailureDuplicateChild ref
Nothing -> tryStartChild ch >>= initialised st ch
configuredRestartPeriod =
let maxT' = maxT (intensity strategy')
tI = asTimeout maxT'
tMs = (fromIntegral tI * (0.000001 :: Float))
in fromRational (toRational tMs) :: NominalDiffTime
initialised :: State
-> ChildSpec
-> Either StartFailure ChildRef
-> Process State
initialised _ _ (Left err) = liftIO $ throwIO $ ChildInitFailure (show err)
initialised state spec (Right ref) = do
mPid <- resolve ref
case mPid of
Nothing -> die $ (childKey spec) ++ ": InvalidChildRef"
Just childPid -> do
return $ ( (active ^: Map.insert childPid chId)
. (specs ^: (|> (ref, spec)))
$ bumpStats Active chType (+1) state
)
where chId = childKey spec
chType = childType spec
--------------------------------------------------------------------------------
-- Server Definition/State --
--------------------------------------------------------------------------------
emptyState :: ShutdownMode -> State
emptyState strat = State {
_specs = Seq.empty
, _active = Map.empty
, _strategy = restartAll
, _restartPeriod = (fromIntegral (0 :: Integer)) :: NominalDiffTime
, _restarts = []
, _stats = emptyStats
, _logger = LogChan
, shutdownStrategy = strat
}
emptyStats :: SupervisorStats
emptyStats = SupervisorStats {
_children = 0
, _workers = 0
, _supervisors = 0
, _running = 0
, _activeSupervisors = 0
, _activeWorkers = 0
, totalRestarts = 0
-- , avgRestartFrequency = 0
}
serverDefinition :: PrioritisedProcessDefinition State
serverDefinition = prioritised processDefinition supPriorities
where
supPriorities :: [DispatchPriority State]
supPriorities = [
prioritiseCast_ (\(IgnoreChildReq _) -> setPriority 100)
, prioritiseInfo_ (\(ProcessMonitorNotification _ _ _) -> setPriority 99 )
-- , prioritiseCast_ (\(DelayedRestartReq _ _) -> setPriority 80 )
, prioritiseCall_ (\(_ :: FindReq) ->
(setPriority 10) :: Priority (Maybe (ChildRef, ChildSpec)))
]
processDefinition :: ProcessDefinition State
processDefinition =
defaultProcess {
apiHandlers = [
Restricted.handleCast handleIgnore
-- adding, removing and (optionally) starting new child specs
, handleCall handleTerminateChild
-- , handleCast handleDelayedRestart
, Restricted.handleCall handleDeleteChild
, Restricted.handleCallIf (input (\(AddChild immediate _) -> not immediate))
handleAddChild
, handleCall handleStartNewChild
, handleCall handleStartChild
, handleCall handleRestartChild
-- stats/info
, Restricted.handleCall handleLookupChild
, Restricted.handleCall handleListChildren
, Restricted.handleCall handleGetStats
]
, infoHandlers = [handleInfo handleMonitorSignal]
, shutdownHandler = handleShutdown
, unhandledMessagePolicy = Drop
} :: ProcessDefinition State
--------------------------------------------------------------------------------
-- API Handlers --
--------------------------------------------------------------------------------
handleLookupChild :: FindReq
-> RestrictedProcess State (Result (Maybe (ChildRef, ChildSpec)))
handleLookupChild (FindReq key) = getState >>= Restricted.reply . findChild key
handleListChildren :: ListReq
-> RestrictedProcess State (Result [Child])
handleListChildren _ = getState >>= Restricted.reply . toList . (^. specs)
handleAddChild :: AddChildReq
-> RestrictedProcess State (Result AddChildResult)
handleAddChild req = getState >>= return . doAddChild req True >>= doReply
where doReply :: AddChildRes -> RestrictedProcess State (Result AddChildResult)
doReply (Added s) = putState s >> Restricted.reply (ChildAdded ChildStopped)
doReply (Exists e) = Restricted.reply (ChildFailedToStart $ StartFailureDuplicateChild e)
handleIgnore :: IgnoreChildReq
-> RestrictedProcess State RestrictedAction
handleIgnore (IgnoreChildReq childPid) = do
{- not only must we take this child out of the `active' field,
we also delete the child spec if it's restart type is Temporary,
since restarting Temporary children is dis-allowed -}
state <- getState
let (cId, active') =
Map.updateLookupWithKey (\_ _ -> Nothing) childPid $ state ^. active
case cId of
Nothing -> Restricted.continue
Just c -> do
putState $ ( (active ^= active')
. (resetChildIgnored c)
$ state
)
Restricted.continue
where
resetChildIgnored :: ChildKey -> State -> State
resetChildIgnored key state =
maybe state id $ updateChild key (setChildStopped True) state
handleDeleteChild :: DeleteChild
-> RestrictedProcess State (Result DeleteChildResult)
handleDeleteChild (DeleteChild k) = getState >>= handleDelete k
where
handleDelete :: ChildKey
-> State
-> RestrictedProcess State (Result DeleteChildResult)
handleDelete key state =
let (prefix, suffix) = Seq.breakl ((== key) . childKey . snd) $ state ^. specs
in case (Seq.viewl suffix) of
EmptyL -> Restricted.reply ChildNotFound
child :< remaining -> tryDeleteChild child prefix remaining state
tryDeleteChild (ref, spec) pfx sfx st
| ref == ChildStopped = do
putState $ ( (specs ^= pfx >< sfx)
$ bumpStats Specified (childType spec) decrement st
)
Restricted.reply ChildDeleted
| otherwise = Restricted.reply $ ChildNotStopped ref
handleStartChild :: State
-> StartChildReq
-> Process (ProcessReply StartChildResult State)
handleStartChild state (StartChild key) =
let child = findChild key state in
case child of
Nothing ->
reply ChildStartUnknownId state
Just (ref@(ChildRunning _), _) ->
reply (ChildStartFailed (StartFailureAlreadyRunning ref)) state
Just (ref@(ChildRunningExtra _ _), _) ->
reply (ChildStartFailed (StartFailureAlreadyRunning ref)) state
Just (ref@(ChildRestarting _), _) ->
reply (ChildStartFailed (StartFailureAlreadyRunning ref)) state
Just (_, spec) -> do
started <- doStartChild spec state
case started of
Left err -> reply (ChildStartFailed err) state
Right (ref, st') -> reply (ChildStartOk ref) st'
handleStartNewChild :: State
-> AddChildReq
-> Process (ProcessReply AddChildResult State)
handleStartNewChild state req@(AddChild _ spec) =
let added = doAddChild req False state in
case added of
Exists e -> reply (ChildFailedToStart $ StartFailureDuplicateChild e) state
Added _ -> attemptStart state spec
where
attemptStart st ch = do
started <- tryStartChild ch
case started of
Left err -> reply (ChildFailedToStart err) $ removeChild spec st -- TODO: document this!
Right ref -> do
let st' = ( (specs ^: (|> (ref, spec)))
$ bumpStats Specified (childType spec) (+1) st
)
in reply (ChildAdded ref) $ markActive st' ref ch
handleRestartChild :: State
-> RestartChildReq
-> Process (ProcessReply RestartChildResult State)
handleRestartChild state (RestartChildReq key) =
let child = findChild key state in
case child of
Nothing ->
reply ChildRestartUnknownId state
Just (ref@(ChildRunning _), _) ->
reply (ChildRestartFailed (StartFailureAlreadyRunning ref)) state
Just (ref@(ChildRunningExtra _ _), _) ->
reply (ChildRestartFailed (StartFailureAlreadyRunning ref)) state
Just (ref@(ChildRestarting _), _) ->
reply (ChildRestartFailed (StartFailureAlreadyRunning ref)) state
Just (_, spec) -> do
started <- doStartChild spec state
case started of
Left err -> reply (ChildRestartFailed err) state
Right (ref, st') -> reply (ChildRestartOk ref) st'
{-
handleDelayedRestart :: State
-> DelayedRestartReq
-> Process (ProcessAction State)
handleDelayedRestart state (DelayedRestartReq key reason) =
let child = findChild key state in
case child of
Nothing ->
continue state -- a child could've been terminated and removed by now
Just ((ChildRestarting childPid), spec) -> do
-- TODO: we ignore the unnecessary .active re-assignments in
-- tryRestartChild, in order to keep the code simple - it would be good to
-- clean this up so we don't have to though...
tryRestartChild childPid state (state ^. active) spec reason
-}
handleTerminateChild :: State
-> TerminateChildReq
-> Process (ProcessReply TerminateChildResult State)
handleTerminateChild state (TerminateChildReq key) =
let child = findChild key state in
case child of
Nothing ->
reply TerminateChildUnknownId state
Just (ChildStopped, _) ->
reply TerminateChildOk state
Just (ref, spec) ->
reply TerminateChildOk =<< doTerminateChild ref spec state
handleGetStats :: StatsReq
-> RestrictedProcess State (Result SupervisorStats)
handleGetStats _ = Restricted.reply . (^. stats) =<< getState
--------------------------------------------------------------------------------
-- Child Monitoring --
--------------------------------------------------------------------------------
handleMonitorSignal :: State
-> ProcessMonitorNotification
-> Process (ProcessAction State)
handleMonitorSignal state (ProcessMonitorNotification _ childPid reason) = do
let (cId, active') =
Map.updateLookupWithKey (\_ _ -> Nothing) childPid $ state ^. active
let mSpec =
case cId of
Nothing -> Nothing
Just c -> fmap snd $ findChild c state
case mSpec of
Nothing -> continue $ (active ^= active') state
Just spec -> tryRestart childPid state active' spec reason
--------------------------------------------------------------------------------
-- Child Monitoring --
--------------------------------------------------------------------------------
handleShutdown :: State -> ExitReason -> Process ()
handleShutdown state (ExitOther reason) = terminateChildren state >> die reason
handleShutdown state _ = terminateChildren state
--------------------------------------------------------------------------------
-- Child Start/Restart Handling --
--------------------------------------------------------------------------------
tryRestart :: ChildPid
-> State
-> Map ChildPid ChildKey
-> ChildSpec
-> DiedReason
-> Process (ProcessAction State)
tryRestart childPid state active' spec reason = do
sup <- getSelfPid
logEntry Log.debug $ do
mkReport "tryRestart" sup (childKey spec) (show reason)
case state ^. strategy of
RestartOne _ -> tryRestartChild childPid state active' spec reason
strat -> do
case (childRestart spec, isNormal reason) of
(Intrinsic, True) -> stopWith newState ExitNormal
(Transient, True) -> continue newState
(Temporary, _) -> continue removeTemp
_ -> tryRestartBranch strat spec reason $ newState
where
newState = (active ^= active') state
removeTemp = removeChild spec $ newState
isNormal (DiedException _) = False
isNormal _ = True
tryRestartBranch :: RestartStrategy
-> ChildSpec
-> DiedReason
-> State
-> Process (ProcessAction State)
tryRestartBranch rs sp dr st = -- TODO: use DiedReason for logging...
let mode' = mode rs
tree' = case rs of
RestartAll _ _ -> childSpecs
RestartLeft _ _ -> subTreeL
RestartRight _ _ -> subTreeR
_ -> error "IllegalState"
proc = case mode' of
RestartEach _ -> stopStart
RestartInOrder _ -> restartL
RestartRevOrder _ -> reverseRestart
dir' = order mode' in do
proc tree' dir'
where
stopStart :: ChildSpecs -> RestartOrder -> Process (ProcessAction State)
stopStart tree order' = do
let tree' = case order' of
LeftToRight -> tree
RightToLeft -> Seq.reverse tree
state <- addRestart activeState
case state of
Nothing -> die errorMaxIntensityReached
Just st' -> apply (foldlM stopStartIt st' tree')
reverseRestart :: ChildSpecs
-> RestartOrder
-> Process (ProcessAction State)
reverseRestart tree LeftToRight = restartL tree RightToLeft -- force re-order
reverseRestart tree dir@(RightToLeft) = restartL (Seq.reverse tree) dir
-- TODO: rename me for heaven's sake - this ISN'T a left biased traversal after all!
restartL :: ChildSpecs -> RestartOrder -> Process (ProcessAction State)
restartL tree ro = do
let rev = (ro == RightToLeft)
let tree' = case rev of
False -> tree
True -> Seq.reverse tree
state <- addRestart activeState
case state of
Nothing -> die errorMaxIntensityReached
Just st' -> foldlM stopIt st' tree >>= \s -> do
apply $ foldlM startIt s tree'
stopStartIt :: State -> Child -> Process State
stopStartIt s ch@(cr, cs) = doTerminateChild cr cs s >>= (flip startIt) ch
stopIt :: State -> Child -> Process State
stopIt s (cr, cs) = doTerminateChild cr cs s
startIt :: State -> Child -> Process State
startIt s (_, cs)
| isTemporary (childRestart cs) = return $ removeChild cs s
| otherwise = ensureActive cs =<< doStartChild cs s
-- Note that ensureActive will kill this (supervisor) process if
-- doStartChild fails, simply because the /only/ failure that can
-- come out of that function (as `Left err') is *bad closure* and
-- that should have either been picked up during init (i.e., caused
-- the super to refuse to start) or been removed during `startChild'
-- or later on. Any other kind of failure will crop up (once we've
-- finished the restart sequence) as a monitor signal.
ensureActive :: ChildSpec
-> Either StartFailure (ChildRef, State)
-> Process State
ensureActive cs it
| (Right (ref, st')) <- it = return $ markActive st' ref cs
| (Left err) <- it = die $ ExitOther $ (childKey cs) ++ ": " ++ (show err)
| otherwise = error "IllegalState"
apply :: (Process State) -> Process (ProcessAction State)
apply proc = do
catchExit (proc >>= continue) (\(_ :: ProcessId) -> stop)
activeState = maybe st id $ updateChild (childKey sp)
(setChildStopped False) st
subTreeL :: ChildSpecs
subTreeL =
let (prefix, suffix) = splitTree Seq.breakl
in case (Seq.viewl suffix) of
child :< _ -> prefix |> child
EmptyL -> prefix
subTreeR :: ChildSpecs
subTreeR =
let (prefix, suffix) = splitTree Seq.breakr
in case (Seq.viewr suffix) of
_ :> child -> child <| prefix
EmptyR -> prefix
splitTree splitWith = splitWith ((== childKey sp) . childKey . snd) childSpecs
childSpecs :: ChildSpecs
childSpecs =
let cs = activeState ^. specs
ck = childKey sp
rs' = childRestart sp
in case (isTransient rs', isTemporary rs', dr) of
(True, _, DiedNormal) -> filter ((/= ck) . childKey . snd) cs
(_, True, _) -> filter ((/= ck) . childKey . snd) cs
_ -> cs
{- restartParallel :: ChildSpecs
-> RestartOrder
-> Process (ProcessAction State)
restartParallel tree order = do
liftIO $ putStrLn "handling parallel restart"
let tree' = case order of
LeftToRight -> tree
RightToLeft -> Seq.reverse tree
-- TODO: THIS IS INCORRECT... currently (below), we terminate
-- the branch in parallel, but wait on all the exits and then
-- restart sequentially (based on 'order'). That's not what the
-- 'RestartParallel' mode advertised, but more importantly, it's
-- not clear what the semantics for error handling (viz restart errors)
-- should actually be.
asyncs <- forM (toList tree') $ \ch -> async $ asyncTerminate ch
(_errs, st') <- foldlM collectExits ([], activeState) asyncs
-- TODO: report errs
apply $ foldlM startIt st' tree'
where
asyncTerminate :: Child -> Process (Maybe (ChildKey, ChildPid))
asyncTerminate (cr, cs) = do
mPid <- resolve cr
case mPid of
Nothing -> return Nothing
Just childPid -> do
void $ doTerminateChild cr cs activeState
return $ Just (childKey cs, childPid)
collectExits :: ([ExitReason], State)
-> Async (Maybe (ChildKey, ChildPid))
-> Process ([ExitReason], State)
collectExits (errs, state) hAsync = do
-- we perform a blocking wait on each handle, since we'll
-- always wait until the last shutdown has occurred anyway
asyncResult <- wait hAsync
let res = mergeState asyncResult state
case res of
Left err -> return ((err:errs), state)
Right st -> return (errs, st)
mergeState :: AsyncResult (Maybe (ChildKey, ChildPid))
-> State
-> Either ExitReason State
mergeState (AsyncDone Nothing) state = Right state
mergeState (AsyncDone (Just (key, childPid))) state = Right $ mergeIt key childPid state
mergeState (AsyncFailed r) _ = Left $ ExitOther (show r)
mergeState (AsyncLinkFailed r) _ = Left $ ExitOther (show r)
mergeState _ _ = Left $ ExitOther "IllegalState"
mergeIt :: ChildKey -> ChildPid -> State -> State
mergeIt key childPid state =
-- TODO: lookup the old ref -> childPid and delete from the active map
( (active ^: Map.delete childPid)
$ maybe state id (updateChild key (setChildStopped False) state)
)
-}
tryRestartChild :: ChildPid
-> State
-> Map ChildPid ChildKey
-> ChildSpec
-> DiedReason
-> Process (ProcessAction State)
tryRestartChild childPid st active' spec reason
| DiedNormal <- reason
, True <- isTransient (childRestart spec) = continue childDown
| True <- isTemporary (childRestart spec) = continue childRemoved
| DiedNormal <- reason
, True <- isIntrinsic (childRestart spec) = stopWith updateStopped ExitNormal
| otherwise = doRestartChild childPid spec reason st
where
childDown = (active ^= active') $ updateStopped
childRemoved = (active ^= active') $ removeChild spec st
updateStopped = maybe st id $ updateChild chKey (setChildStopped False) st
chKey = childKey spec
doRestartChild :: ChildPid -> ChildSpec -> DiedReason -> State -> Process (ProcessAction State)
doRestartChild _ spec _ state = do -- TODO: use ChildPid and DiedReason to log
state' <- addRestart state
case state' of
Nothing -> die errorMaxIntensityReached
-- case restartPolicy of
-- Restart _ -> die errorMaxIntensityReached
-- DelayedRestart _ del -> doRestartDelay oldPid del spec reason state
Just st -> do
start' <- doStartChild spec st
case start' of
Right (ref, st') -> continue $ markActive st' ref spec
Left err -> do
-- All child failures are handled via monitor signals, apart from
-- BadClosure and UnresolvableAddress from the StarterProcess
-- variants of ChildStart, which both come back from
-- doStartChild as (Left err).
sup <- getSelfPid
if isTemporary (childRestart spec)
then do
logEntry Log.warning $
mkReport "Error in temporary child" sup (childKey spec) (show err)
continue $ ( (active ^: Map.filter (/= chKey))
. (bumpStats Active chType decrement)
. (bumpStats Specified chType decrement)
$ removeChild spec st)
else do
logEntry Log.error $
mkReport "Unrecoverable error in child. Stopping supervisor"
sup (childKey spec) (show err)
stopWith st $ ExitOther $ "Unrecoverable error in child " ++ (childKey spec)
where
chKey = childKey spec
chType = childType spec
{-
doRestartDelay :: ChildPid
-> TimeInterval
-> ChildSpec
-> DiedReason
-> State
-> Process State
doRestartDelay oldPid rDelay spec reason state = do
self <- getSelfPid
_ <- runAfter rDelay $ MP.cast self (DelayedRestartReq (childKey spec) reason)
return $ ( (active ^: Map.filter (/= chKey))
. (bumpStats Active chType decrement)
$ maybe state id (updateChild chKey (setChildRestarting oldPid) state)
)
where
chKey = childKey spec
chType = childType spec
-}
addRestart :: State -> Process (Maybe State)
addRestart state = do
now <- liftIO $ getCurrentTime
let acc = foldl' (accRestarts now) [] (now:restarted)
case length acc of
n | n > maxAttempts -> return Nothing
_ -> return $ Just $ (restarts ^= acc) $ state
where
maxAttempts = maxNumberOfRestarts $ maxR $ maxIntensity
slot = state ^. restartPeriod
restarted = state ^. restarts
maxIntensity = state ^. strategy .> restartIntensity
accRestarts :: UTCTime -> [UTCTime] -> UTCTime -> [UTCTime]
accRestarts now' acc r =
let diff = diffUTCTime now' r in
if diff > slot then acc else (r:acc)
doStartChild :: ChildSpec
-> State
-> Process (Either StartFailure (ChildRef, State))
doStartChild spec st = do
restart <- tryStartChild spec
case restart of
Left f -> return $ Left f
Right p -> do
let mState = updateChild chKey (chRunning p) st
case mState of
-- TODO: better error message if the child is unrecognised
Nothing -> die $ "InternalError in doStartChild " ++ show spec
Just s' -> return $ Right $ (p, markActive s' p spec)
where
chKey = childKey spec
chRunning :: ChildRef -> Child -> Prefix -> Suffix -> State -> Maybe State
chRunning newRef (_, chSpec) prefix suffix st' =
Just $ ( (specs ^= prefix >< ((newRef, chSpec) <| suffix))
$ bumpStats Active (childType spec) (+1) st'
)
tryStartChild :: ChildSpec
-> Process (Either StartFailure ChildRef)
tryStartChild ChildSpec{..} =
case childStart of
RunClosure proc -> do
-- TODO: cache your closures!!!
mProc <- catch (unClosure proc >>= return . Right)
(\(e :: SomeException) -> return $ Left (show e))
case mProc of
Left err -> logStartFailure $ StartFailureBadClosure err
Right p -> wrapClosure childRegName p >>= return . Right
CreateHandle fn -> do
mFn <- catch (unClosure fn >>= return . Right)
(\(e :: SomeException) -> return $ Left (show e))
case mFn of
Left err -> logStartFailure $ StartFailureBadClosure err
Right fn' -> do
wrapHandle childRegName fn' >>= return . Right
StarterProcess starterPid ->
wrapRestarterProcess childRegName starterPid
where
logStartFailure sf = do
sup <- getSelfPid
logEntry Log.error $ mkReport "Child Start Error" sup childKey (show sf)
return $ Left sf
wrapClosure :: Maybe RegisteredName
-> Process ()
-> Process ChildRef
wrapClosure regName proc = do
supervisor <- getSelfPid
childPid <- spawnLocal $ do
self <- getSelfPid
link supervisor -- die if our parent dies
maybeRegister regName self
() <- expect -- wait for a start signal (pid is still private)
-- we translate `ExitShutdown' into a /normal/ exit
(proc `catches` [ Handler $ filterInitFailures supervisor self
, Handler $ logFailure supervisor self ])
`catchesExit` [
(\_ m -> handleMessageIf m (== ExitShutdown)
(\_ -> return ()))]
void $ monitor childPid
send childPid ()
return $ ChildRunning childPid
wrapHandle :: Maybe RegisteredName
-> (SupervisorPid -> Process (ChildPid, Message))
-> Process ChildRef
wrapHandle regName proc = do
super <- getSelfPid
(childPid, msg) <- proc super
maybeRegister regName childPid
void $ monitor childPid
return $ ChildRunningExtra childPid msg
wrapRestarterProcess :: Maybe RegisteredName
-> StarterPid
-> Process (Either StartFailure ChildRef)
wrapRestarterProcess regName starterPid = do
sup <- getSelfPid
(sendPid, recvPid) <- newChan
ref <- monitor starterPid
send starterPid (sup, childKey, sendPid)
ePid <- receiveWait [
-- TODO: tighten up this contract to correct for erroneous mail
matchChan recvPid (\(pid :: ChildPid) -> return $ Right pid)
, matchIf (\(ProcessMonitorNotification mref _ dr) ->
mref == ref && dr /= DiedNormal)
(\(ProcessMonitorNotification _ _ dr) ->
return $ Left dr)
] `finally` (unmonitor ref)
case ePid of
Right pid -> do
maybeRegister regName pid
void $ monitor pid
return $ Right $ ChildRunning pid
Left dr -> return $ Left $ StartFailureDied dr
maybeRegister :: Maybe RegisteredName -> ChildPid -> Process ()
maybeRegister Nothing _ = return ()
maybeRegister (Just (LocalName n)) pid = register n pid
maybeRegister (Just (GlobalName _)) _ = return ()
maybeRegister (Just (CustomRegister clj)) pid = do
-- TODO: cache your closures!!!
mProc <- catch (unClosure clj >>= return . Right)
(\(e :: SomeException) -> return $ Left (show e))
case mProc of
Left err -> die $ ExitOther (show err)
Right p -> p pid
filterInitFailures :: SupervisorPid
-> ChildPid
-> ChildInitFailure
-> Process ()
filterInitFailures sup childPid ex = do
case ex of
ChildInitFailure _ -> do
-- This is used as a `catches` handler in multiple places
-- and matches first before the other handlers that
-- would call logFailure.
-- We log here to avoid silent failure in those cases.
logEntry Log.error $ mkReport "ChildInitFailure" sup (show childPid) (show ex)
liftIO $ throwIO ex
ChildInitIgnore -> Unsafe.cast sup $ IgnoreChildReq childPid
--------------------------------------------------------------------------------
-- Child Termination/Shutdown --
--------------------------------------------------------------------------------
terminateChildren :: State -> Process ()
terminateChildren state = do
case (shutdownStrategy state) of
ParallelShutdown -> do
let allChildren = toList $ state ^. specs
terminatorPids <- forM allChildren $ \ch -> do
pid <- spawnLocal $ void $ syncTerminate ch $ (active ^= Map.empty) state
void $ monitor pid
return pid
terminationErrors <- collectExits [] terminatorPids
-- it seems these would also be logged individually in doTerminateChild
case terminationErrors of
[] -> return ()
_ -> do
sup <- getSelfPid
void $ logEntry Log.error $
mkReport "Errors in terminateChildren / ParallelShutdown"
sup "n/a" (show terminationErrors)
SequentialShutdown ord -> do
let specs' = state ^. specs
let allChildren = case ord of
RightToLeft -> Seq.reverse specs'
LeftToRight -> specs'
void $ foldlM (flip syncTerminate) state (toList allChildren)
where
syncTerminate :: Child -> State -> Process State
syncTerminate (cr, cs) state' = doTerminateChild cr cs state'
collectExits :: [(ProcessId, DiedReason)]
-> [ChildPid]
-> Process [(ProcessId, DiedReason)]
collectExits errors [] = return errors
collectExits errors pids = do
(pid, reason) <- receiveWait [
match (\(ProcessMonitorNotification _ pid' reason') -> do
return (pid', reason'))
]
let remaining = List.delete pid pids
case reason of
DiedNormal -> collectExits errors remaining
_ -> collectExits ((pid, reason):errors) remaining
doTerminateChild :: ChildRef -> ChildSpec -> State -> Process State
doTerminateChild ref spec state = do
mPid <- resolve ref
case mPid of
Nothing -> return state -- an already dead child is not an error
Just pid -> do
stopped <- childShutdown (childStop spec) pid state
state' <- shutdownComplete state pid stopped
return $ ( (active ^: Map.delete pid)
$ state'
)
where
shutdownComplete :: State -> ChildPid -> DiedReason -> Process State
shutdownComplete _ _ DiedNormal = return $ updateStopped
shutdownComplete state' pid (r :: DiedReason) = do
logShutdown (state' ^. logger) chKey pid r >> return state'
chKey = childKey spec
updateStopped = maybe state id $ updateChild chKey (setChildStopped False) state
childShutdown :: ChildTerminationPolicy
-> ChildPid
-> State
-> Process DiedReason
childShutdown policy childPid st = do
case policy of
(TerminateTimeout t) -> exit childPid ExitShutdown >> await childPid t st
-- we ignore DiedReason for brutal kills
TerminateImmediately -> do
kill childPid "TerminatedBySupervisor"
void $ await childPid Infinity st
return DiedNormal
where
await :: ChildPid -> Delay -> State -> Process DiedReason
await childPid' delay state = do
let monitored = (Map.member childPid' $ state ^. active)
let recv = case delay of
Infinity -> receiveWait (matches childPid') >>= return . Just
NoDelay -> receiveTimeout 0 (matches childPid')
Delay t -> receiveTimeout (asTimeout t) (matches childPid')
-- We require and additional monitor here when child shutdown occurs
-- during a restart which was triggered by the /old/ monitor signal.
let recv' = if monitored then recv else withMonitor childPid' recv
recv' >>= maybe (childShutdown TerminateImmediately childPid' state) return
matches :: ChildPid -> [Match DiedReason]
matches p = [
matchIf (\(ProcessMonitorNotification _ p' _) -> p == p')
(\(ProcessMonitorNotification _ _ r) -> return r)
]
--------------------------------------------------------------------------------
-- Loging/Reporting --
--------------------------------------------------------------------------------
errorMaxIntensityReached :: ExitReason
errorMaxIntensityReached = ExitOther "ReachedMaxRestartIntensity"
logShutdown :: LogSink -> ChildKey -> ChildPid -> DiedReason -> Process ()
logShutdown log' child childPid reason = do
sup <- getSelfPid
Log.info log' $ mkReport banner sup (show childPid) shutdownReason
where
banner = "Child Shutdown Complete"
shutdownReason = (show reason) ++ ", child-key: " ++ child
logFailure :: SupervisorPid -> ChildPid -> SomeException -> Process ()
logFailure sup childPid ex = do
logEntry Log.notice $ mkReport "Detected Child Exit" sup (show childPid) (show ex)
liftIO $ throwIO ex
logEntry :: (LogChan -> LogText -> Process ()) -> String -> Process ()
logEntry lg = Log.report lg Log.logChannel
mkReport :: String -> SupervisorPid -> String -> String -> String
mkReport b s c r = foldl' (\x xs -> xs ++ " " ++ x) "" items
where
items :: [String]
items = [ "[" ++ s' ++ "]" | s' <- [ b
, "supervisor: " ++ show s
, "child: " ++ c
, "reason: " ++ r] ]
--------------------------------------------------------------------------------
-- Accessors and State/Stats Utilities --
--------------------------------------------------------------------------------
type Ignored = Bool
-- TODO: test that setChildStopped does not re-order the 'specs sequence
setChildStopped :: Ignored -> Child -> Prefix -> Suffix -> State -> Maybe State
setChildStopped ignored child prefix remaining st =
let spec = snd child
rType = childRestart spec
newRef = if ignored then ChildStartIgnored else ChildStopped
in case isTemporary rType of
True -> Just $ (specs ^= prefix >< remaining) $ st
False -> Just $ (specs ^= prefix >< ((newRef, spec) <| remaining)) st
{-
setChildRestarting :: ChildPid -> Child -> Prefix -> Suffix -> State -> Maybe State
setChildRestarting oldPid child prefix remaining st =
let spec = snd child
newRef = ChildRestarting oldPid
in Just $ (specs ^= prefix >< ((newRef, spec) <| remaining)) st
-}
doAddChild :: AddChildReq -> Bool -> State -> AddChildRes
doAddChild (AddChild _ spec) update st =
let chType = childType spec
in case (findChild (childKey spec) st) of
Just (ref, _) -> Exists ref
Nothing ->
case update of
True -> Added $ ( (specs ^: (|> (ChildStopped, spec)))
$ bumpStats Specified chType (+1) st
)
False -> Added st
updateChild :: ChildKey
-> (Child -> Prefix -> Suffix -> State -> Maybe State)
-> State
-> Maybe State
updateChild key updateFn state =
let (prefix, suffix) = Seq.breakl ((== key) . childKey . snd) $ state ^. specs
in case (Seq.viewl suffix) of
EmptyL -> Nothing
child :< remaining -> updateFn child prefix remaining state
removeChild :: ChildSpec -> State -> State
removeChild spec state =
let k = childKey spec
in specs ^: filter ((/= k) . childKey . snd) $ state
-- DO NOT call this function unless you've verified the ChildRef first.
markActive :: State -> ChildRef -> ChildSpec -> State
markActive state ref spec =
case ref of
ChildRunning (pid :: ChildPid) -> inserted pid
ChildRunningExtra pid _ -> inserted pid
_ -> error $ "InternalError"
where
inserted pid' = active ^: Map.insert pid' (childKey spec) $ state
decrement :: Int -> Int
decrement n = n - 1
-- this is O(n) in the worst case, which is a bit naff, but we
-- can optimise it later with a different data structure, if required
findChild :: ChildKey -> State -> Maybe (ChildRef, ChildSpec)
findChild key st = find ((== key) . childKey . snd) $ st ^. specs
bumpStats :: StatsType -> ChildType -> (Int -> Int) -> State -> State
bumpStats Specified Supervisor fn st = (bump fn) . (stats .> supervisors ^: fn) $ st
bumpStats Specified Worker fn st = (bump fn) . (stats .> workers ^: fn) $ st
bumpStats Active Worker fn st = (stats .> running ^: fn) . (stats .> activeWorkers ^: fn) $ st
bumpStats Active Supervisor fn st = (stats .> running ^: fn) . (stats .> activeSupervisors ^: fn) $ st
bump :: (Int -> Int) -> State -> State
bump with' = stats .> children ^: with'
isTemporary :: RestartPolicy -> Bool
isTemporary = (== Temporary)
isTransient :: RestartPolicy -> Bool
isTransient = (== Transient)
isIntrinsic :: RestartPolicy -> Bool
isIntrinsic = (== Intrinsic)
active :: Accessor State (Map ChildPid ChildKey)
active = accessor _active (\act' st -> st { _active = act' })
strategy :: Accessor State RestartStrategy
strategy = accessor _strategy (\s st -> st { _strategy = s })
restartIntensity :: Accessor RestartStrategy RestartLimit
restartIntensity = accessor intensity (\i l -> l { intensity = i })
restartPeriod :: Accessor State NominalDiffTime
restartPeriod = accessor _restartPeriod (\p st -> st { _restartPeriod = p })
restarts :: Accessor State [UTCTime]
restarts = accessor _restarts (\r st -> st { _restarts = r })
specs :: Accessor State ChildSpecs
specs = accessor _specs (\sp' st -> st { _specs = sp' })
stats :: Accessor State SupervisorStats
stats = accessor _stats (\st' st -> st { _stats = st' })
logger :: Accessor State LogSink
logger = accessor _logger (\l st -> st { _logger = l })
children :: Accessor SupervisorStats Int
children = accessor _children (\c st -> st { _children = c })
workers :: Accessor SupervisorStats Int
workers = accessor _workers (\c st -> st { _workers = c })
running :: Accessor SupervisorStats Int
running = accessor _running (\r st -> st { _running = r })
supervisors :: Accessor SupervisorStats Int
supervisors = accessor _supervisors (\c st -> st { _supervisors = c })
activeWorkers :: Accessor SupervisorStats Int
activeWorkers = accessor _activeWorkers (\c st -> st { _activeWorkers = c })
activeSupervisors :: Accessor SupervisorStats Int
activeSupervisors = accessor _activeSupervisors (\c st -> st { _activeSupervisors = c })
|
qnikst/distributed-process-supervisor
|
src/Control/Distributed/Process/Supervisor.hs
|
bsd-3-clause
| 63,785 | 0 | 28 | 16,709 | 12,606 | 6,614 | 5,992 | 998 | 15 |
{-# LANGUAGE ConstraintKinds #-}
module Handler.Wallet where
import Import
import Web.MangoPay
import Yesod.MangoPay
import Control.Monad (join)
import Control.Arrow ((&&&))
import Data.Text (pack)
-- | get wallet list
getWalletsR :: AnyUserId -> Handler Html
getWalletsR uid=do
-- no paging, should be reasonable
wallets<-runYesodMPTToken $ getAll $ listWallets uid (ByCreationDate ASC)
defaultLayout $ do
setTitleI MsgTitleWallets
$(widgetFile "wallets")
-- | get wallet creation form
getWalletR :: AnyUserId -> Handler Html
getWalletR uid = readerWallet uid Nothing
-- | get wallet edition form
getWalletEditR :: AnyUserId -> WalletId -> Handler Html
getWalletEditR uid wid = do
wallet <- runYesodMPTToken $ fetchWallet wid
readerWallet uid $ Just wallet
-- | helper to generate the proper form given maybe an existing wallet
readerWallet :: AnyUserId -> Maybe Wallet -> Handler Html
readerWallet uid mwallet = do
(widget, enctype) <- generateFormPost $ walletForm mwallet
let mwid = join $ wId <$> mwallet
defaultLayout $ do
setTitleI MsgTitleWallet
$(widgetFile "wallet")
-- | helper to create or modify a wallet
helperWallet :: (Wallet -> AccessToken -> MangoPayT Handler Wallet) ->
Maybe Wallet -> AnyUserId -> Handler Html
helperWallet fn mw uid=do
((result, _), _) <- runFormPost $ walletForm mw
mwallet<-case result of
FormSuccess w->do
-- set the owner to current user
let wo= w{wOwners=[uid]}
catchMP (do
wallet<-runYesodMPTToken $ fn wo
setMessageI MsgWalletDone
return (Just wallet)
)
(\e->do
$(logError) $ pack $ show e
setMessage $ toHtml $ show e
return (Just wo)
)
_ -> do
setMessageI MsgErrorData
return Nothing
readerWallet uid mwallet
postWalletR :: AnyUserId -> Handler Html
postWalletR = helperWallet createWallet Nothing
putWalletEditR :: AnyUserId -> WalletId -> Handler Html
putWalletEditR uid wid = do
wallet <- runYesodMPTToken $ fetchWallet wid
helperWallet modifyWallet (Just wallet) uid
-- | form for wallet
walletForm :: HtmlForm Wallet
walletForm mwallet= renderDivs $ Wallet
<$> aopt hiddenField "" (wId <$> mwallet)
<*> pure (join $ wCreationDate <$> mwallet)
<*> aopt textField (localizedFS MsgWalletCustomData) (wTag <$> mwallet)
<*> pure []
<*> areq textField (localizedFS MsgWalletDescription) (wDescription <$> mwallet)
<*> areq (selectFieldList (map (id &&& id) $ maybe supportedCurrencies (\mw -> [wCurrency mw]) mwallet))
(localizedFS MsgWalletCurrency) (wCurrency <$> mwallet)
-- we can't edit the amount anyway, so we show it as disabled and return a const 0 value
<*> (fmap (const $ Amount "EUR" 0) <$> aopt intField (disabled $ localizedFS MsgWalletBalance) (fmap aAmount <$> wBalance <$> mwallet))
|
prowdsponsor/mangopay
|
yesod-mangopay/app/Handler/Wallet.hs
|
bsd-3-clause
| 2,962 | 0 | 21 | 702 | 851 | 417 | 434 | -1 | -1 |
module GHCJS.DOM.MouseEvent where
data MouseEvent = MouseEvent
class IsMouseEvent a
instance IsMouseEvent MouseEvent
ghcjs_dom_mouse_event_init_mouse_event = undefined
mouseEventInitMouseEvent = undefined
ghcjs_dom_mouse_event_get_screen_x = undefined
mouseEventGetScreenX = undefined
ghcjs_dom_mouse_event_get_screen_y = undefined
mouseEventGetScreenY = undefined
ghcjs_dom_mouse_event_get_client_x = undefined
mouseEventGetClientX = undefined
ghcjs_dom_mouse_event_get_client_y = undefined
mouseEventGetClientY = undefined
ghcjs_dom_mouse_event_get_ctrl_key = undefined
mouseEventGetCtrlKey = undefined
ghcjs_dom_mouse_event_get_shift_key = undefined
mouseEventGetShiftKey = undefined
ghcjs_dom_mouse_event_get_alt_key = undefined
mouseEventGetAltKey = undefined
ghcjs_dom_mouse_event_get_meta_key = undefined
mouseEventGetMetaKey = undefined
ghcjs_dom_mouse_event_get_button = undefined
mouseEventGetButton = undefined
ghcjs_dom_mouse_event_get_related_target = undefined
mouseEventGetRelatedTarget = undefined
ghcjs_dom_mouse_event_get_movement_x = undefined
mouseEventGetMovementX = undefined
ghcjs_dom_mouse_event_get_movement_y = undefined
mouseEventGetMovementY = undefined
ghcjs_dom_mouse_event_get_offset_x = undefined
mouseEventGetOffsetX = undefined
ghcjs_dom_mouse_event_get_offset_y = undefined
mouseEventGetOffsetY = undefined
ghcjs_dom_mouse_event_get_x = undefined
mouseEventGetX = undefined
ghcjs_dom_mouse_event_get_y = undefined
mouseEventGetY = undefined
ghcjs_dom_mouse_event_get_from_element = undefined
mouseEventGetFromElement = undefined
ghcjs_dom_mouse_event_get_to_element = undefined
mouseEventGetToElement = undefined
castToMouseEvent = undefined
gTypeMouseEvent = undefined
toMouseEvent = undefined
|
mightybyte/reflex-dom-stubs
|
src/GHCJS/DOM/MouseEvent.hs
|
bsd-3-clause
| 1,732 | 0 | 5 | 138 | 233 | 138 | 95 | -1 | -1 |
{-# LANGUAGE DeriveGeneric, RecordWildCards, TupleSections #-}
import Data.Monoid
import GHC.Generics
import Options.Applicative
import Options.Applicative.Types
import Network.URI
import System.Directory
import System.Log.Logger
import Text.Read
import qualified Text.Parsec as P
import qualified Text.Parsec.Error as P
import Vaultaire.Types
import Parse
import Eval
data Mode
= Align Source Source
| Export URI Origin TimeStamp TimeStamp
| Fetch (String, String) URI Origin TimeStamp TimeStamp
data CmdArgs
= CmdArgs { output :: FilePath
, operation :: Mode }
deriving Generic
-- wow so lisp
mode :: Parser Mode
mode = subparser
( (command "align"
(info pAlign
(progDesc $ concat
["align discrete two time series, e.g "
,"align file:format=csv,points=points.txt,dict=sd.txt "
," vault:reader=tcp://foo.com:9999,origin=ABCDEF,address=7yHojf,start=2099-07-07,end=2100-12-22"]
)
)
)
<> (command "export"
(info pExport
(progDesc $ concat
["export simple points for all addresses"
," e.g. export tcp://foo.com:9999 ABCDEF 0 999"]
)
)
)
<> (command "fetch"
(info pFetch
(progDesc $ concat
["fetch data for a metric matching some (key,value), e.g."
," fetch hostname=deadbeef tcp://foo.com:9999 ABCDEF 0 999"]
)
)
)
)
where pAlign = Align <$> sauce <*> sauce
pExport = Export <$> uri <*> origin <*> timestamp <*> timestamp
pFetch = Fetch <$> keyval <*> uri <*> origin <*> timestamp <*> timestamp
sauce = flip argument mempty $
do s <- readerAsk
case P.parse pSource "" s of
Left e -> readerError $ "Parsing source failed here: "
++ (showParserErrors $ P.errorMessages e)
Right x -> return x
keyval = flip argument mempty $
do s <- readerAsk
case P.parse pKeyVal "" s of
Left e -> readerError $ "Parsing keyval failed: "
++ (showParserErrors $ P.errorMessages e)
Right x -> return x
uri = argument (readerAsk >>= maybe (readerError "cannot parse broker URI") return . parseURI) mempty
origin = argument (readerAsk >>= maybe (readerError "cannot parse origin") return . readMaybe) mempty
timestamp = argument (readerAsk >>= maybe (readerError "cannot read timestamp") return . readMaybe) mempty
args :: Parser CmdArgs
args = CmdArgs
<$> strOption ( long "output" <> short 'o' <> metavar "OUT"
<> help "output file" )
<*> mode
main :: IO ()
main = do
updateGlobalLogger "Query" (setLevel INFO)
infoM "Query" "starting..."
CmdArgs{..} <- execParser toplevel
case operation of
Align sauce1 sauce2 -> evalAlign output sauce1 sauce2
Export u org s e -> createDirectoryIfMissing True output
>> evalExport output u org s e
Fetch q u org s e -> createDirectoryIfMissing True output
>> evalFetch output q u org s e
where toplevel = info (helper <*> args) (fullDesc <> header "Simple query CLI")
|
anchor/vaultaire-query
|
src/Query.hs
|
bsd-3-clause
| 3,451 | 0 | 17 | 1,177 | 809 | 413 | 396 | 75 | 3 |
module Network.MoHWS.ByteString where
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
import qualified System.IO as IO
import Control.Monad (liftM2, )
import System.IO.Unsafe (unsafeInterleaveIO, )
{- |
Like 'L.hGetContents' but it does not try to close the file when reaching the end.
Since you may abort reading before reaching the end,
or the run-time system reads more than necessary
(you don't know how unsafeInterleaveIO works),
you never know, whether 'L.hGetContents' has already closed the file or not.
With this function however it is always sure,
that the file is not closed and you are responsible for closing it.
-}
hGetContentsN :: Int -> IO.Handle -> IO L.ByteString
hGetContentsN k h =
let loop = unsafeInterleaveIO $ do
eof <- IO.hIsEOF h
if eof
then return L.empty
else
do liftM2
(\c -> L.append (L.fromChunks [c]))
(S.hGet h k) loop
in loop
{- |
Variant of 'hGetContentsN' that may choose smaller chunks
when currently no more data is available.
The chunk size may however become arbitrarily small,
making the whole process inefficient.
But when real-time fetching counts, it is the better choice.
-}
hGetContentsNonBlockingN :: Int -> IO.Handle -> IO L.ByteString
hGetContentsNonBlockingN k h =
let lazyRead = unsafeInterleaveIO loop
loop = do
c <- S.hGetNonBlocking h k
if S.null c
then do eof <- IO.hIsEOF h
if eof
then return L.empty
else IO.hWaitForInput h (-1) >> loop
else fmap (L.append $ L.fromChunks [c]) lazyRead
in lazyRead
-- | Read the given number of bytes from a Handle
hGetChars :: IO.Handle -> Int -> IO String
hGetChars h n = fmap L.unpack $ L.hGet h n
|
xpika/mohws
|
src/Network/MoHWS/ByteString.hs
|
bsd-3-clause
| 1,869 | 0 | 21 | 498 | 366 | 192 | 174 | 30 | 3 |
module Nancy.Interpreter where
import Nancy.Core.Language as L
import Nancy.Core.Util
import Nancy.Core.Output
import Nancy.Core.Errors.Interpreter as Err
import Control.Monad.Identity
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.Writer
type InterpretEnv = Trail
type InterpretM = ReaderT InterpretEnv (ExceptT Err.InterpretError (WriterT [String] Identity)) (Value, Trail)
runInterpretM :: InterpretEnv -> InterpretM -> (Either Err.InterpretError (Value, Trail), [String])
runInterpretM env m = runIdentity (runWriterT (runExceptT (runReaderT m env)))
interpretProgram :: Program -> InterpreterOutput
interpretProgram (Program term) =
processResult
$ runInterpretM unusedInitialTrail (interpretTerm term)
where
unusedInitialTrail = L.RTrail $ L.Number 0
processResult (result, logs) =
case result of
(Right (value, _)) -> InterpretSuccess (value, logs)
(Left err) -> InterpretFailure (err, logs)
interpretTerm :: Term -> InterpretM
interpretTerm (Number n) =
return (IntVal n, L.RTrail $ L.Number n)
interpretTerm (Boolean b) =
return (BoolVal b, L.RTrail $ L.Boolean b)
interpretTerm (Brack term) =
interpretTerm term
interpretTerm (Var x) =
return (VarVal x, L.RTrail $ L.Var x)
interpretTerm (AVar u) =
return (AVarVal u, L.RTrail $ L.AVar u)
interpretTerm term@(Lam arg argType body) =
return (LamVal arg argType body, L.RTrail $ getWit term)
interpretTerm (App lam arg) = do
(lamVal, lamTrail) <- interpretTerm lam
case lamVal of
(LamVal var varType body) -> do
(argVal, argTrail) <- local (updateTrailForArg lamTrail arg) (interpretTerm arg)
(result, resultTrail) <-
local (updateTrailForBody lamTrail argTrail var varType)
(interpretTerm (valueSubOverVar argVal var body))
return (result, getReturnTrail lamTrail argTrail var varType resultTrail)
_ ->
throwError (Err.ExpectedLam lamVal)
where
updateTrailForArg lamTrail lamArg currentTrail =
currentTrail <--> L.AppTrail lamTrail (L.RTrail $ getWit lamArg)
updateTrailForBody lamTrail argTrail var varType currentTrail =
currentTrail
<--> L.AppTrail lamTrail argTrail
<--> L.BaTrail var varType (getTarget argTrail) (getTarget lamTrail)
getReturnTrail lamTrail argTrail var varType resultTrail =
L.AppTrail lamTrail argTrail
<--> L.BaTrail var varType (getTarget argTrail) (getTarget lamTrail)
<--> resultTrail
interpretTerm plusTerm@(Plus leftTerm rightTerm) = do
(leftVal, leftTrail) <- interpretTerm leftTerm
(rightVal, rightTrail) <- local (updateTrailForRight leftTrail) (interpretTerm rightTerm)
case (leftVal, rightVal) of
(IntVal leftInt, IntVal rightInt) ->
return (IntVal (leftInt + rightInt), L.PlusTrail leftTrail rightTrail)
_ ->
throwError (Err.InvalidPlusArgs plusTerm)
where
updateTrailForRight leftTrail currentTrail =
currentTrail <--> L.PlusTrail leftTrail (L.RTrail (getWit rightTerm))
interpretTerm eqTerm@(Eq leftTerm rightTerm) = do
(leftVal, leftTrail) <- interpretTerm leftTerm
(rightVal, rightTrail) <- local (updateTrailForRight leftTrail) (interpretTerm rightTerm)
case (leftVal, rightVal) of
(IntVal leftInt, IntVal rightInt) ->
return (BoolVal (leftInt == rightInt), L.EqTrail leftTrail rightTrail)
(BoolVal leftBool, BoolVal rightBool) ->
return (BoolVal (leftBool == rightBool), L.EqTrail leftTrail rightTrail)
_ ->
throwError (Err.InvalidEqArgs eqTerm)
where
updateTrailForRight leftTrail currentTrail =
currentTrail <--> L.EqTrail leftTrail (L.RTrail (getWit rightTerm))
interpretTerm (Ite condTerm thenTerm elseTerm) = do
(condVal, condTrail) <- interpretTerm condTerm
(thenVal, thenTrail) <- local (updateTrailForThen condTrail) (interpretTerm thenTerm)
(elseVal, elseTrail) <- local (updateTrailForElse condTrail thenTrail) (interpretTerm elseTerm)
case condVal of
(L.BoolVal bool) | bool ->
return (thenVal, L.IteTrail condTrail thenTrail elseTrail)
(L.BoolVal _) ->
return (elseVal, L.IteTrail condTrail thenTrail elseTrail)
_ ->
throwError (Err.InvalidIfCond condTerm condVal)
where
updateTrailForThen condTrail currentTrail =
currentTrail <--> L.IteTrail condTrail (L.RTrail (getWit thenTerm)) (L.RTrail (getWit elseTerm))
updateTrailForElse condTrail thenTrail currentTrail =
currentTrail <--> L.IteTrail condTrail thenTrail (L.RTrail (getWit elseTerm))
interpretTerm term@(Bang body bangTrail) = do
(bodyVal, bodyTrail) <- local (const bangTrail) (interpretTerm body)
return (BangVal bodyVal (TrailWithMode (Standard, L.TTrail bangTrail bodyTrail)), L.RTrail $ getWit term)
interpretTerm (ALet letVar letVarType letArg letBody) = do
(argValue, argTrail) <- interpretTerm letArg
case argValue of
(L.BangVal bangVal (TrailWithMode (_, bangTrail))) -> do
(resultVal, resultTrail) <-
local (updateTrailForBody argTrail bangTrail bangVal)
(interpretTerm (termSubOverAVar bangTrail letVar bangVal (getSource bangTrail) letBody))
return (resultVal, getReturnTrail argTrail bangTrail bangVal resultTrail)
_ -> throwError (Err.ExpectedBang argValue)
where
updateTrailForBody argTrail bangTrail bangVal currentTrail =
currentTrail
<--> L.ALetTrail letVar letVarType argTrail (L.RTrail $ getWit letBody)
<--> L.BbTrail letVar letVarType (getSource bangTrail) (getWit letBody)
<--> trailSubOverAVar bangTrail letVar bangVal (getSource bangTrail) letBody
getReturnTrail argTrail bangTrail bangVal resultTrail =
L.ALetTrail letVar letVarType argTrail (L.RTrail $ getWit letBody)
<--> L.BbTrail letVar letVarType (getSource bangTrail) (getWit letBody)
<--> trailSubOverAVar bangTrail letVar bangVal (getSource bangTrail) letBody
<--> resultTrail
interpretTerm (Inspect branches) = do
currentTrail <- ask
(branchValues, trplTrail) <- interpretBranches
let foldTerm = foldTrailToExpr (valueToTerm <$> branchValues) (addTrplTrail trplTrail currentTrail)
(foldValue, foldTrail) <- local (addTrplTrail trplTrail) (interpretTerm foldTerm)
return (foldValue, getResultTrail trplTrail foldTrail currentTrail)
where
baseTrailList = trailBranchesToList (L.RTrail . getWit <$> branches)
addTrplTrail trplTrail currentTrail =
currentTrail <--> L.TrplTrail trplTrail
interpretBranchesFold acc (idx, branch) = do
(values, trails) <- acc
let trailBranchList = trails ++ snd (splitAt idx baseTrailList)
maybeTrplTrail = trailBranchesFromList trailBranchList
case maybeTrplTrail of
(Just trplTrail) -> do
(branchValue, branchTrail) <- local (addTrplTrail trplTrail) (interpretTerm branch)
return (values ++ [branchValue], trails ++ [branchTrail])
Nothing ->
throwError Err.InvalidTrailBranchList
interpretBranches = do
(resultValues, resultTrail) <-
foldl interpretBranchesFold
(return ([], []))
(zip [0..] (trailBranchesToList branches))
case (trailBranchesFromList resultValues, trailBranchesFromList resultTrail) of
(Just branchValues, Just branchTrail) ->
return (branchValues, branchTrail)
_ ->
throwError Err.InvalidTrailBranchList
getResultTrail trplTrail foldTrail currentTrail =
let
currentWithTrpl = currentTrail <--> L.TrplTrail trplTrail
in
currentTrail
<--> L.TrplTrail trplTrail
<--> L.TiTrail currentWithTrpl (fmap getWit branches)
<--> foldTrail
|
jgardella/nancy
|
src/Nancy/Interpreter.hs
|
mit
| 7,618 | 0 | 19 | 1,443 | 2,430 | 1,221 | 1,209 | 151 | 10 |
module HidingMultipleUnused where
import Data.List hiding (lookup, sort)
import GHC.OldList (sort)
foo = sort
|
serokell/importify
|
test/test-data/base@basic/08-Z01-HidingMultipleUnused.hs
|
mit
| 134 | 0 | 5 | 38 | 33 | 21 | 12 | 4 | 1 |
import Network.MateLight.Simple
import Network.MateLight
import SDLEventProvider.SDLKeyEventProvider
import Control.Monad.State
import Control.Monad.Reader
import Data.Maybe
import qualified Network.Socket as Sock
type KeyStatus = (String, String, Integer) -- Represents the tuple (KeyStatusString, KeyNameString, Time)
{-
TODO:
- Geschwindigkeit Obstacles anpassen
- Kollisionsabfrage generieren (wichtig!)
- Obstacles field.txt erweitern
- .:BONUS:. Geschwindigkeit erhöhen (bei längeren Spielverlauf)
-}
-- Color Codes for the Elements
backgroundPixel = Pixel 240 248 255
groundPixel = Pixel 160 82 45
saurPixel = Pixel 0 158 130
cactusPixel = Pixel 0 100 0
birdPixel = Pixel 220 20 60
-- Create Pixelsaur
data Saur = Ducked | Normal | Jump Int deriving (Eq, Show)
data SaurState = SaurState {
saur :: Saur
,field :: [[Obstacles]]
} deriving (Show, Eq)
-- Create Obstacles
data Obstacles = Free | Cactus | Bird | Ground deriving (Eq, Show)
-- Create Colors for the Obstacles
colours :: Obstacles -> Pixel
colours Ground = groundPixel
colours Cactus = cactusPixel
colours Bird = birdPixel
colours Free = backgroundPixel
-- Empty State for the Game
empty :: [[Obstacles]] -> SaurState
empty = SaurState Normal
-- Move the Pixelsaur (only UP and DOWN)
move :: (Int, Int) -> KeyStatus -> SaurState -> SaurState
move (xdim, ydim) ("Pressed","DOWN", _) saurState = saurState {saur = Ducked}
move (xdim, ydim) ("Released", "DOWN", _) saurState = saurState {saur = Normal}
move (xdim, ydim) ("Pressed", "UP", _) saurState = saurState {saur = Jump 0}
move (xdim, ydim) ("Released", "UP", _) saurState = saurState {saur = Normal}
move _ _ s = s
-- reate the Frame
myFrame :: (Int, Int) -> SaurState -> ListFrame
myFrame (xdim, ydim) saurState = ListFrame $ map (\y -> map (\x -> generate (saur saurState) x y) [0 .. xdim - 1]) [0 .. ydim - 1]
where
generate Normal x y | x == 1 && y >= 8 && y <= 10 = saurPixel
| otherwise = colours $ (field saurState !! y) !! x
generate Ducked x y | x == 1 && y >= 9 && y <= 10 || x == 2 && y == 9 = saurPixel
| otherwise = colours $ (field saurState !! y) !! x
generate (Jump d) x y = let d' = d `div` 3 in if isSaurJump d' (x, y) then saurPixel else colours $ (field saurState !! y) !! x
isSaurJump d (x, y) | d <= 5 = x == 1 && y >= 8 - d && y <= 10 - d
| otherwise = x == 1 && y >= 8 - (10 - d) && y <= 10 - (10 - d)
getKeyDataTuples keyState = (map (\(k,t) -> ("Pressed",k,t)) (pressed $ keyState)) ++ (map (\(k,d) -> ("Held",k,d)) (held $ keyState)) ++ (map (\(k,t) -> ("Released",k,t)) (released $ keyState))
eventTest :: [EventT] -> MateMonad ListFrame SaurState IO ListFrame
eventTest events = do
state <- get
let state' = case saur state of
Jump dur | dur >= 30 -> state {saur = Normal}
| otherwise -> state {saur = Jump (dur + 1)}
_ -> foldl (\acc (EventT mod ev) -> if mod == "SDL_KEY_DATA" then foldl (\accState key -> move dim key accState) acc (getKeyDataTuples (read $ show ev)) else acc) state events
put $ state' {field = map tail $ field state'} --Geschwindigkeit ändern!
return (myFrame dim state')
dim :: (Int, Int)
dim = (30, 12)
main :: IO ()
main = do
showSDLControlWindow
-- Read field.txt
field <- lines `fmap` readFile "field.txt"
-- Create Obstacles from field.txt
let field' = map (cycle . map (\c -> case c of {'_' -> Ground; '*' -> Cactus; 'x' -> Bird; _ -> Free})) field :: [[Obstacles]]
Sock.withSocketsDo $ runMateM (Config (fromJust $ parseAddress "134.28.70.172") 1337 dim (Just 33000) True [sdlKeyEventProvider]) eventTest (empty field')
|
Alveran/Pixelsaur-FP
|
SDLEventTest.hs
|
gpl-3.0
| 3,767 | 0 | 22 | 882 | 1,430 | 777 | 653 | 59 | 4 |
-- | Parsing of documentation nodes.
module Data.GI.GIR.Documentation
( Documentation(..)
, queryDocumentation
) where
import Data.Text (Text)
import Text.XML (Element)
import Data.GI.GIR.XMLUtils (firstChildWithLocalName, getElementContent,
lookupAttr)
-- | Documentation for a given element. The documentation text is
-- typically encoded in the gtk-doc format, see
-- https://developer.gnome.org/gtk-doc-manual/ . This can be parsed
-- with `Data.GI.GIR.parseGtkDoc`.
data Documentation = Documentation { rawDocText :: Maybe Text
, sinceVersion :: Maybe Text
} deriving (Show, Eq, Ord)
-- | Parse the documentation node for the given element of the GIR file.
queryDocumentation :: Element -> Documentation
queryDocumentation element = Documentation {
rawDocText = firstChildWithLocalName "doc" element >>= getElementContent,
sinceVersion = lookupAttr "version" element
}
|
ford-prefect/haskell-gi
|
lib/Data/GI/GIR/Documentation.hs
|
lgpl-2.1
| 997 | 0 | 9 | 233 | 151 | 91 | 60 | 14 | 1 |
module SwiftNav.SBP.FileIo where
import Control.Monad
import Control.Monad.Loops
import Data.Binary
import Data.Binary.Get
import Data.Binary.IEEE754
import Data.Binary.Put
import Data.ByteString
import Data.ByteString.Lazy hiding ( ByteString )
import Data.Int
import Data.Word
msgFileioReadReq :: Word16
msgFileioReadReq = 0x00A8
data MsgFileioReadReq = MsgFileioReadReq
{ msgFileioReadReqSequence :: Word32
, msgFileioReadReqOffset :: Word32
, msgFileioReadReqChunkSize :: Word8
, msgFileioReadReqFilename :: ByteString
} deriving ( Show, Read, Eq )
instance Binary MsgFileioReadReq where
get = do
msgFileioReadReqSequence <- getWord32le
msgFileioReadReqOffset <- getWord32le
msgFileioReadReqChunkSize <- getWord8
msgFileioReadReqFilename <- liftM toStrict getRemainingLazyByteString
return MsgFileioReadReq {..}
put MsgFileioReadReq {..} = do
putWord32le msgFileioReadReqSequence
putWord32le msgFileioReadReqOffset
putWord8 msgFileioReadReqChunkSize
putByteString msgFileioReadReqFilename
msgFileioReadResp :: Word16
msgFileioReadResp = 0x00A3
data MsgFileioReadResp = MsgFileioReadResp
{ msgFileioReadRespSequence :: Word32
, msgFileioReadRespContents :: [Word8]
} deriving ( Show, Read, Eq )
instance Binary MsgFileioReadResp where
get = do
msgFileioReadRespSequence <- getWord32le
msgFileioReadRespContents <- whileM (liftM not isEmpty) getWord8
return MsgFileioReadResp {..}
put MsgFileioReadResp {..} = do
putWord32le msgFileioReadRespSequence
mapM_ putWord8 msgFileioReadRespContents
msgFileioReadDirReq :: Word16
msgFileioReadDirReq = 0x00A9
data MsgFileioReadDirReq = MsgFileioReadDirReq
{ msgFileioReadDirReqSequence :: Word32
, msgFileioReadDirReqOffset :: Word32
, msgFileioReadDirReqDirname :: ByteString
} deriving ( Show, Read, Eq )
instance Binary MsgFileioReadDirReq where
get = do
msgFileioReadDirReqSequence <- getWord32le
msgFileioReadDirReqOffset <- getWord32le
msgFileioReadDirReqDirname <- liftM toStrict getRemainingLazyByteString
return MsgFileioReadDirReq {..}
put MsgFileioReadDirReq {..} = do
putWord32le msgFileioReadDirReqSequence
putWord32le msgFileioReadDirReqOffset
putByteString msgFileioReadDirReqDirname
msgFileioReadDirResp :: Word16
msgFileioReadDirResp = 0x00AA
data MsgFileioReadDirResp = MsgFileioReadDirResp
{ msgFileioReadDirRespSequence :: Word32
, msgFileioReadDirRespContents :: [Word8]
} deriving ( Show, Read, Eq )
instance Binary MsgFileioReadDirResp where
get = do
msgFileioReadDirRespSequence <- getWord32le
msgFileioReadDirRespContents <- whileM (liftM not isEmpty) getWord8
return MsgFileioReadDirResp {..}
put MsgFileioReadDirResp {..} = do
putWord32le msgFileioReadDirRespSequence
mapM_ putWord8 msgFileioReadDirRespContents
msgFileioRemove :: Word16
msgFileioRemove = 0x00AC
data MsgFileioRemove = MsgFileioRemove
{ msgFileioRemoveFilename :: ByteString
} deriving ( Show, Read, Eq )
instance Binary MsgFileioRemove where
get = do
msgFileioRemoveFilename <- liftM toStrict getRemainingLazyByteString
return MsgFileioRemove {..}
put MsgFileioRemove {..} = do
putByteString msgFileioRemoveFilename
msgFileioWriteReq :: Word16
msgFileioWriteReq = 0x00AD
data MsgFileioWriteReq = MsgFileioWriteReq
{ msgFileioWriteReqSequence :: Word32
, msgFileioWriteReqOffset :: Word32
, msgFileioWriteReqFilename :: ByteString
, msgFileioWriteReqData :: [Word8]
} deriving ( Show, Read, Eq )
instance Binary MsgFileioWriteReq where
get = do
msgFileioWriteReqSequence <- getWord32le
msgFileioWriteReqOffset <- getWord32le
msgFileioWriteReqFilename <- liftM toStrict getRemainingLazyByteString
msgFileioWriteReqData <- whileM (liftM not isEmpty) getWord8
return MsgFileioWriteReq {..}
put MsgFileioWriteReq {..} = do
putWord32le msgFileioWriteReqSequence
putWord32le msgFileioWriteReqOffset
putByteString msgFileioWriteReqFilename
mapM_ putWord8 msgFileioWriteReqData
msgFileioWriteResp :: Word16
msgFileioWriteResp = 0x00AB
data MsgFileioWriteResp = MsgFileioWriteResp
{ msgFileioWriteRespSequence :: Word32
} deriving ( Show, Read, Eq )
instance Binary MsgFileioWriteResp where
get = do
msgFileioWriteRespSequence <- getWord32le
return MsgFileioWriteResp {..}
put MsgFileioWriteResp {..} = do
putWord32le msgFileioWriteRespSequence
|
hankaiwen/libsbp
|
haskell/src/SwiftNav/SBP/FileIo.hs
|
lgpl-3.0
| 4,461 | 0 | 11 | 714 | 969 | 498 | 471 | -1 | -1 |
-- | Wrapper program for propellor distribution.
--
-- Distributions should install this program into PATH.
-- (Cabal builds it as dist/build/propellor/propellor).
--
-- This is not the propellor main program (that's config.hs)
--
-- This installs propellor's source into ~/.propellor,
-- uses it to build the real propellor program (if not already built),
-- and runs it.
--
-- The source is cloned from /usr/src/propellor when available,
-- or is cloned from git over the network.
module Main where
import Propellor.Message
import Propellor.Bootstrap
import Utility.UserInfo
import Utility.Monad
import Utility.Process
import Utility.SafeCommand
import Utility.Exception
import Control.Monad
import Control.Monad.IfElse
import Control.Applicative
import System.Directory
import System.FilePath
import System.Environment (getArgs)
import System.Exit
import System.Posix.Directory
import System.IO
distdir :: FilePath
distdir = "/usr/src/propellor"
distrepo :: FilePath
distrepo = distdir </> "propellor.git"
disthead :: FilePath
disthead = distdir </> "head"
upstreambranch :: String
upstreambranch = "upstream/master"
-- Using the github mirror of the main propellor repo because
-- it is accessible over https for better security.
netrepo :: String
netrepo = "https://github.com/joeyh/propellor.git"
main :: IO ()
main = do
args <- getArgs
home <- myHomeDir
let propellordir = home </> ".propellor"
let propellorbin = propellordir </> "propellor"
wrapper args propellordir propellorbin
wrapper :: [String] -> FilePath -> FilePath -> IO ()
wrapper args propellordir propellorbin = do
ifM (doesDirectoryExist propellordir)
( checkRepo
, makeRepo
)
buildruncfg
where
makeRepo = do
putStrLn $ "Setting up your propellor repo in " ++ propellordir
putStrLn ""
ifM (doesFileExist distrepo <||> doesDirectoryExist distrepo)
( do
void $ boolSystem "git" [Param "clone", File distrepo, File propellordir]
fetchUpstreamBranch propellordir distrepo
changeWorkingDirectory propellordir
void $ boolSystem "git" [Param "remote", Param "rm", Param "origin"]
, void $ boolSystem "git" [Param "clone", Param netrepo, File propellordir]
)
checkRepo = whenM (doesFileExist disthead <&&> doesFileExist (propellordir </> "propellor.cabal")) $ do
headrev <- takeWhile (/= '\n') <$> readFile disthead
changeWorkingDirectory propellordir
headknown <- catchMaybeIO $
withQuietOutput createProcessSuccess $
proc "git" ["log", headrev]
if (headknown == Nothing)
then setupupstreammaster headrev propellordir
else do
merged <- not . null <$>
readProcess "git" ["log", headrev ++ "..HEAD", "--ancestry-path"]
unless merged $
warnoutofdate propellordir True
buildruncfg = do
changeWorkingDirectory propellordir
buildPropellor
putStrLn ""
putStrLn ""
chain
chain = do
(_, _, _, pid) <- createProcess (proc propellorbin args)
exitWith =<< waitForProcess pid
-- Passed the user's propellordir repository, makes upstream/master
-- be a usefully mergeable branch.
--
-- We cannot just use origin/master, because in the case of a distrepo,
-- it only contains 1 commit. So, trying to merge with it will result
-- in lots of merge conflicts, since git cannot find a common parent
-- commit.
--
-- Instead, the upstream/master branch is created by taking the
-- upstream/master branch (which must be an old version of propellor,
-- as distributed), and diffing from it to the current origin/master,
-- and committing the result. This is done in a temporary clone of the
-- repository, giving it a new master branch. That new branch is fetched
-- into the user's repository, as if fetching from a upstream remote,
-- yielding a new upstream/master branch.
setupupstreammaster :: String -> FilePath -> IO ()
setupupstreammaster newref propellordir = do
changeWorkingDirectory propellordir
go =<< catchMaybeIO getoldrev
where
go Nothing = warnoutofdate propellordir False
go (Just oldref) = do
let tmprepo = ".git/propellordisttmp"
let cleantmprepo = void $ catchMaybeIO $ removeDirectoryRecursive tmprepo
cleantmprepo
git ["clone", "--quiet", ".", tmprepo]
changeWorkingDirectory tmprepo
git ["fetch", distrepo, "--quiet"]
git ["reset", "--hard", oldref, "--quiet"]
git ["merge", newref, "-s", "recursive", "-Xtheirs", "--quiet", "-m", "merging upstream version"]
fetchUpstreamBranch propellordir tmprepo
cleantmprepo
warnoutofdate propellordir True
getoldrev = takeWhile (/= '\n')
<$> readProcess "git" ["show-ref", upstreambranch, "--hash"]
git = run "git"
run cmd ps = unlessM (boolSystem cmd (map Param ps)) $
error $ "Failed to run " ++ cmd ++ " " ++ show ps
warnoutofdate :: FilePath -> Bool -> IO ()
warnoutofdate propellordir havebranch = do
warningMessage ("** Your " ++ propellordir ++ " is out of date..")
let also s = hPutStrLn stderr (" " ++ s)
also ("A newer upstream version is available in " ++ distrepo)
if havebranch
then also ("To merge it, run: git merge " ++ upstreambranch)
else also ("To merge it, find the most recent commit in your repository's history that corresponds to an upstream release of propellor, and set refs/remotes/" ++ upstreambranch ++ " to it. Then run propellor again.")
also ""
fetchUpstreamBranch :: FilePath -> FilePath -> IO ()
fetchUpstreamBranch propellordir repo = do
changeWorkingDirectory propellordir
void $ boolSystem "git"
[ Param "fetch"
, File repo
, Param ("+refs/heads/master:refs/remotes/" ++ upstreambranch)
, Param "--quiet"
]
|
shosti/propellor
|
src/wrapper.hs
|
bsd-2-clause
| 5,539 | 48 | 17 | 945 | 1,231 | 632 | 599 | 111 | 2 |
module Distribution.Server.Features.LegacyRedirects (
legacyRedirectsFeature
) where
import Distribution.Server.Framework
import Distribution.Server.Features.Upload
import Distribution.Package
( PackageIdentifier(..), packageName, PackageId )
import Distribution.Text
( display, simpleParse )
import Data.Version ( Version (..) )
import qualified System.FilePath.Posix as Posix (joinPath, splitExtension)
import Control.Applicative ( (<$>) )
import Control.Monad (msum, mzero)
-- | A feature to provide redirection for URLs that existed in the first
-- incarnation of the hackage server.
--
legacyRedirectsFeature :: UploadFeature -> HackageFeature
legacyRedirectsFeature upload = (emptyHackageFeature "legacy") {
-- get rid of trailing resource and manually create a mapping?
featureResources = [(resourceAt "/..") { resourceGet = [("", \_ -> serveLegacyGets)], resourcePost = [("", \_ -> serveLegacyPosts upload)] }]
}
-- | Support for the old URL scheme from the first version of hackage.
--
-- | POST for package upload, particularly for cabal-install compatibility.
--
-- "check" no longer exists; it's now "candidates", and probably
-- provides too different functionality to redirect
serveLegacyPosts :: UploadFeature -> ServerPart Response
serveLegacyPosts upload = msum
[ dir "packages" $ msum
[ dir "upload" $ movedUpload
--, postedMove "check" "/check"
]
, dir "cgi-bin" $ dir "hackage-scripts" $ msum
[ dir "protected" $ dir "upload" $ movedUpload
--, postedMove "check" "/check"
]
, dir "upload" movedUpload
]
where
-- We assume we don't need to serve a fancy HTML response
movedUpload :: ServerPart Response
movedUpload = nullDir >> do
upResult <- runServerPartE (uploadPackage upload)
ok $ toResponse $ unlines $ uploadWarnings upResult
-- | GETs, both for cabal-install to use, and for links scattered throughout the web.
--
-- method is already guarded against, but methodSP is a nicer combinator than nullDir.
serveLegacyGets :: ServerPart Response
serveLegacyGets = msum
[ dir "packages" $ msum
[ dir "archive" $ serveArchiveTree
, simpleMove "hackage.html" "/"
, simpleMove "00-index.tar.gz" "/packages/index.tar.gz"
--also search.html, advancedsearch.html, accounts.html, and admin.html
]
, dir "cgi-bin" $ dir "hackage-scripts" $ msum
[ dir "package" $ path $ \packageId -> methodSP GET $
movedPermanently ("/package/" ++ display (packageId :: PackageId)) $
toResponse ""
]
]
where
-- HTTP 301 is suitable for permanently redirecting pages
simpleMove from to = dir from $ methodSP GET $ movedPermanently to (toResponse "")
-- Some of the old-style paths may contain a version number
-- or the text 'latest'. We represent the path '$pkgName/latest'
-- as a package id of '$pkgName' in the new url schemes.
data VersionOrLatest
= V Version
| Latest
instance FromReqURI VersionOrLatest where
fromReqURI "latest" = Just Latest
fromReqURI str = V <$> fromReqURI str
volToVersion :: VersionOrLatest -> Version
volToVersion Latest = Version [] []
volToVersion (V v) = v
serveArchiveTree :: ServerPart Response
serveArchiveTree = msum
[ dir "pkg-list.html" $ methodSP GET $ movedPermanently "/packages/" (toResponse "")
, dir "package" $ path $ \fileName -> methodSP GET $
case Posix.splitExtension fileName of
(fileName', ".gz") -> case Posix.splitExtension fileName' of
(packageStr, ".tar") -> case simpleParse packageStr of
Just pkgid ->
movedPermanently (packageTarball pkgid) $ toResponse ""
_ -> mzero
_ -> mzero
_ -> mzero
, dir "00-index.tar.gz" $ methodSP GET $ movedPermanently "/packages/index.tar.gz" (toResponse "")
, path $ \name -> do
msum
[ path $ \version ->
let pkgid = PackageIdentifier {pkgName = name, pkgVersion = volToVersion version}
in msum
[ let dirName = display pkgid ++ ".tar.gz"
in dir dirName $ methodSP GET $
movedPermanently (packageTarball pkgid) (toResponse "")
, let fileName = display name ++ ".cabal"
in dir fileName $ methodSP GET $
movedPermanently (cabalPath pkgid) (toResponse "")
, dir "doc" $ dir "html" $ remainingPath $ \paths ->
let doc = Posix.joinPath paths
in methodSP GET $
movedPermanently (docPath pkgid doc) (toResponse "")
]
]
]
where
packageTarball :: PackageId -> String
packageTarball pkgid = "/package/" ++ display pkgid ++ "/" ++ display pkgid ++ ".tar.gz"
docPath pkgid file = "/package/" ++ display pkgid ++ "/" ++ "doc/" ++ file
cabalPath pkgid = "/package/" ++ display pkgid ++ "/"
++ display (packageName pkgid) ++ ".cabal"
|
isomorphism/hackage2
|
Distribution/Server/Features/LegacyRedirects.hs
|
bsd-3-clause
| 4,891 | 0 | 26 | 1,133 | 1,144 | 592 | 552 | 79 | 4 |
-- -----------------------------------------------------------------------------
--
-- Output.hs, part of Alex
--
-- (c) Simon Marlow 2003
--
-- Code-outputing and table-generation routines
--
-- ----------------------------------------------------------------------------}
module Output (outputDFA) where
import AbsSyn
import CharSet
import Util
import qualified Map
import qualified Data.IntMap as IntMap
import Control.Monad.ST ( ST, runST )
import Data.Array ( Array )
import Data.Array.Base ( unsafeRead )
import Data.Array.ST ( STUArray, newArray, readArray, writeArray, freeze )
import Data.Array.Unboxed ( UArray, elems, (!), array, listArray )
import Data.Maybe (isJust)
import Data.Bits
import Data.Char ( ord, chr )
import Data.List ( maximumBy, sortBy, groupBy, mapAccumR )
-- -----------------------------------------------------------------------------
-- Printing the output
outputDFA :: Target -> Int -> String -> Scheme -> DFA SNum Code -> ShowS
outputDFA target _ _ scheme dfa
= interleave_shows nl
[outputBase, outputTable, outputCheck, outputDefault,
outputAccept, outputActions, outputSigs]
where
(base, table, check, deflt, accept) = mkTables dfa
intty = case target of
GhcTarget -> "Int#"
HaskellTarget -> "Int"
table_size = length table - 1
n_states = length base - 1
base_nm = "alex_base"
table_nm = "alex_table"
check_nm = "alex_check"
deflt_nm = "alex_deflt"
accept_nm = "alex_accept"
actions_nm = "alex_actions"
outputBase = do_array hexChars32 base_nm n_states base
outputTable = do_array hexChars16 table_nm table_size table
outputCheck = do_array hexChars16 check_nm table_size check
outputDefault = do_array hexChars16 deflt_nm n_states deflt
formatArray :: String -> Int -> [ShowS] -> ShowS
formatArray constructFunction size contents =
str constructFunction
. str " (0 :: Int, " . shows size . str ")\n"
. str " [ "
. interleave_shows (str "\n , ") contents
. str "\n ]"
do_array hex_chars nm upper_bound ints = -- trace ("do_array: " ++ nm) $
case target of
GhcTarget ->
str nm . str " :: AlexAddr\n"
. str nm . str " = AlexA#\n"
. str " \"" . str (hex_chars ints) . str "\"#\n"
_ ->
str nm . str " :: Array Int Int\n"
. str nm . str " = "
. formatArray "listArray" upper_bound (map shows ints)
. nl
outputAccept :: ShowS
outputAccept =
-- Don't emit explicit type signature as it contains unknown user type,
-- see: https://github.com/simonmar/alex/issues/98
-- str accept_nm . str " :: Array Int (AlexAcc " . str userStateTy . str ")\n"
str accept_nm . str " = "
. formatArray "listArray" n_states (snd (mapAccumR outputAccs 0 accept))
. nl
gscanActionType res =
str "AlexPosn -> Char -> String -> Int -> ((Int, state) -> "
. str res . str ") -> (Int, state) -> " . str res
outputActions = signature . body
where
(nacts, acts) = mapAccumR outputActs 0 accept
actionsArray :: ShowS
actionsArray = formatArray "array" nacts (concat acts)
body :: ShowS
body = str actions_nm . str " = " . actionsArray . nl
signature :: ShowS
signature = case scheme of
Default { defaultTypeInfo = Just (Nothing, actionty) } ->
str actions_nm . str " :: Array Int (" . str actionty . str ")\n"
Default { defaultTypeInfo = Just (Just tyclasses, actionty) } ->
str actions_nm . str " :: (" . str tyclasses
. str ") => Array Int (" . str actionty . str ")\n"
GScan { gscanTypeInfo = Just (Nothing, toktype) } ->
str actions_nm . str " :: Array Int ("
. gscanActionType toktype . str ")\n"
GScan { gscanTypeInfo = Just (Just tyclasses, toktype) } ->
str actions_nm . str " :: (" . str tyclasses
. str ") => Array Int ("
. gscanActionType toktype . str ")\n"
Basic { basicStrType = strty,
basicTypeInfo = Just (Nothing, toktype) } ->
str actions_nm . str " :: Array Int ("
. str (show strty) . str " -> " . str toktype
. str ")\n"
Basic { basicStrType = strty,
basicTypeInfo = Just (Just tyclasses, toktype) } ->
str actions_nm . str " :: (" . str tyclasses
. str ") => Array Int ("
. str (show strty) . str " -> " . str toktype
. str ")\n"
Posn { posnByteString = isByteString,
posnTypeInfo = Just (Nothing, toktype) } ->
str actions_nm . str " :: Array Int (AlexPosn -> "
. str (strtype isByteString) . str " -> " . str toktype
. str ")\n"
Posn { posnByteString = isByteString,
posnTypeInfo = Just (Just tyclasses, toktype) } ->
str actions_nm . str " :: (" . str tyclasses
. str ") => Array Int (AlexPosn -> "
. str (strtype isByteString) . str " -> " . str toktype
. str ")\n"
Monad { monadByteString = isByteString,
monadTypeInfo = Just (Nothing, toktype) } ->
let
actintty = if isByteString then "Int64" else "Int"
in
str actions_nm . str " :: Array Int (AlexInput -> "
. str actintty . str " -> Alex(" . str toktype . str "))\n"
Monad { monadByteString = isByteString,
monadTypeInfo = Just (Just tyclasses, toktype) } ->
let
actintty = if isByteString then "Int64" else "Int"
in
str actions_nm . str " :: (" . str tyclasses
. str ") => Array Int (AlexInput -> "
. str actintty . str " -> Alex(" . str toktype . str "))\n"
_ ->
-- No type signature: we don't know what the type of the actions is.
-- str accept_nm . str " :: Array Int (Accept Code)\n"
id
outputSigs
= case scheme of
Default { defaultTypeInfo = Just (Nothing, toktype) } ->
str "alex_scan_tkn :: () -> AlexInput -> " . str intty
. str " -> " . str "AlexInput -> " . str intty
. str " -> AlexLastAcc -> (AlexLastAcc, AlexInput)\n"
. str "alexScanUser :: () -> AlexInput -> Int -> AlexReturn ("
. str toktype . str ")\n"
. str "alexScan :: AlexInput -> Int -> AlexReturn ("
. str toktype . str ")\n"
Default { defaultTypeInfo = Just (Just tyclasses, toktype) } ->
str "alex_scan_tkn :: () -> AlexInput -> " . str intty
. str " -> " . str "AlexInput -> " . str intty
. str " -> AlexLastAcc -> (AlexLastAcc, AlexInput)\n"
. str "alexScanUser :: (" . str tyclasses
. str ") => () -> AlexInput -> Int -> AlexReturn ("
. str toktype . str ")\n"
. str "alexScan :: (" . str tyclasses
. str ") => AlexInput -> Int -> AlexReturn ("
. str toktype . str ")\n"
GScan { gscanTypeInfo = Just (Nothing, toktype) } ->
str "alex_scan_tkn :: () -> AlexInput -> " . str intty
. str " -> " . str "AlexInput -> " . str intty
. str " -> AlexLastAcc -> (AlexLastAcc, AlexInput)\n"
. str "alexScanUser :: () -> AlexInput -> Int -> "
. str "AlexReturn (" . gscanActionType toktype . str ")\n"
. str "alexScan :: AlexInput -> Int -> AlexReturn ("
. gscanActionType toktype . str ")\n"
GScan { gscanTypeInfo = Just (Just tyclasses, toktype) } ->
str "alex_scan_tkn :: () -> AlexInput -> " . str intty
. str " -> " . str "AlexInput -> " . str intty
. str " -> AlexLastAcc -> (AlexLastAcc, AlexInput)\n"
. str "alexScanUser :: (" . str tyclasses
. str ") => () -> AlexInput -> Int -> AlexReturn ("
. gscanActionType toktype . str ")\n"
. str "alexScan :: (" . str tyclasses
. str ") => AlexInput -> Int -> AlexReturn ("
. gscanActionType toktype . str ")\n"
Basic { basicStrType = strty,
basicTypeInfo = Just (Nothing, toktype) } ->
str "alex_scan_tkn :: () -> AlexInput -> " . str intty
. str " -> " . str "AlexInput -> " . str intty
. str " -> AlexLastAcc -> (AlexLastAcc, AlexInput)\n"
. str "alexScanUser :: () -> AlexInput -> Int -> AlexReturn ("
. str (show strty) . str " -> " . str toktype . str ")\n"
. str "alexScan :: AlexInput -> Int -> AlexReturn ("
. str (show strty) . str " -> " . str toktype . str ")\n"
Basic { basicStrType = strty,
basicTypeInfo = Just (Just tyclasses, toktype) } ->
str "alex_scan_tkn :: () -> AlexInput -> " . str intty
. str " -> " . str "AlexInput -> " . str intty
. str " -> AlexLastAcc -> (AlexLastAcc, AlexInput)\n"
. str "alexScanUser :: (" . str tyclasses
. str ") => () -> AlexInput -> Int -> AlexReturn ("
. str (show strty) . str " -> " . str toktype . str ")\n"
. str "alexScan :: (" . str tyclasses
. str ") => AlexInput -> Int -> AlexReturn ("
. str (show strty) . str " -> " . str toktype . str ")\n"
Posn { posnByteString = isByteString,
posnTypeInfo = Just (Nothing, toktype) } ->
str "alex_scan_tkn :: () -> AlexInput -> " . str intty
. str " -> " . str "AlexInput -> " . str intty
. str " -> AlexLastAcc -> (AlexLastAcc, AlexInput)\n"
. str "alexScanUser :: () -> AlexInput -> Int -> AlexReturn (AlexPosn -> "
. str (strtype isByteString) . str " -> " . str toktype . str ")\n"
. str "alexScan :: AlexInput -> Int -> AlexReturn (AlexPosn -> "
. str (strtype isByteString) . str " -> " . str toktype . str ")\n"
Posn { posnByteString = isByteString,
posnTypeInfo = Just (Just tyclasses, toktype) } ->
str "alex_scan_tkn :: () -> AlexInput -> " . str intty
. str " -> " . str "AlexInput -> " . str intty
. str " -> AlexLastAcc -> (AlexLastAcc, AlexInput)\n"
. str "alexScanUser :: (" . str tyclasses
. str ") => () -> AlexInput -> Int -> AlexReturn (AlexPosn -> "
. str (strtype isByteString) . str " -> " . str toktype . str ")\n"
. str "alexScan :: (" . str tyclasses
. str ") => AlexInput -> Int -> AlexReturn (AlexPosn -> "
. str (strtype isByteString) . str " -> " . str toktype . str ")\n"
Monad { monadTypeInfo = Just (Nothing, toktype),
monadByteString = isByteString,
monadUserState = userState } ->
let
actintty = if isByteString then "Int64" else "Int"
userStateTy | userState = "AlexUserState"
| otherwise = "()"
in
str "alex_scan_tkn :: " . str userStateTy
. str " -> AlexInput -> " . str intty
. str " -> " . str "AlexInput -> " . str intty
. str " -> AlexLastAcc -> (AlexLastAcc, AlexInput)\n"
. str "alexScanUser :: " . str userStateTy
. str " -> AlexInput -> Int -> AlexReturn ("
. str "AlexInput -> " . str actintty . str " -> Alex ("
. str toktype . str "))\n"
. str "alexScan :: AlexInput -> Int -> AlexReturn ("
. str "AlexInput -> " . str actintty
. str " -> Alex (" . str toktype . str "))\n"
. str "alexMonadScan :: Alex (" . str toktype . str ")\n"
Monad { monadTypeInfo = Just (Just tyclasses, toktype),
monadByteString = isByteString,
monadUserState = userState } ->
let
actintty = if isByteString then "Int64" else "Int"
userStateTy | userState = "AlexUserState"
| otherwise = "()"
in
str "alex_scan_tkn :: " . str userStateTy
. str " -> AlexInput -> " . str intty
. str " -> " . str "AlexInput -> " . str intty
. str " -> AlexLastAcc -> (AlexLastAcc, AlexInput)\n"
. str "alexScanUser :: (" . str tyclasses . str ") => "
. str userStateTy . str " -> AlexInput -> Int -> AlexReturn ("
. str "AlexInput -> " . str actintty
. str " -> Alex (" . str toktype . str "))\n"
. str "alexScan :: (" . str tyclasses
. str ") => AlexInput -> Int -> AlexReturn ("
. str "AlexInput -> " . str actintty
. str " -> Alex (" . str toktype . str "))\n"
. str "alexMonadScan :: (" . str tyclasses
. str ") => Alex (" . str toktype . str ")\n"
_ ->
str ""
outputAccs :: Int -> [Accept Code] -> (Int, ShowS)
outputAccs idx [] = (idx, str "AlexAccNone")
outputAccs idx (Acc _ Nothing Nothing NoRightContext : [])
= (idx, str "AlexAccSkip")
outputAccs idx (Acc _ (Just _) Nothing NoRightContext : [])
= (idx + 1, str "AlexAcc " . str (show idx))
outputAccs idx (Acc _ Nothing lctx rctx : rest)
= let (idx', rest') = outputAccs idx rest
in (idx', str "AlexAccSkipPred" . space
. paren (outputPred lctx rctx)
. paren rest')
outputAccs idx (Acc _ (Just _) lctx rctx : rest)
= let (idx', rest') = outputAccs idx rest
in (idx' + 1, str "AlexAccPred" . space
. str (show idx') . space
. paren (outputPred lctx rctx)
. paren rest')
outputActs :: Int -> [Accept Code] -> (Int, [ShowS])
outputActs idx =
let
outputAct _ (Acc _ Nothing _ _) = error "Shouldn't see this"
outputAct inneridx (Acc _ (Just act) _ _) =
(inneridx + 1, paren (shows inneridx . str "," . str act))
in
mapAccumR outputAct idx . filter (\(Acc _ act _ _) -> isJust act)
outputPred (Just set) NoRightContext
= outputLCtx set
outputPred Nothing rctx
= outputRCtx rctx
outputPred (Just set) rctx
= outputLCtx set
. str " `alexAndPred` "
. outputRCtx rctx
outputLCtx set = str "alexPrevCharMatches" . str (charSetQuote set)
outputRCtx NoRightContext = id
outputRCtx (RightContextRExp sn)
= str "alexRightContext " . shows sn
outputRCtx (RightContextCode code)
= str code
-- outputArr arr
-- = str "array " . shows (bounds arr) . space
-- . shows (assocs arr)
-- -----------------------------------------------------------------------------
-- Generating arrays.
-- Here we use the table-compression algorithm described in section
-- 3.9 of the dragon book, which is a common technique used by lexical
-- analyser generators.
-- We want to generate:
--
-- base :: Array SNum Int
-- maps the current state to an offset in the main table
--
-- table :: Array Int SNum
-- maps (base!state + char) to the next state
--
-- check :: Array Int SNum
-- maps (base!state + char) to state if table entry is valid,
-- otherwise we use the default for this state
--
-- default :: Array SNum SNum
-- default production for this state
--
-- accept :: Array SNum [Accept Code]
-- maps state to list of accept codes for this state
--
-- For each state, we decide what will be the default symbol (pick the
-- most common). We now have a mapping Char -> SNum, with one special
-- state reserved as the default.
mkTables :: DFA SNum Code
-> (
[Int], -- base
[Int], -- table
[Int], -- check
[Int], -- default
[[Accept Code]] -- accept
)
mkTables dfa = -- trace (show (defaults)) $
-- trace (show (fmap (length . snd) dfa_no_defaults)) $
( elems base_offs,
take max_off (elems table),
take max_off (elems check),
elems defaults,
accept
)
where
accept = [ as | State as _ <- elems dfa_arr ]
state_assocs = Map.toAscList (dfa_states dfa)
n_states = length state_assocs
top_state = n_states - 1
dfa_arr :: Array SNum (State SNum Code)
dfa_arr = array (0,top_state) state_assocs
-- fill in all the error productions
expand_states =
[ expand (dfa_arr!state) | state <- [0..top_state] ]
expand (State _ out) =
[(i, lookup' out i) | i <- [0..0xff]]
where lookup' out' i = case IntMap.lookup i out' of
Nothing -> -1
Just s -> s
defaults :: UArray SNum SNum
defaults = listArray (0,top_state) (map best_default expand_states)
-- find the most common destination state in a given state, and
-- make it the default.
best_default :: [(Int,SNum)] -> SNum
best_default prod_list
| null sorted = -1
| otherwise = snd (head (maximumBy lengths eq))
where sorted = sortBy compareSnds prod_list
compareSnds (_,a) (_,b) = compare a b
eq = groupBy (\(_,a) (_,b) -> a == b) sorted
lengths a b = length a `compare` length b
-- remove all the default productions from the DFA
dfa_no_defaults =
[ (s, prods_without_defaults s out)
| (s, out) <- zip [0..] expand_states
]
prods_without_defaults s out
= [ (fromIntegral c, dest) | (c,dest) <- out, dest /= defaults!s ]
(base_offs, table, check, max_off)
= runST (genTables n_states 255 dfa_no_defaults)
genTables
:: Int -- number of states
-> Int -- maximum token no.
-> [(SNum,[(Int,SNum)])] -- entries for the table
-> ST s (UArray Int Int, -- base
UArray Int Int, -- table
UArray Int Int, -- check
Int -- highest offset in table
)
genTables n_states max_token entries = do
base <- newArray (0, n_states-1) 0
table <- newArray (0, mAX_TABLE_SIZE) 0
check <- newArray (0, mAX_TABLE_SIZE) (-1)
off_arr <- newArray (-max_token, mAX_TABLE_SIZE) 0
max_off <- genTables' base table check off_arr entries max_token
base' <- freeze base
table' <- freeze table
check' <- freeze check
return (base', table',check',max_off+1)
where mAX_TABLE_SIZE = n_states * (max_token + 1)
genTables'
:: STUArray s Int Int -- base
-> STUArray s Int Int -- table
-> STUArray s Int Int -- check
-> STUArray s Int Int -- offset array
-> [(SNum,[(Int,SNum)])] -- entries for the table
-> Int -- maximum token no.
-> ST s Int -- highest offset in table
genTables' base table check off_arr entries max_token
= fit_all entries 0 1
where
fit_all [] max_off _ = return max_off
fit_all (s:ss) max_off fst_zero = do
(off, new_max_off, new_fst_zero) <- fit s max_off fst_zero
writeArray off_arr off 1
fit_all ss new_max_off new_fst_zero
-- fit a vector into the table. Return the offset of the vector,
-- the maximum offset used in the table, and the offset of the first
-- entry in the table (used to speed up the lookups a bit).
fit (_,[]) max_off fst_zero = return (0,max_off,fst_zero)
fit (state_no, state@((t,_):_)) max_off fst_zero = do
-- start at offset 1 in the table: all the empty states
-- (states with just a default reduction) are mapped to
-- offset zero.
off <- findFreeOffset (-t + fst_zero) check off_arr state
let new_max_off | furthest_right > max_off = furthest_right
| otherwise = max_off
furthest_right = off + max_token
--trace ("fit: state " ++ show state_no ++ ", off " ++ show off ++ ", elems " ++ show state) $ do
writeArray base state_no off
addState off table check state
new_fst_zero <- findFstFreeSlot check fst_zero
return (off, new_max_off, new_fst_zero)
-- Find a valid offset in the table for this state.
findFreeOffset :: Int
-> STUArray s Int Int
-> STUArray s Int Int
-> [(Int, Int)]
-> ST s Int
findFreeOffset off check off_arr state = do
-- offset 0 isn't allowed
if off == 0 then try_next else do
-- don't use an offset we've used before
b <- readArray off_arr off
if b /= 0 then try_next else do
-- check whether the actions for this state fit in the table
ok <- fits off state check
if ok then return off else try_next
where
try_next = findFreeOffset (off+1) check off_arr state
-- This is an inner loop, so we use some strictness hacks, and avoid
-- array bounds checks (unsafeRead instead of readArray) to speed
-- things up a bit.
fits :: Int -> [(Int,Int)] -> STUArray s Int Int -> ST s Bool
fits off [] check = off `seq` check `seq` return True -- strictness hacks
fits off ((t,_):rest) check = do
i <- unsafeRead check (off+t)
if i /= -1 then return False
else fits off rest check
addState :: Int -> STUArray s Int Int -> STUArray s Int Int -> [(Int, Int)]
-> ST s ()
addState _ _ _ [] = return ()
addState off table check ((t,val):state) = do
writeArray table (off+t) val
writeArray check (off+t) t
addState off table check state
findFstFreeSlot :: STUArray s Int Int -> Int -> ST s Int
findFstFreeSlot table n = do
i <- readArray table n
if i == -1 then return n
else findFstFreeSlot table (n+1)
-----------------------------------------------------------------------------
-- Convert an integer to a 16-bit number encoded in \xNN\xNN format suitable
-- for placing in a string (copied from Happy's ProduceCode.lhs)
hexChars16 :: [Int] -> String
hexChars16 acts = concat (map conv16 acts)
where
conv16 i | i > 0x7fff || i < -0x8000
= error ("Internal error: hexChars16: out of range: " ++ show i)
| otherwise
= hexChar16 i
hexChars32 :: [Int] -> String
hexChars32 acts = concat (map conv32 acts)
where
conv32 i = hexChar16 (i .&. 0xffff) ++
hexChar16 ((i `shiftR` 16) .&. 0xffff)
hexChar16 :: Int -> String
hexChar16 i = toHex (i .&. 0xff)
++ toHex ((i `shiftR` 8) .&. 0xff) -- force little-endian
toHex :: Int -> String
toHex i = ['\\','x', hexDig (i `div` 16), hexDig (i `mod` 16)]
hexDig :: Int -> Char
hexDig i | i <= 9 = chr (i + ord '0')
| otherwise = chr (i - 10 + ord 'a')
|
alanz/Alex
|
src/Output.hs
|
bsd-3-clause
| 23,475 | 0 | 42 | 8,042 | 6,045 | 3,018 | 3,027 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude, MagicHash, MultiParamTypeClasses,
UnboxedTuples, BangPatterns, FlexibleInstances,
FlexibleContexts, UndecidableInstances, DefaultSignatures,
DeriveAnyClass, FunctionalDependencies, StandaloneDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : Java.Array
-- Copyright : (c) Rahul Muttineni 2016-2017
--
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Dealing with native Java arrays.
--
-----------------------------------------------------------------------------
module Java.Array
( JByteArray(..),
JShortArray(..),
JCharArray(..),
JIntArray(..),
JLongArray(..),
JFloatArray(..),
JDoubleArray(..),
JStringArray(..),
JObjectArray(..),
JArray(..),
alength,
arrayToList,
arrayFromList
)
where
import GHC.Base
import GHC.Int
import GHC.List
import GHC.Num
import GHC.Real
import GHC.Show
import GHC.Word
import Java.Core
import Java.Primitive
import Java.Utils
class (Class c) => JArray e c | c -> e, e -> c where
anew :: Int -> Java a c
default anew :: (Class e) => Int -> Java a c
{-# INLINE anew #-}
anew (I# n#) = Java $ \o ->
case jobjectArrayNew# n# realWorld# of
(# _, o' #) -> case obj o' of
c -> (# o, c #)
aget :: Int -> Java c e
default aget :: (Class e) => Int -> Java c e
{-# INLINE aget #-}
aget (I# n#) = Java $ \o ->
case jobjectArrayAt# o n# realWorld# of
(# _, o' #) -> case obj o' of
o'' -> (# o, o'' #)
aset :: Int -> e -> Java c ()
default aset :: (Class e) => Int -> e -> Java c ()
{-# INLINE aset #-}
aset (I# n#) e = Java $ \o ->
case jobjectArraySet# o n# (unobj e) realWorld# of
_ -> (# o, () #)
data {-# CLASS "boolean[]" #-} JBooleanArray = JBooleanArray (Object# JBooleanArray)
deriving (Class, Show)
instance JArray Bool JBooleanArray where
anew (I# n#) = Java $ \o ->
case newJBooleanArray# n# realWorld# of
(# _, o' #) -> case obj o' of
c -> (# o, c #)
aget (I# n#) = Java $ \o ->
case readJBooleanArray# o n# realWorld# of
(# _, i# #) -> (# o, isTrue# i# #)
aset (I# n#) b = Java $ \o ->
case writeJBooleanArray# o n# (dataToTag# b) realWorld# of
_ -> (# o, () #)
deriving instance Class JByteArray
instance JArray Byte JByteArray where
anew (I# n#) = Java $ \o ->
case newJByteArray# n# realWorld# of
(# _, o' #) -> case obj o' of
c -> (# o, c #)
aget (I# n#) = Java $ \o ->
case readJByteArray# o n# realWorld# of
(# _, b #) -> (# o, B# b #)
aset (I# n#) (B# e#) = Java $ \o ->
case writeJByteArray# o n# e# realWorld# of
_ -> (# o, () #)
instance JavaConverter [Word8] JByteArray where
toJava ws = pureJava $ arrayFromList bytes
where bytes = map fromIntegral ws :: [Byte]
fromJava ba = map fromIntegral $ pureJavaWith ba arrayToList
instance JavaConverter [Int8] JByteArray where
toJava ws = pureJava $ arrayFromList bytes
where bytes = map fromIntegral ws :: [Byte]
fromJava ba = map fromIntegral $ pureJavaWith ba arrayToList
data {-# CLASS "char[]" #-} JCharArray = JCharArray (Object# JCharArray)
deriving (Class, Show)
instance JArray JChar JCharArray where
anew (I# n#) = Java $ \o ->
case newJCharArray# n# realWorld# of
(# _, o' #) -> case obj o' of
c -> (# o, c #)
aget (I# n#) = Java $ \o ->
case readJCharArray# o n# realWorld# of
(# _, e# #) -> (# o, JC# e# #)
aset (I# n#) (JC# e#) = Java $ \o ->
case writeJCharArray# o n# e# realWorld# of
_ -> (# o, () #)
data {-# CLASS "short[]" #-} JShortArray = JShortArray (Object# JShortArray)
deriving (Class, Show)
instance JArray Short JShortArray where
anew (I# n#) = Java $ \o ->
case newJShortArray# n# realWorld# of
(# _, o' #) -> case obj o' of
c -> (# o, c #)
aget (I# n#) = Java $ \o ->
case readJShortArray# o n# realWorld# of
(# _, e# #) -> (# o, S# e# #)
aset (I# n#) (S# e#) = Java $ \o ->
case writeJShortArray# o n# e# realWorld# of
_ -> (# o, () #)
instance JavaConverter [Word16] JShortArray where
toJava ws = pureJava $ arrayFromList bytes
where bytes = map fromIntegral ws :: [Short]
fromJava ba = map fromIntegral $ pureJavaWith ba arrayToList
instance JavaConverter [Int16] JShortArray where
toJava ws = pureJava $ arrayFromList bytes
where bytes = map fromIntegral ws :: [Short]
fromJava ba = map fromIntegral $ pureJavaWith ba arrayToList
data {-# CLASS "int[]" #-} JIntArray = JIntArray (Object# JIntArray)
deriving (Class, Show)
instance JArray Int JIntArray where
anew (I# n#) = Java $ \o ->
case newJIntArray# n# realWorld# of
(# _, o' #) -> case obj o' of
c -> (# o, c #)
aget (I# n#) = Java $ \o ->
case readJIntArray# o n# realWorld# of
(# _, e# #) -> (# o, I# e# #)
aset (I# n#) (I# e#) = Java $ \o ->
case writeJIntArray# o n# e# realWorld# of
_ -> (# o, () #)
instance JavaConverter [Word32] JIntArray where
toJava ws = pureJava $ arrayFromList bytes
where bytes = map fromIntegral ws :: [Int]
fromJava ba = map fromIntegral $ pureJavaWith ba arrayToList
instance JavaConverter [Int32] JIntArray where
toJava ws = pureJava $ arrayFromList bytes
where bytes = map fromIntegral ws :: [Int]
fromJava ba = map fromIntegral $ pureJavaWith ba arrayToList
data {-# CLASS "long[]" #-} JLongArray = JLongArray (Object# JLongArray)
deriving (Class, Show)
instance JArray Int64 JLongArray where
anew (I# n#) = Java $ \o ->
case newJLongArray# n# realWorld# of
(# _, o' #) -> case obj o' of
c -> (# o, c #)
aget (I# n#) = Java $ \o ->
case readJLongArray# o n# realWorld# of
(# _, e# #) -> (# o, I64# e# #)
aset (I# n#) (I64# e#) = Java $ \o ->
case writeJLongArray# o n# e# realWorld# of
_ -> (# o, () #)
instance JavaConverter [Word64] JLongArray where
toJava ws = pureJava $ arrayFromList bytes
where bytes = map fromIntegral ws :: [Int64]
fromJava ba = map fromIntegral $ pureJavaWith ba arrayToList
data {-# CLASS "float[]" #-} JFloatArray = JFloatArray (Object# JFloatArray)
deriving (Class, Show)
instance JArray Float JFloatArray where
anew (I# n#) = Java $ \o ->
case newJFloatArray# n# realWorld# of
(# _, o' #) -> case obj o' of
c -> (# o, c #)
aget (I# n#) = Java $ \o ->
case readJFloatArray# o n# realWorld# of
(# _, e# #) -> (# o, F# e# #)
aset (I# n#) (F# e#) = Java $ \o ->
case writeJFloatArray# o n# e# realWorld# of
_ -> (# o, () #)
data {-# CLASS "double[]" #-} JDoubleArray = JDoubleArray (Object# JDoubleArray)
deriving (Class, Show)
instance JArray Double JDoubleArray where
anew (I# n#) = Java $ \o ->
case newJDoubleArray# n# realWorld# of
(# _, o' #) -> case obj o' of
c -> (# o, c #)
aget (I# n#) = Java $ \o ->
case readJDoubleArray# o n# realWorld# of
(# _, e# #) -> (# o, D# e# #)
aset (I# n#) (D# e#) = Java $ \o ->
case writeJDoubleArray# o n# e# realWorld# of
_ -> (# o, () #)
data {-# CLASS "java.lang.String[]" #-} JStringArray = JStringArray (Object# JStringArray)
deriving (Class, Show)
instance JArray JString JStringArray
instance JavaConverter [String] JStringArray where
toJava ws = pureJava $ arrayFromList bytes
where bytes = map toJava ws :: [JString]
fromJava ba = map fromJava $ pureJavaWith ba arrayToList
data {-# CLASS "java.lang.Object[]" #-} JObjectArray = JObjectArray (Object# JObjectArray)
deriving (Class, Show)
instance JArray Object JObjectArray
{-# INLINE alength #-}
alength :: JArray e c => Java c Int
alength = Java $ \o -> (# o, I# (alength# o) #)
{-# INLINE arrayToList #-}
arrayToList :: JArray e c => Java c [e]
arrayToList = do
len <- alength
go (len - 1) []
where go n xs
| n >= 0 = do
x <- aget n
go (n - 1) (x:xs)
| otherwise = return xs
{-# INLINE arrayFromList #-}
arrayFromList :: JArray e c => [e] -> Java a c
arrayFromList xs = do
jarray <- anew (length xs)
jarray <.> go 0 xs
return jarray
where go _ [] = return ()
go !n (x:xs) = aset n x >> go (n + 1) xs
instance {-# OVERLAPS #-} (JArray e c) => JavaConverter [e] c where
toJava xs = pureJava $ arrayFromList xs
fromJava c = pureJavaWith c arrayToList
{-# INLINE toJava #-}
{-# INLINE fromJava #-}
|
pparkkin/eta
|
libraries/base/Java/Array.hs
|
bsd-3-clause
| 8,615 | 0 | 15 | 2,200 | 3,089 | 1,602 | 1,487 | 216 | 2 |
{-# LANGUAGE CPP, FlexibleInstances, Rank2Types, BangPatterns #-}
-- |
-- Module : Data.Vector.Fusion.Bundle
-- Copyright : (c) Roman Leshchinskiy 2008-2010
-- License : BSD-style
--
-- Maintainer : Roman Leshchinskiy <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Bundles for stream fusion
--
module Data.Vector.Fusion.Bundle (
-- * Types
Step(..), Chunk(..), Bundle, MBundle,
-- * In-place markers
inplace,
-- * Size hints
size, sized,
-- * Length information
length, null,
-- * Construction
empty, singleton, cons, snoc, replicate, generate, (++),
-- * Accessing individual elements
head, last, (!!), (!?),
-- * Substreams
slice, init, tail, take, drop,
-- * Mapping
map, concatMap, flatten, unbox,
-- * Zipping
indexed, indexedR,
zipWith, zipWith3, zipWith4, zipWith5, zipWith6,
zip, zip3, zip4, zip5, zip6,
-- * Filtering
filter, takeWhile, dropWhile,
-- * Searching
elem, notElem, find, findIndex,
-- * Folding
foldl, foldl1, foldl', foldl1', foldr, foldr1,
-- * Specialised folds
and, or,
-- * Unfolding
unfoldr, unfoldrN, iterateN,
-- * Scans
prescanl, prescanl',
postscanl, postscanl',
scanl, scanl',
scanl1, scanl1',
-- * Enumerations
enumFromStepN, enumFromTo, enumFromThenTo,
-- * Conversions
toList, fromList, fromListN, unsafeFromList, lift,
fromVector, reVector, fromVectors, concatVectors,
-- * Monadic combinators
mapM, mapM_, zipWithM, zipWithM_, filterM, foldM, fold1M, foldM', fold1M',
eq, cmp, eqBy, cmpBy
) where
import Data.Vector.Generic.Base ( Vector )
import Data.Vector.Fusion.Bundle.Size
import Data.Vector.Fusion.Util
import Data.Vector.Fusion.Stream.Monadic ( Stream(..), Step(..) )
import Data.Vector.Fusion.Bundle.Monadic ( Chunk(..) )
import qualified Data.Vector.Fusion.Bundle.Monadic as M
import qualified Data.Vector.Fusion.Stream.Monadic as S
import Prelude hiding ( length, null,
replicate, (++),
head, last, (!!),
init, tail, take, drop,
map, concatMap,
zipWith, zipWith3, zip, zip3,
filter, takeWhile, dropWhile,
elem, notElem,
foldl, foldl1, foldr, foldr1,
and, or,
scanl, scanl1,
enumFromTo, enumFromThenTo,
mapM, mapM_ )
#if MIN_VERSION_base(4,9,0)
import Data.Functor.Classes (Eq1 (..), Ord1 (..))
#endif
import GHC.Base ( build )
-- Data.Vector.Internal.Check is unused
#define NOT_VECTOR_MODULE
#include "vector.h"
-- | The type of pure streams
type Bundle = M.Bundle Id
-- | Alternative name for monadic streams
type MBundle = M.Bundle
inplace :: (forall m. Monad m => S.Stream m a -> S.Stream m b)
-> (Size -> Size) -> Bundle v a -> Bundle v b
{-# INLINE_FUSED inplace #-}
inplace f g b = b `seq` M.fromStream (f (M.elements b)) (g (M.size b))
{-# RULES
"inplace/inplace [Vector]"
forall (f1 :: forall m. Monad m => S.Stream m a -> S.Stream m a)
(f2 :: forall m. Monad m => S.Stream m a -> S.Stream m a)
g1 g2 s.
inplace f1 g1 (inplace f2 g2 s) = inplace (f1 . f2) (g1 . g2) s #-}
-- | Convert a pure stream to a monadic stream
lift :: Monad m => Bundle v a -> M.Bundle m v a
{-# INLINE_FUSED lift #-}
lift (M.Bundle (Stream step s) (Stream vstep t) v sz)
= M.Bundle (Stream (return . unId . step) s)
(Stream (return . unId . vstep) t) v sz
-- | 'Size' hint of a 'Bundle'
size :: Bundle v a -> Size
{-# INLINE size #-}
size = M.size
-- | Attach a 'Size' hint to a 'Bundle'
sized :: Bundle v a -> Size -> Bundle v a
{-# INLINE sized #-}
sized = M.sized
-- Length
-- ------
-- | Length of a 'Bundle'
length :: Bundle v a -> Int
{-# INLINE length #-}
length = unId . M.length
-- | Check if a 'Bundle' is empty
null :: Bundle v a -> Bool
{-# INLINE null #-}
null = unId . M.null
-- Construction
-- ------------
-- | Empty 'Bundle'
empty :: Bundle v a
{-# INLINE empty #-}
empty = M.empty
-- | Singleton 'Bundle'
singleton :: a -> Bundle v a
{-# INLINE singleton #-}
singleton = M.singleton
-- | Replicate a value to a given length
replicate :: Int -> a -> Bundle v a
{-# INLINE replicate #-}
replicate = M.replicate
-- | Generate a stream from its indices
generate :: Int -> (Int -> a) -> Bundle v a
{-# INLINE generate #-}
generate = M.generate
-- | Prepend an element
cons :: a -> Bundle v a -> Bundle v a
{-# INLINE cons #-}
cons = M.cons
-- | Append an element
snoc :: Bundle v a -> a -> Bundle v a
{-# INLINE snoc #-}
snoc = M.snoc
infixr 5 ++
-- | Concatenate two 'Bundle's
(++) :: Bundle v a -> Bundle v a -> Bundle v a
{-# INLINE (++) #-}
(++) = (M.++)
-- Accessing elements
-- ------------------
-- | First element of the 'Bundle' or error if empty
head :: Bundle v a -> a
{-# INLINE head #-}
head = unId . M.head
-- | Last element of the 'Bundle' or error if empty
last :: Bundle v a -> a
{-# INLINE last #-}
last = unId . M.last
infixl 9 !!
-- | Element at the given position
(!!) :: Bundle v a -> Int -> a
{-# INLINE (!!) #-}
s !! i = unId (s M.!! i)
infixl 9 !?
-- | Element at the given position or 'Nothing' if out of bounds
(!?) :: Bundle v a -> Int -> Maybe a
{-# INLINE (!?) #-}
s !? i = unId (s M.!? i)
-- Substreams
-- ----------
-- | Extract a substream of the given length starting at the given position.
slice :: Int -- ^ starting index
-> Int -- ^ length
-> Bundle v a
-> Bundle v a
{-# INLINE slice #-}
slice = M.slice
-- | All but the last element
init :: Bundle v a -> Bundle v a
{-# INLINE init #-}
init = M.init
-- | All but the first element
tail :: Bundle v a -> Bundle v a
{-# INLINE tail #-}
tail = M.tail
-- | The first @n@ elements
take :: Int -> Bundle v a -> Bundle v a
{-# INLINE take #-}
take = M.take
-- | All but the first @n@ elements
drop :: Int -> Bundle v a -> Bundle v a
{-# INLINE drop #-}
drop = M.drop
-- Mapping
-- ---------------
-- | Map a function over a 'Bundle'
map :: (a -> b) -> Bundle v a -> Bundle v b
{-# INLINE map #-}
map = M.map
unbox :: Bundle v (Box a) -> Bundle v a
{-# INLINE unbox #-}
unbox = M.unbox
concatMap :: (a -> Bundle v b) -> Bundle v a -> Bundle v b
{-# INLINE concatMap #-}
concatMap = M.concatMap
-- Zipping
-- -------
-- | Pair each element in a 'Bundle' with its index
indexed :: Bundle v a -> Bundle v (Int,a)
{-# INLINE indexed #-}
indexed = M.indexed
-- | Pair each element in a 'Bundle' with its index, starting from the right
-- and counting down
indexedR :: Int -> Bundle v a -> Bundle v (Int,a)
{-# INLINE_FUSED indexedR #-}
indexedR = M.indexedR
-- | Zip two 'Bundle's with the given function
zipWith :: (a -> b -> c) -> Bundle v a -> Bundle v b -> Bundle v c
{-# INLINE zipWith #-}
zipWith = M.zipWith
-- | Zip three 'Bundle's with the given function
zipWith3 :: (a -> b -> c -> d) -> Bundle v a -> Bundle v b -> Bundle v c -> Bundle v d
{-# INLINE zipWith3 #-}
zipWith3 = M.zipWith3
zipWith4 :: (a -> b -> c -> d -> e)
-> Bundle v a -> Bundle v b -> Bundle v c -> Bundle v d
-> Bundle v e
{-# INLINE zipWith4 #-}
zipWith4 = M.zipWith4
zipWith5 :: (a -> b -> c -> d -> e -> f)
-> Bundle v a -> Bundle v b -> Bundle v c -> Bundle v d
-> Bundle v e -> Bundle v f
{-# INLINE zipWith5 #-}
zipWith5 = M.zipWith5
zipWith6 :: (a -> b -> c -> d -> e -> f -> g)
-> Bundle v a -> Bundle v b -> Bundle v c -> Bundle v d
-> Bundle v e -> Bundle v f -> Bundle v g
{-# INLINE zipWith6 #-}
zipWith6 = M.zipWith6
zip :: Bundle v a -> Bundle v b -> Bundle v (a,b)
{-# INLINE zip #-}
zip = M.zip
zip3 :: Bundle v a -> Bundle v b -> Bundle v c -> Bundle v (a,b,c)
{-# INLINE zip3 #-}
zip3 = M.zip3
zip4 :: Bundle v a -> Bundle v b -> Bundle v c -> Bundle v d
-> Bundle v (a,b,c,d)
{-# INLINE zip4 #-}
zip4 = M.zip4
zip5 :: Bundle v a -> Bundle v b -> Bundle v c -> Bundle v d
-> Bundle v e -> Bundle v (a,b,c,d,e)
{-# INLINE zip5 #-}
zip5 = M.zip5
zip6 :: Bundle v a -> Bundle v b -> Bundle v c -> Bundle v d
-> Bundle v e -> Bundle v f -> Bundle v (a,b,c,d,e,f)
{-# INLINE zip6 #-}
zip6 = M.zip6
-- Filtering
-- ---------
-- | Drop elements which do not satisfy the predicate
filter :: (a -> Bool) -> Bundle v a -> Bundle v a
{-# INLINE filter #-}
filter = M.filter
-- | Longest prefix of elements that satisfy the predicate
takeWhile :: (a -> Bool) -> Bundle v a -> Bundle v a
{-# INLINE takeWhile #-}
takeWhile = M.takeWhile
-- | Drop the longest prefix of elements that satisfy the predicate
dropWhile :: (a -> Bool) -> Bundle v a -> Bundle v a
{-# INLINE dropWhile #-}
dropWhile = M.dropWhile
-- Searching
-- ---------
infix 4 `elem`
-- | Check whether the 'Bundle' contains an element
elem :: Eq a => a -> Bundle v a -> Bool
{-# INLINE elem #-}
elem x = unId . M.elem x
infix 4 `notElem`
-- | Inverse of `elem`
notElem :: Eq a => a -> Bundle v a -> Bool
{-# INLINE notElem #-}
notElem x = unId . M.notElem x
-- | Yield 'Just' the first element matching the predicate or 'Nothing' if no
-- such element exists.
find :: (a -> Bool) -> Bundle v a -> Maybe a
{-# INLINE find #-}
find f = unId . M.find f
-- | Yield 'Just' the index of the first element matching the predicate or
-- 'Nothing' if no such element exists.
findIndex :: (a -> Bool) -> Bundle v a -> Maybe Int
{-# INLINE findIndex #-}
findIndex f = unId . M.findIndex f
-- Folding
-- -------
-- | Left fold
foldl :: (a -> b -> a) -> a -> Bundle v b -> a
{-# INLINE foldl #-}
foldl f z = unId . M.foldl f z
-- | Left fold on non-empty 'Bundle's
foldl1 :: (a -> a -> a) -> Bundle v a -> a
{-# INLINE foldl1 #-}
foldl1 f = unId . M.foldl1 f
-- | Left fold with strict accumulator
foldl' :: (a -> b -> a) -> a -> Bundle v b -> a
{-# INLINE foldl' #-}
foldl' f z = unId . M.foldl' f z
-- | Left fold on non-empty 'Bundle's with strict accumulator
foldl1' :: (a -> a -> a) -> Bundle v a -> a
{-# INLINE foldl1' #-}
foldl1' f = unId . M.foldl1' f
-- | Right fold
foldr :: (a -> b -> b) -> b -> Bundle v a -> b
{-# INLINE foldr #-}
foldr f z = unId . M.foldr f z
-- | Right fold on non-empty 'Bundle's
foldr1 :: (a -> a -> a) -> Bundle v a -> a
{-# INLINE foldr1 #-}
foldr1 f = unId . M.foldr1 f
-- Specialised folds
-- -----------------
and :: Bundle v Bool -> Bool
{-# INLINE and #-}
and = unId . M.and
or :: Bundle v Bool -> Bool
{-# INLINE or #-}
or = unId . M.or
-- Unfolding
-- ---------
-- | Unfold
unfoldr :: (s -> Maybe (a, s)) -> s -> Bundle v a
{-# INLINE unfoldr #-}
unfoldr = M.unfoldr
-- | Unfold at most @n@ elements
unfoldrN :: Int -> (s -> Maybe (a, s)) -> s -> Bundle v a
{-# INLINE unfoldrN #-}
unfoldrN = M.unfoldrN
-- | Apply function n-1 times to value. Zeroth element is original value.
iterateN :: Int -> (a -> a) -> a -> Bundle v a
{-# INLINE iterateN #-}
iterateN = M.iterateN
-- Scans
-- -----
-- | Prefix scan
prescanl :: (a -> b -> a) -> a -> Bundle v b -> Bundle v a
{-# INLINE prescanl #-}
prescanl = M.prescanl
-- | Prefix scan with strict accumulator
prescanl' :: (a -> b -> a) -> a -> Bundle v b -> Bundle v a
{-# INLINE prescanl' #-}
prescanl' = M.prescanl'
-- | Suffix scan
postscanl :: (a -> b -> a) -> a -> Bundle v b -> Bundle v a
{-# INLINE postscanl #-}
postscanl = M.postscanl
-- | Suffix scan with strict accumulator
postscanl' :: (a -> b -> a) -> a -> Bundle v b -> Bundle v a
{-# INLINE postscanl' #-}
postscanl' = M.postscanl'
-- | Haskell-style scan
scanl :: (a -> b -> a) -> a -> Bundle v b -> Bundle v a
{-# INLINE scanl #-}
scanl = M.scanl
-- | Haskell-style scan with strict accumulator
scanl' :: (a -> b -> a) -> a -> Bundle v b -> Bundle v a
{-# INLINE scanl' #-}
scanl' = M.scanl'
-- | Scan over a non-empty 'Bundle'
scanl1 :: (a -> a -> a) -> Bundle v a -> Bundle v a
{-# INLINE scanl1 #-}
scanl1 = M.scanl1
-- | Scan over a non-empty 'Bundle' with a strict accumulator
scanl1' :: (a -> a -> a) -> Bundle v a -> Bundle v a
{-# INLINE scanl1' #-}
scanl1' = M.scanl1'
-- Comparisons
-- -----------
-- | Check if two 'Bundle's are equal
eq :: (Eq a) => Bundle v a -> Bundle v a -> Bool
{-# INLINE eq #-}
eq = eqBy (==)
eqBy :: (a -> b -> Bool) -> Bundle v a -> Bundle v b -> Bool
{-# INLINE eqBy #-}
eqBy e x y = unId (M.eqBy e x y)
-- | Lexicographically compare two 'Bundle's
cmp :: (Ord a) => Bundle v a -> Bundle v a -> Ordering
{-# INLINE cmp #-}
cmp = cmpBy compare
cmpBy :: (a -> b -> Ordering) -> Bundle v a -> Bundle v b -> Ordering
{-# INLINE cmpBy #-}
cmpBy c x y = unId (M.cmpBy c x y)
instance Eq a => Eq (M.Bundle Id v a) where
{-# INLINE (==) #-}
(==) = eq
instance Ord a => Ord (M.Bundle Id v a) where
{-# INLINE compare #-}
compare = cmp
#if MIN_VERSION_base(4,9,0)
instance Eq1 (M.Bundle Id v) where
{-# INLINE liftEq #-}
liftEq = eqBy
instance Ord1 (M.Bundle Id v) where
{-# INLINE liftCompare #-}
liftCompare = cmpBy
#endif
-- Monadic combinators
-- -------------------
-- | Apply a monadic action to each element of the stream, producing a monadic
-- stream of results
mapM :: Monad m => (a -> m b) -> Bundle v a -> M.Bundle m v b
{-# INLINE mapM #-}
mapM f = M.mapM f . lift
-- | Apply a monadic action to each element of the stream
mapM_ :: Monad m => (a -> m b) -> Bundle v a -> m ()
{-# INLINE mapM_ #-}
mapM_ f = M.mapM_ f . lift
zipWithM :: Monad m => (a -> b -> m c) -> Bundle v a -> Bundle v b -> M.Bundle m v c
{-# INLINE zipWithM #-}
zipWithM f as bs = M.zipWithM f (lift as) (lift bs)
zipWithM_ :: Monad m => (a -> b -> m c) -> Bundle v a -> Bundle v b -> m ()
{-# INLINE zipWithM_ #-}
zipWithM_ f as bs = M.zipWithM_ f (lift as) (lift bs)
-- | Yield a monadic stream of elements that satisfy the monadic predicate
filterM :: Monad m => (a -> m Bool) -> Bundle v a -> M.Bundle m v a
{-# INLINE filterM #-}
filterM f = M.filterM f . lift
-- | Monadic fold
foldM :: Monad m => (a -> b -> m a) -> a -> Bundle v b -> m a
{-# INLINE foldM #-}
foldM m z = M.foldM m z . lift
-- | Monadic fold over non-empty stream
fold1M :: Monad m => (a -> a -> m a) -> Bundle v a -> m a
{-# INLINE fold1M #-}
fold1M m = M.fold1M m . lift
-- | Monadic fold with strict accumulator
foldM' :: Monad m => (a -> b -> m a) -> a -> Bundle v b -> m a
{-# INLINE foldM' #-}
foldM' m z = M.foldM' m z . lift
-- | Monad fold over non-empty stream with strict accumulator
fold1M' :: Monad m => (a -> a -> m a) -> Bundle v a -> m a
{-# INLINE fold1M' #-}
fold1M' m = M.fold1M' m . lift
-- Enumerations
-- ------------
-- | Yield a 'Bundle' of the given length containing the values @x@, @x+y@,
-- @x+y+y@ etc.
enumFromStepN :: Num a => a -> a -> Int -> Bundle v a
{-# INLINE enumFromStepN #-}
enumFromStepN = M.enumFromStepN
-- | Enumerate values
--
-- /WARNING:/ This operations can be very inefficient. If at all possible, use
-- 'enumFromStepN' instead.
enumFromTo :: Enum a => a -> a -> Bundle v a
{-# INLINE enumFromTo #-}
enumFromTo = M.enumFromTo
-- | Enumerate values with a given step.
--
-- /WARNING:/ This operations is very inefficient. If at all possible, use
-- 'enumFromStepN' instead.
enumFromThenTo :: Enum a => a -> a -> a -> Bundle v a
{-# INLINE enumFromThenTo #-}
enumFromThenTo = M.enumFromThenTo
-- Conversions
-- -----------
-- | Convert a 'Bundle' to a list
toList :: Bundle v a -> [a]
{-# INLINE toList #-}
-- toList s = unId (M.toList s)
toList s = build (\c n -> toListFB c n s)
-- This supports foldr/build list fusion that GHC implements
toListFB :: (a -> b -> b) -> b -> Bundle v a -> b
{-# INLINE [0] toListFB #-}
toListFB c n M.Bundle{M.sElems = Stream step t} = go t
where
go s = case unId (step s) of
Yield x s' -> x `c` go s'
Skip s' -> go s'
Done -> n
-- | Create a 'Bundle' from a list
fromList :: [a] -> Bundle v a
{-# INLINE fromList #-}
fromList = M.fromList
-- | Create a 'Bundle' from the first @n@ elements of a list
--
-- > fromListN n xs = fromList (take n xs)
fromListN :: Int -> [a] -> Bundle v a
{-# INLINE fromListN #-}
fromListN = M.fromListN
unsafeFromList :: Size -> [a] -> Bundle v a
{-# INLINE unsafeFromList #-}
unsafeFromList = M.unsafeFromList
fromVector :: Vector v a => v a -> Bundle v a
{-# INLINE fromVector #-}
fromVector = M.fromVector
reVector :: Bundle u a -> Bundle v a
{-# INLINE reVector #-}
reVector = M.reVector
fromVectors :: Vector v a => [v a] -> Bundle v a
{-# INLINE fromVectors #-}
fromVectors = M.fromVectors
concatVectors :: Vector v a => Bundle u (v a) -> Bundle v a
{-# INLINE concatVectors #-}
concatVectors = M.concatVectors
-- | Create a 'Bundle' of values from a 'Bundle' of streamable things
flatten :: (a -> s) -> (s -> Step s b) -> Size -> Bundle v a -> Bundle v b
{-# INLINE_FUSED flatten #-}
flatten mk istep sz = M.flatten (return . mk) (return . istep) sz . lift
|
dolio/vector
|
Data/Vector/Fusion/Bundle.hs
|
bsd-3-clause
| 16,957 | 0 | 12 | 4,136 | 5,154 | 2,810 | 2,344 | 349 | 3 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="az-AZ">
<title>Context Alert Filters | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
0xkasun/security-tools
|
src/org/zaproxy/zap/extension/alertFilters/resources/help_az_AZ/helpset_az_AZ.hs
|
apache-2.0
| 983 | 80 | 66 | 161 | 417 | 211 | 206 | -1 | -1 |
{-
(c) The University of Glasgow, 2000-2006
\section[Finder]{Module Finder}
-}
{-# LANGUAGE CPP #-}
module Finder (
flushFinderCaches,
FindResult(..),
findImportedModule,
findPluginModule,
findExactModule,
findHomeModule,
findExposedPackageModule,
mkHomeModLocation,
mkHomeModLocation2,
mkHiOnlyModLocation,
mkHiPath,
mkObjPath,
addHomeModuleToFinder,
uncacheModule,
mkStubPaths,
findObjectLinkableMaybe,
findObjectLinkable,
cannotFindModule,
cannotFindInterface,
) where
#include "HsVersions.h"
import Module
import HscTypes
import Packages
import FastString
import Util
import PrelNames ( gHC_PRIM )
import DynFlags
import Outputable
import Maybes ( expectJust )
import Data.IORef ( IORef, readIORef, atomicModifyIORef' )
import System.Directory
import System.FilePath
import Control.Monad
import Data.Time
import Data.List ( foldl' )
type FileExt = String -- Filename extension
type BaseName = String -- Basename of file
-- -----------------------------------------------------------------------------
-- The Finder
-- The Finder provides a thin filesystem abstraction to the rest of
-- the compiler. For a given module, it can tell you where the
-- source, interface, and object files for that module live.
-- It does *not* know which particular package a module lives in. Use
-- Packages.lookupModuleInAllPackages for that.
-- -----------------------------------------------------------------------------
-- The finder's cache
-- remove all the home modules from the cache; package modules are
-- assumed to not move around during a session.
flushFinderCaches :: HscEnv -> IO ()
flushFinderCaches hsc_env =
atomicModifyIORef' fc_ref $ \fm -> (filterModuleEnv is_ext fm, ())
where
this_pkg = thisPackage (hsc_dflags hsc_env)
fc_ref = hsc_FC hsc_env
is_ext mod _ | moduleUnitId mod /= this_pkg = True
| otherwise = False
addToFinderCache :: IORef FinderCache -> Module -> FindResult -> IO ()
addToFinderCache ref key val =
atomicModifyIORef' ref $ \c -> (extendModuleEnv c key val, ())
removeFromFinderCache :: IORef FinderCache -> Module -> IO ()
removeFromFinderCache ref key =
atomicModifyIORef' ref $ \c -> (delModuleEnv c key, ())
lookupFinderCache :: IORef FinderCache -> Module -> IO (Maybe FindResult)
lookupFinderCache ref key = do
c <- readIORef ref
return $! lookupModuleEnv c key
-- -----------------------------------------------------------------------------
-- The three external entry points
-- | Locate a module that was imported by the user. We have the
-- module's name, and possibly a package name. Without a package
-- name, this function will use the search path and the known exposed
-- packages to find the module, if a package is specified then only
-- that package is searched for the module.
findImportedModule :: HscEnv -> ModuleName -> Maybe FastString -> IO FindResult
findImportedModule hsc_env mod_name mb_pkg =
case mb_pkg of
Nothing -> unqual_import
Just pkg | pkg == fsLit "this" -> home_import -- "this" is special
| otherwise -> pkg_import
where
home_import = findHomeModule hsc_env mod_name
pkg_import = findExposedPackageModule hsc_env mod_name mb_pkg
unqual_import = home_import
`orIfNotFound`
findExposedPackageModule hsc_env mod_name Nothing
-- | Locate a plugin module requested by the user, for a compiler
-- plugin. This consults the same set of exposed packages as
-- 'findImportedModule', unless @-hide-all-plugin-packages@ or
-- @-plugin-package@ are specified.
findPluginModule :: HscEnv -> ModuleName -> IO FindResult
findPluginModule hsc_env mod_name =
findHomeModule hsc_env mod_name
`orIfNotFound`
findExposedPluginPackageModule hsc_env mod_name
-- | Locate a specific 'Module'. The purpose of this function is to
-- create a 'ModLocation' for a given 'Module', that is to find out
-- where the files associated with this module live. It is used when
-- reading the interface for a module mentioned by another interface,
-- for example (a "system import").
findExactModule :: HscEnv -> Module -> IO FindResult
findExactModule hsc_env mod =
let dflags = hsc_dflags hsc_env
in if moduleUnitId mod == thisPackage dflags
then findHomeModule hsc_env (moduleName mod)
else findPackageModule hsc_env mod
-- -----------------------------------------------------------------------------
-- Helpers
orIfNotFound :: IO FindResult -> IO FindResult -> IO FindResult
orIfNotFound this or_this = do
res <- this
case res of
NotFound { fr_paths = paths1, fr_mods_hidden = mh1
, fr_pkgs_hidden = ph1, fr_suggestions = s1 }
-> do res2 <- or_this
case res2 of
NotFound { fr_paths = paths2, fr_pkg = mb_pkg2, fr_mods_hidden = mh2
, fr_pkgs_hidden = ph2, fr_suggestions = s2 }
-> return (NotFound { fr_paths = paths1 ++ paths2
, fr_pkg = mb_pkg2 -- snd arg is the package search
, fr_mods_hidden = mh1 ++ mh2
, fr_pkgs_hidden = ph1 ++ ph2
, fr_suggestions = s1 ++ s2 })
_other -> return res2
_other -> return res
-- | Helper function for 'findHomeModule': this function wraps an IO action
-- which would look up @mod_name@ in the file system (the home package),
-- and first consults the 'hsc_FC' cache to see if the lookup has already
-- been done. Otherwise, do the lookup (with the IO action) and save
-- the result in the finder cache and the module location cache (if it
-- was successful.)
homeSearchCache :: HscEnv -> ModuleName -> IO FindResult -> IO FindResult
homeSearchCache hsc_env mod_name do_this = do
let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
modLocationCache hsc_env mod do_this
findExposedPackageModule :: HscEnv -> ModuleName -> Maybe FastString
-> IO FindResult
findExposedPackageModule hsc_env mod_name mb_pkg
= findLookupResult hsc_env
$ lookupModuleWithSuggestions
(hsc_dflags hsc_env) mod_name mb_pkg
findExposedPluginPackageModule :: HscEnv -> ModuleName
-> IO FindResult
findExposedPluginPackageModule hsc_env mod_name
= findLookupResult hsc_env
$ lookupPluginModuleWithSuggestions
(hsc_dflags hsc_env) mod_name Nothing
findLookupResult :: HscEnv -> LookupResult -> IO FindResult
findLookupResult hsc_env r = case r of
LookupFound m pkg_conf ->
findPackageModule_ hsc_env m pkg_conf
LookupMultiple rs ->
return (FoundMultiple rs)
LookupHidden pkg_hiddens mod_hiddens ->
return (NotFound{ fr_paths = [], fr_pkg = Nothing
, fr_pkgs_hidden = map (moduleUnitId.fst) pkg_hiddens
, fr_mods_hidden = map (moduleUnitId.fst) mod_hiddens
, fr_suggestions = [] })
LookupNotFound suggest ->
return (NotFound{ fr_paths = [], fr_pkg = Nothing
, fr_pkgs_hidden = []
, fr_mods_hidden = []
, fr_suggestions = suggest })
modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult
modLocationCache hsc_env mod do_this = do
m <- lookupFinderCache (hsc_FC hsc_env) mod
case m of
Just result -> return result
Nothing -> do
result <- do_this
addToFinderCache (hsc_FC hsc_env) mod result
return result
addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
addHomeModuleToFinder hsc_env mod_name loc = do
let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
addToFinderCache (hsc_FC hsc_env) mod (Found loc mod)
return mod
uncacheModule :: HscEnv -> ModuleName -> IO ()
uncacheModule hsc_env mod = do
let this_pkg = thisPackage (hsc_dflags hsc_env)
removeFromFinderCache (hsc_FC hsc_env) (mkModule this_pkg mod)
-- -----------------------------------------------------------------------------
-- The internal workers
-- | Implements the search for a module name in the home package only. Calling
-- this function directly is usually *not* what you want; currently, it's used
-- as a building block for the following operations:
--
-- 1. When you do a normal package lookup, we first check if the module
-- is available in the home module, before looking it up in the package
-- database.
--
-- 2. When you have a package qualified import with package name "this",
-- we shortcut to the home module.
--
-- 3. When we look up an exact 'Module', if the unit id associated with
-- the module is the current home module do a look up in the home module.
--
-- 4. Some special-case code in GHCi (ToDo: Figure out why that needs to
-- call this.)
findHomeModule :: HscEnv -> ModuleName -> IO FindResult
findHomeModule hsc_env mod_name =
homeSearchCache hsc_env mod_name $
let
dflags = hsc_dflags hsc_env
home_path = importPaths dflags
hisuf = hiSuf dflags
mod = mkModule (thisPackage dflags) mod_name
source_exts =
[ ("hs", mkHomeModLocationSearched dflags mod_name "hs")
, ("lhs", mkHomeModLocationSearched dflags mod_name "lhs")
, ("hsig", mkHomeModLocationSearched dflags mod_name "hsig")
, ("lhsig", mkHomeModLocationSearched dflags mod_name "lhsig")
]
hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf)
, (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf)
]
-- In compilation manager modes, we look for source files in the home
-- package because we can compile these automatically. In one-shot
-- compilation mode we look for .hi and .hi-boot files only.
exts | isOneShot (ghcMode dflags) = hi_exts
| otherwise = source_exts
in
-- special case for GHC.Prim; we won't find it in the filesystem.
-- This is important only when compiling the base package (where GHC.Prim
-- is a home module).
if mod == gHC_PRIM
then return (Found (error "GHC.Prim ModLocation") mod)
else searchPathExts home_path mod exts
-- | Search for a module in external packages only.
findPackageModule :: HscEnv -> Module -> IO FindResult
findPackageModule hsc_env mod = do
let
dflags = hsc_dflags hsc_env
pkg_id = moduleUnitId mod
--
case lookupPackage dflags pkg_id of
Nothing -> return (NoPackage pkg_id)
Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
-- | Look up the interface file associated with module @mod@. This function
-- requires a few invariants to be upheld: (1) the 'Module' in question must
-- be the module identifier of the *original* implementation of a module,
-- not a reexport (this invariant is upheld by @Packages.hs@) and (2)
-- the 'PackageConfig' must be consistent with the unit id in the 'Module'.
-- The redundancy is to avoid an extra lookup in the package state
-- for the appropriate config.
findPackageModule_ :: HscEnv -> Module -> PackageConfig -> IO FindResult
findPackageModule_ hsc_env mod pkg_conf =
ASSERT( moduleUnitId mod == packageConfigId pkg_conf )
modLocationCache hsc_env mod $
-- special case for GHC.Prim; we won't find it in the filesystem.
if mod == gHC_PRIM
then return (Found (error "GHC.Prim ModLocation") mod)
else
let
dflags = hsc_dflags hsc_env
tag = buildTag dflags
-- hi-suffix for packages depends on the build tag.
package_hisuf | null tag = "hi"
| otherwise = tag ++ "_hi"
mk_hi_loc = mkHiOnlyModLocation dflags package_hisuf
import_dirs = importDirs pkg_conf
-- we never look for a .hi-boot file in an external package;
-- .hi-boot files only make sense for the home package.
in
case import_dirs of
[one] | MkDepend <- ghcMode dflags -> do
-- there's only one place that this .hi file can be, so
-- don't bother looking for it.
let basename = moduleNameSlashes (moduleName mod)
loc <- mk_hi_loc one basename
return (Found loc mod)
_otherwise ->
searchPathExts import_dirs mod [(package_hisuf, mk_hi_loc)]
-- -----------------------------------------------------------------------------
-- General path searching
searchPathExts
:: [FilePath] -- paths to search
-> Module -- module name
-> [ (
FileExt, -- suffix
FilePath -> BaseName -> IO ModLocation -- action
)
]
-> IO FindResult
searchPathExts paths mod exts
= do result <- search to_search
{-
hPutStrLn stderr (showSDoc $
vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
, nest 2 (vcat (map text paths))
, case result of
Succeeded (loc, p) -> text "Found" <+> ppr loc
Failed fs -> text "not found"])
-}
return result
where
basename = moduleNameSlashes (moduleName mod)
to_search :: [(FilePath, IO ModLocation)]
to_search = [ (file, fn path basename)
| path <- paths,
(ext,fn) <- exts,
let base | path == "." = basename
| otherwise = path </> basename
file = base <.> ext
]
search [] = return (NotFound { fr_paths = map fst to_search
, fr_pkg = Just (moduleUnitId mod)
, fr_mods_hidden = [], fr_pkgs_hidden = []
, fr_suggestions = [] })
search ((file, mk_result) : rest) = do
b <- doesFileExist file
if b
then do { loc <- mk_result; return (Found loc mod) }
else search rest
mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
-> FilePath -> BaseName -> IO ModLocation
mkHomeModLocationSearched dflags mod suff path basename = do
mkHomeModLocation2 dflags mod (path </> basename) suff
-- -----------------------------------------------------------------------------
-- Constructing a home module location
-- This is where we construct the ModLocation for a module in the home
-- package, for which we have a source file. It is called from three
-- places:
--
-- (a) Here in the finder, when we are searching for a module to import,
-- using the search path (-i option).
--
-- (b) The compilation manager, when constructing the ModLocation for
-- a "root" module (a source file named explicitly on the command line
-- or in a :load command in GHCi).
--
-- (c) The driver in one-shot mode, when we need to construct a
-- ModLocation for a source file named on the command-line.
--
-- Parameters are:
--
-- mod
-- The name of the module
--
-- path
-- (a): The search path component where the source file was found.
-- (b) and (c): "."
--
-- src_basename
-- (a): (moduleNameSlashes mod)
-- (b) and (c): The filename of the source file, minus its extension
--
-- ext
-- The filename extension of the source file (usually "hs" or "lhs").
mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
mkHomeModLocation dflags mod src_filename = do
let (basename,extension) = splitExtension src_filename
mkHomeModLocation2 dflags mod basename extension
mkHomeModLocation2 :: DynFlags
-> ModuleName
-> FilePath -- Of source module, without suffix
-> String -- Suffix
-> IO ModLocation
mkHomeModLocation2 dflags mod src_basename ext = do
let mod_basename = moduleNameSlashes mod
obj_fn = mkObjPath dflags src_basename mod_basename
hi_fn = mkHiPath dflags src_basename mod_basename
return (ModLocation{ ml_hs_file = Just (src_basename <.> ext),
ml_hi_file = hi_fn,
ml_obj_file = obj_fn })
mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
-> IO ModLocation
mkHiOnlyModLocation dflags hisuf path basename
= do let full_basename = path </> basename
obj_fn = mkObjPath dflags full_basename basename
return ModLocation{ ml_hs_file = Nothing,
ml_hi_file = full_basename <.> hisuf,
-- Remove the .hi-boot suffix from
-- hi_file, if it had one. We always
-- want the name of the real .hi file
-- in the ml_hi_file field.
ml_obj_file = obj_fn
}
-- | Constructs the filename of a .o file for a given source file.
-- Does /not/ check whether the .o file exists
mkObjPath
:: DynFlags
-> FilePath -- the filename of the source file, minus the extension
-> String -- the module name with dots replaced by slashes
-> FilePath
mkObjPath dflags basename mod_basename = obj_basename <.> osuf
where
odir = objectDir dflags
osuf = objectSuf dflags
obj_basename | Just dir <- odir = dir </> mod_basename
| otherwise = basename
-- | Constructs the filename of a .hi file for a given source file.
-- Does /not/ check whether the .hi file exists
mkHiPath
:: DynFlags
-> FilePath -- the filename of the source file, minus the extension
-> String -- the module name with dots replaced by slashes
-> FilePath
mkHiPath dflags basename mod_basename = hi_basename <.> hisuf
where
hidir = hiDir dflags
hisuf = hiSuf dflags
hi_basename | Just dir <- hidir = dir </> mod_basename
| otherwise = basename
-- -----------------------------------------------------------------------------
-- Filenames of the stub files
-- We don't have to store these in ModLocations, because they can be derived
-- from other available information, and they're only rarely needed.
mkStubPaths
:: DynFlags
-> ModuleName
-> ModLocation
-> FilePath
mkStubPaths dflags mod location
= let
stubdir = stubDir dflags
mod_basename = moduleNameSlashes mod
src_basename = dropExtension $ expectJust "mkStubPaths"
(ml_hs_file location)
stub_basename0
| Just dir <- stubdir = dir </> mod_basename
| otherwise = src_basename
stub_basename = stub_basename0 ++ "_stub"
in
stub_basename <.> "h"
-- -----------------------------------------------------------------------------
-- findLinkable isn't related to the other stuff in here,
-- but there's no other obvious place for it
findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable)
findObjectLinkableMaybe mod locn
= do let obj_fn = ml_obj_file locn
maybe_obj_time <- modificationTimeIfExists obj_fn
case maybe_obj_time of
Nothing -> return Nothing
Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)
-- Make an object linkable when we know the object file exists, and we know
-- its modification time.
findObjectLinkable :: Module -> FilePath -> UTCTime -> IO Linkable
findObjectLinkable mod obj_fn obj_time = return (LM obj_time mod [DotO obj_fn])
-- We used to look for _stub.o files here, but that was a bug (#706)
-- Now GHC merges the stub.o into the main .o (#3687)
-- -----------------------------------------------------------------------------
-- Error messages
cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
cannotFindModule = cantFindErr (sLit "Could not find module")
(sLit "Ambiguous module name")
cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc
cannotFindInterface = cantFindErr (sLit "Failed to load interface for")
(sLit "Ambiguous interface for")
cantFindErr :: LitString -> LitString -> DynFlags -> ModuleName -> FindResult
-> SDoc
cantFindErr _ multiple_found _ mod_name (FoundMultiple mods)
| Just pkgs <- unambiguousPackages
= hang (ptext multiple_found <+> quotes (ppr mod_name) <> colon) 2 (
sep [text "it was found in multiple packages:",
hsep (map ppr pkgs) ]
)
| otherwise
= hang (ptext multiple_found <+> quotes (ppr mod_name) <> colon) 2 (
vcat (map pprMod mods)
)
where
unambiguousPackages = foldl' unambiguousPackage (Just []) mods
unambiguousPackage (Just xs) (m, ModOrigin (Just _) _ _ _)
= Just (moduleUnitId m : xs)
unambiguousPackage _ _ = Nothing
pprMod (m, o) = text "it is bound as" <+> ppr m <+>
text "by" <+> pprOrigin m o
pprOrigin _ ModHidden = panic "cantFindErr: bound by mod hidden"
pprOrigin m (ModOrigin e res _ f) = sep $ punctuate comma (
if e == Just True
then [text "package" <+> ppr (moduleUnitId m)]
else [] ++
map ((text "a reexport in package" <+>)
.ppr.packageConfigId) res ++
if f then [text "a package flag"] else []
)
cantFindErr cannot_find _ dflags mod_name find_result
= ptext cannot_find <+> quotes (ppr mod_name)
$$ more_info
where
more_info
= case find_result of
NoPackage pkg
-> text "no unit id matching" <+> quotes (ppr pkg) <+>
text "was found" $$ looks_like_srcpkgid pkg
NotFound { fr_paths = files, fr_pkg = mb_pkg
, fr_mods_hidden = mod_hiddens, fr_pkgs_hidden = pkg_hiddens
, fr_suggestions = suggest }
| Just pkg <- mb_pkg, pkg /= thisPackage dflags
-> not_found_in_package pkg files
| not (null suggest)
-> pp_suggestions suggest $$ tried_these files
| null files && null mod_hiddens && null pkg_hiddens
-> text "It is not a module in the current program, or in any known package."
| otherwise
-> vcat (map pkg_hidden pkg_hiddens) $$
vcat (map mod_hidden mod_hiddens) $$
tried_these files
_ -> panic "cantFindErr"
build_tag = buildTag dflags
not_found_in_package pkg files
| build_tag /= ""
= let
build = if build_tag == "p" then "profiling"
else "\"" ++ build_tag ++ "\""
in
text "Perhaps you haven't installed the " <> text build <>
text " libraries for package " <> quotes (ppr pkg) <> char '?' $$
tried_these files
| otherwise
= text "There are files missing in the " <> quotes (ppr pkg) <>
text " package," $$
text "try running 'ghc-pkg check'." $$
tried_these files
tried_these files
| null files = Outputable.empty
| verbosity dflags < 3 =
text "Use -v to see a list of the files searched for."
| otherwise =
hang (text "Locations searched:") 2 $ vcat (map text files)
pkg_hidden :: UnitId -> SDoc
pkg_hidden pkgid =
text "It is a member of the hidden package"
<+> quotes (ppr pkgid)
--FIXME: we don't really want to show the unit id here we should
-- show the source package id or installed package id if it's ambiguous
<> dot $$ cabal_pkg_hidden_hint pkgid
cabal_pkg_hidden_hint pkgid
| gopt Opt_BuildingCabalPackage dflags
= let pkg = expectJust "pkg_hidden" (lookupPackage dflags pkgid)
in text "Perhaps you need to add" <+>
quotes (ppr (packageName pkg)) <+>
text "to the build-depends in your .cabal file."
| otherwise = Outputable.empty
looks_like_srcpkgid :: UnitId -> SDoc
looks_like_srcpkgid pk
-- Unsafely coerce a unit id FastString into a source package ID
-- FastString and see if it means anything.
| (pkg:pkgs) <- searchPackageId dflags (SourcePackageId (unitIdFS pk))
= parens (text "This unit ID looks like the source package ID;" $$
text "the real unit ID is" <+> quotes (ftext (unitIdFS (unitId pkg))) $$
(if null pkgs then Outputable.empty
else text "and" <+> int (length pkgs) <+> text "other candidates"))
-- Todo: also check if it looks like a package name!
| otherwise = Outputable.empty
mod_hidden pkg =
text "it is a hidden module in the package" <+> quotes (ppr pkg)
pp_suggestions :: [ModuleSuggestion] -> SDoc
pp_suggestions sugs
| null sugs = Outputable.empty
| otherwise = hang (text "Perhaps you meant")
2 (vcat (map pp_sugg sugs))
-- NB: Prefer the *original* location, and then reexports, and then
-- package flags when making suggestions. ToDo: if the original package
-- also has a reexport, prefer that one
pp_sugg (SuggestVisible m mod o) = ppr m <+> provenance o
where provenance ModHidden = Outputable.empty
provenance (ModOrigin{ fromOrigPackage = e,
fromExposedReexport = res,
fromPackageFlag = f })
| Just True <- e
= parens (text "from" <+> ppr (moduleUnitId mod))
| f && moduleName mod == m
= parens (text "from" <+> ppr (moduleUnitId mod))
| (pkg:_) <- res
= parens (text "from" <+> ppr (packageConfigId pkg)
<> comma <+> text "reexporting" <+> ppr mod)
| f
= parens (text "defined via package flags to be"
<+> ppr mod)
| otherwise = Outputable.empty
pp_sugg (SuggestHidden m mod o) = ppr m <+> provenance o
where provenance ModHidden = Outputable.empty
provenance (ModOrigin{ fromOrigPackage = e,
fromHiddenReexport = rhs })
| Just False <- e
= parens (text "needs flag -package-key"
<+> ppr (moduleUnitId mod))
| (pkg:_) <- rhs
= parens (text "needs flag -package-id"
<+> ppr (packageConfigId pkg))
| otherwise = Outputable.empty
|
oldmanmike/ghc
|
compiler/main/Finder.hs
|
bsd-3-clause
| 26,711 | 1 | 20 | 7,687 | 5,073 | 2,582 | 2,491 | 418 | 12 |
{-# OPTIONS -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module Data.Either.Extra where
-- | When a value is Right, do something with it, monadically.
whenRight :: Monad m => Either a b -> (b -> m c) -> m ()
whenRight (Right x) m = m x >> return ()
whenRight _ _ = return ()
-- | When a value is Left, do something with it, monadically.
whenLeft :: Monad m => Either a b -> (a -> m c) -> m ()
whenLeft (Left x) m = m x >> return ()
whenLeft _ _ = return ()
|
lwm/haskellnews
|
src/Data/Either/Extra.hs
|
bsd-3-clause
| 476 | 0 | 10 | 118 | 177 | 87 | 90 | 9 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.OfflineAudioContext (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.OfflineAudioContext
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.OfflineAudioContext
#else
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/OfflineAudioContext.hs
|
mit
| 370 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
module Yage.Uniform
( module Material
, module Light
, module UniformVar
, module Image
) where
import Yage.Uniform.Material as Material
import Yage.Uniform.Light as Light
import Yage.Uniform.Image as Image
import Yage.Uniform.UniformVar as UniformVar
|
MaxDaten/yage
|
src/Yage/Uniform.hs
|
mit
| 275 | 0 | 4 | 55 | 56 | 41 | 15 | 9 | 0 |
import Text.Parsec
import Parser
import AST
import Generator
import Paths_poorscript
main =
do
s <- readFile "in.js"
coreFile <- Paths_poorscript.getDataFileName "core.js"
core <- readFile coreFile
let result = parseAll s
putStrLn "start"
case result of
Right x -> do
writeFile "out.js" $ generate x
writeFile "core.js" core
Left e -> print e
parseAll :: String -> Either ParseError AST.Module
parseAll src = parse all' "* ParseError *" src
|
jinjor/poorscript
|
src/Main.hs
|
mit
| 498 | 0 | 13 | 125 | 153 | 69 | 84 | 19 | 2 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.IDBCursorWithValue
(getValue, IDBCursorWithValue(..), gTypeIDBCursorWithValue) where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/IDBCursorWithValue.value Mozilla IDBCursorWithValue.value documentation>
getValue :: (MonadDOM m) => IDBCursorWithValue -> m JSVal
getValue self = liftDOM ((self ^. js "value") >>= toJSVal)
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/IDBCursorWithValue.hs
|
mit
| 1,276 | 0 | 10 | 136 | 345 | 224 | 121 | 20 | 1 |
{-|
Module : Main
Description : Main module
Licence : MIT
Maintainer : [email protected]
Stability : experimental
Portability : portable
Main module
-}
module Main where
import qualified MMM.OOP.Main.Flags as Fl
import MMM.Core.All
import MMM.OOP.Language.Syntax
import MMM.OOP.Language.Parser
import MMM.OOP.Language.Utils
import MMM.OOP.ToMMM
import MMM.HsMMM
import MMM.Util.Pretty
import MMM.Util.Util
import System.IO
main :: IO ()
main = do
opts <- Fl.getOpts
case opts of
Fl.Help -> Fl.showHelp
Fl.Compile {} -> compile opts
--------------------------------------------------------------------------------
-- * Compilation
-- ghci interface
compileIn :: FilePath -> IO ()
compileIn f = compile (Fl.Compile f Nothing True True)
compileInOut :: FilePath -> FilePath -> IO ()
compileInOut fin fout = compile (Fl.Compile fin (Just fout) True True)
inExamples :: String -> FilePath
inExamples = ("MMM/Examples/" ++)
-- Compilation Routine
compile :: Fl.Options -> IO ()
compile opts
= do
case Fl.ocOutput opts of
Nothing -> compileOut
Just f -> withFile f WriteMode compileOutTo
where
compileOutTo hout
= oopParse (Fl.ocInput opts) >>= either (putStrLn . show) (runCompilation $ Just hout)
compileOut
= oopParse (Fl.ocInput opts) >>= either (putStrLn . show) (runCompilation Nothing)
runCompilation hout m
= do
defs' <- mapM (simplifyAll . classDef) (moduleDecls m)
let m' = m { moduleDecls = map (\(c, d) -> c { classDef = d }) (zip (moduleDecls m) defs') }
when (Fl.ocDump opts) $ hPrettyPutStrLn stdout m'
hsmod <- runErrorT $ trModule m'
case hsmod of
Left err -> hPutStrLn stderr $ show err
Right m -> let mname = hsmoduleGetName m ++ ".hs"
in case hout of
Nothing -> withFile mname WriteMode $ \out ->
mapM_ (hPutStrLn out . show . pretty) (hsmodOpts opts m)
Just o -> mapM_ (hPutStrLn o . show . pretty) (hsmodOpts opts m)
hsmodOpts o m
= if Fl.ocOmmitLinePs o
then filter (not . hsStmtIsLineP) m
else m
hPrettyPutStrLn h a
= do hPutStrLn h $ replicate 45 '#'
hPutStrLn h $ show $ pretty a
hPutStrLn h $ replicate 45 '#'
|
VictorCMiraldo/mmm
|
MMM/OOP/Main/Main.hs
|
mit
| 2,421 | 0 | 23 | 701 | 743 | 376 | 367 | 54 | 5 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module GhostLang.InterpreterGenerators
( TestInstrSet (..)
, SimpleSequencePattern (..)
, ManySimpleSequencePatterns (..)
, NonNestedLoopPattern (..)
, NonNestedConcPattern (..)
) where
import Data.Serialize (Serialize (..))
import Data.Text (pack)
import GHC.Generics (Generic)
import GhostLang.CommonGenerators ()
import GhostLang.Interpreter.InstructionSet (InstructionSet (..))
import GhostLang.Types ( Label
, Value (..)
, Program (..)
, Pattern (..)
, Operation (..)
)
import Test.QuickCheck
import Text.Parsec.Pos (initialPos)
-- | Arbitrary instance for Program.
instance Arbitrary a => Arbitrary (Program a) where
arbitrary = Program <$> (listOf arbitrary)
-- | Generate a label with at least length 1.
instance Arbitrary Label where
arbitrary = pack <$> (listOf1 $ elements fromValidChars)
where fromValidChars = ['0'..'9'] ++ ['a'..'z'] ++ ['A'..'Z'] ++ "_.-"
-- | Simple instruction set for testing purposes. The instructions
-- shall have no side effects.
data TestInstrSet = Instr1 | Instr2
deriving (Eq, Generic, Show)
instance Serialize TestInstrSet
instance Arbitrary TestInstrSet where
arbitrary = elements [ Instr1, Instr2 ]
instance InstructionSet TestInstrSet where
exec _ = return ()
-- | Test case wrapper type. A simple sequence pattern is a pattern
-- with only plain TestInstrSet instructions invoked.
data SimpleSequencePattern =
SimpleSequencePattern (Pattern TestInstrSet)
deriving Show
instance Arbitrary SimpleSequencePattern where
arbitrary = SimpleSequencePattern <$> simpleSequencePattern
-- | Test case wrapper type. Many simple sequence patterns. See
-- SimpleSequencePattern for explanation.
data ManySimpleSequencePatterns =
ManySimpleSequencePatterns [Pattern TestInstrSet]
deriving Show
instance Arbitrary ManySimpleSequencePatterns where
arbitrary = ManySimpleSequencePatterns <$> (listOf simpleSequencePattern)
simpleSequencePattern :: Gen (Pattern TestInstrSet)
simpleSequencePattern = Pattern <$> pure (initialPos "")
<*> arbitrary
<*> arbitrary
<*> (listOf invokeOperation)
-- | Test case wrapper type. A sequence with simple instructions and
-- non nested loops.
data NonNestedLoopPattern =
NonNestedLoopPattern (Pattern TestInstrSet)
deriving Show
instance Arbitrary NonNestedLoopPattern where
arbitrary = NonNestedLoopPattern <$> pattern'
where
pattern' = Pattern <$> pure (initialPos "")
<*> arbitrary
<*> arbitrary
<*> (listOf $ oneof [ invokeOperation
, nonNestedLoop
])
-- | Test case wrapper type. A sequence with simple instructions and
-- non nested concurrency sections.
data NonNestedConcPattern =
NonNestedConcPattern (Pattern TestInstrSet)
deriving Show
instance Arbitrary NonNestedConcPattern where
arbitrary = NonNestedConcPattern <$> pattern
where
pattern = Pattern <$> pure (initialPos "")
<*> arbitrary
<*> arbitrary
<*> (listOf $ oneof [ invokeOperation
, nonNestedConc
])
nonNestedConc = Concurrently <$> (listOf invokeOperation)
invokeOperation :: Gen (Operation TestInstrSet)
invokeOperation = Invoke <$> arbitrary
nonNestedLoop :: Gen (Operation TestInstrSet)
nonNestedLoop = Loop <$> value
<*> (listOf invokeOperation)
where
value = Literal <$> choose (0, 10)
|
kosmoskatten/ghost-lang
|
ghost-lang/test/GhostLang/InterpreterGenerators.hs
|
mit
| 4,016 | 0 | 14 | 1,185 | 724 | 409 | 315 | 75 | 1 |
-----------------------------------------------------------------------------
--
-- Module : ResidualSpace
-- Copyright : Armin Kazmi (2015)
-- License : MIT
--
-- Maintainer : Armin Kazmi
-- Stability : experimental
-- Portability : GHC only or compatible
--
-- |
--
-----------------------------------------------------------------------------
{-# OPTIONS_GHC -F -pgmF htfpp #-}
{-# LANGUAGE FlexibleInstances #-}
module DAAK.Core.ResidualSpace where
import Test.Framework
import Control.Applicative
import Control.Monad
import DAAK.Core.Debug
import DAAK.Core.Space3D as SP
import Data.Function
import Data.List as L
import Data.Maybe
import qualified Data.Set as S
import Data.Vect
import qualified Data.Vector as V
import Debug.Trace
-- | Defines equality of vectors, heavily relying on
-- 'Eq Vec'
instance Ord Vec3 where
compare a@(Vec3 x y z) b@(Vec3 x1 y1 z1)
| a == b = EQ
| absDeq z z1 && absDeq y y1 = compare x x1
| absDeq z z1 = compare y y1
| otherwise = compare z z1
type LoadSpace = EuclideanSpace3D
data ResidualSpace = EmptyResidualSpace
| ResidualSpace !EuclideanSpace3D deriving (Show, Eq)
rspace :: ResidualSpace -> EuclideanSpace3D
rspace EmptyResidualSpace = EmptySpace3D
rspace (ResidualSpace a) = a
maybeEmptySpace :: EuclideanSpace3D -> Maybe EuclideanSpace3D
maybeEmptySpace EmptySpace3D = Nothing
maybeEmptySpace a = Just a
maybeEmptyResSpace :: ResidualSpace -> Maybe ResidualSpace
-- maybeEmptyResSpace EmptyResidualSpace = Nothing
-- maybeEmptyResSpace a = Just a
maybeEmptyResSpace = maybeEmptySpace . rspace >=> return . ResidualSpace
minMax :: (Ord a) => a -> a -> (a, a)
minMax a b
| a >= b = (b, a)
| otherwise = (a, b)
mkResidualSpace :: EuclideanSpace3D -> ResidualSpace
mkResidualSpace EmptySpace3D = EmptyResidualSpace
mkResidualSpace s = ResidualSpace s
startOrdSpace :: EuclideanSpace3D -> EuclideanSpace3D -> Ordering
startOrdSpace EmptySpace3D _ = GT
startOrdSpace _ EmptySpace3D = LT
startOrdSpace a b
| eq == EQ
= (compare `on` volume) b a
| otherwise
= eq
where eq = (compare `on` start) a b
startOrd :: ResidualSpace -> ResidualSpace -> Ordering
startOrd EmptyResidualSpace _ = GT
startOrd _ EmptyResidualSpace = LT
startOrd (ResidualSpace a) (ResidualSpace b)
| eq == EQ
= (compare `on` volume) b a
| otherwise
= eq
where eq = (compare `on` start) a b
toMaybeResSpace :: Vec3 -> Vec3 -> Maybe ResidualSpace
toMaybeResSpace l = maybeEmptyResSpace . mkResidualSpace . mkEuclidean3D l
-- | direct splitting case of spaces
-- | it is assumed that 2nd space lies completely in 1st space
splitSpaceDirect :: EuclideanSpace3D -> EuclideanSpace3D -> [ResidualSpace]
splitSpaceDirect EmptySpace3D _ = []
splitSpaceDirect a EmptySpace3D = [mkResidualSpace a]
splitSpaceDirect a@(EuclideanSpace3D l1 r1) b@(EuclideanSpace3D l2 r2) = catMaybes
[ -- FRONT
toMaybeResSpace (start a) (Vec3 (ex a) (sy b) (ez a))
-- LEFT
, toMaybeResSpace (start a) (Vec3 (sx b) (ey a) (ez a))
-- RIGHT
, toMaybeResSpace (Vec3 (ex b) (sy a) (sz a)) (end a)
-- BACK
, toMaybeResSpace (Vec3 (sx a) (ey b) (sz a)) (end a)
-- BOT (nope)
-- TOP
--, toMaybeResSpace (Vec3 (sx a) (sy a) (ez b)) (end a)
]
-- | direct splitting case of spaces
-- | it is assumed that 2nd space lies completely in 1st space
splitSpaceDirectSupport :: EuclideanSpace3D -> EuclideanSpace3D -> [ResidualSpace]
splitSpaceDirectSupport EmptySpace3D _ = []
splitSpaceDirectSupport a EmptySpace3D = [mkResidualSpace a]
splitSpaceDirectSupport a b = catMaybes
[ -- FRONT
toMaybeResSpace (start a) (Vec3 (ex a) (sy b) (ez a))
-- LEFT
, toMaybeResSpace (start a) (Vec3 (sx b) (ey a) (ez a))
-- RIGHT
, toMaybeResSpace (Vec3 (ex b) (sy a) (sz a)) (end a)
-- BACK
, toMaybeResSpace (Vec3 (sx a) (ey b) (sz a)) (end a)
-- BOT (nope)
-- TOP
-- , toMaybeResSpace (Vec3 (sx b) (sy b) (ez b)) (Vec3 (ex b) (ey b) (ez a))
]
-- | split 1st space by 2nd space, taking into account non overlapping and only
-- | partially overlapping cases
splitSpaceSupport :: EuclideanSpace3D -> EuclideanSpace3D -> [ResidualSpace]
splitSpaceSupport a b
| overlap a b
= splitSpaceDirectSupport a (a `SP.intersect` b)
| otherwise = [mkResidualSpace a]
-- | split 1st space by 2nd space, taking into account non overlapping and only
-- | partially overlapping cases
splitSpace :: EuclideanSpace3D -> EuclideanSpace3D -> [ResidualSpace]
splitSpace a b
| overlap a b
= splitSpaceDirect a (a `SP.intersect` b)
| otherwise = [mkResidualSpace a]
-- | Does the given space fit in the given freespace completely?
-- | If so return Just tupeliziation of both
fitMaybe :: EuclideanSpace3D -> ResidualSpace -> Maybe (EuclideanSpace3D, ResidualSpace)
fitMaybe _ EmptyResidualSpace = Nothing
fitMaybe a r@(ResidualSpace b)
| sizex a <= sizex b
, sizey a <= sizey b
, sizez a <= sizez b
= Just (a, r)
| otherwise
= Nothing
isDominant :: ResidualSpace -> ResidualSpace -> Bool
isDominant = isInside `on` rspace
dominantsExtend :: [ResidualSpace] -> ResidualSpace -> [ResidualSpace]
dominantsExtend rs r
| any (isDominant r) rs
= rs
| otherwise
-- TODO: sorting?
= r : rs
-- | Split every given residual space by given space and concat the result
splitAll :: [ResidualSpace] -> EuclideanSpace3D -> [ResidualSpace]
splitAll rs e = concatMap (flip splitSpace e . rspace) rs
-- split all residual spaces by given spaces, also
-- splitting all resulting new residual spaces by the next given space
splitFold :: [ResidualSpace] -> [EuclideanSpace3D] -> [ResidualSpace]
splitFold = L.foldl splitAll
-- | Build reduced list of residuals filtered by dominance relation
buildUpDominants :: [ResidualSpace] -> [ResidualSpace]
buildUpDominants = L.foldl dominantsExtend [] . sortBy startOrd
-- | Split all residual spaces by the given spaces (and their resulting new
-- | residual spaces) and make sure the dominance relation holds
splitFoldDominant :: [ResidualSpace] -> [EuclideanSpace3D] -> [ResidualSpace]
splitFoldDominant rs es = sortBy startOrd $ buildUpDominants $ splitFold rs es
---------
-- | Split every given residual space by given space and concat the result
splitAllSupport :: [ResidualSpace] -> EuclideanSpace3D -> [ResidualSpace]
splitAllSupport rs e = concatMap (flip splitSpaceSupport e . rspace) rs
-- split all residual spaces by given spaces, also
-- splitting all resulting new residual spaces by the next given space
splitFoldSupport :: [ResidualSpace] -> [EuclideanSpace3D] -> [ResidualSpace]
splitFoldSupport = L.foldl splitAllSupport
-- | Split all residual spaces by the given spaces (and their resulting new
-- | residual spaces) and make sure the dominance relation holds
splitFoldDominantSupport :: [ResidualSpace] -> [EuclideanSpace3D] -> [ResidualSpace]
splitFoldDominantSupport rs es = sortBy startOrd $ buildUpDominants $ splitFoldSupport rs es
----
-- | Filter in all spaces that lie in the given residual space
determineInside :: ResidualSpace -> [EuclideanSpace3D] -> [EuclideanSpace3D]
determineInside r = filter (`isInside` rspace r)
splitFoldSupport' :: [EuclideanSpace3D] -> [EuclideanSpace3D] -> [(ResidualSpace, [EuclideanSpace3D])]
splitFoldSupport' grouped others =
zipWith (\r es -> (r, determineInside r es))
(splitFoldDominantSupport [mkResidualSpace groupBB] sortedOthers) $ repeat grouped
where
groupBB = boundingBox grouped
sortedOthers = sortBy (compare `on` ez) others
-- splitFold2 :: LoadSpace -> [EuclideanSpace3D] -> [ResidualSpace] -> [ResidualSpace]
-- splitFold2 l packs res =
-- sortBy (startOrdSpace `on` rspace) $ rest ++ splitFoldDominant splitrs (rspace <$> rest)
-- where
-- mz = maximum $ ez <$> packs
-- (splitrs, rest) = partition ((==) mz . sz . rspace) res
splitFold2 :: LoadSpace -> [EuclideanSpace3D] -> [ResidualSpace] -> [ResidualSpace]
splitFold2 l packs res =
sortBy (startOrdSpace `on` rspace) $ splitFoldDominant [mkResidualSpace l] $ rspace <$> res
heightLayerUnionSplitWork :: [[EuclideanSpace3D]] -> [[(ResidualSpace, [EuclideanSpace3D])]]
heightLayerUnionSplitWork [] = []
heightLayerUnionSplitWork (frontGroup : rest) = splitFoldSupport' frontGroup (concat rest) : heightLayerUnionSplitWork rest
heightLayerUnionSplit :: [[EuclideanSpace3D]] -> [(ResidualSpace, [EuclideanSpace3D])]
heightLayerUnionSplit = concat . heightLayerUnionSplitWork
|
apriori/daak
|
lib/DAAK/Core/ResidualSpace.hs
|
mit
| 8,544 | 0 | 11 | 1,588 | 2,147 | 1,150 | 997 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module DAAK.Algorithms.Gamo.JsonImport where
import Control.Monad
import DAAK.Algorithms.Gamo.Packing
import DAAK.Core.Space3D
import Data.Aeson
import Data.ByteString.Lazy as BS hiding (zip)
import Data.Map as M
import Data.Text hiding (zip)
import Data.Vect
import qualified Data.Vector as V
data LoadItem = LoadItem
{ itemName :: Text
, quantity :: Int
, itemSize :: Vec3
, positions :: Maybe [Vec3]
}
deriving (Show)
data Load = Load
{ loadSpaceSize :: Vec3
}
deriving (Show)
data Document = Document
{ load :: Load
, items :: [LoadItem]
}
instance FromJSON Vec3 where
parseJSON (Array a)
| V.length a == 3
, vals <- fmap parseJSON a
= Vec3 <$> (vals V.! 0) <*> (vals V.! 1) <*> (vals V.! 2)
| otherwise
= mzero
parseJSON _ = mzero
instance ToJSON Vec3 where
toJSON (Vec3 x y z) = toJSON [x, y, z]
instance FromJSON LoadItem where
parseJSON (Object v) = LoadItem <$>
v .: "itemName" <*>
v .: "quantity" <*>
v .: "itemSize" <*>
v .:? "positions"
parseJSON _ = mzero
instance ToJSON LoadItem where
toJSON (LoadItem n q i p) = object [ "itemName" .= n
, "quantity" .= q
, "itemSize" .= i
, "positions" .= p
]
instance FromJSON Load where
parseJSON (Object v) = Load <$> v .: "loadSpaceSize"
parseJSON _ = mzero
instance ToJSON Load where
toJSON (Load s) = object [ "loadSpaceSize" .= s ]
instance FromJSON Document where
parseJSON (Object v) = Document <$> v .: "load" <*> v .: "items"
parseJSON _ = mzero
instance ToJSON Document where
toJSON (Document l i) = object [ "load" .= l, "items" .= i ]
data CompleteProblem = CompleteProblem ItemQuantityMap ProblemDescription deriving (Show)
extractProblem :: Document -> CompleteProblem
extractProblem (Document l i) =
CompleteProblem itemMap $ ProblemDescription (mkSizeSpaceVec $ loadSpaceSize l) indexedItems quantities
where
mkSizeSpaceVec (Vec3 l w h) = mkSizeSpace l w h
indexedItems = zip [0..] $ mkSizeSpaceVec . itemSize <$> i
quantities = zip [0..] $ quantity <$> i
itemMap = M.fromList quantities
eitherDecodeFile :: FilePath -> IO (Either String CompleteProblem)
eitherDecodeFile = liftM (eitherDecode >=> Right . extractProblem) . BS.readFile
|
apriori/daak
|
lib/DAAK/Algorithms/Gamo/JsonImport.hs
|
mit
| 2,780 | 0 | 13 | 986 | 782 | 419 | 363 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
module PagedResponse (Paged, nextPage) where
import Data.Text (Text, unpack)
import Data.ByteString.UTF8 (fromString)
import Servant.API
import Network.HTTP.Link
import Network.HTTP.Types.URI
type Paged a = Headers '[Header "Link" Text] a
extractNextURI :: [Link] -> Maybe URI
extractNextURI [] = Nothing
extractNextURI (link:rest) =
case link of
Link uri params ->
if hasNext params then
Just uri
else extractNextURI rest
where hasNext = foldr ((||) . isNext) False
isNext (Rel, "next") = True
isNext _ = False
extractPageParam :: URI -> Maybe Text
extractPageParam uri =
do
item <- extractPageQueryItem queryText
case item of (_, value) -> value
where queryText = parseQueryText $ fromString $ uriQuery uri
extractPageQueryItem [] = Nothing
extractPageQueryItem (x:xs) =
if isPageItem x then Just x else extractPageQueryItem xs
isPageItem item =
case item of
("page", _) -> True
_ -> False
nextPage :: Paged a -> Maybe String
nextPage pagedResult = let hdrs = getHeadersHList pagedResult in
case hdrs of
HCons (Header val) _ ->
do
links <- parseLinkHeader val
uri <- extractNextURI links
pageText <- extractPageParam uri
return $ unpack pageText
_ -> Nothing
|
miciek/mr-stats-haskell-servant
|
src/PagedResponse.hs
|
mit
| 1,594 | 0 | 13 | 403 | 441 | 230 | 211 | 48 | 4 |
module Melchior.Dom.Events where
import Melchior.Data.String
import Melchior.Dom.Html
data Event a = ElementEvt ElementEvent | MouseEvt MouseEvent | KeyboardEvt KeyboardEvent
instance Show (Event a) where
show (ElementEvt a) = show a
show (MouseEvt a) = show a
show (KeyboardEvt a) = show a
data ElementEvent = InputEvt | ChangeEvt | ResetEvt | SubmitEvt | InvalidEvt
instance Show ElementEvent where
show InputEvt = "input"
show ChangeEvt = "change"
show ResetEvt = "reset"
show SubmitEvt = "submit"
show InvalidEvt = "invalid"
data MouseEvent = ClickEvt | DblClick | MouseDown | MouseUp | MouseEnter | MouseLeave
| MouseOut | MouseOver | MouseMove
instance Show MouseEvent where
show ClickEvt = "click"
show DblClick = "dblclick"
show MouseDown = "mousedown"
show MouseUp = "mouseup"
show MouseEnter = "mouseenter"
show MouseLeave = "mouseleave"
show MouseOut = "mouseout"
show MouseOver = "mouseover"
show MouseMove = "mousemove"
instance Renderable MouseEvent where
render e = stringToJSString $ show e
data KeyboardEvent = KeyDown | KeyPress | KeyUp
instance Show KeyboardEvent where
show KeyDown = "keydown"
show KeyPress = "keypress"
show KeyUp = "keyup"
instance Renderable KeyboardEvent where
render e = stringToJSString $ show e
|
kjgorman/melchior
|
Melchior/Dom/Events.hs
|
mit
| 1,299 | 0 | 8 | 244 | 373 | 198 | 175 | 36 | 0 |
module Chapter05.EqExercises where
data TisAnInteger =
TisAn Integer
instance Eq TisAnInteger where
(==) (TisAn x) (TisAn y) =
x == y
data TwoIntegers =
Two Integer Integer
deriving Show
instance Eq TwoIntegers where
(==) (Two x y) (Two p q) =
x == y && p == q
data StringOrInt =
TisAnInt Int
| TisAString String
instance Eq StringOrInt where
(==) (TisAnInt x) (TisAnInt y) =
x == y
(==) (TisAString s) (TisAString s') =
s == s'
data Pair a =
Pair a a
deriving Show
-- so (Pair a) in the instance line is talking
-- about the line 'data Pair a' not the value
-- constructor 'Pair a a'
instance Eq a => Eq (Pair a) where
(==) (Pair x y) (Pair p q) =
x == p &&
y == q
data Tuple a b =
Tuple a b
instance (Eq a, Eq b) => Eq (Tuple a b) where
(==) (Tuple x y) (Tuple x' y') =
x == x' &&
y == y'
data Which a =
ThisOne a
| ThatOne a
instance (Eq a) => Eq (Which a) where
(==) (ThisOne x) (ThisOne x') =
x == x'
(==) (ThatOne x) (ThatOne x') =
x == x'
data EitherOr a b =
Hello a
| GoodBye b
instance (Eq a, Eq b) => Eq (EitherOr a b) where
(==) (Hello x) (Hello x') =
x == x'
(==) (GoodBye x) (GoodBye x') =
x == x'
|
brodyberg/LearnHaskell
|
HaskellProgramming.hsproj/Chapter05/EqExercises.hs
|
mit
| 1,417 | 0 | 8 | 549 | 551 | 298 | 253 | 49 | 0 |
module Main
( main
)
where
-- doctest
import qualified Test.DocTest as DocTest
main :: IO ()
main =
DocTest.doctest
[ "-isrc"
, "src/Party.hs"
]
|
mauriciofierrom/cis194-homework
|
homework08/test/examples/Main.hs
|
mit
| 168 | 0 | 6 | 48 | 44 | 27 | 17 | 8 | 1 |
main :: IO ()
main = print "cow"
|
hausdorff/manifold_stats
|
src/Main.hs
|
mit
| 32 | 0 | 6 | 7 | 19 | 9 | 10 | 2 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE StrictData #-}
module Data.Raft.Index where
import Data.RaftPrelude
newtype Index = Index Word64
deriving (Eq, Ord, Bounded, Enum, Generic, Typeable, Show, Hashable)
instance Default Index where
def = Index 0
class HasIndex a where
index :: Lens' a Index
distance :: Index -> Index -> Int
distance (Index a) (Index b) = fromIntegral a - fromIntegral b
-- | The index which as been safly commited.
type Committed = Index
class HasCommitted a where
committed :: Lens' a Committed
-- | The leaders maximum commited index.
type LeaderCommit = Index
class HasLeaderCommit a where
leaderCommit :: Lens' a LeaderCommit
|
AndrewRademacher/zotac
|
lib/Data/Raft/Index.hs
|
mit
| 847 | 0 | 7 | 192 | 192 | 103 | 89 | 21 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
module U.Util.Term where
import qualified U.Core.ABT as ABT
import qualified U.Codebase.Term as Term
import U.Codebase.Term (Pattern(..), MatchCase(..), F'(..))
import Control.Monad.Writer (tell, execWriter)
import Data.Foldable (traverse_, for_)
text :: Ord v => ABT.Term (Term.F' text termRef typeRef termLink typeLink vt) v a -> [text]
text = execWriter . ABT.visit_ \case
Text t -> tell [t]
_ -> pure ()
dependencies :: Ord v => ABT.Term (Term.F' text termRef typeRef termLink typeLink vt) v a ->
([termRef], [typeRef], [termLink], [typeLink])
dependencies = execWriter . ABT.visit_ \case
Ref r -> termRef r
Constructor r _ -> typeRef r
Request r _ -> typeRef r
Match _ cases -> for_ cases \case
MatchCase pat _guard _body -> go pat where
go = \case
PConstructor r _i args -> typeRef r *> traverse_ go args
PAs pat -> go pat
PEffectPure pat -> go pat
PEffectBind r _i args k -> typeRef r *> traverse_ go args *> go k
PSequenceLiteral pats -> traverse_ go pats
PSequenceOp l _op r -> go l *> go r
_ -> pure ()
TermLink r -> termLink r
TypeLink r -> typeLink r
_ -> pure ()
where
termRef r = tell (pure r, mempty, mempty, mempty)
typeRef r = tell (mempty, pure r, mempty, mempty)
termLink r = tell (mempty, mempty, pure r, mempty)
typeLink r = tell (mempty, mempty, mempty, pure r)
|
unisonweb/platform
|
codebase2/util-term/U/Util/Term.hs
|
mit
| 1,493 | 0 | 21 | 327 | 611 | 314 | 297 | -1 | -1 |
module Text.Docvim.Visitor.Header (extractHeader) where
import Control.Applicative
import Text.Docvim.AST
import Text.Docvim.Visitor
-- | Extracts a list of nodes (if any exist) from the `@header` section(s) of
-- the source code.
--
-- It is not recommended to have multiple headers in a project. If multiple
-- headers (potentially across multiple translation units) exist, there are no
-- guarantees about order but they just get concatenated in the order we see
-- them.
extractHeader :: Alternative f => [Node] -> (f [Node], [Node])
extractHeader = extractBlocks f
where
f x = if x == HeaderAnnotation
then Just endSection
else Nothing
|
wincent/docvim
|
lib/Text/Docvim/Visitor/Header.hs
|
mit
| 669 | 0 | 9 | 126 | 104 | 63 | 41 | 9 | 2 |
{-# LANGUAGE FlexibleContexts #-}
module IAFinance.Environment.Config(
Has(..),
EnvConfig,
Config(..),
ServerConfig(..),
SessionConfig(..),
IAPIConfig(..),
IAPIMethod(..),
modify,
get
) where
-----------------------------------------------------------------------------
-- import
import Control.Monad.Reader (MonadReader, MonadIO, ask, liftIO)
import Control.Concurrent.Async.Lifted.Safe ()
import Control.Concurrent.STM (atomically, modifyTVar', readTVarIO)
import IAFinance.Environment.Internal (
Has(..),
EnvConfig,
Config(..),
ServerConfig(..),
SessionConfig(..),
IAPIConfig(..),
IAPIMethod(..))
-----------------------------------------------------------------------------
-- config
modify :: (MonadReader env m, Has EnvConfig env, MonadIO m)
=> (Config -> Config) -> m ()
modify f = ask >>= \env -> io $ atomically $ flip modifyTVar' f $ member env
get :: (MonadReader env m, Has EnvConfig env, MonadIO m)
=> m Config
get = ask >>= \env -> io $ readTVarIO $ member env
-- helper
io :: (MonadIO m) => IO a -> m a
io = liftIO
|
wiryls/HomeworkCollectionOfMYLS
|
2018.ProjectV/src/IAFinance/Environment/Config.hs
|
mit
| 1,114 | 0 | 9 | 205 | 337 | 204 | 133 | 30 | 1 |
-- import Data.Char
-- digitToIntMay :: Char -> Maybe Int
-- digitToIntMay '.' = Nothing
-- digitToIntMay x = Just $ digitToInt x
-- main = putStrLn $ show $ fmap digitToIntMay "13.2..2"
import Data.Char
charToMaybeInt :: Char -> Maybe Int
charToMaybeInt x
| isDigit x = Just $ digitToInt x
| otherwise = Nothing
main = putStrLn $ show $ fmap charToMaybeInt "13.2..2"
|
michalc/haskell-experiments
|
digits.hs
|
mit
| 380 | 1 | 8 | 76 | 72 | 37 | 35 | 6 | 1 |
{-# LANGUAGE FlexibleInstances, ScopedTypeVariables, TupleSections #-}
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.QuickCheck.Property
import Data.IORef
import Data.Void
import Data.Either
import Numeric.Limp.Solvers.Cbc (solve, Error(..))
import Numeric.Limp.Program
import Numeric.Limp.Rep.IntDouble
import Numeric.Limp.Solvers.Cbc.MatrixRepr (matrixReprOfProgram)
import qualified Numeric.Limp.Canon as Canon
import qualified Numeric.Limp.Canon.Pretty as Canon
main :: IO ()
main = defaultMain limpTest
instance Arbitrary (Program Int Void IntDouble) where
arbitrary = do
let
vars :: [Int]
vars = [1 .. 10]
bounds = map binary vars
obj = LZ ((,1) <$> vars) 0
constraints <- fmap mconcat . vectorOf 5 $ do
vars1 <- sublistOf vars
return $ LZ ((,1) <$> vars1) 0 :== c1
return $ minimise obj constraints bounds
limpTest :: TestTree
limpTest = testProperty "limp" $ \(prog1 :: Program Int Void IntDouble) ->
ioProperty $ do
-- prevent CSE
v <- newIORef prog1
prog2 <- readIORef v
let sol1 = solve prog1
sol2 = solve prog2
score1 = eval <$> sol1 <*> pure (_objective prog1)
score2 = eval <$> sol2 <*> pure (_objective prog2)
valid1 = checkProgram <$> sol1 <*> pure prog1
valid2 = checkProgram <$> sol2 <*> pure prog2
return $
classify (isRight sol1) "feasible" $
if score1 == score2
then property True
else property $
MkResult (Just False) True
("\n" ++ show (score1,valid1,sol1) ++
"\n" ++ show (score2,valid2,sol2) ++
"\n\n" ++ ppr prog1)
Nothing False Nothing mempty mempty mempty [show prog1]
ppr :: Program Int Void IntDouble -> String
ppr p0 =
let p = Canon.program p0
m = matrixReprOfProgram p
lp = Canon.ppr (("Z"++) . show) (("R"++) . show) p
in lp ++ "\n\n" ++ show m
{-
(Right -9.223372036854776e18,Right (Assignment (fromList [(1,-9223372036854775808),(2,0),(3,0),(4,1),(5,1),(6,0),(7,0),(8,1),(9,0),(10,0)]) (fromList [])))
(Right 3.0,Right (Assignment (fromList [(1,0),(2,0),(3,0),(4,1),(5,1),(6,0),(7,0),(8,1),(9,0),(10,0)]) (fromList [])))
Minimize
1.0 Z1 + 1.0 Z2 + 1.0 Z3 + 1.0 Z4 + 1.0 Z5 + 1.0 Z6 + 1.0 Z7 + 1.0 Z8 + 1.0 Z9 + 1.0 Z10
Subject to
-1.0 Z1 - 1.0 Z2 - 1.0 Z6 - 1.0 Z8 - 1.0 Z10 >= -1.0
-1.0 Z1 - 1.0 Z2 - 1.0 Z6 - 1.0 Z8 - 1.0 Z10 <= -1.0
-1.0 Z1 - 1.0 Z2 - 1.0 Z5 - 1.0 Z7 - 1.0 Z9 >= -1.0
-1.0 Z1 - 1.0 Z2 - 1.0 Z5 - 1.0 Z7 - 1.0 Z9 <= -1.0
-1.0 Z5 >= -1.0
-1.0 Z5 <= -1.0
-1.0 Z1 - 1.0 Z4 - 1.0 Z7 - 1.0 Z9 >= -1.0
-1.0 Z1 - 1.0 Z4 - 1.0 Z7 - 1.0 Z9 <= -1.0
-1.0 Z7 - 1.0 Z8 >= -1.0
-1.0 Z7 - 1.0 Z8 <= -1.0
Bounds
0.0 <= Z1 <= 1.0
0.0 <= Z2 <= 1.0
0.0 <= Z3 <= 1.0
0.0 <= Z4 <= 1.0
0.0 <= Z5 <= 1.0
0.0 <= Z6 <= 1.0
0.0 <= Z7 <= 1.0
0.0 <= Z8 <= 1.0
0.0 <= Z9 <= 1.0
0.0 <= Z10 <= 1.0
Generals
Z1
Z2
Z3
Z4
Z5
Z6
Z7
Z8
Z9
Z10
-}
|
amosr/limp-cbc
|
test/Main.hs
|
mit
| 3,000 | 0 | 21 | 803 | 642 | 341 | 301 | 53 | 2 |
import XMonad
import XMonad.Layout.NoBorders
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.SetWMName
import XMonad.Hooks.DynamicLog
import XMonad.Actions.CycleWS
import XMonad.Util.EZConfig
-- LAYOUTS
import XMonad.Layout.Spacing
import XMonad.Layout.ResizableTile
import XMonad.Layout.Grid
--------------------------------------------------------------------------------------------------------------------
-- DECLARE WORKSPACES RULES
--------------------------------------------------------------------------------------------------------------------
myLayout = avoidStruts (tiledSpace |||
Mirror tiledSpace |||
fullscreen |||
grid |||
Mirror grid |||
tiled |||
Mirror tiled)
where
tiled = spacing 5 $ ResizableTall nmaster delta ratio []
tiledSpace = spacing 60 $ ResizableTall nmaster delta ratio []
grid = spacing 20 $ Grid
fullscreen = noBorders Full
-- Default number of windows in master pane
nmaster = 1
-- Percent of the screen to increment when resizing
delta = 5/100
-- Default proportion of the screen taken up by main pane
ratio = toRational (2/(1 + sqrt 5 :: Double))
--------------------------------------------------------------------------------------------------------------------
-- WORKSPACE DEFINITIONS
--------------------------------------------------------------------------------------------------------------------
myWorkspaces = map show [1..10]
main = do
xmonad =<< myXmobar (defaultConfig
{ terminal = myTerminal
, borderWidth = 1
, layoutHook = smartBorders $ myLayout
, workspaces = myWorkspaces
, normalBorderColor = color8
, focusedBorderColor = color8
-- Hack to make java apps work
, startupHook = setWMName "LG3D"
} `additionalKeys` [ ((mod1Mask, xK_Right), nextWS)
, ((mod1Mask, xK_Left), prevWS)
, ((mod1Mask .|. shiftMask, xK_Right), shiftToNext >> nextWS)
, ((mod1Mask .|. shiftMask, xK_Left), shiftToPrev >> prevWS)
, ((mod1Mask, xK_Down), moveTo Next EmptyWS)
, ((mod1Mask, xK_Up), toggleWS)
])
myTerminal = "urxvtc"
background= "#181512"
foreground= "#D6C3B6"
color0= "#332d29"
color8= "#817267"
color1= "#8c644c"
color9= "#9f7155"
color2= "#746C48"
color10= "#9f7155"
color3= "#bfba92"
color11= "#E0DAAC"
color4= "#646a6d"
color12= "#777E82"
color5= "#766782"
color13= "#897796"
color6= "#4B5C5E"
color14= "#556D70"
color7= "#504339"
color15= "#9a875f"
myXmobar conf = statusBar "xmobar" myXmobarPP toggleStrutsKey conf
toggleStrutsKey XConfig {XMonad.modMask = modMask1} = (modMask1, xK_b)
myXmobarPP = defaultPP { ppCurrent = xmobarColor color9 "" . wrap "[" "]"
, ppTitle = xmobarColor color8 "" . shorten 110
, ppLayout = concat . map (" " ++) . map (take 2) . words
, ppVisible = wrap "(" ")"
, ppUrgent = xmobarColor color12 color13
}
|
hmrm/arch-computer-setup
|
modules/x11/files/xmonad.hs
|
mit
| 3,337 | 21 | 14 | 963 | 684 | 391 | 293 | 66 | 1 |
module P012 (main, solveBasic, triangles) where
{-
The sequence of triangle numbers is generated by adding the natural numbers.
So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred
divisors?
-}
import qualified Common as C
import qualified Control.Arrow as A
input :: Int
input = 500
main :: IO ()
main = -- do
C.time "P012(Basic): " $ solveBasic input
triangles :: [Int]
triangles = scanl (+) 1 [2..]
-- 素因数分解の結果から約数の個数を出す
solveBasic :: Int -> Int
solveBasic = fst . head . flip dropWhile (map (id A.&&& divisorCount) triangles) . flip (.) snd . flip (<=)
where divisorCount = product . map ((+ 1) . fst) . C.primeFactors . fromIntegral
{-
FIXME 素因数の個数を O(n^(1/3)) で出せるアルゴリズムがあるようなので試す
http://pekempey.hatenablog.com/entry/2016/02/09/213718
-}
|
yyotti/euler_haskell
|
src/P012.hs
|
mit
| 1,262 | 0 | 13 | 252 | 194 | 112 | 82 | 13 | 1 |
-- Copyright (C) 2007 Eric Kow
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2, or (at your option)
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; see the file COPYING. If not, write to
-- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301, USA.
{-# LANGUAGE CPP #-}
module Darcs.UI.Commands.ShowBug ( showBug ) where
import Darcs.UI.Commands ( DarcsCommand(..), withStdOpts, nodefaults, findRepository )
import Darcs.UI.Flags ( DarcsFlag )
import Darcs.UI.Options ( DarcsOption, oid, odesc, ocheck, onormalise, defaultFlags )
import qualified Darcs.UI.Options.All as O ( workingRepoDir, StdCmdAction, Verbosity, UseCache )
import Darcs.Util.Path ( AbsolutePath )
#include "impossible.h"
showBugDescription :: String
showBugDescription = "Simulate a run-time failure."
showBugHelp :: String
showBugHelp =
"Show bug can be used to see what darcs would show you if you encountered.\n"
++"a bug in darcs.\n"
showBugBasicOpts :: DarcsOption a (Maybe String -> a)
showBugBasicOpts = O.workingRepoDir
showBugOpts :: DarcsOption a
(Maybe String
-> Maybe O.StdCmdAction
-> Bool
-> Bool
-> O.Verbosity
-> Bool
-> O.UseCache
-> Maybe String
-> Bool
-> Maybe String
-> Bool
-> a)
showBugOpts = showBugBasicOpts `withStdOpts` oid
showBug :: DarcsCommand [DarcsFlag]
showBug = DarcsCommand
{ commandProgramName = "darcs"
, commandName = "bug"
, commandHelp = showBugHelp
, commandDescription = showBugDescription
, commandExtraArgs = 0
, commandExtraArgHelp = []
, commandCommand = showBugCmd
, commandPrereq = findRepository
, commandGetArgPossibilities = return []
, commandArgdefaults = nodefaults
, commandAdvancedOptions = []
, commandBasicOptions = odesc showBugBasicOpts
, commandDefaults = defaultFlags showBugOpts
, commandCheckOptions = ocheck showBugOpts
, commandParseOptions = onormalise showBugOpts
}
showBugCmd :: (AbsolutePath, AbsolutePath) -> [DarcsFlag] -> [String] -> IO ()
showBugCmd _ _ _ = bug "This is actually a fake bug in darcs."
|
DavidAlphaFox/darcs
|
src/Darcs/UI/Commands/ShowBug.hs
|
gpl-2.0
| 2,744 | 0 | 17 | 649 | 442 | 266 | 176 | 48 | 1 |
module Capture.Win32 where
import Data
import qualified Data.MyText as T
import Control.Monad
import Control.Exception (bracket)
import Control.Applicative
import Data.Maybe
import Data.Time.Clock
import System.IO
import Graphics.Win32.Window.Extra
setupCapture :: IO ()
setupCapture = do
return ()
captureData :: IO CaptureData
captureData = do
titles <- fetchWindowTitles
foreground <- getForegroundWindow
let winData = [ fromWDv0 (h == foreground, T.pack t, T.pack p)
| (h, t, p) <- titles]
it <- fromIntegral `fmap` getIdleTime
return $ CaptureData winData it (T.pack "")
|
nomeata/darcs-mirror-arbtt
|
src/Capture/Win32.hs
|
gpl-2.0
| 653 | 0 | 14 | 154 | 200 | 109 | 91 | 21 | 1 |
-- Copyright: (c) Johan Astborg, Andreas Bock
-- License: BSD-3
-- Maintainers: Andreas Bock <[email protected]>
-- Johan Astborg <[email protected]>
-- Stability: experimental
-- Portability: portable
module HQL where
-- import Utils.Brownian
import Utils.Calendar
import Utils.Payments
import Utils.Currency
import Utils.DayCount
import Utils.Graphics.Visualize
import Instruments.Instrument
import Instruments.Derivatives.Derivatives
import Instruments.Utils.BinomialModel
import Instruments.Utils.InterestRate
import Instruments.Utils.TermStructure
import Instruments.FixedIncome.Bonds
|
andreasbock/hql
|
src/HQL.hs
|
gpl-2.0
| 617 | 0 | 4 | 78 | 72 | 49 | 23 | 12 | 0 |
module Probability.BivariateDistributions where
import Notes
import Functions.Application.Macro
import Functions.Basics.Macro
import Functions.Basics.Terms
import Functions.Inverse.Macro
import Logic.PropositionalLogic.Macro
import Probability.Intro.Macro
import Probability.ProbabilityMeasure.Macro
import Probability.ProbabilityMeasure.Terms
import Probability.RandomVariable.Macro
import Probability.RandomVariable.Terms
import Probability.BivariateDistributions.Terms
bivariateDistributionS :: Note
bivariateDistributionS = section "Bivariate distributions" $ do
stochasticTupleDefinition
stochasticTupleInducesProbabilityMeasure
bivariateDistributionFunctionDefinition
bivariateDistributionFunctionProperties
stochasticTupleDefinition :: Note
stochasticTupleDefinition = de $ do
let x = "X"
y = "Y"
s ["Let", m x, and, m y, "be two", randomVariables, "in a", probabilitySpace, m prsp_]
s ["The tuple", m $ tuple x y, "is called a", stochasticTuple', or, stochasticVector, "of dimension", m 2]
ma $ func (tuple x y) univ_ (reals ^ 2) omega $ tuple (fn x omega) (fn y omega)
stochasticTupleInducesProbabilityMeasure :: Note
stochasticTupleInducesProbabilityMeasure = thm $ do
let x = "X"
y = "Y"
s ["Let", m $ tuple x y, "be a", stochasticTuple]
let p = prm_ !: (tuple x y)
s ["This induces a", probabilityMeasure, m p]
let a = "a"
b = "b"
ma $ fn p ((ocint minfty a) ⨯ (ocint minfty b)) =: prob (fn (inv x) (ocint minfty a) ∩ fn (inv y) (ocint minfty b))
toprove
bivariateDistributionFunctionDefinition :: Note
bivariateDistributionFunctionDefinition = de $ do
let x = "X"
y = "Y"
s ["Let", m $ tuple x y, "be a", stochasticTuple]
s ["A", bivariateDistributionFunction, "is a", function, "as follows"]
let d = df $ tuple x y
a = "a"
b = "b"
ma $ func2 d reals reals reals a b $ prob (x <= a ∧ y <= b)
bivariateDistributionFunctionProperties :: Note
bivariateDistributionFunctionProperties = prop $ do
let x = "X"
y = "Y"
d = df $ tuple x y
s ["Let", m d, "be the", bivariateDistributionFunction, "of a", stochasticTuple, m $ tuple x y]
let a = "a"
b = "b"
itemize $ do
item $ s [m d, "is", increasing, "in every argument"]
item $ s [m d, "is", rightCongruent, "in every argument"]
item $ m $ lim a minfty (fn2 d a b) =: lim b minfty (fn2 d a b) =: 0
item $ m $ lim2 a pinfty b pinfty (fn2 d a b) =: 1
|
NorfairKing/the-notes
|
src/Probability/BivariateDistributions.hs
|
gpl-2.0
| 2,643 | 0 | 16 | 682 | 857 | 445 | 412 | -1 | -1 |
module PrisonersDilemma.Renderer (
renderPDFrame
) where
import FRP.FrABS
import PrisonersDilemma.Model
import qualified Graphics.Gloss as GLO
type PDRenderFrame = RenderFrame PDAgentState PDEnvironment
type PDAgentColorer = AgentCellColorerDisc2d PDAgentState
renderPDFrame :: PDRenderFrame
renderPDFrame = renderFrameDisc2d
(defaultAgentRendererDisc2d pdAgentColor pdCoord)
voidEnvRendererDisc2d
pdAgentColor :: PDAgentColorer
pdAgentColor PDAgentState { pdCurrAction = curr, pdPrevAction = prev } = agentActionsToColor prev curr
agentActionsToColor :: PDAction -> PDAction -> GLO.Color
agentActionsToColor Cooperator Cooperator = GLO.makeColor (realToFrac 0.0) (realToFrac 0.0) (realToFrac 0.7) 1.0
agentActionsToColor Defector Defector = GLO.makeColor (realToFrac 0.7) (realToFrac 0.0) (realToFrac 0.0) 1.0
agentActionsToColor Defector Cooperator = GLO.makeColor (realToFrac 0.0) (realToFrac 0.4) (realToFrac 0.0) 1.0
agentActionsToColor Cooperator Defector = GLO.makeColor (realToFrac 1.0) (realToFrac 0.9) (realToFrac 0.0) 1.0
|
thalerjonathan/phd
|
coding/libraries/chimera/examples/ABS/PrisonersDilemma/Renderer.hs
|
gpl-3.0
| 1,087 | 0 | 8 | 162 | 276 | 144 | 132 | 18 | 1 |
Maybe [Int] -> Maybe [Int]
|
hmemcpy/milewski-ctfp-pdf
|
src/content/1.7/code/haskell/snippet35.hs
|
gpl-3.0
| 26 | 2 | 5 | 4 | 18 | 9 | 9 | -1 | -1 |
module HEP.Automation.MadGraph.Dataset.Set20110708set1 where
import HEP.Storage.WebDAV.Type
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Model.ZpH
import HEP.Automation.MadGraph.Dataset.Processes
import HEP.Automation.JobQueue.JobType
psetup_zph_TTBar0or1J :: ProcessSetup ZpH
psetup_zph_TTBar0or1J = PS {
model = ZpH
, process = preDefProcess TTBar0or1J
, processBrief = "TTBar0or1J"
, workname = "628ZpH_TTBar0or1J"
}
zphParamSet :: [ModelParam ZpH]
zphParamSet = [ ZpHParam { massZp = m,
gRZp = g } | m <- [200,220..1000]
, g <- [0.5,0.6..4] ]
-- m <- [200,400,600,800,1000], g <- [1,2,3,4,5] ]
psetuplist :: [ProcessSetup ZpH ]
psetuplist = [ psetup_zph_TTBar0or1J ]
sets :: [Int]
sets = [1]
ucut :: UserCut
ucut = UserCut {
uc_metcut = 15.0
, uc_etacutlep = 2.7
, uc_etcutlep = 18.0
, uc_etacutjet = 2.7
, uc_etcutjet = 15.0
}
eventsets :: [EventSet]
eventsets =
[ EventSet (psetup_zph_TTBar0or1J)
(RS { param = p
, numevent = 10000
, machine = LHC7 ATLAS
, rgrun = Fixed
, rgscale = 200.0
, match = MLM
, cut = DefCut
, pythia = NoPYTHIA
, usercut = NoUserCutDef
, pgs = NoPGS
, jetalgo = AntiKTJet 0.4
, uploadhep = NoUploadHEP
, setnum = num
})
| p <- zphParamSet , num <- sets ]
webdavdir :: WebDAVRemoteDir
webdavdir = WebDAVRemoteDir "paper3/ttbarLHCpartonscan"
|
wavewave/madgraph-auto-dataset
|
src/HEP/Automation/MadGraph/Dataset/Set20110708set1.hs
|
gpl-3.0
| 1,825 | 0 | 10 | 610 | 394 | 247 | 147 | 49 | 1 |
-- Copyright (C) 2015 Guillem Marpons
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Main where
import Codec.Archive.Zip
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.ParallelIO.Local
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger
import Control.Monad.Trans.Control
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Resource
import Data.Binary hiding (get)
import Data.Binary.Get
import qualified Data.ByteString.Char8 as BS8
import Data.Conduit
import qualified Data.Conduit.Combinators as CC
import qualified Data.Conduit.List as CL
import qualified Data.Conduit.Serialization.Binary as CS
import Data.List ((\\), partition)
import Data.Maybe
import Data.String
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Calendar
import Data.Time.LocalTime
import Database.Persist
import Database.Persist.Postgresql hiding (get, getTableName)
import Database.Persist.TH
import qualified Filesystem as F
import qualified Filesystem.Path.CurrentOS as F
import Options.Applicative
-- |
-- = DB schema definition
--
-- See doc/FICHEROS.txt. For definitions of CERA and CERE see
-- http://www.ine.es/ss/Satellite?L=es_ES&c=Page&cid=1254735788994&p=1254735788994&pagename=CensoElectoral%2FINELayout.
share
[ mkPersist sqlSettings { mpsPrefixFields = True
, mpsGeneric = False
, mpsGenerateLenses = False
}
, mkMigrate "migrateAll"
]
[persistLowerCase|
TiposFichero
tipoFichero Int
descrTipoFichero Text
Primary tipoFichero
deriving Show
TiposEleccion
tipoEleccion Int
descrTipoEleccion Text
Primary tipoEleccion
deriving Show
ComunidadesAutonomas
codigoComunidad Int
comunidad Text
Primary codigoComunidad
deriving Show
DistritosElectorales
tipoEleccion Int
codigoProvincia Int
codigoDistritoElectoral Int
provincia Text -- Idx FTS
distritoElectoral Text -- Idx FTS
Primary tipoEleccion codigoProvincia codigoDistritoElectoral
Foreign TiposEleccion tipos_eleccion_fkey tipoEleccion
deriving Show
-- No indexes for (ano, mes), as we can search by (tipoEleccion, ano, mes)
-- with PKey's indexes.
-- In the following DB tables DistritosElectorales cannot be used for
-- foreign keys, as codigoDistritoElectoral can take values 0 or 9 (see
-- doc/FICHEROS.txt).
ProcesosElectorales -- 02xxaamm.DAT
tipoEleccion Int
ano Int
mes Int
vuelta Int
tipoAmbito String sqltype=varchar(1)
ambito Int
fecha Day
horaApertura TimeOfDay
horaCierre TimeOfDay
horaPrimerAvanceParticipacion TimeOfDay
horaSegundoAvanceParticipacion TimeOfDay
Primary tipoEleccion ano mes vuelta tipoAmbito ambito
Foreign TiposEleccion tipos_eleccion_fkey tipoEleccion
deriving Show
Candidaturas -- 03xxaamm.DAT
tipoEleccion Int
ano Int
mes Int
codigoCandidatura Int
siglas Text sqltype=varchar(50) -- Idx FTS
denominacion Text sqltype=varchar(150) -- Idx FTS
codigoCandidaturaProvincial Int
codigoCandidaturaAutonomico Int
codigoCandidaturaNacional Int
Primary tipoEleccion ano mes codigoCandidatura
Foreign TiposEleccion tipos_eleccion_fkey tipoEleccion
deriving Show
Candidatos -- 04xxaamm.DAT
tipoEleccion Int
ano Int
mes Int
vuelta Int
codigoProvincia Int -- Idx (a)
codigoDistritoElectoral Int
codigoMunicipio Int -- Idx (a)
codigoCandidatura Int
numeroOrden Int
tipoCandidato String sqltype=varchar(1)
nombreCandidato Text sqltype=varchar(75) -- Idx FTS
nombrePila Text Maybe sqltype=varchar(25) -- Idx FTS
primerApellido Text Maybe sqltype=varchar(25) -- Idx FTS
segundoApellido Text Maybe sqltype=varchar(25) -- Idx FTS
independiente String sqltype=varchar(1)
sexo String sqltype=varchar(1)
fechaNacimiento Day Maybe
dni Text Maybe sqltype=varchar(10) -- Idx
elegido String sqltype=varchar(1)
Primary tipoEleccion ano mes vuelta codigoProvincia codigoDistritoElectoral codigoMunicipio codigoCandidatura numeroOrden
Foreign TiposEleccion tipos_eleccion_fkey tipoEleccion
deriving Show
DatosMunicipios -- 05xxaamm.DAT and 1104aamm.DAT
tipoEleccion Int -- 4 if < 250
ano Int
mes Int
-- Called 'vuelta' in < 250
vuelta Int -- 0 in referendums
pregunta Int -- 0 in non-referendums
codigoComunidad Int
codigoProvincia Int -- Idx (a)
codigoMunicipio Int -- Idx (a)
distritoMunicipal Int -- 99 if < 250 or total
-- Called 'nombreMunicipio' in < 250
nombreMunicipioODistrito Text sqltype=varchar(100) -- Idx FTS
codigoDistritoElectoral Int -- 0 if < 250
codigoPartidoJudicial Int
codigoDiputacionProvincial Int
codigoComarca Int
poblacionDerecho Int
numeroMesas Int
censoIne Int
censoEscrutinio Int
censoResidentesExtranjeros Int -- CERE
votantesResidentesExtranejros Int -- CERE
votantesPrimerAvanceParticipacion Int
votantesSegundoAvanceParticipacion Int
votosEnBlanco Int
votosNulos Int
votosACandidaturas Int
numeroEscanos Int
votosAfirmativos Int Maybe -- Nothing if < 250
votosNegativos Int Maybe -- Nothing if < 250
datosOficiales String sqltype=varchar(1)
-- The following field must be Nothing if > 250
tipoMunicipio String Maybe sqltype=varchar(2)
Primary tipoEleccion ano mes vuelta pregunta codigoProvincia codigoMunicipio distritoMunicipal
Foreign TiposEleccion tipos_eleccion_fkey tipoEleccion
Foreign ComunidadesAutonomas comunidades_autonomas_fkey codigoComunidad
deriving Show
VotosMunicipios -- 06xxaamm.DAT and 1204aamm.DAT
tipoEleccion Int
ano Int
mes Int
vuelta Int
codigoProvincia Int -- Idx (a)
codigoMunicipio Int -- Idx (a)
distritoMunicipal Int -- 99 if < 250 or total
codigoCandidatura Int
-- Called 'votos' in > 250
votosCandidatura Int
numeroCandidatos Int
-- The following field must be "" if > 250
nombreCandidato Text sqltype=varchar(75) -- Idx FTS
nombrePila Text Maybe sqltype=varchar(25) -- Idx FTS
primerApellido Text Maybe sqltype=varchar(25) -- Idx FTS
segundoApellido Text Maybe sqltype=varchar(25) -- Idx FTS
independiente String Maybe sqltype=varchar(1)
-- The 5 that follow: Nothing if > 250 (fechaNacimiento and dni can also
-- be Noting in some < 250)
tipoMunicipio String Maybe sqltype=varchar(2)
sexo String Maybe sqltype=varchar(1)
fechaNacimiento Day Maybe
dni Text Maybe sqltype=varchar(10) -- Idx
votosCandidato Int Maybe
elegido String Maybe sqltype=varchar(1)
Primary tipoEleccion ano mes vuelta codigoProvincia codigoMunicipio distritoMunicipal codigoCandidatura nombreCandidato
Foreign TiposEleccion tipos_eleccion_fkey tipoEleccion
deriving Show
DatosAmbitoSuperior -- 07xxaamm.DAT
tipoEleccion Int
ano Int
mes Int
vuelta Int -- 0 in referendums
pregunta Int -- 0 in non-referendums
codigoComunidad Int
codigoProvincia Int -- Idx
codigoDistritoElectoral Int
nombreAmbitoTerritorial Text sqltype=varchar(50)
poblacionDerecho Int
numeroMesas Int
censoIne Int
censoEscrutinio Int
censoResidentesExtranjeros Int -- CERE
votantesResidentesExtranejros Int -- CERE
votantesPrimerAvanceParticipacion Int
votantesSegundoAvanceParticipacion Int
votosEnBlanco Int
votosNulos Int
votosACandidaturas Int
numeroEscanos Int
votosAfirmativos Int
votosNegativos Int
datosOficiales String sqltype=varchar(1)
-- codigoComunidad necessary in PKey because totals CERA by Comunidad have
-- codigoProvincia = 99.
Primary tipoEleccion ano mes vuelta pregunta codigoComunidad codigoProvincia codigoDistritoElectoral
Foreign TiposEleccion tipos_eleccion_fkey tipoEleccion
Foreign ComunidadesAutonomas comunidades_autonomas_fkey codigoComunidad
deriving Show
VotosAmbitoSuperior -- 08xxaamm.DAT
tipoEleccion Int
ano Int
mes Int
vuelta Int
codigoComunidad Int
codigoProvincia Int -- Idx
codigoDistritoElectoral Int
codigoCandidatura Int
votos Int
numeroCandidatos Int
-- codigoComunidad necessary in PKey because totals CERA by Comunidad have
-- codigoProvincia = 99.
Primary tipoEleccion ano mes vuelta codigoComunidad codigoProvincia codigoDistritoElectoral codigoCandidatura
Foreign TiposEleccion tipos_eleccion_fkey tipoEleccion
deriving Show
DatosMesas -- 09xxaamm.DAT, includes CERA (except local el.)
tipoEleccion Int
ano Int
mes Int
vuelta Int -- 0 in referendums
pregunta Int -- 0 in non-referendums
codigoComunidad Int -- 99 if CERA national total
codigoProvincia Int -- Idx (a), 99 if CERA nat. or aut. total
codigoMunicipio Int -- Idx (a), 999 if CERA
distritoMunicipal Int -- distritoElectoral if CERA, 9 if =codigoProvincia
codigoSeccion String sqltype=varchar(4) -- 0000 if CERA
codigoMesa String sqltype=varchar(1) -- "U" if CERA
censoIne Int
censoEscrutinio Int
censoResidentesExtranjeros Int -- CERE. 0 if CERA
votantesResidentesExtranejros Int -- CERE. 0 if CERA
votantesPrimerAvanceParticipacion Int -- 0 if CERA
votantesSegundoAvanceParticipacion Int -- 0 if CERA
votosEnBlanco Int
votosNulos Int
votosACandidaturas Int
votosAfirmativos Int
votosNegativos Int
datosOficiales String sqltype=varchar(1)
-- codigoComunidad necessary in PKey because totals CERA by Comunidad have
-- codigoProvincia = 99.
Primary tipoEleccion ano mes vuelta pregunta codigoComunidad codigoProvincia codigoMunicipio distritoMunicipal codigoSeccion codigoMesa
Foreign TiposEleccion tipos_eleccion_fkey tipoEleccion
Foreign ComunidadesAutonomas comunidades_autonomas_fkey codigoComunidad
deriving Show
VotosMesas -- 10xxaamm.DAT, includes CERA (except local el.)
tipoEleccion Int
ano Int
mes Int
vuelta Int
codigoComunidad Int -- 99 if CERA national total
codigoProvincia Int -- Idx (a), 99 if CERA nat. or aut. total
codigoMunicipio Int -- Idx (a), 999 if CERA
distritoMunicipal Int -- distritoElectoral if CERA, 9 if =codigoProvincia
codigoSeccion String sqltype=varchar(4) -- 0000 if CERA
codigoMesa String sqltype=varchar(1) -- "U" if CERA
codigoCandidatura Int
votos Int
-- codigoComunidad necessary in PKey because totals CERA by Comunidad
-- have codigoProvincia = 99.
Primary tipoEleccion ano mes vuelta codigoComunidad codigoProvincia codigoMunicipio distritoMunicipal codigoSeccion codigoMesa codigoCandidatura
Foreign TiposEleccion tipos_eleccion_fkey tipoEleccion
Foreign ComunidadesAutonomas comunidades_autonomas_fkey codigoComunidad
deriving Show
|]
-- |
-- = Static data
insertStaticDataIntoDb :: (MonadResource m, MonadIO m, MonadCatch m)
=>
ReaderT SqlBackend m ()
insertStaticDataIntoDb = do
-- Reinsert all (after delete) on every execution, as no foreign keys
-- are involved
deleteWhere ([] :: [Filter TiposFichero])
insertMany_
[ TiposFichero 1 "Control."
, TiposFichero 2 "Identificación del proceso electoral."
, TiposFichero 3 "Candidaturas."
, TiposFichero 4 "Candidatos."
, TiposFichero 5 "Datos globales de ámbito municipal."
, TiposFichero 6 "Datos de candidaturas de ámbito municipal."
, TiposFichero 7 "Datos globales de ámbito superior al municipio."
, TiposFichero 8 "Datos de candidaturas de ámbito superior al municipio."
, TiposFichero 9 "Datos globales de mesas."
, TiposFichero 10 "Datos de candidaturas de mesas."
, TiposFichero 11 "Datos globales de municipios menores de 250 habitantes (en elecciones municipales)."
, TiposFichero 12 "Datos de candidaturas de municipios menores de 250 habitantes (en elecciones municipales)."
]
updateMany (TiposEleccionKey . tiposEleccionTipoEleccion)
[ TiposEleccion 1 "Referéndum."
, TiposEleccion 2 "Elecciones al Congreso de los Diputados."
, TiposEleccion 3 "Elecciones al Senado."
, TiposEleccion 4 "Elecciones Municipales."
, TiposEleccion 5 "Elecciones Autonómicas."
, TiposEleccion 6 "Elecciones a Cabildos Insulares."
, TiposEleccion 7 "Elecciones al Parlamento Europeo."
, TiposEleccion 10 "Elecciones a Partidos Judiciales y Diputaciones Provinciales."
, TiposEleccion 15 "Elecciones a Juntas Generales."
]
updateMany (ComunidadesAutonomasKey . comunidadesAutonomasCodigoComunidad)
[ ComunidadesAutonomas 1 "Andalucía"
, ComunidadesAutonomas 2 "Aragón"
, ComunidadesAutonomas 3 "Asturias"
, ComunidadesAutonomas 4 "Baleares"
, ComunidadesAutonomas 5 "Canarias"
, ComunidadesAutonomas 6 "Cantabria"
, ComunidadesAutonomas 7 "Castilla - La Mancha"
, ComunidadesAutonomas 8 "Castilla y León"
, ComunidadesAutonomas 9 "Cataluña"
, ComunidadesAutonomas 10 "Extremadura"
, ComunidadesAutonomas 11 "Galicia"
, ComunidadesAutonomas 12 "Madrid"
, ComunidadesAutonomas 13 "Navarra"
, ComunidadesAutonomas 14 "País Vasco"
, ComunidadesAutonomas 15 "Región de Murcia"
, ComunidadesAutonomas 16 "La Rioja"
, ComunidadesAutonomas 17 "Comunidad Valenciana"
, ComunidadesAutonomas 18 "Ceuta"
, ComunidadesAutonomas 19 "Melilla"
, ComunidadesAutonomas 99 "TOTAL NACIONAL C.E.R.A."
]
-- Reinsert all (after delete) on every execution, as no foreign keys
-- are involved
deleteWhere ([] :: [Filter DistritosElectorales])
insertMany_
[ DistritosElectorales 3 7 1 "Baleares" "MALLORCA"
, DistritosElectorales 3 7 2 "Baleares" "MENORCA"
, DistritosElectorales 3 7 3 "Baleares" "IBIZA-FORMENTERA"
, DistritosElectorales 3 35 1 "Las Palmas" "GRAN CANARIA"
, DistritosElectorales 3 35 2 "Las Palmas" "LANZAROTE"
, DistritosElectorales 3 35 3 "Las Palmas" "FUERTEVENTURA"
, DistritosElectorales 3 38 4 "Santa Cruz de Tenerife" "TENERIFE"
, DistritosElectorales 3 38 5 "Santa Cruz de Tenerife" "LA PALMA"
, DistritosElectorales 3 38 6 "Santa Cruz de Tenerife" "LA GOMERA"
, DistritosElectorales 3 38 7 "Santa Cruz de Tenerife" "EL HIERRO"
, DistritosElectorales 5 7 1 "Baleares" "MALLORCA"
, DistritosElectorales 5 7 2 "Baleares" "MENORCA"
, DistritosElectorales 5 7 3 "Baleares" "IBIZA"
, DistritosElectorales 5 7 4 "Baleares" "FORMENTERA"
, DistritosElectorales 5 30 1 "Murcia" "PRIMERA"
, DistritosElectorales 5 30 2 "Murcia" "SEGUNDA"
, DistritosElectorales 5 30 3 "Murcia" "TERCERA"
, DistritosElectorales 5 30 4 "Murcia" "CUARTA"
, DistritosElectorales 5 30 5 "Murcia" "QUINTA"
, DistritosElectorales 5 33 1 "Asturias" "ORIENTE"
, DistritosElectorales 5 33 2 "Asturias" "CENTRO"
, DistritosElectorales 5 33 3 "Asturias" "OCCIDENTE"
, DistritosElectorales 5 35 1 "Las Palmas" "GRAN CANARIA"
, DistritosElectorales 5 35 2 "Las Palmas" "LANZAROTE"
, DistritosElectorales 5 35 3 "Las Palmas" "FUERTEVENTURA"
, DistritosElectorales 5 38 4 "Santa Cruz de Tenerife" "TENERIFE"
, DistritosElectorales 5 38 5 "Santa Cruz de Tenerife" "LA PALMA"
, DistritosElectorales 5 38 6 "Santa Cruz de Tenerife" "LA GOMERA"
, DistritosElectorales 5 38 7 "Santa Cruz de Tenerife" "EL HIERRO"
, DistritosElectorales 6 35 1 "Las Palmas" "GRAN CANARIA"
, DistritosElectorales 6 35 2 "Las Palmas" "LANZAROTE"
, DistritosElectorales 6 35 3 "Las Palmas" "FUERTEVENTURA"
, DistritosElectorales 6 38 4 "Santa Cruz de Tenerife" "TENERIFE"
, DistritosElectorales 6 38 5 "Santa Cruz de Tenerife" "LA PALMA"
, DistritosElectorales 6 38 6 "Santa Cruz de Tenerife" "LA GOMERA"
, DistritosElectorales 6 38 7 "Santa Cruz de Tenerife" "EL HIERRO"
, DistritosElectorales 15 1 1 "Álava" "VITORIA-GASTEIZ"
, DistritosElectorales 15 1 2 "Álava" "AIRA-AYALA"
, DistritosElectorales 15 1 3 "Álava" "RESTO"
, DistritosElectorales 15 20 1 "Guipúzcoa" "DEBA-UROLA"
, DistritosElectorales 15 20 2 "Guipúzcoa" "BIDASOA-OYARZUN"
, DistritosElectorales 15 20 3 "Guipúzcoa" "DONOSTIALDEA"
, DistritosElectorales 15 20 4 "Guipúzcoa" "ORIA"
, DistritosElectorales 15 48 1 "Vizcaya" "BILBAO"
, DistritosElectorales 15 48 2 "Vizcaya" "ENCARTACIONES"
, DistritosElectorales 15 48 3 "Vizcaya" "DURANGO-ARRATIA"
, DistritosElectorales 15 48 4 "Vizcaya" "BUSTURIA-URIBE"
]
where
updateMany
:: forall a m.
(MonadIO m, PersistEntity a, PersistEntityBackend a ~ SqlBackend)
=>
(a -> Key a) -> [a] -> ReaderT SqlBackend m ()
updateMany keyFunc newRecords = do
let newKeys = map keyFunc newRecords
-- The following throws an exception (a bug in Persistent?):
-- droppedKeys <- selectKeysList [persistIdField /<-. newKeys] []
oldKeys <- selectKeysList ([] :: [Filter a]) []
let droppedKeys = oldKeys \\ newKeys
forM_ droppedKeys $ \key ->
liftIO $ putStrLn $ "Warning: " <> show key <> " deprecated but needs \
\to be deleted manually to not broke foreign keys."
-- The following throws an exception (a bug in Persistent?):
-- zipWithM_ repsert newKeys newRecords
let (recordsToUpd, recordsToIns) = partition (flip elem oldKeys . keyFunc) newRecords
insertMany_ recordsToIns
zipWithM_ replace (map keyFunc recordsToUpd) recordsToUpd
return ()
-- |
-- = Dynamic data
getProcesoElectoral :: Get ProcesosElectorales
getProcesoElectoral =
ProcesosElectorales
<$> (snd <$> getTipoEleccion)
<*> (snd <$> getAno)
<*> (snd <$> getMes)
<*> (snd <$> getVuelta)
<*> getTipoAmbito
<*> (snd <$> getAmbito)
<*> getFecha
<*> getHora
<*> getHora
<*> getHora
<*> getHora
<* getSpaces
getCandidatura :: Get Candidaturas
getCandidatura =
Candidaturas
<$> (snd <$> getTipoEleccion)
<*> (snd <$> getAno)
<*> (snd <$> getMes)
<*> (snd <$> getCodigoCandidatura)
<*> getSiglas
<*> getDenominacion
<*> (snd <$> getCodigoCandidatura)
<*> (snd <$> getCodigoCandidatura)
<*> (snd <$> getCodigoCandidatura)
<* getSpaces
getCandidato :: PersonNameMode -> Get Candidatos
getCandidato mode =
(\ctor (nc, np, a1, a2, i) (s, f, mD, e) -> ctor nc np a1 a2 i s f mD e)
<$> getCandidato'
<*> getNombreCandidato mode
<*> getCandidato''
<* getSpaces
where
getCandidato' =
Candidatos
<$> (snd <$> getTipoEleccion)
<*> (snd <$> getAno)
<*> (snd <$> getMes)
<*> (snd <$> getVuelta)
<*> (snd <$> getCodigoProvincia)
<*> (snd <$> getCodigoDistritoElectoral)
<*> (snd <$> getCodigoMunicipio)
<*> (snd <$> getCodigoCandidatura)
<*> (snd <$> getNumeroOrden)
<*> getTipoCandidato
getCandidato'' =
(,,,)
<$> getSexo
<*> ((Just <$> getFecha) <|> (Nothing <$ skip 8))
<*> getDniMaybe
<*> getElegido
getDatosMunicipio :: Get DatosMunicipios
getDatosMunicipio =
(\t a m v_p -> if t == 1 then DatosMunicipios t a m 0 v_p
else DatosMunicipios t a m v_p 0)
<$> (snd <$> getTipoEleccion)
<*> (snd <$> getAno)
<*> (snd <$> getMes)
<*> (snd <$> getVueltaOPregunta)
<*> (snd <$> getCodigoComunidad)
<*> (snd <$> getCodigoProvincia)
<*> (snd <$> getCodigoMunicipio)
<*> (snd <$> getDistritoMunicipal)
<*> getNombreMunicipioODistrito
<*> (snd <$> getCodigoDistritoElectoral)
<*> (snd <$> getCodigoPartidoJudicial)
<*> (snd <$> getCodigoDiputacionProvincial)
<*> (snd <$> getCodigoComarca)
<*> (snd <$> getPoblacionDerecho 8)
<*> (snd <$> getNumeroMesas 5)
<*> (snd <$> getCensoINE 8)
<*> (snd <$> getCensoEscrutinio 8)
<*> (snd <$> getCensoResidentesExtranjeros 8)
<*> (snd <$> getVotantesResidentesExtranjeros 8)
<*> (snd <$> getVotantesPrimerAvanceParticipacion 8)
<*> (snd <$> getVotantesSegundoAvancePArticipacion 8)
<*> (snd <$> getVotosEnBlanco 8)
<*> (snd <$> getVotosNulos 8)
<*> (snd <$> getVotosACandidaturas 8)
<*> (snd <$> getNumeroEscanos 3)
<*> (Just . snd <$> getVotosAfirmativos 8)
<*> (Just . snd <$> getVotosNegativos 8)
<*> getDatosOficiales
<*> pure Nothing -- tipoMunicipio
<* getSpaces
getVotosMunicipio :: Get VotosMunicipios
getVotosMunicipio =
VotosMunicipios
<$> (snd <$> getTipoEleccion)
<*> (snd <$> getAno)
<*> (snd <$> getMes)
<*> (snd <$> getVuelta)
<*> (snd <$> getCodigoProvincia)
<*> (snd <$> getCodigoMunicipio)
<*> (snd <$> getDistritoMunicipal)
<*> (snd <$> getCodigoCandidatura)
<*> (snd <$> getVotos 8)
<*> (snd <$> getNumeroCandidatos 3)
<*> pure ""
<*> pure Nothing
<*> pure Nothing
<*> pure Nothing
<*> pure Nothing
<*> pure Nothing
<*> pure Nothing
<*> pure Nothing
<*> pure Nothing
<*> pure Nothing
<*> pure Nothing
<* getSpaces
getDatosAmbitoSuperior :: Get DatosAmbitoSuperior
getDatosAmbitoSuperior =
(\t a m v_p -> if t == 1 then DatosAmbitoSuperior t a m 0 v_p
else DatosAmbitoSuperior t a m v_p 0)
<$> (snd <$> getTipoEleccion)
<*> (snd <$> getAno)
<*> (snd <$> getMes)
<*> (snd <$> getVueltaOPregunta)
<*> (snd <$> getCodigoComunidad)
<*> (snd <$> getCodigoProvincia)
<*> (snd <$> getCodigoDistritoElectoral)
<*> getNombreAmbitoTerritorial
<*> (snd <$> getPoblacionDerecho 8)
<*> (snd <$> getNumeroMesas 5)
<*> (snd <$> getCensoINE 8)
<*> (snd <$> getCensoEscrutinio 8)
<*> (snd <$> getCensoResidentesExtranjeros 8)
<*> (snd <$> getVotantesResidentesExtranjeros 8)
<*> (snd <$> getVotantesPrimerAvanceParticipacion 8)
<*> (snd <$> getVotantesSegundoAvancePArticipacion 8)
<*> (snd <$> getVotosEnBlanco 8)
<*> (snd <$> getVotosNulos 8)
<*> (snd <$> getVotosACandidaturas 8)
<*> (snd <$> getNumeroEscanos 6)
<*> (snd <$> getVotosAfirmativos 8)
<*> (snd <$> getVotosNegativos 8)
<*> getDatosOficiales
<* getSpaces
getVotosAmbitoSuperior :: Get VotosAmbitoSuperior
getVotosAmbitoSuperior =
VotosAmbitoSuperior
<$> (snd <$> getTipoEleccion)
<*> (snd <$> getAno)
<*> (snd <$> getMes)
<*> (snd <$> getVuelta)
<*> (snd <$> getCodigoComunidad)
<*> (snd <$> getCodigoProvincia)
<*> (snd <$> getCodigoDistritoElectoral)
<*> (snd <$> getCodigoCandidatura)
<*> (snd <$> getVotos 8)
<*> (snd <$> getNumeroCandidatos 5)
<* getSpaces
getDatosMesa :: Get DatosMesas
getDatosMesa =
(\t a m v_p -> if t == 1 then DatosMesas t a m 0 v_p
else DatosMesas t a m v_p 0)
<$> (snd <$> getTipoEleccion)
<*> (snd <$> getAno)
<*> (snd <$> getMes)
<*> (snd <$> getVueltaOPregunta)
<*> (snd <$> getCodigoComunidad)
<*> (snd <$> getCodigoProvincia)
<*> (snd <$> getCodigoMunicipio)
<*> (snd <$> getDistritoMunicipal)
<*> getCodigoSeccion
<*> getCodigoMesa
<*> (snd <$> getCensoINE 7)
<*> (snd <$> getCensoEscrutinio 7)
<*> (snd <$> getCensoResidentesExtranjeros 7)
<*> (snd <$> getVotantesResidentesExtranjeros 7)
<*> (snd <$> getVotantesPrimerAvanceParticipacion 7)
<*> (snd <$> getVotantesSegundoAvancePArticipacion 7)
<*> (snd <$> getVotosEnBlanco 7)
<*> (snd <$> getVotosNulos 7)
<*> (snd <$> getVotosACandidaturas 7)
<*> (snd <$> getVotosAfirmativos 7)
<*> (snd <$> getVotosNegativos 7)
<*> getDatosOficiales
<* getSpaces
getVotosMesa :: Get VotosMesas
getVotosMesa =
VotosMesas
<$> (snd <$> getTipoEleccion)
<*> (snd <$> getAno)
<*> (snd <$> getMes)
<*> (snd <$> getVuelta)
<*> (snd <$> getCodigoComunidad)
<*> (snd <$> getCodigoProvincia)
<*> (snd <$> getCodigoMunicipio)
<*> (snd <$> getDistritoMunicipal)
<*> getCodigoSeccion
<*> getCodigoMesa
<*> (snd <$> getCodigoCandidatura)
<*> (snd <$> getVotos 7)
<* getSpaces
getDatosMunicipio250 :: Get DatosMunicipios
getDatosMunicipio250 =
((\tm ctor -> ctor (Just tm)) <$> getTipoMunicipio <*>)
$
DatosMunicipios
<$> pure 4 -- tipoEleccion
<*> (snd <$> getAno)
<*> (snd <$> getMes)
<*> (snd <$> getVueltaOPregunta)
<*> pure 0 -- pregunta
<*> (snd <$> getCodigoComunidad)
<*> (snd <$> getCodigoProvincia)
<*> (snd <$> getCodigoMunicipio)
<*> pure 99 -- distritoMunicipal
<*> getNombreMunicipio
<*> pure 0 -- codigoDistritoElectoral
<*> (snd <$> getCodigoPartidoJudicial)
<*> (snd <$> getCodigoDiputacionProvincial)
<*> (snd <$> getCodigoComarca)
<*> (snd <$> getPoblacionDerecho 3)
<*> (snd <$> getNumeroMesas 2)
<*> (snd <$> getCensoINE 3)
<*> (snd <$> getCensoEscrutinio 3)
<*> (snd <$> getCensoResidentesExtranjeros 3)
<*> (snd <$> getVotantesResidentesExtranjeros 3)
<*> (snd <$> getVotantesPrimerAvanceParticipacion 3)
<*> (snd <$> getVotantesSegundoAvancePArticipacion 3)
<*> (snd <$> getVotosEnBlanco 3)
<*> (snd <$> getVotosNulos 3)
<*> (snd <$> getVotosACandidaturas 3)
<*> (snd <$> getNumeroEscanos 2)
<*> pure Nothing -- votosAfirmativos
<*> pure Nothing -- votosNegativos
<*> getDatosOficiales
<* getSpaces
getVotosMunicipio250 :: PersonNameMode -> Get VotosMunicipios
getVotosMunicipio250 mode =
(\tm ctor (nc, np, a1, a2, i) (s, mF) (mD, vc, e) ->
ctor nc np a1 a2 (Just i) (Just tm) (Just s) mF mD (Just vc) (Just e))
<$> getTipoMunicipio
<*> getVotosMunicipios'
<*> getNombreCandidato mode
<*> getVotosMunicipios''
<*> getVotosMunicipios'''
where
getVotosMunicipios' =
VotosMunicipios
<$> pure 4 -- tipoEleccion
<*> (snd <$> getAno)
<*> (snd <$> getMes)
<*> (snd <$> getVuelta)
<*> (snd <$> getCodigoProvincia)
<*> (snd <$> getCodigoMunicipio)
<*> pure 99 -- distritoMunicipal
<*> (snd <$> getCodigoCandidatura)
<*> (snd <$> getVotos 3) -- votosCandidatura
<*> (snd <$> getNumeroCandidatos 2)
getVotosMunicipios'' =
(,)
<$> getSexo
<*> ((Just <$> getFecha) <|> (Nothing <$ skip 8))
getVotosMunicipios''' =
(rightFields <|> wrongFields)
<* getSpaces
rightFields =
(,,)
<$> getDniMaybe
<*> (snd <$> getVotos 3) -- votosCandidato
<*> getElegido
-- Some files have a missing byte in dni and an extra space at line end
wrongFields =
(,,)
<$> (Nothing <$ skip 9)
<*> (snd <$> getVotos 3) -- votosCandidato
<*> getElegido
<* skip 1
data AnyPersistEntityGetFunc
= forall a. (PersistEntity a, PersistEntityBackend a ~ SqlBackend)
=> MkAPEGF (Get a)
| forall a. (PersistEntity a, PersistEntityBackend a ~ SqlBackend)
=> MkAPEGF' (PersonNameMode -> Get a)
getAnyPersistEntity :: FileRef -> Maybe AnyPersistEntityGetFunc
getAnyPersistEntity fRef =
case twoFirstDigits fRef of
"02" -> Just $ MkAPEGF getProcesoElectoral
"03" -> Just $ MkAPEGF getCandidatura
"04" -> Just $ MkAPEGF' getCandidato
"05" -> Just $ MkAPEGF getDatosMunicipio
"06" -> Just $ MkAPEGF getVotosMunicipio
"07" -> Just $ MkAPEGF getDatosAmbitoSuperior
"08" -> Just $ MkAPEGF getVotosAmbitoSuperior
"09" -> Just $ MkAPEGF getDatosMesa
"10" -> Just $ MkAPEGF getVotosMesa
"11" -> Just $ MkAPEGF getDatosMunicipio250
"12" -> Just $ MkAPEGF' getVotosMunicipio250
_ -> Nothing
getSpaces :: Get String
getSpaces = many getSpace
getSpace :: Get Char
getSpace = do
bs <- getByteString 1
if BS8.null (BS8.takeWhile (== ' ') bs)
then empty
else return ' '
getTipoEleccion :: Get (Text, Int)
getTipoEleccion = getInt 2
getAno :: Get (Text, Int)
getAno = getInt 4
getMes :: Get (Text, Int)
getMes = getInt 2
getVuelta :: Get (Text, Int)
getVuelta = getInt 1
getTipoAmbito :: Get String
getTipoAmbito = BS8.unpack <$> getByteString 1
getAmbito :: Get (Text, Int)
getAmbito = getInt 2
getFecha :: Get Day
getFecha = do
d <- snd <$> getInt 2
m <- snd <$> getInt 2
y <- fromIntegral . snd <$> getInt 4
if d == 0 || m == 0 then empty else return $ fromGregorian y m d
-- | Error if reads "hh:mm" where @hh > 23@ or @mm > 59@.
getHora :: Get TimeOfDay
getHora =
TimeOfDay
<$> (snd <$> getInt 2)
<* skip 1 -- ":"
<*> (snd <$> getInt 2)
<*> pure 0
getCodigoCandidatura :: Get (Text, Int)
getCodigoCandidatura = getInt 6
getSiglas :: Get Text
getSiglas = getText 50
getDenominacion :: Get Text
getDenominacion = getText 150
getVueltaOPregunta :: Get (Text, Int)
getVueltaOPregunta = getInt 1
getCodigoComunidad :: Get (Text, Int)
getCodigoComunidad = getInt 2
getCodigoProvincia :: Get (Text, Int)
getCodigoProvincia = getInt 2
getCodigoMunicipio :: Get (Text, Int)
getCodigoMunicipio = getInt 3
getDistritoMunicipal :: Get (Text, Int)
getDistritoMunicipal = getInt 2
getNombreMunicipioODistrito, getNombreMunicipio :: Get Text
getNombreMunicipioODistrito = getText 100
getNombreMunicipio = getText 100
getCodigoDistritoElectoral :: Get (Text, Int)
getCodigoDistritoElectoral = getInt 1
getCodigoPartidoJudicial :: Get (Text, Int)
getCodigoPartidoJudicial = getInt 3
getCodigoDiputacionProvincial :: Get (Text, Int)
getCodigoDiputacionProvincial = getInt 3
getCodigoComarca :: Get (Text, Int)
getCodigoComarca = getInt 3
getPoblacionDerecho :: Int -> Get (Text, Int)
getPoblacionDerecho = getInt
getNumeroMesas :: Int -> Get (Text, Int)
getNumeroMesas = getInt
getCensoINE :: Int -> Get (Text, Int)
getCensoINE = getInt
getCensoEscrutinio :: Int -> Get (Text, Int)
getCensoEscrutinio = getInt
getCensoResidentesExtranjeros :: Int -> Get (Text, Int)
getCensoResidentesExtranjeros = getInt
getVotantesResidentesExtranjeros :: Int -> Get (Text, Int)
getVotantesResidentesExtranjeros = getInt
getVotantesPrimerAvanceParticipacion :: Int -> Get (Text, Int)
getVotantesPrimerAvanceParticipacion = getInt
getVotantesSegundoAvancePArticipacion :: Int -> Get (Text, Int)
getVotantesSegundoAvancePArticipacion = getInt
getVotosEnBlanco :: Int -> Get (Text, Int)
getVotosEnBlanco = getInt
getVotosNulos :: Int -> Get (Text, Int)
getVotosNulos = getInt
getVotosACandidaturas :: Int -> Get (Text, Int)
getVotosACandidaturas = getInt
getNumeroEscanos :: Int -> Get (Text, Int)
getNumeroEscanos = getInt
getVotosAfirmativos :: Int -> Get (Text, Int)
getVotosAfirmativos = getInt
getVotosNegativos :: Int -> Get (Text, Int)
getVotosNegativos = getInt
getDatosOficiales :: Get String
getDatosOficiales = BS8.unpack <$> getByteString 1
getNumeroOrden :: Get (Text, Int)
getNumeroOrden = getInt 3
getTipoCandidato :: Get String
getTipoCandidato = BS8.unpack <$> getByteString 1
class
(PersistEntity a, PersistEntityBackend a ~ SqlBackend)
=>
HasPersonName a
where
nameOneField :: (HasPersonName a) => a -> Text
nameThreeFields :: (HasPersonName a) => a -> Text
fields :: [a -> Maybe Text]
nameThreeFields e = T.intercalate " " $ fromMaybe "" <$> ap fields [e]
instance HasPersonName Candidatos where
nameOneField = candidatosNombreCandidato
fields = [ candidatosNombrePila
, candidatosPrimerApellido
, candidatosSegundoApellido ]
instance HasPersonName VotosMunicipios where
nameOneField = votosMunicipiosNombreCandidato
fields = [ votosMunicipiosNombrePila
, votosMunicipiosPrimerApellido
, votosMunicipiosSegundoApellido ]
-- | Read person names in four different ways, depending on
-- parameter. 'OneFieldName' and 'ThreeFieldsName' are the main alternatives
-- that must be chosen depending on file format. If 'NoInteractionName' is
-- passed, and algorithm is used that tries to read person names as one single
-- 'Text', independently of which of the following cases we are faced on:
--
-- 1. Name and two surnames are split up into three pieces of 25 bytes length.
-- 2. All the 75 bytes are a single piece of data with the name and two
-- surnames.
--
-- There is one situation in which the algorithm does the wrong thing: we are in
-- case (1) and some of the two first pieces of text are using all the 25
-- bytes. Then, we will concat the pieces without the necessary white-space.
--
-- The option 'TryOneAndThreeFieldsName' is used to get both the results of the
-- first two options, possibly to show the results to the user and let her chose
-- between them.
getNombreCandidato
:: PersonNameMode -> Get (Text, Maybe Text, Maybe Text, Maybe Text, String)
getNombreCandidato OneFieldName =
(\(i, nc) -> (nc, Nothing, Nothing, Nothing, i))
<$> (splitIndFlag . T.stripEnd . T.pack . BS8.unpack)
<$> getByteString 75
getNombreCandidato ThreeFieldsName =
(\np a1 (i, a2) -> (np <> " " <> a1 <> " " <> a2, Just np, Just a1, Just a2, i))
<$> ((T.stripEnd . T.pack . BS8.unpack) <$> getByteString 25)
<*> ((T.stripEnd . T.pack . BS8.unpack) <$> getByteString 25)
<*> ((splitIndFlag . T.stripEnd . T.pack . BS8.unpack) <$> getByteString 25)
getNombreCandidato NoInteractionName =
(\(i, nc) -> (nc, Nothing, Nothing, Nothing, i))
<$> (splitIndFlag . T.unwords . T.words . T.pack . BS8.unpack) -- rm rdnt. ws
<$> getByteString 75
getNombreCandidato TryOneAndThreeFieldsName =
(\np a1 (i, a2) -> ( T.stripEnd (np <> a1 <> a2)
, Just (T.stripEnd np)
, Just (T.stripEnd a1)
, Just (T.stripEnd a2)
, i )
)
<$> ((T.pack . BS8.unpack) <$> getByteString 25)
<*> ((T.pack . BS8.unpack) <$> getByteString 25)
<*> ((splitIndFlag . T.pack . BS8.unpack) <$> getByteString 25)
splitIndFlag :: Text -> (String, Text)
splitIndFlag t = if upEnd == "(IND)" then ("S", T.stripEnd begin) else ("N", t)
where
(begin, end) = T.splitAt (T.length t - 5) t
upEnd = T.toUpper end
getNombre :: Get Text
getNombre = getText 25
getSexo :: Get String
getSexo = BS8.unpack <$> getByteString 1
getDniMaybe :: Get (Maybe Text)
getDniMaybe = do
t <- getText 10
if T.all (== ' ') t
then return Nothing
else return $ Just t
getElegido :: Get String
getElegido = BS8.unpack <$> getByteString 1
getVotos :: Int -> Get (Text, Int)
getVotos = getInt
getNumeroCandidatos :: Int -> Get (Text, Int)
getNumeroCandidatos = getInt
getNombreAmbitoTerritorial :: Get Text
getNombreAmbitoTerritorial = getText 50
getCodigoSeccion :: Get String
getCodigoSeccion = BS8.unpack <$> getByteString 4
getCodigoMesa :: Get String
getCodigoMesa = BS8.unpack <$> getByteString 1
getTipoMunicipio :: Get String
getTipoMunicipio = BS8.unpack <$> getByteString 2
-- | Given a number of bytes to read, gets and 'Int' (into the Get monad) both
-- as a number and as Text. It fails if fewer than @n@ bytes are left in the
-- input or some of the read bytes is not a decimal digit, with the exception of
-- all bytes being spaces. In this case, and due to some .DAT files not honoring
-- their specification, (<n spaces>, 0) is returned.
getInt :: Int -> Get (Text, Int)
getInt n = do
bs <- getByteString n
case BS8.readInt bs of
Just (i, bs') | BS8.null bs' -> return (T.pack (BS8.unpack bs), i)
Nothing -> if BS8.all (== ' ') bs
then return (T.pack (BS8.unpack bs), 0)
else empty
_ -> empty
-- | Given a number of bytes to read, gets (into the Get monad) the end-stripped
-- 'Text' represented by those bytes. It fails if fewer than @n@ bytes are left
-- in the input.
getText :: Int -> Get Text
getText n = T.stripEnd . T.pack . BS8.unpack <$> getByteString n
-- |
-- = Command line options
data MigrateFlag = Migrate | DonTMigrate
data InteractiveFlag = Interactive | NoInteractive
data Options
= Options
{ dbConnOpts :: BS8.ByteString
, usersToGrantAccessTo :: [String]
, migrateFlag :: MigrateFlag
, interactiveFlag :: InteractiveFlag
, files :: [F.FilePath]
}
options :: Parser Options
options = Options
<$> dbConnOptions
<*> option ((fmap T.unpack . T.splitOn "," . T.pack) <$> str)
( long "grant-access-to"
<> short 'g'
<> metavar "USERS"
<> help "Comma-separated list of DB users to grant reading access privileges to"
<> value []
)
<*> flagMigrate
<*> flagInteractive
<*> some (argument (fromString <$> str) (metavar "FILES..."))
where
flagMigrate =
caseMigrate
<$> flag (Just Migrate) (Just DonTMigrate)
( long "no-migration"
<> help "Disable DB migration and static data insertion"
)
<*> flag Nothing (Just Migrate)
( long "migration"
<> help "Enable DB migration and static data insertion (default)"
)
caseMigrate (Just Migrate) _ = Migrate
caseMigrate _ (Just Migrate) = Migrate
caseMigrate _ _ = DonTMigrate
flagInteractive =
caseInteractive
<$> flag (Just Interactive) (Just NoInteractive)
( long "no-interactive"
<> help "Disable interaction to choose person name format"
)
<*> flag Nothing (Just Interactive)
( long "interactive"
<> help "Enable interaction to choose person name format (default)"
)
caseInteractive (Just Interactive) _ = Interactive
caseInteractive _ (Just Interactive) = Interactive
caseInteractive _ _ = NoInteractive
dbConnOptions :: Parser BS8.ByteString
dbConnOptions =
(\h p d u pwd -> BS8.pack $ concat [h, p, d, u, pwd])
<$> option (str >>= param "host")
( long "host"
<> short 'H'
<> metavar "HOSTNAME"
<> help "Passes parameter host=HOSTNAME to database connection"
<> value "localhost"
)
<*> option (str >>= param "port")
( long "port"
<> short 'p'
<> metavar "PORT"
<> help "Passes parameter port=PORT to database connection"
<> value "5432" -- Default postgresql port
)
<*> option (str >>= param "dbname")
( long "dbname"
<> short 'd'
<> metavar "DB"
<> help "Passes parameter dbname=DB to database connection"
<> value ""
)
<*> option (str >>= param "user")
( long "username"
<> short 'u'
<> metavar "USER"
<> help "Passes parameter user=USER to database connection"
<> value ""
)
<*> option (str >>= param "password")
( long "password"
<> short 'P'
<> metavar "PASSWD"
<> help "Passes param. password=PASSWD to database connection"
<> value ""
)
where
param _ "" = return ""
param p s = return $ p ++ "=" ++ s ++ " "
helpMessage :: InfoMod a
helpMessage =
fullDesc
<> progDesc "Connect to database and do things"
<> header "Relational-ize .DAT files\
\ from www.infoelectoral.interior.es"
-- |
-- = Entry point and auxiliary functions.
-- | Entry point. All SQL commands related to a file are run in a single
-- connection/transaction.
main :: IO ()
main = execParser options' >>= \(Options c g migrFlag interFlag filePaths) ->
runNoLoggingT $ withPostgresqlPool c poolSize $ \dbPool -> do
-- Migration and insertion of static data
case migrFlag of
Migrate -> liftIO $ flip runSqlPersistMPool dbPool $ do
liftIO $ putStrLn "Migrating database"
runMigration migrateAll
liftIO $ putStrLn "Inserting static data"
insertStaticDataIntoDb `onException` liftIO (putStrLn "Uncaught exception")
DonTMigrate -> do
liftIO $ putStrLn "Skipping database migration"
liftIO $ putStrLn "Skipping static data insertion"
-- Ask for person name syntax
fileRefsL <- mapM (toFileRefsWithPersonNameMode interFlag) filePaths
let fileRefs = concat fileRefsL
-- Insertion of dynamic data
liftIO $ putStrLn "Inserting dynamic data"
nCapabilities <- liftIO getNumCapabilities
liftIO $ withPool (nCapabilities * 2) $ \ioPool ->
parallel_ ioPool [readFileRefIntoDb g dbPool fileRef | fileRef <- fileRefs]
where
-- TODO: adapt poolSize to actual max_connections
options' = info (helper <*> options) helpMessage
poolSize = 80 -- PG's max_connections = 100 by default in Debian
data PersonNameMode
= OneFieldName
| ThreeFieldsName
| NoInteractionName
| TryOneAndThreeFieldsName
deriving Show
data FileRef
= Path F.FilePath
| ZipEntry F.FilePath Entry
instance Show FileRef where
show (Path p) = filePathToStr p
show (ZipEntry p e) = filePathToStr p <> "[" <> eRelativePath e <> "]"
filePathToStr :: F.FilePath -> String
filePathToStr p = T.unpack $ either id id $ F.toText p
twoFirstDigits :: FileRef -> String
twoFirstDigits (Path p)
= take 2 $ T.unpack $ either id id $ F.toText $ F.basename p
twoFirstDigits (ZipEntry _p e)
= twoFirstDigits $ Path $ F.fromText $ T.pack $ eRelativePath e
sourceFileRef
:: forall m.
MonadResource m
=> FileRef -> Producer m BS8.ByteString
sourceFileRef (Path p) = CC.sourceFile p
sourceFileRef (ZipEntry _ e) = CC.sourceLazy (fromEntry e)
-- | Returns a list of @FileRef@s with an associated @PersonNameMode@ that
-- depends on the result of user interaction. In case of .zip files one pair per
-- entry is returned. A @FileRef@ will have 'Nothing' assigned if it doesn't
-- contain person names. In the case of a parsing or I/O error while reading the
-- file (or one of its entries) an empty list is returned.
toFileRefsWithPersonNameMode
:: forall m.
(MonadIO m, MonadCatch m, MonadBaseControl IO m)
=>
InteractiveFlag -> F.FilePath -> m [(FileRef, Maybe PersonNameMode)]
toFileRefsWithPersonNameMode interFlag filePath = do
isRegularFile <- liftIO $ F.isFile filePath
if isRegularFile then runResourceT $
handleAll (expWhen' $ "reading file " <> show filePath) $
childRefs (Path filePath) extension (twoFirstDigits (Path filePath))
else do liftIO $ putStrLn $ "Error: File " ++ show filePath
++ " doesn't exist or is not readable"
return []
where
childRefs fRef "DAT" "04" = handle (expParse fRef) $
case interFlag of
Interactive -> do
m <- sourceFileRef fRef
$$ askForPersonNameMode getCandidato'
return [(fRef, Just m)]
NoInteractive ->
return [(fRef, Just NoInteractionName)]
childRefs fRef "DAT" "12" = handle (expParse fRef) $
case interFlag of
Interactive -> do
m <- sourceFileRef fRef
$$ askForPersonNameMode getVotos'
return [(fRef, Just m)]
NoInteractive ->
return [(fRef, Just NoInteractionName)]
childRefs fRef "DAT" _ = return [(fRef, Nothing)]
childRefs _ "ZIP" _ = sourceDatEntriesFromZipFile filePath
$= CC.mapM recCall
=$= CC.concat
$$ CL.consume
childRefs _ _ _ = do liftIO $ putStrLn $ "Error: File "
++ show filePath
++ " is not a .DAT or .ZIP file"
return []
recCall e = let fRef = ZipEntry filePath e
in childRefs fRef "DAT" (twoFirstDigits fRef)
extension = T.toUpper (fromMaybe "" (F.extension filePath))
getCandidato' = getCandidato TryOneAndThreeFieldsName
getVotos' = getVotosMunicipio250 TryOneAndThreeFieldsName
expParse fRef exception = do
expWhenParseError ("reading file " <> show fRef) exception
return []
expWhen' msg exception = do { expWhen msg exception; return [] }
sourceDatEntriesFromZipFile
:: forall m.
(MonadResource m, MonadCatch m)
=>
F.FilePath -> Producer m Entry
sourceDatEntriesFromZipFile filePath =
CC.sourceFile filePath
$= CS.conduitDecode
=$= CC.map getEntries
=$= CC.concat
=$= CC.filter hasDatExt
where
getEntries ar = catMaybes $ fmap (`findEntryByPath` ar) (filesInArchive ar)
hasDatExt en = T.toUpper (fromMaybe "" (F.extension (entryPath en))) == "DAT"
entryPath = F.fromText . T.pack . eRelativePath
askForPersonNameMode
:: forall a m.
(HasPersonName a, MonadResource m)
=>
Get a -> Consumer BS8.ByteString m PersonNameMode
askForPersonNameMode getFunc =
CC.filterE (/= 10) -- filter out spaces
=$= CS.conduitGet getFunc
=$ askForPersonNameModeLoop
askForPersonNameModeLoop
:: forall a m.
(HasPersonName a, MonadResource m)
=>
Consumer a m PersonNameMode
askForPersonNameModeLoop = do
mEntity <- await
case mEntity of
Nothing -> return NoInteractionName
Just entity -> do
liftIO $ putStrLn "Which of the two choices (A or B) looks better:"
liftIO $ putStrLn $ "A: [" <> T.unpack (nameOneField entity) <> "]"
liftIO $ putStrLn $ "B: [" <> T.unpack (nameThreeFields entity) <> "]"
isNull <- CC.null
let getCharLoop = do
liftIO $ putStrLn $ "Type 'a' or 'b'"
<> if isNull then ":" else " (or 'm' for more examples):"
line <- liftIO getLine
case line of
"a" -> return OneFieldName
"b" -> return ThreeFieldsName
"m" -> if isNull then getCharLoop else askForPersonNameModeLoop
_ -> getCharLoop
getCharLoop
-- | Read a file from a file path or a zip entry and insert its contents into
-- the database. A new DB connection is started on every call to this functions,
-- thus for every file reference.
readFileRefIntoDb
:: forall m.
(MonadIO m, MonadCatch m, MonadBaseControl IO m)
=>
[String] -> ConnectionPool -> (FileRef, Maybe PersonNameMode) -> m ()
readFileRefIntoDb grantUsers pool (fRef, mMode) =
case getAnyPersistEntity fRef of
Just anyGetFunc ->
handleAll (expWhen $ "inserting rows to " <> show fRef) $
handle (expWhenParseError $ "reading file " <> show fRef) $
liftIO $ flip runSqlPersistMPool pool $ do
liftIO $ putStrLn $ "Inserting rows from " <> show fRef
sourceFileRef fRef $$ sinkDatContentsToDb anyGetFunc mMode
let tableName' = getTableName anyGetFunc
liftIO $ putStrLn $ "Inserted "<> show fRef <>" to "<> show tableName'
grantReadAccessAll tableName' grantUsers
Nothing ->
liftIO $ putStrLn $ "Warning: file " <> show fRef <> " not processed"
sinkDatContentsToDb
:: (MonadIO m, MonadCatch m)
=>
AnyPersistEntityGetFunc
-> Maybe PersonNameMode
-> Consumer BS8.ByteString (ReaderT SqlBackend m) ()
sinkDatContentsToDb (MkAPEGF getFunc) _mode =
CC.filterE (`notElem` [10, 13]) -- filter out newline chars
=$= CS.conduitGet getFunc
=$= CL.sequence (CL.take 1000) -- bulk insert in chunks of size 1000
=$ CC.mapM_ insertMany_
sinkDatContentsToDb (MkAPEGF' getFunc) (Just mode) =
CC.filterE (`notElem` [10, 13]) -- filter out newline chars
=$= CS.conduitGet (getFunc mode)
=$= CL.sequence (CL.take 1000) -- bulk insert in chunks of size 1000
=$ CC.mapM_ insertMany_
sinkDatContentsToDb (MkAPEGF' _) Nothing =
error "sinkDatContentsToDb: no PersonNameMode specified"
getTableName :: AnyPersistEntityGetFunc -> Text
getTableName = getTableName'
where
getTableName' :: AnyPersistEntityGetFunc -> Text
getTableName' (MkAPEGF getFunc) = getTableName'' getFunc
getTableName' (MkAPEGF' getFunc) = getTableName'' $
getFunc TryOneAndThreeFieldsName
getTableName''
:: forall a.
(PersistEntity a, PersistEntityBackend a ~ SqlBackend)
=>
Get a -> Text
-- The following call to head is never performed, so code works even for
-- empty lists
getTableName'' _getFunc = T.filter (/='"') $ tableName (head ([] :: [a]))
grantReadAccessAll
:: forall m.
(MonadIO m, MonadCatch m)
=>
Text -> [String] -> ReaderT SqlBackend m ()
grantReadAccessAll tableName' grantUsers =
forM_ grantUsers $ \user' ->
handleAll (expWhen ("granting access privileges for user " ++ user')) $
grantReadAccess tableName' user'
-- | Grant reading access to 'table' for database user 'dbUser' using a raw
-- PostgreSQL query.
grantReadAccess
:: forall m. MonadIO m
=>
Text -> String -> ReaderT SqlBackend m ()
grantReadAccess table dbUser
= rawExecute ("GRANT SELECT ON " <> table <> " TO " <> T.pack dbUser) []
expWhen :: MonadIO m => String -> SomeException -> m ()
expWhen msg e = do
let text = "\n\n" ++ "Caught when " ++ msg ++ " :" ++ show e ++ "\n\n"
liftIO $ putStrLn text
expWhenParseError :: MonadIO m => String -> CS.ParseError -> m ()
expWhenParseError msg e@(CS.ParseError unconsumed' _ _) = do
let e' = e {CS.unconsumed = BS8.take 1500 unconsumed'}
let text = "\n\n" ++ "Caught when " ++ msg ++ " :" ++ show e' ++ "\n\n"
liftIO $ putStrLn text
|
gmarpons/elections-in-spain
|
ElectionsInSpain.hs
|
gpl-3.0
| 55,798 | 0 | 42 | 17,139 | 10,451 | 5,411 | 5,040 | 912 | 12 |
phoneBook =
[("Murali", "1234")
,("Sathish", "5678")
,("Balu", "9101")
,("Vishnu", "8983")
,("Vinay", "4315")
]
findElement :: Eq k => k -> [(k, v)] -> v
findElement key map = snd . head . filter (\(k, v) -> k == key) $ map
findKey :: Eq k => k -> [(k, v)] -> Maybe v
findKey _ [] = Nothing
findKey key ((k, v):xs) = if k == key
then Just v
else findKey key xs
|
muralikrishna8/Haskell-problems
|
map.hs
|
gpl-3.0
| 443 | 0 | 10 | 156 | 210 | 118 | 92 | 13 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.FirebaseRules.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.FirebaseRules.Types.Sum where
import Network.Google.Prelude
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | The severity of the issue.
data IssueSeverity
= SeverityUnspecified
-- ^ @SEVERITY_UNSPECIFIED@
-- An unspecified severity.
| Deprecation
-- ^ @DEPRECATION@
-- Deprecation issue for statements and method that may no longer be
-- supported or maintained.
| Warning
-- ^ @WARNING@
-- Warnings such as: unused variables.
| Error'
-- ^ @ERROR@
-- Errors such as: unmatched curly braces or variable redefinition.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable IssueSeverity
instance FromHttpApiData IssueSeverity where
parseQueryParam = \case
"SEVERITY_UNSPECIFIED" -> Right SeverityUnspecified
"DEPRECATION" -> Right Deprecation
"WARNING" -> Right Warning
"ERROR" -> Right Error'
x -> Left ("Unable to parse IssueSeverity from: " <> x)
instance ToHttpApiData IssueSeverity where
toQueryParam = \case
SeverityUnspecified -> "SEVERITY_UNSPECIFIED"
Deprecation -> "DEPRECATION"
Warning -> "WARNING"
Error' -> "ERROR"
instance FromJSON IssueSeverity where
parseJSON = parseJSONText "IssueSeverity"
instance ToJSON IssueSeverity where
toJSON = toJSONText
|
rueshyna/gogol
|
gogol-firebase-rules/gen/Network/Google/FirebaseRules/Types/Sum.hs
|
mpl-2.0
| 2,478 | 0 | 11 | 615 | 394 | 218 | 176 | 50 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Classroom.UserProFiles.GuardianInvitations.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a list of guardian invitations that the requesting user is
-- permitted to view, filtered by the parameters provided. This method
-- returns the following error codes: * \`PERMISSION_DENIED\` if a
-- \`student_id\` is specified, and the requesting user is not permitted to
-- view guardian invitations for that student, if \`\"-\"\` is specified as
-- the \`student_id\` and the user is not a domain administrator, if
-- guardians are not enabled for the domain in question, or for other
-- access errors. * \`INVALID_ARGUMENT\` if a \`student_id\` is specified,
-- but its format cannot be recognized (it is not an email address, nor a
-- \`student_id\` from the API, nor the literal string \`me\`). May also be
-- returned if an invalid \`page_token\` or \`state\` is provided. *
-- \`NOT_FOUND\` if a \`student_id\` is specified, and its format can be
-- recognized, but Classroom has no record of that student.
--
-- /See:/ <https://developers.google.com/classroom/ Google Classroom API Reference> for @classroom.userProfiles.guardianInvitations.list@.
module Network.Google.Resource.Classroom.UserProFiles.GuardianInvitations.List
(
-- * REST Resource
UserProFilesGuardianInvitationsListResource
-- * Creating a Request
, userProFilesGuardianInvitationsList
, UserProFilesGuardianInvitationsList
-- * Request Lenses
, upfgilStudentId
, upfgilStates
, upfgilXgafv
, upfgilUploadProtocol
, upfgilAccessToken
, upfgilUploadType
, upfgilInvitedEmailAddress
, upfgilPageToken
, upfgilPageSize
, upfgilCallback
) where
import Network.Google.Classroom.Types
import Network.Google.Prelude
-- | A resource alias for @classroom.userProfiles.guardianInvitations.list@ method which the
-- 'UserProFilesGuardianInvitationsList' request conforms to.
type UserProFilesGuardianInvitationsListResource =
"v1" :>
"userProfiles" :>
Capture "studentId" Text :>
"guardianInvitations" :>
QueryParams "states"
UserProFilesGuardianInvitationsListStates
:>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "invitedEmailAddress" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListGuardianInvitationsResponse
-- | Returns a list of guardian invitations that the requesting user is
-- permitted to view, filtered by the parameters provided. This method
-- returns the following error codes: * \`PERMISSION_DENIED\` if a
-- \`student_id\` is specified, and the requesting user is not permitted to
-- view guardian invitations for that student, if \`\"-\"\` is specified as
-- the \`student_id\` and the user is not a domain administrator, if
-- guardians are not enabled for the domain in question, or for other
-- access errors. * \`INVALID_ARGUMENT\` if a \`student_id\` is specified,
-- but its format cannot be recognized (it is not an email address, nor a
-- \`student_id\` from the API, nor the literal string \`me\`). May also be
-- returned if an invalid \`page_token\` or \`state\` is provided. *
-- \`NOT_FOUND\` if a \`student_id\` is specified, and its format can be
-- recognized, but Classroom has no record of that student.
--
-- /See:/ 'userProFilesGuardianInvitationsList' smart constructor.
data UserProFilesGuardianInvitationsList =
UserProFilesGuardianInvitationsList'
{ _upfgilStudentId :: !Text
, _upfgilStates :: !(Maybe [UserProFilesGuardianInvitationsListStates])
, _upfgilXgafv :: !(Maybe Xgafv)
, _upfgilUploadProtocol :: !(Maybe Text)
, _upfgilAccessToken :: !(Maybe Text)
, _upfgilUploadType :: !(Maybe Text)
, _upfgilInvitedEmailAddress :: !(Maybe Text)
, _upfgilPageToken :: !(Maybe Text)
, _upfgilPageSize :: !(Maybe (Textual Int32))
, _upfgilCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UserProFilesGuardianInvitationsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'upfgilStudentId'
--
-- * 'upfgilStates'
--
-- * 'upfgilXgafv'
--
-- * 'upfgilUploadProtocol'
--
-- * 'upfgilAccessToken'
--
-- * 'upfgilUploadType'
--
-- * 'upfgilInvitedEmailAddress'
--
-- * 'upfgilPageToken'
--
-- * 'upfgilPageSize'
--
-- * 'upfgilCallback'
userProFilesGuardianInvitationsList
:: Text -- ^ 'upfgilStudentId'
-> UserProFilesGuardianInvitationsList
userProFilesGuardianInvitationsList pUpfgilStudentId_ =
UserProFilesGuardianInvitationsList'
{ _upfgilStudentId = pUpfgilStudentId_
, _upfgilStates = Nothing
, _upfgilXgafv = Nothing
, _upfgilUploadProtocol = Nothing
, _upfgilAccessToken = Nothing
, _upfgilUploadType = Nothing
, _upfgilInvitedEmailAddress = Nothing
, _upfgilPageToken = Nothing
, _upfgilPageSize = Nothing
, _upfgilCallback = Nothing
}
-- | The ID of the student whose guardian invitations are to be returned. The
-- identifier can be one of the following: * the numeric identifier for the
-- user * the email address of the user * the string literal \`\"me\"\`,
-- indicating the requesting user * the string literal \`\"-\"\`,
-- indicating that results should be returned for all students that the
-- requesting user is permitted to view guardian invitations.
upfgilStudentId :: Lens' UserProFilesGuardianInvitationsList Text
upfgilStudentId
= lens _upfgilStudentId
(\ s a -> s{_upfgilStudentId = a})
-- | If specified, only results with the specified \`state\` values are
-- returned. Otherwise, results with a \`state\` of \`PENDING\` are
-- returned.
upfgilStates :: Lens' UserProFilesGuardianInvitationsList [UserProFilesGuardianInvitationsListStates]
upfgilStates
= lens _upfgilStates (\ s a -> s{_upfgilStates = a})
. _Default
. _Coerce
-- | V1 error format.
upfgilXgafv :: Lens' UserProFilesGuardianInvitationsList (Maybe Xgafv)
upfgilXgafv
= lens _upfgilXgafv (\ s a -> s{_upfgilXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
upfgilUploadProtocol :: Lens' UserProFilesGuardianInvitationsList (Maybe Text)
upfgilUploadProtocol
= lens _upfgilUploadProtocol
(\ s a -> s{_upfgilUploadProtocol = a})
-- | OAuth access token.
upfgilAccessToken :: Lens' UserProFilesGuardianInvitationsList (Maybe Text)
upfgilAccessToken
= lens _upfgilAccessToken
(\ s a -> s{_upfgilAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
upfgilUploadType :: Lens' UserProFilesGuardianInvitationsList (Maybe Text)
upfgilUploadType
= lens _upfgilUploadType
(\ s a -> s{_upfgilUploadType = a})
-- | If specified, only results with the specified \`invited_email_address\`
-- are returned.
upfgilInvitedEmailAddress :: Lens' UserProFilesGuardianInvitationsList (Maybe Text)
upfgilInvitedEmailAddress
= lens _upfgilInvitedEmailAddress
(\ s a -> s{_upfgilInvitedEmailAddress = a})
-- | nextPageToken value returned from a previous list call, indicating that
-- the subsequent page of results should be returned. The list request must
-- be otherwise identical to the one that resulted in this token.
upfgilPageToken :: Lens' UserProFilesGuardianInvitationsList (Maybe Text)
upfgilPageToken
= lens _upfgilPageToken
(\ s a -> s{_upfgilPageToken = a})
-- | Maximum number of items to return. Zero or unspecified indicates that
-- the server may assign a maximum. The server may return fewer than the
-- specified number of results.
upfgilPageSize :: Lens' UserProFilesGuardianInvitationsList (Maybe Int32)
upfgilPageSize
= lens _upfgilPageSize
(\ s a -> s{_upfgilPageSize = a})
. mapping _Coerce
-- | JSONP
upfgilCallback :: Lens' UserProFilesGuardianInvitationsList (Maybe Text)
upfgilCallback
= lens _upfgilCallback
(\ s a -> s{_upfgilCallback = a})
instance GoogleRequest
UserProFilesGuardianInvitationsList
where
type Rs UserProFilesGuardianInvitationsList =
ListGuardianInvitationsResponse
type Scopes UserProFilesGuardianInvitationsList =
'["https://www.googleapis.com/auth/classroom.guardianlinks.students",
"https://www.googleapis.com/auth/classroom.guardianlinks.students.readonly"]
requestClient
UserProFilesGuardianInvitationsList'{..}
= go _upfgilStudentId (_upfgilStates ^. _Default)
_upfgilXgafv
_upfgilUploadProtocol
_upfgilAccessToken
_upfgilUploadType
_upfgilInvitedEmailAddress
_upfgilPageToken
_upfgilPageSize
_upfgilCallback
(Just AltJSON)
classroomService
where go
= buildClient
(Proxy ::
Proxy UserProFilesGuardianInvitationsListResource)
mempty
|
brendanhay/gogol
|
gogol-classroom/gen/Network/Google/Resource/Classroom/UserProFiles/GuardianInvitations/List.hs
|
mpl-2.0
| 10,100 | 0 | 21 | 2,135 | 1,096 | 646 | 450 | 161 | 1 |
<h3>Example 60 (categorical bars #1)</h3>
<palette name="mfpal" type="discrete">
female #FF7F7F; male #7F7FFF
</palette>
<palette name="urpal" type="discrete">
rural #10520D; urban #505050
</palette>
<plot height=600 aspect=1.5 axis-x-label="off"
axis-y-label="Rate" stroke="none">
<bars x="[[d1#sex]]" y="[[d1#rate]]" fill="[[mfpal(x)]]"
aggregation="mean" bar-width=0.5></bars>
</plot>
<plot height=600 aspect=1.5 axis-x-label="off" axis-y-label="Rate">
<bars x="[[zip(d1#sex,d1#env)]]" y="[[d1#rate]]"
aggregation="mean" bar-width=0.5 stroke-width=10
stroke="[[urpal(x#1)]]" fill="[[mfpal(x#0)]]"></bars>
</plot>
<plot height=600 aspect=1.5 axis-x-label="off" axis-y-label="Rate"
group-x="1">
<bars x="[[zip(d1#sex,d1#age)]]" y="[[d1#rate]]"
aggregation="mean" bar-width=0.5 stroke-width=2
fill="[[mfpal(x#0)]]"></bars>
</plot>
<plot height=600 aspect=1.5 axis-x-label="off" axis-y-label="Rate"
group-x="1">
<bars x="[[zip(d1#age,d1#sex)]]" y="[[d1#rate]]"
aggregation="mean" bar-width=0.5 stroke-width=2
fill="[[mfpal(x#1)]]"></bars>
</plot>
<plot-data name="d1">
<metadata name="sex" category-order="male;female"></metadata>
<metadata name="env" category-order="urban;rural"></metadata>
<metadata name="age" category-order="50-54;55-59;60-64;65-69;70-74">
</metadata>
[ { "sex": "female", "env": "rural", "age": "50-54", "rate": 15.5 },
{ "sex": "female", "env": "rural", "age": "55-59", "rate": 20.2 },
{ "sex": "female", "env": "rural", "age": "60-64", "rate": 32.1 },
{ "sex": "female", "env": "rural", "age": "65-69", "rate": 48.0 },
{ "sex": "female", "env": "rural", "age": "70-74", "rate": 65.5 },
{ "sex": "female", "env": "urban", "age": "50-54", "rate": 15.5 },
{ "sex": "female", "env": "urban", "age": "55-59", "rate": 20.2 },
{ "sex": "female", "env": "urban", "age": "60-64", "rate": 32.1 },
{ "sex": "female", "env": "urban", "age": "65-69", "rate": 48.0 },
{ "sex": "female", "env": "urban", "age": "70-74", "rate": 65.5 },
{ "sex": "male", "env": "rural", "age": "50-54", "rate": 17.5 },
{ "sex": "male", "env": "rural", "age": "55-59", "rate": 21.2 },
{ "sex": "male", "env": "rural", "age": "60-64", "rate": 37.1 },
{ "sex": "male", "env": "rural", "age": "65-69", "rate": 49.0 },
{ "sex": "male", "env": "rural", "age": "70-74", "rate": 66.5 },
{ "sex": "male", "env": "urban", "age": "50-54", "rate": 18.5 },
{ "sex": "male", "env": "urban", "age": "55-59", "rate": 23.2 },
{ "sex": "male", "env": "urban", "age": "60-64", "rate": 35.1 },
{ "sex": "male", "env": "urban", "age": "65-69", "rate": 49.0 },
{ "sex": "male", "env": "urban", "age": "70-74", "rate": 67.5 } ]
</plot-data>
|
openbrainsrc/hRadian
|
examples/Example/defunct/Eg60.hs
|
mpl-2.0
| 2,788 | 119 | 57 | 470 | 1,307 | 692 | 615 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Templates.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates a GTM Template.
--
-- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.workspaces.templates.update@.
module Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Templates.Update
(
-- * REST Resource
AccountsContainersWorkspacesTemplatesUpdateResource
-- * Creating a Request
, accountsContainersWorkspacesTemplatesUpdate
, AccountsContainersWorkspacesTemplatesUpdate
-- * Request Lenses
, accXgafv
, accUploadProtocol
, accPath
, accFingerprint
, accAccessToken
, accUploadType
, accPayload
, accCallback
) where
import Network.Google.Prelude
import Network.Google.TagManager.Types
-- | A resource alias for @tagmanager.accounts.containers.workspaces.templates.update@ method which the
-- 'AccountsContainersWorkspacesTemplatesUpdate' request conforms to.
type AccountsContainersWorkspacesTemplatesUpdateResource
=
"tagmanager" :>
"v2" :>
Capture "path" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "fingerprint" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] CustomTemplate :>
Put '[JSON] CustomTemplate
-- | Updates a GTM Template.
--
-- /See:/ 'accountsContainersWorkspacesTemplatesUpdate' smart constructor.
data AccountsContainersWorkspacesTemplatesUpdate =
AccountsContainersWorkspacesTemplatesUpdate'
{ _accXgafv :: !(Maybe Xgafv)
, _accUploadProtocol :: !(Maybe Text)
, _accPath :: !Text
, _accFingerprint :: !(Maybe Text)
, _accAccessToken :: !(Maybe Text)
, _accUploadType :: !(Maybe Text)
, _accPayload :: !CustomTemplate
, _accCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsContainersWorkspacesTemplatesUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'accXgafv'
--
-- * 'accUploadProtocol'
--
-- * 'accPath'
--
-- * 'accFingerprint'
--
-- * 'accAccessToken'
--
-- * 'accUploadType'
--
-- * 'accPayload'
--
-- * 'accCallback'
accountsContainersWorkspacesTemplatesUpdate
:: Text -- ^ 'accPath'
-> CustomTemplate -- ^ 'accPayload'
-> AccountsContainersWorkspacesTemplatesUpdate
accountsContainersWorkspacesTemplatesUpdate pAccPath_ pAccPayload_ =
AccountsContainersWorkspacesTemplatesUpdate'
{ _accXgafv = Nothing
, _accUploadProtocol = Nothing
, _accPath = pAccPath_
, _accFingerprint = Nothing
, _accAccessToken = Nothing
, _accUploadType = Nothing
, _accPayload = pAccPayload_
, _accCallback = Nothing
}
-- | V1 error format.
accXgafv :: Lens' AccountsContainersWorkspacesTemplatesUpdate (Maybe Xgafv)
accXgafv = lens _accXgafv (\ s a -> s{_accXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
accUploadProtocol :: Lens' AccountsContainersWorkspacesTemplatesUpdate (Maybe Text)
accUploadProtocol
= lens _accUploadProtocol
(\ s a -> s{_accUploadProtocol = a})
-- | GTM Custom Template\'s API relative path. Example:
-- accounts\/{account_id}\/containers\/{container_id}\/workspaces\/{workspace_id}\/templates\/{template_id}
accPath :: Lens' AccountsContainersWorkspacesTemplatesUpdate Text
accPath = lens _accPath (\ s a -> s{_accPath = a})
-- | When provided, this fingerprint must match the fingerprint of the
-- templates in storage.
accFingerprint :: Lens' AccountsContainersWorkspacesTemplatesUpdate (Maybe Text)
accFingerprint
= lens _accFingerprint
(\ s a -> s{_accFingerprint = a})
-- | OAuth access token.
accAccessToken :: Lens' AccountsContainersWorkspacesTemplatesUpdate (Maybe Text)
accAccessToken
= lens _accAccessToken
(\ s a -> s{_accAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
accUploadType :: Lens' AccountsContainersWorkspacesTemplatesUpdate (Maybe Text)
accUploadType
= lens _accUploadType
(\ s a -> s{_accUploadType = a})
-- | Multipart request metadata.
accPayload :: Lens' AccountsContainersWorkspacesTemplatesUpdate CustomTemplate
accPayload
= lens _accPayload (\ s a -> s{_accPayload = a})
-- | JSONP
accCallback :: Lens' AccountsContainersWorkspacesTemplatesUpdate (Maybe Text)
accCallback
= lens _accCallback (\ s a -> s{_accCallback = a})
instance GoogleRequest
AccountsContainersWorkspacesTemplatesUpdate
where
type Rs AccountsContainersWorkspacesTemplatesUpdate =
CustomTemplate
type Scopes
AccountsContainersWorkspacesTemplatesUpdate
=
'["https://www.googleapis.com/auth/tagmanager.edit.containers"]
requestClient
AccountsContainersWorkspacesTemplatesUpdate'{..}
= go _accPath _accXgafv _accUploadProtocol
_accFingerprint
_accAccessToken
_accUploadType
_accCallback
(Just AltJSON)
_accPayload
tagManagerService
where go
= buildClient
(Proxy ::
Proxy
AccountsContainersWorkspacesTemplatesUpdateResource)
mempty
|
brendanhay/gogol
|
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Workspaces/Templates/Update.hs
|
mpl-2.0
| 6,353 | 0 | 18 | 1,416 | 863 | 503 | 360 | 130 | 1 |
-- |
-- Module : Main
-- Copyright : (c) 2012-2015 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Main (
-- * Main Entry Point
main
) where
import Control.Concurrent
import Control.Exception (try, finally)
import Control.Monad (liftM)
import Network.BSD (getHostName)
import System.IO (BufferMode(..), stderr, hSetBuffering)
import System.IO.Unsafe (unsafePerformIO)
import GameKeeper.API
import GameKeeper.Logger
import GameKeeper.Metric
import GameKeeper.Nagios
import GameKeeper.Options
import System.Exit (ExitCode(..), exitWith)
import Text.Printf (printf)
import Text.Regex
import qualified Data.ByteString.Char8 as BS
--
-- API
--
main :: IO ()
main = do
hSetBuffering stderr LineBuffering
parseOptions >>= run
where
run (Left s) = putStrLn s >> exitWith (ExitFailure 1)
run (Right o) = logDebug ("Mode: " ++ show o) >> mode o
--
-- Modes
--
mode :: Options -> IO ()
mode Measure{..} = do
host <- (BS.pack . safe) `liftM` getHostName
sink <- open host optSink
forkAll [ showOverview optUri >>= push sink
, listConnections optUri >>= idleConnections optDays >>= push sink
, listChannels optUri >>= push sink
, listExchanges optUri >>= mapM_ (push sink)
, do qs <- listQueues optUri
push sink $ idleQueues qs
mapM_ (push sink) qs
, listBindings optUri >>= push sink
]
wait
close sink
where
safe str = subRegex (mkRegex "\\.") str "_"
mode PruneConnections{..} = do
cs <- liftM idle (listConnections optUri >>= idleConnections optDays)
putStrLn $ "Idle Connections Found: " ++ show (length cs)
mapM_ (deleteConnection optUri) cs
mode PruneQueues{..} = do
qs <- listQueues optUri
putStrLn $ "Unused Queues Found: " ++ show (length qs)
mapM_ (deleteQueue optUri) . idle $ unusedQueues qs
mode CheckNode{..} = do
over <- try $ showOverview optUri
node <- try $ showNode optUri optName
check $ Plugin "NODE" optName
[ Check
{ title = "BACKLOG"
, value = liftM (total . count) over
, health = optMessages
, ok = printf "%s %.0f messages ready"
, critical = printf "%s %.0f / %.0f messages ready"
, warning = printf "%s %.0f / %.0f messages ready"
}
, Check
{ title = "MEMORY"
, value = liftM used node
, health = optMemory
, ok = printf "%s %.2fGB mem used"
, critical = printf "%s %.2f / %.2fGB mem used"
, warning = printf "%s %.2f / %.2fGB mem used"
}
]
mode CheckQueue{..} = do
queue <- try $ showQueue optUri optName
check $ Plugin "QUEUE" optName
[ Check
{ title = "BACKLOG"
, value = liftM messages queue
, health = optMessages
, ok = printf "%s %.0f messages ready"
, critical = printf "%s %.0f / %.0f messages ready"
, warning = printf "%s %.0f / %.0f messages ready"
}
, Check
{ title = "MEMORY"
, value = liftM memory queue
, health = optMemory
, ok = printf "%s %.2fMB mem used"
, critical = printf "%s %.2f / %.2fMB mem used"
, warning = printf "%s %.2f / %.2fMB mem used"
}
]
mode _ = logError err >> error err
where
err = "Unsupported mode"
--
-- Forking
--
children :: MVar [MVar ()]
children = unsafePerformIO (newMVar [])
{-# NOINLINE children #-}
forkAll :: [IO ()] -> IO ()
forkAll = mapM_ fork
fork :: IO () -> IO ThreadId
fork io = do
mvar <- newEmptyMVar
threads <- takeMVar children
putMVar children (mvar:threads)
forkIO (io `finally` putMVar mvar ())
wait :: IO ()
wait = do
cs <- takeMVar children
case cs of
[] -> return ()
m:ms -> do
putMVar children ms
takeMVar m
wait
|
brendanhay/gamekeeper
|
src/Main.hs
|
mpl-2.0
| 4,425 | 0 | 14 | 1,416 | 1,187 | 611 | 576 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.YouTube.Comments.SetModerationStatus
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Sets the moderation status of one or more comments. The API request must
-- be authorized by the owner of the channel or video associated with the
-- comments.
--
-- /See:/ <https://developers.google.com/youtube/v3 YouTube Data API Reference> for @youtube.comments.setModerationStatus@.
module Network.Google.Resource.YouTube.Comments.SetModerationStatus
(
-- * REST Resource
CommentsSetModerationStatusResource
-- * Creating a Request
, commentsSetModerationStatus
, CommentsSetModerationStatus
-- * Request Lenses
, csmsBanAuthor
, csmsModerationStatus
, csmsId
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types
-- | A resource alias for @youtube.comments.setModerationStatus@ method which the
-- 'CommentsSetModerationStatus' request conforms to.
type CommentsSetModerationStatusResource =
"youtube" :>
"v3" :>
"comments" :>
"setModerationStatus" :>
QueryParam "id" Text :>
QueryParam "moderationStatus"
CommentsSetModerationStatusModerationStatus
:>
QueryParam "banAuthor" Bool :>
QueryParam "alt" AltJSON :> Post '[JSON] ()
-- | Sets the moderation status of one or more comments. The API request must
-- be authorized by the owner of the channel or video associated with the
-- comments.
--
-- /See:/ 'commentsSetModerationStatus' smart constructor.
data CommentsSetModerationStatus = CommentsSetModerationStatus'
{ _csmsBanAuthor :: !Bool
, _csmsModerationStatus :: !CommentsSetModerationStatusModerationStatus
, _csmsId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'CommentsSetModerationStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csmsBanAuthor'
--
-- * 'csmsModerationStatus'
--
-- * 'csmsId'
commentsSetModerationStatus
:: CommentsSetModerationStatusModerationStatus -- ^ 'csmsModerationStatus'
-> Text -- ^ 'csmsId'
-> CommentsSetModerationStatus
commentsSetModerationStatus pCsmsModerationStatus_ pCsmsId_ =
CommentsSetModerationStatus'
{ _csmsBanAuthor = False
, _csmsModerationStatus = pCsmsModerationStatus_
, _csmsId = pCsmsId_
}
-- | The banAuthor parameter lets you indicate that you want to automatically
-- reject any additional comments written by the comment\'s author. Set the
-- parameter value to true to ban the author. Note: This parameter is only
-- valid if the moderationStatus parameter is also set to rejected.
csmsBanAuthor :: Lens' CommentsSetModerationStatus Bool
csmsBanAuthor
= lens _csmsBanAuthor
(\ s a -> s{_csmsBanAuthor = a})
-- | Identifies the new moderation status of the specified comments.
csmsModerationStatus :: Lens' CommentsSetModerationStatus CommentsSetModerationStatusModerationStatus
csmsModerationStatus
= lens _csmsModerationStatus
(\ s a -> s{_csmsModerationStatus = a})
-- | The id parameter specifies a comma-separated list of IDs that identify
-- the comments for which you are updating the moderation status.
csmsId :: Lens' CommentsSetModerationStatus Text
csmsId = lens _csmsId (\ s a -> s{_csmsId = a})
instance GoogleRequest CommentsSetModerationStatus
where
type Rs CommentsSetModerationStatus = ()
type Scopes CommentsSetModerationStatus =
'["https://www.googleapis.com/auth/youtube.force-ssl"]
requestClient CommentsSetModerationStatus'{..}
= go (Just _csmsId) (Just _csmsModerationStatus)
(Just _csmsBanAuthor)
(Just AltJSON)
youTubeService
where go
= buildClient
(Proxy :: Proxy CommentsSetModerationStatusResource)
mempty
|
rueshyna/gogol
|
gogol-youtube/gen/Network/Google/Resource/YouTube/Comments/SetModerationStatus.hs
|
mpl-2.0
| 4,693 | 0 | 15 | 1,018 | 479 | 287 | 192 | 76 | 1 |
module AST where
data AST = AST [Block] (Maybe FootnoteDefs)
deriving (Show)
data FootnoteDefs = FootnoteDefs [FootnoteDef]
deriving (Show)
data FootnoteDef = FootnoteDef {
index :: Int,
content :: [Block]
}
deriving (Show)
data ListItem = ListItem [Inline]
| SubList List
deriving (Show)
data List = List Bool [ListItem]
deriving (Show)
data TableCell = TableHeaderCell [Inline]
| TableBodyCell [Inline]
deriving (Show)
data TableRow = TableRow [TableCell]
deriving (Show)
data Block = HardRule
| Paragraph [Inline]
| Header Int [Inline]
| ListBlock List
| BlockQuote [Inline]
| BlockCode {
codeClass :: String,
codeContent :: String
}
| BlockHtml Html
| Table {
thead :: Maybe [TableRow],
body :: [TableRow]
}
deriving (Show)
data Inline = Italics [Inline]
| Bold [Inline]
| Code String
| FootnoteRef Int
| Plaintext String
| InlineHtml Html
| Link {
text :: [Inline],
href :: String
}
| Image {
alt :: String,
src :: String
}
deriving (Show)
data HtmlTagType = Open | Close | SelfClosing
deriving (Show, Eq)
data HtmlTag = HtmlTag {
tagname :: String,
attrs :: [Attr]
}
deriving (Show)
data Attr = Attr String String
deriving (Show)
data Html = PairTag HtmlTag [Either String Html]
| SingleTag HtmlTag
deriving (Show)
|
alexbecker/blogdown
|
src/AST.hs
|
agpl-3.0
| 1,534 | 0 | 10 | 512 | 453 | 270 | 183 | 56 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RankNTypes #-}
module Gonimo.Server.Auth where
import Control.Lens
import Control.Monad (unless)
import Control.Monad.Base (MonadBase)
import Control.Monad.Reader (MonadReader, ask)
import Database.Persist (Entity (..), Key)
import Gonimo.Server.Db.Entities
import Gonimo.Server.Error
data AuthData = AuthData { _accountEntity :: Entity Account
-- Usually just one ore two - so using list lookup
-- should be fine.
, _allowedFamilies :: [FamilyId]
, _deviceEntity :: Entity Device
}
$(makeLenses ''AuthData)
type AuthReader = MonadReader AuthData
type AuthConstraint m = (MonadReader AuthData m, MonadBase IO m)
askAccountId :: AuthReader m => m (Key Account)
askAccountId = entityKey . _accountEntity <$> ask
authView :: AuthReader m => Getter AuthData a -> m a
authView g = (^. g) <$> ask
deviceKey :: AuthData -> Key Device
deviceKey = entityKey . _deviceEntity
isFamilyMember :: FamilyId -> AuthData -> Bool
isFamilyMember fid = (fid `elem`) . _allowedFamilies
isDevice :: DeviceId -> AuthData -> Bool
isDevice deviceId = (== deviceId) . entityKey . _deviceEntity
isAccount :: AccountId -> AuthData -> Bool
isAccount accountId = (== accountId) . entityKey . _accountEntity
authorize :: MonadBase IO m => (a -> Bool) -> a -> m ()
authorize check x = unless (check x) (throwServer Forbidden)
authorizeJust :: MonadBase IO m => (a -> Maybe b) -> a -> m b
authorizeJust check x = fromMaybeErr Forbidden . check $ x
authorizeAuthData :: (AuthReader m, MonadBase IO m) => (AuthData -> Bool) -> m ()
authorizeAuthData check = authorize check =<< ask
|
gonimo/gonimo-back
|
src/Gonimo/Server/Auth.hs
|
agpl-3.0
| 1,856 | 0 | 9 | 505 | 523 | 284 | 239 | -1 | -1 |
-----------------------------------------------------------------------------------------
{-|
Module : Draw
Copyright : (c) Daan Leijen 2003
License : wxWindows
Maintainer : [email protected]
Stability : provisional
Portability : portable
Drawing.
-}
-----------------------------------------------------------------------------------------
module Graphics.UI.WXCore.Draw
(
-- * DC
drawLines, drawPolygon, getTextExtent, getFullTextExtent, dcClearRect
-- ** Creation
, withPaintDC, withClientDC, dcDraw
, withSVGFileDC, withSVGFileDCWithSize, withSVGFileDCWithSizeAndResolution
-- ** Draw state
, DrawState, dcEncapsulate, dcGetDrawState, dcSetDrawState, drawStateDelete
-- ** Double buffering
, dcBuffer, dcBufferWithRef, dcBufferWithRefEx
, dcBufferWithRefExGcdc
-- * Scrolled windows
, windowGetViewStart, windowGetViewRect, windowCalcUnscrolledPosition
-- * Font
, FontStyle(..), FontFamily(..), FontShape(..), FontWeight(..)
, fontDefault, fontSwiss, fontSmall, fontItalic, fontFixed
, withFontStyle, dcWithFontStyle
, dcSetFontStyle, dcGetFontStyle
, fontCreateFromStyle, fontGetFontStyle
-- * Brush
, BrushStyle(..), BrushKind(..)
, HatchStyle(..)
, brushDefault, brushSolid, brushTransparent
, dcSetBrushStyle, dcGetBrushStyle
, withBrushStyle, dcWithBrushStyle, dcWithBrush
, brushCreateFromStyle, brushGetBrushStyle
-- * Pen
, PenStyle(..), PenKind(..), CapStyle(..), JoinStyle(..), DashStyle(..)
, penDefault, penColored, penTransparent
, dcSetPenStyle, dcGetPenStyle
, withPenStyle, dcWithPenStyle, dcWithPen
, penCreateFromStyle, penGetPenStyle
) where
import Graphics.UI.WXCore.WxcTypes
import Graphics.UI.WXCore.WxcDefs
import Graphics.UI.WXCore.WxcClasses
import Graphics.UI.WXCore.WxcClassInfo
import Graphics.UI.WXCore.Types
import Graphics.UI.WXCore.Defines
import Foreign.Storable
import Foreign.Marshal.Alloc
{--------------------------------------------------------------------------------
DC creation
--------------------------------------------------------------------------------}
-- | Safely perform a drawing operation on a DC.
dcDraw :: DC a -> IO b -> IO b
dcDraw dc io
= bracket_ (do dcSetPenStyle dc penDefault
dcSetBrushStyle dc brushDefault)
(do dcSetPen dc nullPen
dcSetBrush dc nullBrush)
io
-- | Use a 'PaintDC'.
withPaintDC :: Window a -> (PaintDC () -> IO b) -> IO b
withPaintDC window draw
= bracket (paintDCCreate window) (paintDCDelete) (\dc -> dcDraw dc (draw dc))
-- | Use a 'ClientDC'.
withClientDC :: Window a -> (ClientDC () -> IO b) -> IO b
withClientDC window draw
= bracket (clientDCCreate window) (clientDCDelete) (\dc -> dcDraw dc (draw dc))
-- | Use a 'SVGFileDC'.
withSVGFileDC :: FilePath -> (SVGFileDC () -> IO b) -> IO b
withSVGFileDC fname draw
= bracket (svgFileDCCreate fname) (svgFileDCDelete) (\dc -> dcDraw dc (draw dc))
withSVGFileDCWithSize :: FilePath -> Size -> (SVGFileDC () -> IO b) -> IO b
withSVGFileDCWithSize fname size draw
= bracket (svgFileDCCreateWithSize fname size) (svgFileDCDelete) (\dc -> dcDraw dc (draw dc))
withSVGFileDCWithSizeAndResolution :: FilePath -> Size -> Float -> (SVGFileDC () -> IO b) -> IO b
withSVGFileDCWithSizeAndResolution fname size dpi draw
= bracket (svgFileDCCreateWithSizeAndResolution fname size dpi) (svgFileDCDelete) (\dc -> dcDraw dc (draw dc))
-- | Clear a specific rectangle with the current background brush.
-- This is preferred to 'dcClear' for scrolled windows as 'dcClear' sometimes
-- only clears the original view area, instead of the currently visible scrolled area.
-- Unfortunately, the background brush is not set correctly on wxMAC 2.4, and
-- this will always clear to a white color on mac systems.
dcClearRect :: DC a -> Rect -> IO ()
dcClearRect dc r
= bracket (dcGetBackground dc)
(brushDelete)
(\brush -> dcWithBrush dc brush $
dcWithPenStyle dc penTransparent $
dcDrawRectangle dc r)
{-
-- | Fill a rectangle with a certain color.
dcFillRect :: DC a -> Rect -> Color -> IO ()
dcFillRect dc r color
= dcWithBrushStyle dc (brushSolid color) $
dcWithPenStyle dc penTransparent $
dcDrawRectangle dc r
-}
{--------------------------------------------------------------------------------
Windows
--------------------------------------------------------------------------------}
-- | Get logical view rectangle, adjusted for scrolling.
windowGetViewRect :: Window a -> IO Rect
windowGetViewRect window
= do size <- windowGetClientSize window
org <- windowGetViewStart window
return (rect org size)
-- | Get logical view start, adjusted for scrolling.
windowGetViewStart :: Window a -> IO Point
windowGetViewStart window
= do isScrolled <- objectIsScrolledWindow window
-- adjust coordinates for a scrolled window
if (isScrolled)
then do let scrolledWindow = objectCast window
(Point sx sy) <- scrolledWindowGetViewStart scrolledWindow
(Point w h) <- scrolledWindowGetScrollPixelsPerUnit scrolledWindow
return (Point (w*sx) (h*sy))
else return pointZero
-- | Get logical coordinates adjusted for scrolling.
windowCalcUnscrolledPosition :: Window a -> Point -> IO Point
windowCalcUnscrolledPosition window p
= do isScrolled <- objectIsScrolledWindow window
-- adjust coordinates for a scrolled window
if (isScrolled)
then do let scrolledWindow = objectCast window
scrolledWindowCalcUnscrolledPosition scrolledWindow p
else return p
{--------------------------------------------------------------------------------
Font
--------------------------------------------------------------------------------}
-- | Font descriptor. The font is normally specified thru the 'FontFamily', giving
-- some degree of portability. The '_fontFace' can be used to specify the exact (platform
-- dependent) font.
--
-- Note that the original wxWidgets @FontStyle@ is renamed to @FontShape@.
data FontStyle
= FontStyle{ _fontSize :: !Int
, _fontFamily :: !FontFamily
, _fontShape :: !FontShape
, _fontWeight :: !FontWeight
, _fontUnderline :: !Bool
, _fontFace :: !String -- ^ normally @\"\"@
, _fontEncoding :: !Int -- ^ normally @wxFONTENCODING_DEFAULT@
}
deriving (Eq,Show)
-- | Default 10pt font.
fontDefault :: FontStyle
fontDefault
= FontStyle 10 FontDefault ShapeNormal WeightNormal False "" wxFONTENCODING_DEFAULT
-- | Default 10pt sans-serif font.
fontSwiss :: FontStyle
fontSwiss
= fontDefault{ _fontFamily = FontSwiss }
-- | Default 8pt font.
fontSmall :: FontStyle
fontSmall
= fontDefault{ _fontSize = 8 }
-- | Default 10pt italic.
fontItalic :: FontStyle
fontItalic
= fontDefault{ _fontShape = ShapeItalic }
-- | Monospaced font, 10pt.
fontFixed :: FontStyle
fontFixed
= fontDefault{ _fontFamily = FontModern }
-- | Standard font families.
data FontFamily
= FontDefault -- ^ A system default font.
| FontDecorative -- ^ Decorative font.
| FontRoman -- ^ Formal serif font.
| FontScript -- ^ Hand writing font.
| FontSwiss -- ^ Sans-serif font.
| FontModern -- ^ Fixed pitch font.
| FontTeletype -- ^ A teletype (i.e. monospaced) font
deriving (Eq,Show)
-- | The font style.
data FontShape
= ShapeNormal
| ShapeItalic
| ShapeSlant
deriving (Eq,Show)
-- | The font weight.
data FontWeight
= WeightNormal
| WeightBold
| WeightLight
deriving (Eq,Show)
-- | Use a font that is automatically deleted at the end of the computation.
withFontStyle :: FontStyle -> (Font () -> IO a) -> IO a
withFontStyle fontStyle f
= do (font,delete) <- fontCreateFromStyle fontStyle
finally (f font) delete
-- | Set a font that is automatically deleted at the end of the computation.
dcWithFontStyle :: DC a -> FontStyle -> IO b -> IO b
dcWithFontStyle dc fontStyle io
= withFontStyle fontStyle $ \font ->
bracket (do oldFont <- dcGetFont dc
dcSetFont dc font
return oldFont)
(\oldFont ->
do dcSetFont dc oldFont -- restore previous font
fontDelete oldFont)
(const io)
-- | Set the font info of a DC.
dcSetFontStyle :: DC a -> FontStyle -> IO ()
dcSetFontStyle dc info
= do (font,del) <- fontCreateFromStyle info
finalize del $
do dcSetFont dc font
-- | Get the current font info.
dcGetFontStyle :: DC a -> IO FontStyle
dcGetFontStyle dc
= do font <- dcGetFont dc
finalize (fontDelete font) $
do fontGetFontStyle font
-- | Create a 'Font' from 'FontStyle'. Returns both the font and a deletion procedure.
fontCreateFromStyle :: FontStyle -> IO (Font (),IO ())
fontCreateFromStyle (FontStyle size family style weight underline face encoding)
= do font <- fontCreate size cfamily cstyle cweight underline face encoding
return (font,when (font /= objectNull) (fontDelete font))
where
cfamily
= case family of
FontDefault -> wxFONTFAMILY_DEFAULT
FontDecorative -> wxFONTFAMILY_DECORATIVE
FontRoman -> wxFONTFAMILY_ROMAN
FontScript -> wxFONTFAMILY_SCRIPT
FontSwiss -> wxFONTFAMILY_SWISS
FontModern -> wxFONTFAMILY_MODERN
FontTeletype -> wxFONTFAMILY_TELETYPE
cstyle
= case style of
ShapeNormal -> wxFONTSTYLE_NORMAL
ShapeItalic -> wxFONTSTYLE_ITALIC
ShapeSlant -> wxFONTSTYLE_SLANT
cweight
= case weight of
WeightNormal -> wxFONTWEIGHT_NORMAL
WeightBold -> wxFONTWEIGHT_BOLD
WeightLight -> wxFONTWEIGHT_LIGHT
-- | Get the 'FontStyle' from a 'Font' object.
fontGetFontStyle :: Font () -> IO FontStyle
fontGetFontStyle font
= if (objectIsNull font)
then return fontDefault
else do ok <- fontIsOk font
if not ok
then return fontDefault
else do size <- fontGetPointSize font
cfamily <- fontGetFamily font
cstyle <- fontGetStyle font
cweight <- fontGetWeight font
cunderl <- fontGetUnderlined font
face <- fontGetFaceName font
enc <- fontGetEncoding font
return (FontStyle size (toFamily cfamily) (toStyle cstyle)
(toWeight cweight)
(cunderl /= 0) face enc)
where
toFamily f
| f == wxFONTFAMILY_DECORATIVE = FontDecorative
| f == wxFONTFAMILY_ROMAN = FontRoman
| f == wxFONTFAMILY_SCRIPT = FontScript
| f == wxFONTFAMILY_SWISS = FontSwiss
| f == wxFONTFAMILY_MODERN = FontModern
| f == wxFONTFAMILY_TELETYPE = FontTeletype
| otherwise = FontDefault
toStyle s
| s == wxFONTSTYLE_ITALIC = ShapeItalic
| s == wxFONTSTYLE_SLANT = ShapeSlant
| otherwise = ShapeNormal
toWeight w
| w == wxFONTWEIGHT_BOLD = WeightBold
| w == wxFONTWEIGHT_LIGHT = WeightLight
| otherwise = WeightNormal
{--------------------------------------------------------------------------------
Pen
--------------------------------------------------------------------------------}
-- | Pen style.
data PenStyle
= PenStyle { _penKind :: !PenKind
, _penColor :: !Color
, _penWidth :: !Int
, _penCap :: !CapStyle
, _penJoin :: !JoinStyle
}
deriving (Eq,Show)
-- | Pen kinds.
data PenKind
= PenTransparent -- ^ No edge.
| PenSolid
| PenDash { _penDash :: !DashStyle }
| PenHatch { _penHatch :: !HatchStyle }
| PenStipple{ _penBitmap :: !(Bitmap ())} -- ^ @_penColor@ is ignored
deriving (Eq,Show)
-- | Default pen (@PenStyle PenSolid black 1 CapRound JoinRound@)
penDefault :: PenStyle
penDefault
= PenStyle PenSolid black 1 CapRound JoinRound
-- | A solid pen with a certain color and width.
penColored :: Color -> Int -> PenStyle
penColored color width
= penDefault{ _penColor = color, _penWidth = width }
-- | A transparent pen.
penTransparent :: PenStyle
penTransparent
= penDefault{ _penKind = PenTransparent }
-- | Dash style
data DashStyle
= DashDot
| DashLong
| DashShort
| DashDotShort
-- DashUser [Int]
deriving (Eq,Show)
-- | Cap style
data CapStyle
= CapRound -- ^ End points are rounded
| CapProjecting
| CapButt
deriving (Eq,Show)
-- | Join style.
data JoinStyle
= JoinRound -- ^ Corners are rounded
| JoinBevel -- ^ Corners are bevelled
| JoinMiter -- ^ Corners are blocked
deriving (Eq,Show)
-- | Hatch style.
data HatchStyle
= HatchBDiagonal -- ^ Backward diagonal
| HatchCrossDiag -- ^ Crossed diagonal
| HatchFDiagonal -- ^ Forward diagonal
| HatchCross -- ^ Crossed orthogonal
| HatchHorizontal -- ^ Horizontal
| HatchVertical -- ^ Vertical
deriving (Eq,Show)
-- | Brush style.
data BrushStyle
= BrushStyle { _brushKind :: !BrushKind, _brushColor :: !Color }
deriving (Eq,Show)
-- | Brush kind.
data BrushKind
= BrushTransparent -- ^ No filling
| BrushSolid -- ^ Solid color
| BrushHatch { _brushHatch :: !HatchStyle } -- ^ Hatch pattern
| BrushStipple{ _brushBitmap :: !(Bitmap ())} -- ^ Bitmap pattern (on win95 only 8x8 bitmaps are supported)
deriving (Eq,Show)
-- | Set a pen that is automatically deleted at the end of the computation.
dcWithPenStyle :: DC a -> PenStyle -> IO b -> IO b
dcWithPenStyle dc penStyle io
= withPenStyle penStyle $ \pen ->
dcWithPen dc pen io
-- | Set a pen that is used during a certain computation.
dcWithPen :: DC a -> Pen p -> IO b -> IO b
dcWithPen dc pen io
= bracket (do oldPen <- dcGetPen dc
dcSetPen dc pen
return oldPen)
(\oldPen ->
do dcSetPen dc oldPen -- restore previous pen
penDelete oldPen)
(const io)
-- | Set the current pen style. The text color is also adapted.
dcSetPenStyle :: DC a -> PenStyle -> IO ()
dcSetPenStyle dc penStyle
= withPenStyle penStyle (dcSetPen dc)
-- | Get the current pen style.
dcGetPenStyle :: DC a -> IO PenStyle
dcGetPenStyle dc
= do pen <- dcGetPen dc
finalize (penDelete pen) $
do penGetPenStyle pen
-- | Use a pen that is automatically deleted at the end of the computation.
withPenStyle :: PenStyle -> (Pen () -> IO a) -> IO a
withPenStyle penStyle f
= do (pen,delete) <- penCreateFromStyle penStyle
finally (f pen) delete
-- | Create a new pen from a 'PenStyle'. Returns both the pen and its deletion procedure.
penCreateFromStyle :: PenStyle -> IO (Pen (),IO ())
penCreateFromStyle penStyle
= case penStyle of
PenStyle PenTransparent _color _width _cap _join
-> do pen <- penCreateFromStock 5 {- transparent -}
return (pen,return ())
PenStyle (PenDash DashShort) color 1 CapRound JoinRound | color == black
-> do pen <- penCreateFromStock 6 {- black dashed -}
return (pen,return ())
PenStyle PenSolid color 1 CapRound JoinRound
-> case lookup color stockPens of
Just idx -> do pen <- penCreateFromStock idx
return (pen,return ())
Nothing -> colorPen color 1 wxPENSTYLE_SOLID
PenStyle PenSolid color width _cap _join
-> colorPen color width wxPENSTYLE_SOLID
PenStyle (PenDash dash) color width _cap _join
-> case dash of
DashDot -> colorPen color width wxPENSTYLE_DOT
DashLong -> colorPen color width wxPENSTYLE_LONG_DASH
DashShort -> colorPen color width wxPENSTYLE_SHORT_DASH
DashDotShort -> colorPen color width wxPENSTYLE_DOT_DASH
PenStyle (PenStipple bitmap) _color width _cap _join
-> do pen <- penCreateFromBitmap bitmap width
setCap pen
setJoin pen
return (pen,penDelete pen)
PenStyle (PenHatch hatch) color width _cap _join
-> case hatch of
HatchBDiagonal -> colorPen color width wxPENSTYLE_BDIAGONAL_HATCH
HatchCrossDiag -> colorPen color width wxPENSTYLE_CROSSDIAG_HATCH
HatchFDiagonal -> colorPen color width wxPENSTYLE_FDIAGONAL_HATCH
HatchCross -> colorPen color width wxPENSTYLE_CROSS_HATCH
HatchHorizontal -> colorPen color width wxPENSTYLE_HORIZONTAL_HATCH
HatchVertical -> colorPen color width wxPENSTYLE_VERTICAL_HATCH
where
colorPen color width style
= do pen <- penCreateFromColour color width style
setCap pen
setJoin pen
return (pen,penDelete pen)
setCap pen
= case _penCap penStyle of
CapRound -> return ()
CapProjecting -> penSetCap pen wxCAP_PROJECTING
CapButt -> penSetCap pen wxCAP_BUTT
setJoin pen
= case _penJoin penStyle of
JoinRound -> return ()
JoinBevel -> penSetJoin pen wxJOIN_BEVEL
JoinMiter -> penSetJoin pen wxJOIN_MITER
stockPens
= [(red,0),(cyan,1),(green,2)
,(black,3),(white,4)
,(grey,7),(lightgrey,9)
,(mediumgrey,8)
]
-- | Create a 'PenStyle' from a 'Pen'.
penGetPenStyle :: Pen a -> IO PenStyle
penGetPenStyle pen
= if (objectIsNull pen)
then return penDefault
else do ok <- penIsOk pen
if not ok
then return penDefault
else do stl <- penGetStyle pen
toPenStyle stl
where
toPenStyle stl
| stl == wxPENSTYLE_TRANSPARENT = return penTransparent
| stl == wxPENSTYLE_SOLID = toPenStyleWithKind PenSolid
| stl == wxPENSTYLE_DOT = toPenStyleWithKind (PenDash DashDot)
| stl == wxPENSTYLE_LONG_DASH = toPenStyleWithKind (PenDash DashLong)
| stl == wxPENSTYLE_SHORT_DASH = toPenStyleWithKind (PenDash DashShort)
| stl == wxPENSTYLE_DOT_DASH = toPenStyleWithKind (PenDash DashDotShort)
| stl == wxPENSTYLE_STIPPLE = do stipple <- penGetStipple pen
toPenStyleWithKind (PenStipple stipple)
| stl == wxPENSTYLE_BDIAGONAL_HATCH = toPenStyleWithKind (PenHatch HatchBDiagonal)
| stl == wxPENSTYLE_CROSSDIAG_HATCH = toPenStyleWithKind (PenHatch HatchCrossDiag)
| stl == wxPENSTYLE_FDIAGONAL_HATCH = toPenStyleWithKind (PenHatch HatchFDiagonal)
| stl == wxPENSTYLE_CROSS_HATCH = toPenStyleWithKind (PenHatch HatchCross)
| stl == wxPENSTYLE_HORIZONTAL_HATCH = toPenStyleWithKind (PenHatch HatchHorizontal)
| stl == wxPENSTYLE_VERTICAL_HATCH = toPenStyleWithKind (PenHatch HatchVertical)
| otherwise = toPenStyleWithKind PenSolid
toPenStyleWithKind kind
= do width <- penGetWidth pen
color <- penGetColour pen
cap <- penGetCap pen
join <- penGetJoin pen
return (PenStyle kind color width (toCap cap) (toJoin join))
toCap cap
| cap == wxCAP_PROJECTING = CapProjecting
| cap == wxCAP_BUTT = CapButt
| otherwise = CapRound
toJoin join
| join == wxJOIN_MITER = JoinMiter
| join == wxJOIN_BEVEL = JoinBevel
| otherwise = JoinRound
{--------------------------------------------------------------------------------
Brush
--------------------------------------------------------------------------------}
-- | Default brush (transparent, black).
brushDefault :: BrushStyle
brushDefault
= BrushStyle BrushTransparent black
-- | A solid brush of a specific color.
brushSolid :: Color -> BrushStyle
brushSolid color
= BrushStyle BrushSolid color
-- | A transparent brush.
brushTransparent :: BrushStyle
brushTransparent
= BrushStyle BrushTransparent white
-- | Use a brush that is automatically deleted at the end of the computation.
dcWithBrushStyle :: DC a -> BrushStyle -> IO b -> IO b
dcWithBrushStyle dc brushStyle io
= withBrushStyle brushStyle $ \brush ->
dcWithBrush dc brush io
dcWithBrush :: DC b -> Brush a -> IO c -> IO c
dcWithBrush dc brush io
= bracket (do oldBrush <- dcGetBrush dc
dcSetBrush dc brush
return oldBrush)
(\oldBrush ->
do dcSetBrush dc oldBrush -- restore previous brush
brushDelete oldBrush)
(const io)
-- | Set the brush style (and text background color) of a device context.
dcSetBrushStyle :: DC a -> BrushStyle -> IO ()
dcSetBrushStyle dc brushStyle
= withBrushStyle brushStyle (dcSetBrush dc)
-- | Get the current brush of a device context.
dcGetBrushStyle :: DC a -> IO BrushStyle
dcGetBrushStyle dc
= do brush <- dcGetBrush dc
finalize (brushDelete brush) $
do brushGetBrushStyle brush
-- | Use a brush that is automatically deleted at the end of the computation.
withBrushStyle :: BrushStyle -> (Brush () -> IO a) -> IO a
withBrushStyle brushStyle f
= do (brush,delete) <- brushCreateFromStyle brushStyle
finalize delete $
do f brush
-- | Create a new brush from a 'BrushStyle'. Returns both the brush and its deletion procedure.
brushCreateFromStyle :: BrushStyle -> IO (Brush (), IO ())
brushCreateFromStyle brushStyle
= case brushStyle of
BrushStyle BrushTransparent color
-> do brush <- if (wxToolkit == WxMac)
then brushCreateFromColour color wxBRUSHSTYLE_TRANSPARENT
else brushCreateFromStock 7 {- transparent brush -}
return (brush,return ())
BrushStyle BrushSolid color
-> case lookup color stockBrushes of
Just idx -> do brush <- brushCreateFromStock idx
return (brush,return ())
Nothing -> colorBrush color wxBRUSHSTYLE_SOLID
BrushStyle (BrushHatch HatchBDiagonal) color -> colorBrush color wxBRUSHSTYLE_BDIAGONAL_HATCH
BrushStyle (BrushHatch HatchCrossDiag) color -> colorBrush color wxBRUSHSTYLE_CROSSDIAG_HATCH
BrushStyle (BrushHatch HatchFDiagonal) color -> colorBrush color wxBRUSHSTYLE_FDIAGONAL_HATCH
BrushStyle (BrushHatch HatchCross) color -> colorBrush color wxBRUSHSTYLE_CROSS_HATCH
BrushStyle (BrushHatch HatchHorizontal) color -> colorBrush color wxBRUSHSTYLE_HORIZONTAL_HATCH
BrushStyle (BrushHatch HatchVertical) color -> colorBrush color wxBRUSHSTYLE_VERTICAL_HATCH
BrushStyle (BrushStipple bitmap) _color -> do brush <- brushCreateFromBitmap bitmap
return (brush, brushDelete brush)
where
colorBrush color style
= do brush <- brushCreateFromColour color style
return (brush, brushDelete brush )
stockBrushes
= [(blue,0),(green,1),(white,2)
,(black,3),(grey,4),(lightgrey,6)
,(cyan,8),(red,9)
,(mediumgrey,5)
]
-- | Get the 'BrushStyle' of 'Brush'.
brushGetBrushStyle :: Brush a -> IO BrushStyle
brushGetBrushStyle brush
= if (objectIsNull brush)
then return brushDefault
else do ok <- brushIsOk brush
if not ok
then return brushDefault
else do stl <- brushGetStyle brush
kind <- toBrushKind stl
color <- brushGetColour brush
return (BrushStyle kind color)
where
toBrushKind stl
| stl == wxBRUSHSTYLE_TRANSPARENT = return BrushTransparent
| stl == wxBRUSHSTYLE_SOLID = return BrushSolid
| stl == wxBRUSHSTYLE_STIPPLE = do stipple <- brushGetStipple brush
return (BrushStipple stipple)
| stl == wxBRUSHSTYLE_BDIAGONAL_HATCH = return (BrushHatch HatchBDiagonal)
| stl == wxBRUSHSTYLE_CROSSDIAG_HATCH = return (BrushHatch HatchCrossDiag)
| stl == wxBRUSHSTYLE_FDIAGONAL_HATCH = return (BrushHatch HatchFDiagonal)
| stl == wxBRUSHSTYLE_CROSS_HATCH = return (BrushHatch HatchCross)
| stl == wxBRUSHSTYLE_HORIZONTAL_HATCH = return (BrushHatch HatchHorizontal)
| stl == wxBRUSHSTYLE_VERTICAL_HATCH = return (BrushHatch HatchVertical)
| otherwise = return BrushTransparent
{--------------------------------------------------------------------------------
DC drawing state
--------------------------------------------------------------------------------}
-- | The drawing state (pen,brush,font,text color,text background color) of a device context.
data DrawState = DrawState (Pen ()) (Brush ()) (Font ()) Color Color
-- | Run a computation after which the original drawing state of the 'DC' is restored.
dcEncapsulate :: DC a -> IO b -> IO b
dcEncapsulate dc io
= bracket (dcGetDrawState dc)
(\drawState ->
do dcSetDrawState dc drawState
drawStateDelete drawState)
(const io)
-- | Get the drawing state. (Should be deleted with 'drawStateDelete').
dcGetDrawState :: DC a -> IO DrawState
dcGetDrawState dc
= do pen <- dcGetPen dc
brush <- dcGetBrush dc
font <- dcGetFont dc
textc <- dcGetTextForeground dc
backc <- dcGetTextBackground dc
return (DrawState pen brush font textc backc)
-- | Set the drawing state.
dcSetDrawState :: DC a -> DrawState -> IO ()
dcSetDrawState dc (DrawState pen brush font textc backc)
= do dcSetPen dc pen
dcSetBrush dc brush
dcSetFont dc font
dcSetTextBackground dc backc
dcSetTextForeground dc textc
-- | Release the resources associated with a drawing state.
drawStateDelete :: DrawState -> IO ()
drawStateDelete (DrawState pen brush font _ _)
= do penDelete pen
brushDelete brush
fontDelete font
{--------------------------------------------------------------------------------
DC utils
--------------------------------------------------------------------------------}
-- | Draw connected lines.
drawLines :: DC a -> [Point] -> IO ()
drawLines _dc [] = return ()
drawLines dc ps
= withArray xs $ \pxs ->
withArray ys $ \pys ->
dcDrawLines dc n pxs pys (pt 0 0)
where
n = length ps
xs = map pointX ps
ys = map pointY ps
-- | Draw a polygon. The polygon is filled with the odd-even rule.
drawPolygon :: DC a -> [Point] -> IO ()
drawPolygon _dc [] = return ()
drawPolygon dc ps
= withArray xs $ \pxs ->
withArray ys $ \pys ->
dcDrawPolygon dc n pxs pys (pt 0 0) wxODDEVEN_RULE
where
n = length ps
xs = map pointX ps
ys = map pointY ps
-- | Gets the dimensions of the string using the currently selected font.
getTextExtent :: DC a -> String -> IO Size
getTextExtent dc txt
= do (sz',_,_) <- getFullTextExtent dc txt
return sz'
-- | Gets the dimensions of the string using the currently selected font.
-- Takes text string to measure, and returns the size, /descent/ and /external leading/.
-- Descent is the dimension from the baseline of the font to the bottom of the descender
-- , and external leading is any extra vertical space added to the font by the font designer (is usually zero).
getFullTextExtent :: DC a -> String -> IO (Size,Int,Int)
getFullTextExtent dc txt
= alloca $ \px ->
alloca $ \py ->
alloca $ \pd ->
alloca $ \pe ->
do dcGetTextExtent dc txt px py pd pe objectNull
x <- peek px
y <- peek py
d <- peek pd
e <- peek pe
return (sz (fromCInt x) (fromCInt y), fromCInt d, fromCInt e)
{--------------------------------------------------------------------------------
Double buffering
--------------------------------------------------------------------------------}
-- | Use double buffering to draw to a 'DC' -- reduces flicker. Note that
-- the 'windowOnPaint' handler can already take care of buffering automatically.
-- The rectangle argument is normally the view rectangle ('windowGetViewRect').
-- Uses a 'MemoryDC' to draw into memory first and than blit the result to
-- the device context. The memory area allocated is the minimal size necessary
-- to accomodate the rectangle, but is re-allocated on each invokation.
dcBuffer :: WindowDC a -> Rect -> (DC () -> IO ()) -> IO ()
dcBuffer dc r draw
= dcBufferWithRef dc Nothing r draw
-- | Optimized double buffering. Takes a possible reference to a bitmap. If it is
-- 'Nothing', a new bitmap is allocated everytime. Otherwise, the reference is used
-- to re-use an allocated bitmap if possible. The 'Rect' argument specifies the
-- the current logical view rectangle. The last argument is called to draw on the
-- memory 'DC'.
dcBufferWithRef :: WindowDC a -> Maybe (Var (Bitmap ())) -> Rect -> (DC () -> IO ()) -> IO ()
dcBufferWithRef dc mbVar viewArea draw
= dcBufferWithRefEx dc (\dc' -> dcClearRect dc' viewArea) mbVar viewArea draw
-- | Optimized double buffering. Takes a /clear/ routine as its first argument.
-- Normally this is something like '\dc -> dcClearRect dc viewArea' but on certain platforms, like
-- MacOS X, special handling is necessary.
dcBufferWithRefEx :: WindowDC a -> (DC () -> IO ()) -> Maybe (Var (Bitmap ()))
-> Rect -> (DC () -> IO ()) -> IO ()
dcBufferWithRefEx = dcBufferedAux simpleDraw simpleDraw
where simpleDraw dc draw = draw $ downcastDC dc
-- | Optimized double buffering with a GCDC. Takes a /clear/ routine as its first argument.
-- Normally this is something like '\dc -> dcClearRect dc viewArea' but on certain platforms, like
-- MacOS X, special handling is necessary.
dcBufferWithRefExGcdc :: WindowDC a -> (DC () -> IO ()) -> Maybe (Var (Bitmap ()))
-> Rect -> (GCDC () -> IO b) -> IO ()
dcBufferWithRefExGcdc =
dcBufferedAux (withGC gcdcCreate) (withGC gcdcCreateFromMemory)
where withGC create dc_ draw = do
dc <- create dc_
_ <- draw dc
gcdcDelete dc
dcBufferedAux :: (WindowDC a -> f -> IO ()) -> (MemoryDC c -> f -> IO ())
-> WindowDC a -> (DC () -> IO ()) -> Maybe (Var (Bitmap ()))
-> Rect -> f -> IO ()
dcBufferedAux _ _ _ _ _ view _
| rectSize view == sizeZero = return ()
dcBufferedAux withWinDC withMemoryDC dc clear mbVar view draw
= bracket (initBitmap)
(doneBitmap)
(\bitmap ->
if (bitmap==objectNull)
then drawUnbuffered
else bracket (do p <- memoryDCCreateCompatible dc; return (objectCast p))
(\memdc -> when (memdc/=objectNull) (memoryDCDelete memdc))
(\memdc -> if (memdc==objectNull)
then drawUnbuffered
else do memoryDCSelectObject memdc bitmap
drawBuffered memdc
memoryDCSelectObject memdc nullBitmap))
where
initBitmap
= case mbVar of
Nothing -> bitmapCreateEmpty (rectSize view) (-1)
Just v -> do bitmap <- varGet v
size <- if (bitmap==objectNull)
then return sizeZero
else do bw <- bitmapGetWidth bitmap
bh <- bitmapGetHeight bitmap
return (Size bw bh)
-- re-use the bitmap if possible
if (sizeEncloses size (rectSize view) && bitmap /= objectNull)
then return bitmap
else do when (bitmap/=objectNull) (bitmapDelete bitmap)
varSet v objectNull
-- new size a bit larger to avoid multiple reallocs
let (Size w h) = rectSize view
neww = div (w*105) 100
newh = div (h*105) 100
if (w > 0 && h > 0) then
do bm <- bitmapCreateEmpty (sz neww newh) (-1)
varSet v bm
return bm
else return objectNull
doneBitmap bitmap
= case mbVar of
Nothing -> when (bitmap/=objectNull) (bitmapDelete bitmap)
Just _v -> return ()
drawUnbuffered
= do clear (downcastDC dc)
withWinDC dc draw
drawBuffered memdc
= do -- set the device origin for scrolled windows
dcSetDeviceOrigin memdc (pointFromVec (vecNegate (vecFromPoint (rectTopLeft view))))
dcSetClippingRegion memdc view
-- dcBlit memdc view dc (rectTopLeft view) wxCOPY False
bracket (dcGetBackground dc)
(\brush -> do dcSetBrush memdc nullBrush
brushDelete brush)
(\brush -> do -- set the background to the owner brush
dcSetBackground memdc brush
if (wxToolkit == WxMac)
then withBrushStyle brushTransparent (dcSetBrush memdc)
else dcSetBrush memdc brush
clear (downcastDC memdc)
-- and finally do the drawing!
withMemoryDC memdc draw
)
-- blit the memdc into the owner dc.
_ <- dcBlit dc view memdc (rectTopLeft view) wxCOPY False
return ()
|
sherwoodwang/wxHaskell
|
wxcore/src/haskell/Graphics/UI/WXCore/Draw.hs
|
lgpl-2.1
| 34,611 | 0 | 21 | 10,110 | 7,687 | 3,838 | 3,849 | 648 | 20 |
{-# LANGUAGE OverloadedStrings #-}
module Stubby.Data.Endpoint
( Endpoint
, defaultEndpoint
, getRequest
, getResponses
) where
import Stubby.Data.Request (Request, defaultRequest)
import Stubby.Data.Response (Response, defaultResponse)
import Data.Yaml
import qualified Data.HashMap.Strict as HM (lookup)
import Control.Applicative ((<$>), (<*>), pure)
import Control.Monad (mzero)
data Endpoint = Endpoint
{ request :: Request
, responses :: [Response]
} deriving (Show)
defaultEndpoint :: Endpoint
defaultEndpoint = Endpoint
{ request = defaultRequest
, responses = [defaultResponse]
}
getRequest :: Endpoint -> Request
getRequest = request
getResponses :: Endpoint -> [Response]
getResponses = responses
instance FromJSON Endpoint where
parseJSON (Object o) = Endpoint <$> o .: "request"
<*> parseResponses o
parseJSON _ = mzero
parseResponses :: Object -> Parser [Response]
parseResponses o = case HM.lookup "response" o
of Nothing -> return [defaultResponse]
Just as@(Array _) -> parseJSON as
Just ro@(Object _) -> pure <$> parseJSON ro
_ -> mzero
|
mrak/stubby4hs
|
src/lib/Stubby/Data/Endpoint.hs
|
apache-2.0
| 1,315 | 0 | 11 | 402 | 331 | 190 | 141 | 34 | 4 |
{-# LANGUAGE FlexibleContexts, TemplateHaskell #-}
module JSONCommon where
import Database.Persist.TH
import Data.Aeson.TH (deriveJSON, defaultOptions)
data EndType = TimeOut | ENDE | Disconnect | Resign deriving (Show, Read, Eq)
derivePersistField "EndType"
deriveJSON defaultOptions ''EndType
data BS = JA | NEIN deriving (Show, Read, Eq)
derivePersistField "BS"
deriveJSON defaultOptions ''BS
|
sleepomeno/snooker-statistics
|
src/JSONCommon.hs
|
apache-2.0
| 424 | 0 | 6 | 76 | 113 | 61 | 52 | 10 | 0 |
module Main where
import Graphics.Blank
import Life.Engine.Hutton
import Life.Display.Canvas
import Life.Types
--import Life.Scenes
-- or
import Life.Formations
-- Runs Life indefinitely
life :: Config -> Scene -> IO ()
life c b = blankCanvas 3000 $ \dc -> lifeCanvas dc (scene c b :: Board)
-- Runs Life for the specified number of generations
-- Then it prints the final board configuration as a list of positions
lifeX :: Int -> Config -> Scene -> IO ()
lifeX x c s = blankCanvas 3000 $ \dc -> lifeXCanvas x dc (scene c s :: Board)
main = life ((160,160),False) $ gliders5 (0,0)
|
ku-fpg/better-life
|
examples/simulations/HuttonCanvas.hs
|
bsd-2-clause
| 590 | 0 | 9 | 110 | 189 | 104 | 85 | 11 | 1 |
module HSH.MonitoredDirectory where
import Control.Monad
import Data.List
import qualified Data.Map as Map
import qualified System.Posix.Directory as Posix
import qualified System.Posix.Files as Posix
import qualified System.Posix.Types as Posix
import qualified System.Directory as Dir
import System.FilePath
import System.IO
data MonitoredDirectory = MonitoredDirectory {
dirName :: FilePath,
lastModified :: Posix.EpochTime,
contents :: Map.Map FilePath QualifiedFilePath
} deriving (Eq, Show)
type FileName = FilePath
newtype QualifiedFilePath = QualifiedFilePath FilePath deriving Eq
newtype DirectoryPath = DirectoryPath FilePath
instance Show QualifiedFilePath where
show (QualifiedFilePath x) = show x
takeQualifiedFileName :: QualifiedFilePath -> FilePath
takeQualifiedFileName (QualifiedFilePath path) = takeFileName path
-- | Indicate whether a path references a hidden file.
isVisible :: QualifiedFilePath -> Bool
isVisible qualpath = not $ "." `isPrefixOf` takeQualifiedFileName qualpath
-- | Filter out hidden files from a list.
onlyVisible :: [QualifiedFilePath] -> [QualifiedFilePath]
onlyVisible = filter isVisible
-- | Determine whether the given path refers to an executable unix command.
isCommand :: QualifiedFilePath -> IO Bool
isCommand (QualifiedFilePath path) = do
stat <- Posix.getFileStatus path
executable <- Posix.fileAccess path True False True
return $ (Posix.isRegularFile stat || Posix.isSymbolicLink stat) && executable
-- | Qualify a path to a file by prepending the directory it's in.
qualifyPath :: DirectoryPath -> FilePath -> QualifiedFilePath
qualifyPath (DirectoryPath dir) = QualifiedFilePath . (dir </>)
-- | Do 'System.Directory.listDirectory' to a DirectoryPath.
listDirectory :: DirectoryPath -> IO [FilePath]
listDirectory (DirectoryPath dir) = Dir.listDirectory dir
-- | List the contents of a directory, each prefixed with the name of the directory.
listDirectoryQualified :: DirectoryPath -> IO [QualifiedFilePath]
listDirectoryQualified dir = map (qualifyPath dir) <$> listDirectory dir
-- | Create a command table mapping command names to executable paths based on a list of
-- qualified file paths.
commandTableFrom :: [QualifiedFilePath] -> Map.Map FilePath QualifiedFilePath
commandTableFrom filenames = Map.fromList $ map (\name -> (takeQualifiedFileName name, name)) filenames
-- | Create a MonitoredDirectory for a given path.
--
-- XXX: This function does no validation tha the FilePath points to a directory.
loadDirectory :: FilePath -> IO MonitoredDirectory
loadDirectory dir = do
entries <- onlyVisible <$> listDirectoryQualified (DirectoryPath dir)
fileEntries <- filterM isCommand entries
dirLastModified <- Posix.modificationTime <$> Posix.getFileStatus dir
let entryMap = commandTableFrom fileEntries
return MonitoredDirectory { dirName = dir, lastModified = dirLastModified, contents = entryMap }
-- | Ensure the MonitoredDirectory reflects what is on-disk.
refreshDirectory :: MonitoredDirectory -> IO MonitoredDirectory
refreshDirectory mondir = do
dirLastModified <- Posix.modificationTime <$> Posix.getFileStatus (dirName mondir)
if dirLastModified > lastModified mondir
then
loadDirectory $ dirName mondir
else
return mondir
|
jessekempf/hsh
|
src/HSH/MonitoredDirectory.hs
|
bsd-2-clause
| 3,371 | 0 | 12 | 580 | 684 | 367 | 317 | 52 | 2 |
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ViewPatterns, RecordWildCards, DeriveFunctor #-}
module General.Web(
Input(..),
Output(..), readInput, server, general_web_test
) where
import Network.Wai.Handler.Warp hiding (Port, Handle)
import Network.Wai.Handler.WarpTLS
import Action.CmdLine
import Network.Wai.Logger
import Network.Wai
import Control.DeepSeq
import Network.HTTP.Types (parseQuery, decodePathSegments)
import Network.HTTP.Types.Status
import qualified Data.Text as Text
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.List.Extra
import Data.Aeson.Encoding
import Data.Char
import Data.String
import Data.Tuple.Extra
import Data.Maybe
import Data.Monoid
import System.FilePath
import Control.Exception.Extra
import System.Time.Extra
import General.Log
import General.Util
import Prelude
import qualified Data.ByteString.UTF8 as UTF8
data Input = Input
{inputURL :: [String]
,inputArgs :: [(String, String)]
} deriving (Eq, Show)
readInput :: String -> Maybe Input
readInput (breakOn "?" -> (a,b)) =
if (badPath path || badArgs args) then Nothing else Just $ Input path args
where
path = parsePath a
parsePath = map Text.unpack
. decodePathSegments
. BS.pack
-- Note that there is a difference between URL paths
-- which split on / and only that and file paths where
-- an escaped %2f is equivalent to /. decodePathSegments
-- (correctly) only considers the former so here
-- we add an extra check that the result (which has unescaped %2f to /)
-- does not contain path separators.
badPath = any badSegment . filter (/= "")
badSegment seg = all (== '.') seg || any isPathSeparator seg
args = parseArgs b
parseArgs = map (UTF8.toString *** maybe "" UTF8.toString)
. parseQuery
. UTF8.fromString
badArgs = not . all (all isLower . fst)
data Output
= OutputText LBS.ByteString
| OutputHTML LBS.ByteString
| OutputJavascript LBS.ByteString
| OutputJSON Encoding
| OutputFail LBS.ByteString
| OutputFile FilePath
deriving Show
-- | Force all the output (no delayed exceptions) and produce bytestrings
forceBS :: Output -> LBS.ByteString
forceBS (OutputText x) = force x
forceBS (OutputJSON x) = force $ encodingToLazyByteString x
forceBS (OutputHTML x) = force x
forceBS (OutputJavascript x) = force x
forceBS (OutputFail x) = force x
forceBS (OutputFile x) = rnf x `seq` LBS.empty
instance NFData Output where
rnf x = forceBS x `seq` ()
server :: Log -> CmdLine -> (Input -> IO Output) -> IO ()
server log Server{..} act = do
let
host' = fromString $
if host == "" then
if local then
"127.0.0.1"
else
"*"
else
host
set = setOnExceptionResponse exceptionResponseForDebug
. setHost host'
. setPort port $
defaultSettings
runServer :: Application -> IO ()
runServer = if https then runTLS (tlsSettings cert key) set
else runSettings set
secH = if no_security_headers then []
else [
-- The CSP is giving additional instructions to the browser.
("Content-Security-Policy",
-- For any content type not specifically enumerated in this CSP
-- (e.g. fonts), the only valid origin is the same as the current
-- page.
"default-src 'self';"
-- As an exception to the default rule, allow scripts from jquery
-- and the CDN.
<> " script-src 'self' https://code.jquery.com/ https://rawcdn.githack.com;"
-- As an exception to the default rule, allow stylesheets from
-- the CDN. TODO: for now, we are also enabling inline styles,
-- because it the chosen plugin uses them.
<> " style-src 'self' 'unsafe-inline' https://rawcdn.githack.com;"
-- As an exception to the default rule, allow images from the
-- CDN.
<> " img-src 'self' https://rawcdn.githack.com;"
-- Only allow this request in an iframe if the containing page
-- has the same origin.
<> " frame-ancestors 'self';"
-- Forms are only allowed to target addresses under the same
-- origin as the page.
<> " form-action 'self';"
-- Any request originating from this page and specifying http as
-- its protocol will be automatically upgraded to https.
<> " upgrade-insecure-requests;"
-- Do not display http content if the page was loaded under
-- https.
<> " block-all-mixed-content"),
-- Tells the browser this web page should not be rendered inside a
-- frame, except if the framing page comes from the same origin
-- (i.e. DNS name + port). This is to thwart invisible, keylogging
-- framing pages.
("X-Frame-Options", "sameorigin"),
-- Tells browsers to trust the Content-Type header and not try to
-- otherwise guess at response types. In particular, prevents
-- dangerous browser behaviour that would execute a file loaded
-- from a <script> or <style> tag despite not having a
-- text/javascript or text/css Content-Type.
("X-Content-Type-Options", "nosniff"),
-- Browser should try to detect "reflected" XSS attacks, where
-- some suspicious payload of the request appears in the response.
-- How browsers do that is unspecified. On detection, browser
-- should block the page from rendering at all.
("X-XSS-Protection", "1; mode=block"),
-- Do not include referrer information if user-agent generates a
-- request from an HTTPS page to an HTTP one. Note: this is
-- technically redundant as this should be the browser default
-- behaviour.
("Referrer-Policy", "no-referrer-when-downgrade"),
-- Strict Transport Security (aka HSTS) tells the browser that,
-- from now on and until max-age seconds have passed, it should
-- never try to connect to this domain name through unprotected
-- HTTP. The browser will automatically upgrade any HTTP request
-- to this domain name to HTTPS, client side, before any network
-- call happens.
("Strict-Transport-Security", "max-age=31536000; includeSubDomains")]
logAddMessage log $ "Server starting on port " ++ show port ++ " and host/IP " ++ show host'
runServer $ \req reply -> do
let pq = BS.unpack $ rawPathInfo req <> rawQueryString req
putStrLn pq
(time, res) <- duration $ case readInput pq of
Nothing -> pure $ Right (OutputFail "", LBS.pack $ "Bad URL: " ++ pq)
Just pay ->
handle_ (fmap Left . showException) $ do
s <- act pay; bs <- evaluate $ forceBS s; pure $ Right (s, bs)
logAddEntry log (showSockAddr $ remoteHost req) pq time (either Just (const Nothing) res)
case res of
Left s -> reply $ responseLBS status500 [] $ LBS.pack s
Right (v, bs) -> reply $ case v of
OutputFile file -> responseFile status200
([("content-type",c) | Just c <- [lookup (takeExtension file) contentType]] ++ secH) file Nothing
OutputText{} -> responseLBS status200 (("content-type","text/plain") : secH) bs
OutputJSON{} -> responseLBS status200 (("content-type","application/json") : ("access-control-allow-origin","*") : secH) bs
OutputFail{} -> responseLBS status400 (("content-type","text/plain") : secH) bs
OutputHTML{} -> responseLBS status200 (("content-type","text/html") : secH) bs
OutputJavascript{} -> responseLBS status200 (("content-type","text/javascript") : secH) bs
contentType = [(".html","text/html"),(".css","text/css"),(".js","text/javascript")]
general_web_test :: IO ()
general_web_test = do
testing "General.Web.readInput" $ do
let a === b = if a == b then putChar '.' else errorIO $ show (a,b)
readInput "abc" === Just (Input ["abc"] [])
readInput "/abc" === Just (Input ["abc"] [])
readInput "/abc/" === Just (Input ["abc", ""] [])
readInput "abc?ab=cd&ef=gh" === Just (Input ["abc"] [("ab", "cd"), ("ef", "gh")])
readInput "%2fabc" === Nothing
readInput "%2F" === Nothing
readInput "def%2fabc" === Nothing
readInput "." === Nothing
readInput ".." === Nothing
readInput "..a" === Just (Input ["..a"] [])
readInput "../a" === Nothing
readInput "a/../a" === Nothing
readInput "%2e" === Nothing
readInput "%2E" === Nothing
|
ndmitchell/hoogle
|
src/General/Web.hs
|
bsd-3-clause
| 9,207 | 0 | 27 | 2,727 | 1,799 | 971 | 828 | 135 | 12 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Data.CompactMap.Index where
import Control.Monad
import Data.Maybe
import Foreign hiding (rotateL, rotateR)
import Foreign.Storable
import System.IO.Unsafe
--import Data.Array.IArray
import Data.Array.IO
import Data.Array.Unboxed
import Data.Binary
import qualified Data.ByteString as Strict
import qualified Data.ByteString.Internal as Strict
import qualified Data.ByteString.Lazy as Lazy
import qualified Data.ByteString.Unsafe as Strict
import Data.CompactMap.Buffer
import Data.CompactMap.Fetch
import Data.CompactMap.Types
import Data.Array.Unsafe
import GHC.Exts
import Prelude hiding (Either (..))
type Tag = Int
-- ints are native GHC ints.
{- KeyCursor
void *dataPointer;
int keyLen;
void *key;
-}
{- DataCursor
void *next;
int tag;
word8 isJust;
int dataLen;
void *data;
-}
peekKeyCursorData :: Ptr KeyCursor -> IO (Ptr DataCursor)
peekKeyCursorData ptr
= peek (castPtr ptr)
peekKeyCursorKey :: Ptr KeyCursor -> IO Strict.ByteString
peekKeyCursorKey ptr = do len <- peek (ptr `plusPtr` ptrSize)
Strict.unsafePackCStringLen (ptr `plusPtr` (ptrSize+intSize), len)
pokeKeyCursorData :: Ptr KeyCursor -> Ptr DataCursor -> IO ()
pokeKeyCursorData ptr dataPtr
= poke (castPtr ptr) dataPtr
newKeyCursor :: Buffer -> Lazy.ByteString -> IO (Ptr KeyCursor)
newKeyCursor buffer keyE
= withBytes buffer (intSize*2 + keyLen) $ \keyPtr ->
do poke (castPtr keyPtr) nullPtr
putByteString (keyPtr `plusPtr` intSize) keyE keyLen
return keyPtr
where keyLen = fromIntegral $ Lazy.length keyE
newBinaryKeyCursor :: (Binary a) => Buffer -> a -> IO (Ptr KeyCursor)
newBinaryKeyCursor !buffer !key
= newKeyCursor buffer (encode key)
pushNewDataCursor :: Ptr KeyCursor -> Ptr DataCursor -> IO ()
pushNewDataCursor keyCursor dataCursor
= do oldData <- peekKeyCursorData keyCursor
pokeDataCursorNext dataCursor oldData
pokeKeyCursorData keyCursor dataCursor
peekDataCursorNext :: Ptr DataCursor -> IO (Ptr DataCursor)
peekDataCursorNext ptr = peek (castPtr ptr)
peekDataCursorTag :: Ptr DataCursor -> IO Int
peekDataCursorTag ptr = peek (ptr `plusPtr` ptrSize)
peekDataCursorData :: Ptr DataCursor -> IO (Maybe Strict.ByteString)
peekDataCursorData ptr
= do isJ <- peek (ptr `plusPtr` (ptrSize+intSize))
case isJ == (1::Word8) of
False -> do return Nothing
True -> do len <- peek (ptr `plusPtr` (ptrSize+intSize+1))
bs <- Strict.unsafePackCStringLen (ptr `plusPtr` (intSize+intSize+1+intSize),len)
return (Just bs)
pokeDataCursorNext :: Ptr DataCursor -> Ptr DataCursor -> IO ()
pokeDataCursorNext ptr next
= poke (castPtr ptr) next
newDataCursor :: Buffer -> Tag -> Maybe Lazy.ByteString -> IO (Ptr DataCursor)
newDataCursor !buffer !tag !mbString
= do let !bsLen = fromIntegral $ maybe 0 Lazy.length mbString
!ext = if isJust mbString then intSize else 0
withBytes buffer (ptrSize+intSize+1+bsLen+ext) $ \ !ptr ->
do poke (castPtr ptr) (nullPtr :: Ptr DataCursor)
poke (ptr `plusPtr` ptrSize) tag
case mbString of
Nothing -> do poke (ptr `plusPtr` (ptrSize+intSize)) (0::Word8)
Just bs -> do poke (ptr `plusPtr` (ptrSize+intSize)) (1::Word8)
putByteString (ptr `plusPtr` (ptrSize+intSize+1)) bs bsLen
return ptr
intToPtr i = nullPtr `plusPtr` i
ptrToInt (Ptr addr#) = I# (addr2Int# addr#)
extractTop = extractField 0
extractSize = fmap ptrToInt . extractField 1
extractElemIdx = fmap castPtr . extractField 2
extractLeft = extractField 3
extractRight = extractField 4
putTop ptr val = if ptr == nullPtr then return () else putField 0 ptr val
putSize p s = putField 1 p (intToPtr s)
--putElemIdx p e = putField 2 p (castPtr e)
putLeft = putField 3
putRight :: Ptr IndexItem -> Ptr IndexItem -> IO ()
putRight = putField 4
--getElement set e = return $ set IntMap.! e
{-
ppHex n = "0x" ++ (drop (length hex) zeroes) ++ hex
where hex = showHex n ""
zeroes = replicate ((sizeOf nullPtr) * 2) '0'
-}
data Direction = Left | Right | Stop
{-# INLINE walkTree #-}
walkTree start move
= let loop n = do keyCursor <- extractElemIdx n
dir <- move keyCursor
case dir of
Left -> extractLeft n >>= \left ->
if left == nullPtr
then return (Left, n) else loop left
Right -> extractRight n >>= \right ->
if right == nullPtr
then return (Right, n) else loop right
Stop -> return (Stop, n)
in loop start
{-# INLINE lookupNearest #-}
lookupNearest :: (Ord a, Binary a) => Ptr IndexItem
-> a -> IO (Direction, Ptr IndexItem)
lookupNearest start e
= walkTree start $ \keyCursor ->
do idxElem <- getElement (keyCursor `plusPtr` intSize)
case compare e idxElem of
LT -> return Left
GT -> return Right
EQ -> return Stop
{-# INLINE lookupLargest #-}
lookupLargest :: Ptr IndexItem
-> IO (Direction, Ptr IndexItem)
lookupLargest start
= walkTree start $ \_ -> return Right
putByteString :: Ptr () -> Lazy.ByteString -> Int -> IO ()
putByteString dst lbs len
= do poke (castPtr dst) len
let loop !ptr [] = return ()
loop !ptr (chunk:cs) = do Strict.unsafeUseAsCString chunk $ \cstr ->
copyArray ptr cstr (Strict.length chunk)
loop (ptr `plusPtr` Strict.length chunk) cs
loop (dst `plusPtr` intSize) (Lazy.toChunks lbs)
intSize :: Int
intSize = sizeOf (undefined::Int)
ptrSize :: Int
ptrSize = sizeOf (undefined::Ptr ())
insert :: (Ord k, Binary k, Binary a) => Index -> k -> Tag -> Maybe a -> IO [(Tag,Maybe Strict.ByteString)]
insert idx key tag mbVal
= insertBS idx key tag (fmap encode mbVal)
{-
insertWith :: (Ord k, Binary k, Binary a) => Index -> k -> Tag -> (Ptr DataCursor -> IO (Maybe a)) -> IO [(Tag,Maybe Strict.ByteString)]
insertWith idx key tag genVal
= insertWithBS idx key tag (\dataCursor -> do val <- genVal dataCursor; return $ fmap encode val)
-}
{- SPECIALISE insertBS :: Index -> Strict.ByteString -> Tag -> Maybe Lazy.ByteString -> IO [(Tag,Maybe Strict.ByteString)] -}
insertBS :: (Ord k, Binary k) => Index -> k -> Tag -> Maybe Lazy.ByteString -> IO [(Tag,Maybe Strict.ByteString)]
insertBS idx key tag mbVal
= insertWithBS idx key tag (\_ -> return mbVal)
{- SPECIALISE insertWithBS :: Index -> Strict.ByteString -> Tag -> (Ptr DataCursor -> IO (Maybe Lazy.ByteString)) -> IO [(Tag,Maybe Strict.ByteString)] -}
insertWithBS :: (Ord k, Binary k) => Index -> k -> Tag -> (Ptr DataCursor -> IO (Maybe Lazy.ByteString)) -> IO [(Tag,Maybe Strict.ByteString)]
insertWithBS (Index orig buffer) key tag genVal
= do keyCursor <- insertKey (Index orig buffer) key
oldData <- peekKeyCursorData keyCursor -- Get the old data item
dataPtr <- newDataCursor buffer tag =<< genVal oldData
pushNewDataCursor keyCursor dataPtr
if oldData == nullPtr
then return []
else fetchAllElts oldData
{-# INLINE insertKey #-}
insertKey :: (Ord k, Binary k) => Index -> k -> IO (Ptr KeyCursor)
insertKey (Index orig buffer) key
= insertPrim (lookupNearest orig key) orig buffer (newBinaryKeyCursor buffer key)
{-# INLINE insertLargestKey #-}
insertLargestKey :: (Binary k) => Index -> k -> IO (Ptr KeyCursor)
insertLargestKey (Index orig buffer) key
= insertPrim (lookupLargest orig) orig buffer (newBinaryKeyCursor buffer key)
insertLargestKeyCursor :: Index -> Ptr KeyCursor -> IO ()
insertLargestKeyCursor (Index orig buffer) keyCursor
= do insertPrim (lookupLargest orig) orig buffer (return keyCursor)
return ()
lookupKey :: (Ord k, Binary k) => Index -> k -> IO (Maybe (Ptr KeyCursor))
lookupKey (Index orig buffer) key
= do (dir,pos) <- lookupNearest orig key
case dir of
Stop -> fmap Just $ extractElemIdx pos
_ -> return Nothing
lookupList :: (Ord k, Binary k) => Index -> k -> IO [(Tag,Maybe Strict.ByteString)]
lookupList idx key
= do mbKey <- lookupKey idx key
case mbKey of
Nothing -> return []
Just key -> fetchAllElts =<< peekKeyCursorData key
fetchAllElts :: Ptr DataCursor -> IO [(Tag,Maybe Strict.ByteString)]
fetchAllElts ptr | ptr == nullPtr = return []
fetchAllElts ptr
= unsafeInterleaveIO $
do next <- peekDataCursorNext ptr
tag <- peekDataCursorTag ptr
mbData <- peekDataCursorData ptr
liftM ((tag,mbData):) (fetchAllElts next)
indexItemSize :: Int
indexItemSize = sizeOf (undefined :: IndexItem)
{-
Insert a key in the map. Return pointer to the old key if it exists.
-}
{- SPECIALISE insertPrim :: IO (Direction,Ptr IndexItem) -> Ptr IndexItem -> Buffer -> IO (Ptr KeyCursor) -> IO (Ptr KeyCursor) -}
{-# INLINE insertPrim #-}
insertPrim :: (IO (Direction,Ptr IndexItem)) -> Ptr IndexItem -> Buffer -> IO (Ptr KeyCursor) -> IO (Ptr KeyCursor)
insertPrim getPos !orig !buffer genIdx
= do size <- getSize orig
if size==0 -- We need a special case for size=0 /-:
then do eIdx <- genIdx
poke orig (IndexItem nullPtr (intToPtr 1) eIdx nullPtr nullPtr)
return eIdx
else do (dir,pos) <- getPos
case dir of
Right -> withBytes buffer indexItemSize $ \ptr ->
do eIdx <- genIdx
poke ptr (IndexItem pos (intToPtr 1) eIdx nullPtr nullPtr)
putRight pos ptr
balanceTree pos
return eIdx
Left -> withBytes buffer indexItemSize $ \ptr ->
do eIdx <- genIdx
poke ptr (IndexItem pos (intToPtr 1) eIdx nullPtr nullPtr)
putLeft pos ptr
balanceTree pos
return eIdx
Stop -> extractElemIdx pos
listKeyPointers :: Index -> IO (UArray Int (Ptr KeyCursor))
listKeyPointers (Index orig buffer)
= do size <- getSize orig
a <- newArray_ (0,size-1) :: IO (IOUArray Int (Ptr KeyCursor))
let loop n ptr | ptr == nullPtr = return ()
loop n ptr = do left <- extractLeft ptr
right <- extractRight ptr
leftSize <- getSize left
key <- extractElemIdx ptr
writeArray a (leftSize+n) key
loop (n) left
loop (leftSize+1+n) right
unless (size==0) $ loop (0::Int) orig
unsafeFreeze a
getKeyFromPointer :: Ptr KeyCursor -> IO Strict.ByteString
getKeyFromPointer ptr
= peekKeyCursorKey ptr
getDataFromPointer :: Ptr KeyCursor -> IO [(Tag, Maybe Strict.ByteString)]
getDataFromPointer ptr
= do dataPtr <- peekKeyCursorData ptr
fetchAllElts dataPtr
{-
getAllElements fn (Index buffer)
= do elems <- readBufferPos buffer
indices <- if elems == 0 then return id else sumIndex 0 buffer
vals <- forM (indices []) $ \idx -> sumIndex idx buffer
return $ concatMap ($ []) vals
where sumIndex = foldIndex sumNode sumLeaf
sumNode _ _ idx left right = return $ fn idx left right
sumLeaf = return id
getSortedElements = getAllElements (\idx left right -> left . (idx:) . right)
getReverseElements = getAllElements (\idx left right -> right . (idx:) . left)
-}
newIndex = do buffer <- newBuffer 512
withBytes buffer indexItemSize $ \ptr -> ptr `seq`
do poke ptr (IndexItem nullPtr (intToPtr 0) nullPtr nullPtr nullPtr)
return $ Index ptr buffer
touchIndex (Index _ buffer) = touchBuffer buffer
{-
foldIndex node leaf start buffer
= do ptr <- bufferPtr buffer
let loop (-1) = leaf
loop n = do IndexItem size idx left right <- peekElemOff ptr n
restLeft <- loop left
restRight <- loop right
node n size idx restLeft restRight
loop start
showPrimIndex set
= do let Index buffer = (fromJust (tIndex set))
let leaf = return []
node n _size _idx left right
= return $ n:left++right
values <- foldIndex node leaf 0 buffer
free <- readBufferPos buffer
printf " \tSize\tIndex\tLeft\tRight\n"
ptr <- bufferPtr buffer
forM_ [0..free-1] $ \n ->
do IndexItem size idx left right <- peekElemOff ptr n
let isntValue = n `notElem` values
printf "%s%d\t%d\t%d\t%d\t%d\n" (if isntValue then "*" else " ") n size idx left right
showIndex set
= do let Index buffer = (fromJust (tIndex set))
elems <- readBufferPos buffer
ptr <- bufferPtr buffer
let leaf = return $ [Node "Leaf" []]
node _ size idx restLeft restRight
= do eIdx <- return idx -- getElement idx -- set =<< extractElemIdx ptr idx
positions <- foldIndex (\_ _ pos left right -> return [Node pos (left++right)]) (return []) idx buffer
return $ [Node (show eIdx ++ ": " ++ show positions) (restLeft++restRight)]
unless (elems==0)
$ do tree <- foldIndex node leaf 0 buffer
putStrLn (drawForest tree)
{- SPECIALIZE isValid :: DiskSet RawString -> IO () -}
-- isValid :: IO ()
isValid set
= do let Index buffer = (fromJust (tIndex set))
elems <- readBufferPos buffer
ptr <- bufferPtr buffer
let check True _ = return ()
check False msg = putStrLn msg >> exitWith (ExitFailure 1)
leaf = return (Nothing, 0)
node n size idx (mbLeft, leftN) (mbRight, rightN)
= do eIdx <- return idx -- getElement idx -- set =<< extractElemIdx ptr idx
check (leftN+rightN+1 == size) $ "Size check failed at " ++ show (n,size,leftN,rightN)
flip (maybe (return ())) mbLeft $ \el -> check (el < eIdx) $ "LT check failed at: " ++ show (idx,el,eIdx)
flip (maybe (return ())) mbRight $ \el -> check (el > eIdx) $ "GT check failed at: " ++ show (idx,el,eIdx)
return (Just eIdx, size)
unless (elems==0) $ foldIndex node leaf 0 buffer >> return ()
return ()
-}
{-
testSet :: [String]
testSet = [("Hello")
,("World")
,("This")
,("Is")
,("A Test")
,("Yay")
,("I think it works")]
test :: IO ()
test = do idx <- newIndex
forM_ (IntMap.keys testSet) $ \key -> do insert testSet idx key
balanceIndex idx
showIndex testSet idx
isValid testSet idx
putStrLn "Index is valid"
-}
{-
verify prev !pos | pos == nullPtr = return ()
verify prev !pos
= do !top <- extractTop pos
!left <- extractLeft pos
!right <- extractRight pos
!sizeL <- getSize left
!sizeR <- getSize right
size <- getSize pos
unless (size==sizeL+sizeR+1) $ putStrLn $ "Size fail: " ++ show (size,sizeL,sizeR)
unless (top==prev) $ putStrLn "Top fail"
verify pos left
verify pos right
-}
balanceTree !pos | pos==nullPtr = return ()
balanceTree !pos
= do balance pos
!top <- extractTop pos
balanceTree top
getSize pos | pos == nullPtr = return $! 0
getSize pos
= extractSize pos
balance !pos
= do --keyCursor <- extractElemIdx pos
--bs <- peekKeyCursorKey keyCursor
--putStrLn $ "Balancing: " ++ show (decode (Lazy.fromChunks [bs]) :: Integer)
!left <- extractLeft pos
!right <- extractRight pos
!sizeL <- getSize left
!sizeR <- getSize right
putSize pos (sizeL+sizeR+1)
case () of
() | sizeL + sizeR <= 1 -> return ()
| sizeR >= delta*sizeL -> rotateL pos left right
| sizeL >= delta*sizeR -> rotateR pos left right
| otherwise -> return ()
rotateL pos left right
= do !sizeLY <- getSize =<< extractLeft right
!sizeRY <- getSize =<< extractRight right
if sizeLY < ratio * sizeRY then singleL pos
else doubleL pos
rotateR pos left right
= do !sizeLY <- getSize =<< extractLeft left
!sizeRY <- getSize =<< extractRight left
if sizeRY < ratio * sizeLY then singleR pos
else doubleR pos
singleL pos
= do IndexItem kTop kSize kElemIdx p1 k2 <- peek pos
IndexItem k2Top k2Size k2ElemIdx p2 p3 <- peek k2
--unless (k2Top == pos) $ putStrLn "Assertion failure"
!p2Size <- getSize p2
let p1Size = ptrToInt kSize-ptrToInt k2Size-1
poke pos (IndexItem kTop kSize k2ElemIdx k2 p3) -- kSize hasn't changed
poke k2 (IndexItem k2Top (intToPtr $ p2Size+p1Size+1) kElemIdx p1 p2)
putTop p3 pos
putTop p1 k2
-- recalcSize ptr k2 p1 p2
singleR pos
= do IndexItem kTop kSize kElemIdx k2 p3 <- peek pos
IndexItem k2Top k2Size k2ElemIdx p1 p2 <- peek k2
--unless (k2Top == pos) $ putStrLn "Assertion failure"
!p2Size <- getSize p2
let p3Size = ptrToInt kSize-ptrToInt k2Size-1
poke pos (IndexItem kTop kSize k2ElemIdx p1 k2) -- kSize hasn't changed
poke k2 (IndexItem k2Top (intToPtr $ p2Size+p3Size+1) kElemIdx p2 p3)
putTop p1 pos
putTop p3 k2
-- recalcSize ptr k2 p2 p3
doubleL pos
= do IndexItem kTop kSize kElemIdx p1 k2 <- peek pos
IndexItem k2Top k2Size k2ElemIdx k3 p4 <- peek k2
IndexItem k3Top k3Size k3ElemIdx p2 p3 <- peek k3
-- putStrLn "doubleL"
!p2Size <- getSize p2
!p3Size <- getSize p3
let p1Size = ptrToInt kSize - ptrToInt k2Size - 1
p4Size = ptrToInt k2Size - ptrToInt k3Size - 1
poke pos (IndexItem kTop kSize k3ElemIdx k3 k2) -- kSize hasn't changed
poke k2 (IndexItem k2Top (intToPtr $ p3Size+p4Size+1) k2ElemIdx p3 p4) -- k2ElemIdx and p4 hasn't changed
poke k3 (IndexItem k2Top (intToPtr $ p1Size+p2Size+1) kElemIdx p1 p2)
putTop p1 k3
putTop k3 pos
putTop p3 k2
doubleR pos
= do IndexItem kTop kSize kElemIdx k2 p4 <- peek pos
IndexItem k2Top k2Size k2ElemIdx p1 k3 <- peek k2
IndexItem k3Top k3Size k3ElemIdx p2 p3 <- peek k3
-- putStrLn "doubleR"
!p2Size <- getSize p2
!p3Size <- getSize p3
let p1Size = ptrToInt k2Size - ptrToInt k3Size - 1
p4Size = ptrToInt kSize - ptrToInt k2Size - 1
poke pos (IndexItem kTop kSize k3ElemIdx k2 k3) -- kSize hasn't changed
poke k2 (IndexItem pos (intToPtr $ p1Size+p2Size+1) k2ElemIdx p1 p2) -- k2ElemIdx and p1 hasn't changed.
poke k3 (IndexItem pos (intToPtr $ p3Size+p4Size+1) kElemIdx p3 p4)
putTop k3 pos
putTop p2 k2
putTop p4 k3
{-
recalcSize ptr !pos !left !right
= do !sizeL <- getSize ptr left
!sizeR <- getSize ptr right
putSize ptr pos (sizeL+sizeR+1)
-}
delta,ratio :: Int
delta = 5
ratio = 2
{-
balance :: k -> a -> Map k a -> Map k a -> Map k a
balance k x l r
| sizeL + sizeR <= 1 = Bin sizeX k x l r
| sizeR >= delta*sizeL = rotateL k x l r
| sizeL >= delta*sizeR = rotateR k x l r
| otherwise = Bin sizeX k x l r
where
sizeL = size l
sizeR = size r
sizeX = sizeL + sizeR + 1
-- rotate
rotateL k x l r@(Bin _ _ _ ly ry)
| size ly < ratio*size ry = singleL k x l r
| otherwise = doubleL k x l r
rotateR k x l@(Bin _ _ _ ly ry) r
| size ry < ratio*size ly = singleR k x l r
| otherwise = doubleR k x l r
-- basic rotations
singleL k1 x1 t1 (Bin _ k2 x2 t2 t3) = bin k2 x2 (bin k1 x1 t1 t2) t3
singleR k1 x1 (Bin _ k2 x2 t1 t2) t3 = bin k2 x2 t1 (bin k1 x1 t2 t3)
doubleL k1 x1 t1 (Bin _ k2 x2 (Bin _ k3 x3 t2 t3) t4) = bin k3 x3 (bin k1 x1 t1 t2) (bin k2 x2 t3 t4)
doubleR k1 x1 (Bin _ k2 x2 t1 (Bin _ k3 x3 t2 t3)) t4 = bin k3 x3 (bin k2 x2 t1 t2) (bin k1 x1 t3 t4)
-}
|
dmjio/CompactMap
|
src/Data/CompactMap/Index.hs
|
bsd-3-clause
| 21,141 | 0 | 21 | 6,703 | 4,801 | 2,324 | 2,477 | 305 | 5 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
module Main where
import Codec.Picture
import Control.Concurrent (forkOS)
import Control.Lens (view)
import Control.Monad
import Control.Monad.Extra
import qualified Data.Char as C (toLower)
import Data.IORef
import Data.List
import Data.Random
import Graphics.Rasterific
import Pipes
import qualified Pipes.Prelude as P
import System.Environment
import qualified System.Exit as S
import System.IO
import Graphics.Rendering.OpenGL.GL (($=))
import qualified Graphics.UI.GLUT as GLUT
import Evolution
import GlossIndividual
import GLPolygonImage
import ImageUtils
import PolygonImage
import Strategies
data Config s a b c =
Config { strategy :: s
, readPop :: b -> IO a
, runName :: String
, startingGenId :: Int
, render :: a -> IO (Image PixelRGBA8)
, stepCount :: Int
, tweakConfig :: c
}
-- TODO: can I remove the IO constraint on Individual?
runner :: (EvolutionStrategy s, Individual IO a, Show a, Read b)
=> Config s a b (TweakConfig a)
-> IO ()
runner Config {..} = do
putStrLn "loading initial"
startingGen <- loadGen startingGenId
putStrLn $ "starting at gen " ++ show startingGenId
runEffect $ for (pipeline startingGen) processGeneration
where
pipeline startingGen =
P.zip (evolve strategy tweakConfig startingGen) (each [startingGenId+1..])
>-> P.chain (print . snd)
>-> P.chain (const $ hFlush stdout)
>-> pipeSkip stepCount
fileName id = "out/" ++ runName ++ show id
loadGen 0 = replicateM (popSize strategy) (generate tweakConfig)
loadGen id =
mapM readPop . read =<< readFile (fileName id ++ ".data")
processGeneration (gen, genId) =
lift $ do
putStrLn ("completed gen " ++ show genId)
rendered <- render (head gen)
writePng (fileName genId ++ ".png") rendered
writeFile (fileName genId ++ ".data") $ show gen
-- The fact that I had to write this myself feels wrong. Did I miss something?
pipeSkip n = forever $ do
skip (n-1)
await >>= yield
where skip 0 = return ()
skip n = await >> skip (n-1)
polygonConfig sourceImg s startingGen stepCount =
return Config { strategy = s
, readPop = return . PolygonImage sourceImg
, runName = "polygons"
, startingGenId = startingGen
, render = return . renderPolygonImage
, stepCount = stepCount
, tweakConfig = sourceImg
}
glConfig sourceImg s startingGen stepCount = do
GLUT.initialize "darwin" []
window <- GLUT.createWindow "darwin"
GLUT.displayCallback $= return ()
renderState <- initRenderState sourceImg sourceImg
return Config { strategy = s
, readPop = initGlossIndividual renderState . GLPolygonImage . PolygonImage sourceImg
, runName = "glpolys"
, startingGenId = startingGen
, render = return . view getRendered
, stepCount = stepCount
, tweakConfig = renderState
}
-- circleConfig sourceImg s startingGen stepCount =
-- Config { strategy = s
-- , indGen = sample $ circleImageGen 50 sourceImg
-- , readPop = CircleImage sourceImg
-- , runName = "circles"
-- , startingGenId = startingGen
-- , render = renderCircleImage
-- , stepCount = stepCount
-- }
main :: IO ()
main = do
[filename] <- getArgs
(Right source) <- readImage filename --"images/landscape-st-remy-306-240.jpg"
let sourceImg = convertRGBA8 source
forkOS $ do
config <- glConfig sourceImg (MuPlusLambda 1 1) 0 500
-- config <- polygonConfig sourceImg (MuPlusLambda 1 1) 6000 25
runner config
forever $ do
hSetBuffering stdin NoBuffering
c <- getChar
when (C.toLower c == 'q') S.exitSuccess
-- when (C.toLower c == 'q') $ writeIORef quitSignal True
|
mattrrichard/darwin
|
src/Main.hs
|
bsd-3-clause
| 4,417 | 0 | 14 | 1,435 | 1,015 | 536 | 479 | 96 | 3 |
{-
- Hacq (c) 2013 NEC Laboratories America, Inc. All rights reserved.
-
- This file is part of Hacq.
- Hacq is distributed under the 3-clause BSD license.
- See the LICENSE file for more details.
-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
module Control.Monad.Ask.Class (MonadAsk(..), asks) where
import Control.Applicative (Applicative)
import Control.Monad.Reader (ReaderT)
import qualified Control.Monad.Reader as Reader
import Control.Monad.Trans (lift)
import qualified Control.Monad.Writer.Lazy as LWriter
import qualified Control.Monad.Writer.Strict as SWriter
import Data.Functor ((<$>))
import Data.Monoid (Monoid)
class (Applicative m, Monad m) => MonadAsk r m | m -> r where
ask :: m r
asks :: MonadAsk r m => (r -> a) -> m a
asks f = f <$> ask
instance (Applicative m, Monad m) => MonadAsk r (ReaderT r m) where
ask = Reader.ask
instance (Monoid w, MonadAsk r m) => MonadAsk r (LWriter.WriterT w m) where
ask = lift ask
instance (Monoid w, MonadAsk r m) => MonadAsk r (SWriter.WriterT w m) where
ask = lift ask
|
ti1024/hacq
|
src/Control/Monad/Ask/Class.hs
|
bsd-3-clause
| 1,159 | 0 | 8 | 197 | 318 | 184 | 134 | 23 | 1 |
module Data.ICalendar.Types ( ICalObject(..)
, ICalProperty(..)
-- * Property lookups
, lookupProps
, lookupProp
, lookupPropValue
, lookupPropParam
-- * Sub-object lookups
, lookupObjects
, lookupObject
) where
import Data.Maybe (listToMaybe)
data ICalObject = ICalObject { icoName :: String
, icoProperties :: [ICalProperty]
, icoObjects :: [ICalObject]
} deriving (Show, Eq)
data ICalProperty = ICalProperty { icpName :: String
, icpParams :: [(String, [String])]
, icpValue :: String
} deriving (Show, Eq)
-- | Convenience function to find all named properties of an 'ICalObject'
lookupProps :: ICalObject -> String -> [ICalProperty]
lookupProps obj propName = filter (\p -> icpName p == propName) (icoProperties obj)
-- | Convenience function to find a property of an 'ICalObject'
lookupProp :: ICalObject -> String -> Maybe ICalProperty
lookupProp obj propName = listToMaybe $ lookupProps obj propName
lookupPropValue :: ICalObject -> String -> Maybe String
lookupPropValue o propName =
do (ICalProperty _ _ v) <- lookupProp o propName
return v
lookupPropParam :: ICalObject -> String -> String -> Maybe [String]
lookupPropParam o propName paramName =
do (ICalProperty _ params _) <- lookupProp o propName
lookup paramName params
lookupObjects :: ICalObject -> String -> [ICalObject]
lookupObjects obj objName = filter (\o -> icoName o == objName) (icoObjects obj)
lookupObject :: ICalObject -> String -> Maybe ICalObject
lookupObject obj objName = listToMaybe $ lookupObjects obj objName
|
bgamari/icalendar
|
Data/ICalendar/Types.hs
|
bsd-3-clause
| 2,009 | 0 | 11 | 733 | 442 | 240 | 202 | 33 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module: Network.FastIRC.Session
-- Copyright: (c) 2010 Ertugrul Soeylemez
-- License: BSD3
-- Maintainer: Ertugrul Soeylemez <[email protected]>
-- Stability: alpha
--
-- This module implements a framework for IRC client software.
-- Essentially it consists of a dumb bot, which connects to and stays on
-- an IRC server waiting for commands.
--
-- Using the 'onEvent' function (or the convenience functions
-- 'onConnect', 'onDisconnect', etc.) you can attach event handlers to
-- certain events. These event handlers are run in the 'Bot' monad,
-- which encapsulates the current state of the bot.
--
-- Please note that even though unlikely you should expect that parts of
-- this interface will be changed in future revisions.
module Network.FastIRC.Session
( -- * Types
Bot,
BotCommand(..),
BotInfo(..),
Config(..),
BotSession,
Event(..),
EventHandler,
Params(..),
-- * Functions
ircSendCmd,
ircSendMsg,
ircSendString,
onEvent,
sendBotCmd,
startBot,
-- * Event utility functions
onConnect,
onDisconnect,
onError,
onLoggedIn,
onMessage,
onQuit,
-- * Bot monad
getBotInfo
)
where
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as M
import Control.Applicative
import Control.Concurrent
import Control.Exception
import Data.Map (Map)
import Data.Unique
import Control.Monad.State
import Control.Monad.Cont
import Control.Monad.Reader
import Network.Fancy
import Network.FastIRC.IO
import Network.FastIRC.Messages
import Network.FastIRC.ServerSet
import Network.FastIRC.Types
import System.IO
-- | Bot monad.
type Bot = ContT () (StateT Config (ReaderT Params IO))
-- | Commands to be sent to the bot.
data BotCommand
-- | Add an event handler.
= BotAddHandler (EventHandler -> IO ()) (Event -> Bot ())
| BotDispatch Event -- ^ Dispatch simulated event.
| BotError String -- ^ Simulate an error.
| BotQuit (Maybe CommandArg) -- ^ Send a quit message.
| BotRecv Message -- ^ Simulate receiving of a message.
| BotSendCmd Command -- ^ Send a command to the IRC server.
| BotSendMsg Message -- ^ Send a message to the IRC server.
| BotSendString MsgString -- ^ Send a raw string to the IRC server.
| BotTerminate -- ^ Immediately kill the bot.
-- | Runtime bot information.
data BotInfo =
BotInfo {
botCurrentNick :: Maybe NickName
}
-- | Bot session descriptor.
data BotSession =
BotSession {
botCmdChan :: Chan BotCommand -- ^ Command channel.
}
-- | Bot configuration at run-time.
data Config =
Config {
-- | Event handlers.
botEventHandlers :: Map EventHandler (Event -> Bot ()),
botEventChan :: Chan Event, -- ^ Event channel.
botHandle :: Handle, -- ^ Connection handle.
botInfo :: BotInfo, -- ^ Current information.
botIsQuitting :: Bool, -- ^ Quit command issued?
botKillerThread :: Maybe ThreadId, -- ^ Killer thread.
botServers :: ServerSet, -- ^ Nicknames known to be servers.
botSession :: BotSession -- ^ Session information.
}
-- | A bot event.
data Event
= ConnectedEvent -- ^ Bot connected.
| DisconnectedEvent -- ^ Bot disconnected (either error or on demand).
| ErrorEvent String -- ^ Connection failed or disconnected on error.
| LoggedInEvent -- ^ Bot logged in (received numeric 001).
| MessageEvent Message -- ^ Received message from server.
| QuitEvent -- ^ Bot disconnected on demand.
deriving (Eq, Read, Show)
-- | Event handler identifier.
type EventHandler = Unique
-- | Parameters for an IRC client connection.
data Params =
Params {
botGetNick :: IO NickName, -- ^ IRC nick name generator.
botGetUser :: IO UserName, -- ^ IRC user name generator.
botGetRealName :: IO RealName, -- ^ IRC real name generator.
botPassword :: Maybe CommandArg, -- ^ IRC server password.
botServerAddr :: Address -- ^ IRC server address.
}
-- | Core bot management thread.
botManager :: Params -> Config -> IO ()
botManager params cfg = do
-- Initialize bot.
let eventChan = botEventChan $ cfg
cmdChan = botCmdChan . botSession $ cfg
h = botHandle $ cfg
writeChan eventChan ConnectedEvent
dispatchThread <- forkIO $
getChanContents eventChan >>= writeList2Chan cmdChan . map BotDispatch
netThread <- forkIO $ networkHandler cmdChan (botHandle cfg)
-- Main loop.
runBot params cfg $ do
sendLogin
forever $ do
bcmd <- liftIO $ readChan cmdChan
case bcmd of
BotAddHandler reportId f -> do
hid <- liftIO newUnique
handlers <- botEventHandlers <$> get
modify (\cfg -> cfg { botEventHandlers = M.insert hid f handlers })
liftIO $ reportId hid
BotDispatch ev -> do
handlerList <- M.elems . botEventHandlers <$> get
mapM_ ($ ev) handlerList
BotError err -> do
isQuitting <- botIsQuitting <$> get
unless isQuitting . liftIO . writeChan eventChan $ ErrorEvent err
die
BotQuit reason -> do
liftIO $ hPutCommand h (QuitCmd reason)
ktid <- liftIO . forkIO $
threadDelay 1000000 >>
writeChan cmdChan BotTerminate
modify $ \cfg -> cfg { botIsQuitting = True,
botKillerThread = Just ktid }
BotRecv msg ->
liftIO (writeChan eventChan $ MessageEvent msg) >>
handleMsg msg
BotSendCmd cmd -> liftIO $ hPutCommand h cmd
BotSendMsg msg -> liftIO $ hPutMessage h msg
BotSendString str -> liftIO $ B.hPutStr h str
BotTerminate -> die
-- Clean up.
killThread dispatchThread
killThread netThread
where
networkHandler :: Chan BotCommand -> Handle -> IO ()
networkHandler cmdChan h = do
res <- try $ hGetMessage h :: IO (Either IOException Message)
case res of
Left err -> writeChan cmdChan $ BotError (show err)
Right msg ->
writeChan cmdChan (BotRecv msg) >>
networkHandler cmdChan h
die :: Bot ()
die = do
isQuitting <- botIsQuitting <$> get
ktidM <- botKillerThread <$> get
handlerList <- M.elems . botEventHandlers <$> get
when isQuitting $ mapM_ ($ QuitEvent) handlerList
case ktidM of
Just ktid -> liftIO $ killThread ktid
Nothing -> return ()
mapM_ ($ DisconnectedEvent) handlerList
abort ()
where abort x = ContT (\_ -> return x)
-- | Default bot information.
defBotInfo :: BotInfo
defBotInfo =
BotInfo { botCurrentNick = Nothing }
-- | Handle an incoming IRC message.
handleMsg :: Message -> Bot ()
handleMsg msg = do
h <- botHandle <$> get
let cmd = msgCommand msg
eventChan <- botEventChan <$> get
case cmd of
NumericCmd 1 (myNick:_) -> do
liftIO $ writeChan eventChan LoggedInEvent
modify $ \cfg -> let bi = (botInfo cfg) { botCurrentNick = Just myNick }
in cfg { botInfo = bi }
PingCmd a b -> liftIO $ hPutCommand h (PongCmd a b)
_ -> return ()
-- | Send a command to the IRC server.
ircSendCmd :: BotSession -> Command -> IO ()
ircSendCmd bs = sendBotCmd bs . BotSendCmd
-- | Send a message (with origin) to the IRC server. Note that IRC
-- servers ignore the origin prefix, so in general you would want to use
-- 'ircSendCmd' instead.
ircSendMsg :: BotSession -> Message -> IO ()
ircSendMsg bs = sendBotCmd bs . BotSendMsg
-- | Send a raw message string to the IRC server. This is what most IRC
-- clients call /quote.
ircSendString :: BotSession -> MsgString -> IO ()
ircSendString bs = sendBotCmd bs . BotSendString
-- | Add an event handler.
onEvent :: BotSession -> (Event -> Bot ()) -> IO EventHandler
onEvent bs f = do
let cmdChan = botCmdChan bs
answerVar <- newEmptyMVar
writeChan cmdChan $ BotAddHandler (putMVar answerVar) f
takeMVar answerVar
-- | Run a 'Bot' monad computation.
runBot :: Params -> Config -> Bot () -> IO ()
runBot params cfg =
fmap fst .
flip runReaderT params .
flip runStateT cfg .
flip runContT return
-- | Send bot command to a bot.
sendBotCmd :: BotSession -> BotCommand -> IO ()
sendBotCmd bs cmd = writeChan (botCmdChan bs) cmd
-- | Send login commands.
sendLogin :: Bot ()
sendLogin = do
h <- botHandle <$> get
nick <- asks botGetNick >>= liftIO
user <- asks botGetUser >>= liftIO
real <- asks botGetRealName >>= liftIO
addr <- asks botServerAddr
pass <- asks botPassword
let (host, port) =
case addr of
IP h p -> (B.pack h, B.pack $ show p)
IPv4 h p -> (B.pack h, B.pack $ show p)
IPv6 h p -> (B.pack h, B.pack $ show p)
_ -> ("localhost", "6667")
liftIO $ do
case pass of
Just pwd -> hPutCommand h $ PassCmd pwd
Nothing -> return ()
hPutCommand h $ NickCmd nick Nothing
hPutCommand h $ UserCmd user host port real
-- | Launch an IRC bot.
startBot :: Params -> IO (Either IOError BotSession)
startBot params = do
cmdChan <- newChan
eventChan <- newChan
errorVar <- newEmptyMVar
let session = BotSession { botCmdChan = cmdChan }
forkIO $
let comp =
withStream (botServerAddr params) $ \h ->
let cfg =
Config {
botEventHandlers = M.empty,
botEventChan = eventChan,
botHandle = h,
botInfo = defBotInfo,
botIsQuitting = False,
botKillerThread = Nothing,
botServers = emptyServers,
botSession = session
}
in do
hSetBuffering h NoBuffering
putMVar errorVar Nothing
res <- try $ botManager params cfg :: IO (Either IOException ())
case res of
Left err -> do
hPutStrLn stderr "Warning (fastirc): unexpected exception:"
hPrint stderr err
hPutStrLn stderr "Please report this to the author."
Right _ -> return ()
in comp `catch` (putMVar errorVar . Just)
error <- takeMVar errorVar
case error of
Nothing -> return (Right session)
Just err -> return (Left err)
-- | Action to run on connect.
onConnect :: BotSession -> Bot () -> IO EventHandler
onConnect bs c = onEvent bs $ \ev -> case ev of ConnectedEvent -> c; _ -> return ()
-- | Action to run on disconnect.
onDisconnect :: BotSession -> Bot () -> IO EventHandler
onDisconnect bs c = onEvent bs $ \ev -> case ev of DisconnectedEvent -> c; _ -> return ()
-- | Action to run on error (connection failed/aborted).
onError :: BotSession -> (String -> Bot ()) -> IO EventHandler
onError bs f = onEvent bs $ \ev -> case ev of ErrorEvent str -> f str; _ -> return ()
-- | Action to run after login (numeric 001 received).
onLoggedIn :: BotSession -> Bot () -> IO EventHandler
onLoggedIn bs c = onEvent bs $ \ev -> case ev of LoggedInEvent -> c; _ -> return ()
-- | Action to run when a message arrives.
onMessage :: BotSession -> (Message -> Bot ()) -> IO EventHandler
onMessage bs f = onEvent bs $ \ev -> case ev of MessageEvent msg -> f msg; _ -> return ()
-- | Action to run on quit.
onQuit :: BotSession -> Bot () -> IO EventHandler
onQuit bs c = onEvent bs $ \ev -> case ev of QuitEvent -> c; _ -> return ()
-- | Get current bot information.
getBotInfo :: Bot BotInfo
getBotInfo = botInfo <$> get
|
xyzzyz/fastirc
|
Network/FastIRC/Session.hs
|
bsd-3-clause
| 11,696 | 0 | 24 | 3,289 | 2,925 | 1,497 | 1,428 | 248 | 11 |
{-# LANGUAGE ExistentialQuantification, MultiParamTypeClasses #-}
module HTIG.IRCServer.Channel
( IChannel(..)
, Channel(Channel)
, channelName
, joinChannel
, kickChannel
, noticeChannel
, partChannel
, privmsgChannel
, quitChannel
, topicChannel
) where
import Network.FastIRC.Types
import Network.FastIRC.Users (UserSpec)
import HTIG.IRCServer.Core
class IChannel a g l where
onJoin :: a -> ChannelName -> UserSpec -> IRCM g l ()
onJoin _ _ _ = return ()
onKick :: a -> ChannelName -> UserSpec -> NickName -> CommandArg -> IRCM g l ()
onKick _ _ _ _ _ = return ()
onNotice :: a -> ChannelName -> UserSpec -> CommandArg -> IRCM g l ()
onNotice _ _ _ _ = return ()
onPart :: a -> ChannelName -> UserSpec -> IRCM g l ()
onPart _ _ _ = return ()
onPrivmsg :: a -> ChannelName -> UserSpec -> CommandArg -> IRCM g l ()
onPrivmsg _ _ _ _ = return ()
onQuit :: a -> ChannelName -> UserSpec -> Maybe CommandArg -> IRCM g l ()
onQuit _ _ _ _ = return ()
onTopic :: a -> ChannelName -> UserSpec -> CommandArg -> IRCM g l ()
onTopic _ _ _ _ = return ()
data Channel g l = forall a. IChannel a g l => Channel a ChannelName
channelName :: Channel g l -> ChannelName
channelName (Channel _ n) = n
joinChannel :: Channel g l -> UserSpec -> IRCM g l ()
joinChannel (Channel a n) = onJoin a n
kickChannel :: Channel g l -> UserSpec -> NickName -> CommandArg -> IRCM g l ()
kickChannel (Channel a n) = onKick a n
noticeChannel :: Channel g l -> UserSpec -> CommandArg -> IRCM g l ()
noticeChannel (Channel a n) = onNotice a n
partChannel :: Channel g l -> UserSpec -> IRCM g l ()
partChannel (Channel a n) u = onPart a n u
privmsgChannel :: Channel g l -> UserSpec -> CommandArg -> IRCM g l ()
privmsgChannel (Channel a n) u m = onPrivmsg a n u m
quitChannel :: Channel g l -> UserSpec -> Maybe CommandArg -> IRCM g l ()
quitChannel (Channel a n) = onQuit a n
topicChannel :: Channel g l -> UserSpec -> CommandArg -> IRCM g l ()
topicChannel (Channel a n) = onTopic a n
|
nakamuray/htig
|
HTIG/IRCServer/Channel.hs
|
bsd-3-clause
| 2,072 | 0 | 13 | 499 | 858 | 431 | 427 | 50 | 1 |
module Types
where
import System.Console.ANSI
type Grid = [String]
data Player = Player { token :: Char -- the unique token of this player, chosen when calling the program
, color :: Color -- the color in which the token of this player will be printed during the game
} deriving (Show, Eq)
data Game = Game { players :: [Player] -- a list of every player in the game
, grid :: Grid -- the current grid
, winBy :: Int -- the neccesary length of a sequence of connected coins/tokens to win the game
} deriving (Show, Eq)
|
chisaramai/connect4
|
src/Types.hs
|
bsd-3-clause
| 678 | 0 | 9 | 259 | 97 | 62 | 35 | 10 | 0 |
module CodeGen.LispToJs
( genCode
)
where
import Ast
import qualified CodeGen.JsAst as JS
genCode :: Program -> JS.Program
genCode p = map compileFun p ++ [callMain]
where callMain = JS.ExprStatement $ JS.Call (JS.Ref "main") []
compileFun :: Function -> JS.Statement
compileFun f = JS.Assign name (JS.Lambda args body)
where name = funName f
args = funArgs f
body = map (JS.ExprStatement . compileExpr) $ funBody f
compileExpr :: Expr -> JS.Expr
compileExpr (IntLit i) = JS.IntLit i
compileExpr (Ref r) = JS.Ref r
compileExpr (Plus a b) = JS.Plus (compileExpr a) (compileExpr b)
compileExpr (Minus a b) = JS.Minus (compileExpr a) (compileExpr b)
compileExpr (Times a b) = JS.Times (compileExpr a) (compileExpr b)
compileExpr (Greater a b) = JS.Greater (compileExpr a) (compileExpr b)
compileExpr (GreaterEq a b) = JS.GreaterEq (compileExpr a) (compileExpr b)
compileExpr (Less a b) = JS.Less (compileExpr a) (compileExpr b)
compileExpr (LessEq a b) = JS.LessEq (compileExpr a) (compileExpr b)
compileExpr (Eq a b) = JS.Eq (compileExpr a) (compileExpr b)
compileExpr (NotEq a b) = JS.NotEq (compileExpr a) (compileExpr b)
compileExpr (And a b) = JS.And (compileExpr a) (compileExpr b)
compileExpr (Or a b) = JS.Or (compileExpr a) (compileExpr b)
compileExpr (Not a) = JS.Not (compileExpr a)
compileExpr (If cond thenB elseB) = JS.Call lambda []
where lambda = JS.Lambda [] [body]
body = JS.If (compileExpr cond) [thenB'] [elseB']
thenB' = JS.ExprStatement $ compileExpr thenB
elseB' = JS.ExprStatement $ compileExpr elseB
compileExpr (Lambda args body) = JS.Lambda args $ map (JS.ExprStatement . compileExpr) body
compileExpr (Call (Array exprs) [i]) = JS.Subscript (JS.Array $ map compileExpr exprs) (compileExpr i)
compileExpr (Call (Ref "map") [f, array]) =
JS.MethodCall (compileExpr array) "map" [compileExpr f]
compileExpr (Call (Ref "filter") [f, array]) =
JS.MethodCall (compileExpr array) "filter" [compileExpr f]
compileExpr (Call (Ref "fold") [f, start, array]) =
JS.MethodCall (compileExpr array) "reduce" [compileExpr f, compileExpr start]
compileExpr (Call e args) = JS.Call (compileExpr e) (map compileExpr args)
compileExpr (Array es) = JS.Array $ map compileExpr es
compileExpr (Let bindings exprs) =
let bindings' = map (uncurry compileBinding) bindings
exprs' = map (JS.ExprStatement . compileExpr) exprs
lambda = JS.Lambda [] (bindings' ++ exprs')
in JS.Call lambda []
compileExpr (Print a) = JS.Call lambda []
where lambda = JS.Lambda [] [consoleLog, returnStatment]
a' = compileExpr a
consoleLog = JS.ExprStatement $ JS.Call (JS.Ref "console.log") [a']
returnStatment = JS.ExprStatement a'
compileBinding :: Identifier -> Expr -> JS.Statement
compileBinding i e = JS.Assign i $ compileExpr e
|
davidpdrsn/alisp
|
src/CodeGen/LispToJs.hs
|
bsd-3-clause
| 2,855 | 0 | 12 | 540 | 1,245 | 622 | 623 | 54 | 1 |
-- |Internal representation of data types in hasp. The types in this file differ
-- from those defined in Expressions.hs in that Expr represents syntactic forms
-- as they appear in hasp source code, whereas HData represnts hasp values, i.e.
-- results of computations.
module DataTypes
( HData(..)
, HNum(..)
, Env(..)
, emptyEnv
, toMap
) where
import qualified Data.Map as Map
import Expressions
import Error
data HNum = HInt Integer
| HFloat Float
deriving (Eq)
instance Ord HNum where
(HInt x) `compare` (HInt y) = x `compare` y
(HInt x) `compare` (HFloat y) = (fromIntegral x) `compare` y
(HFloat x) `compare` (HInt y) = x `compare` (fromIntegral y)
(HFloat x) `compare` (HFloat y) = x `compare` y
instance Num HNum where
negate (HInt x) = HInt (negate x)
negate (HFloat x) = HFloat (negate x)
abs (HInt x) = HInt (abs x)
abs (HFloat x) = HFloat (abs x)
signum (HInt x) = HInt (signum x)
signum (HFloat x) = HFloat (signum x)
(HInt x) + (HInt y) = HInt (x + y)
(HInt x) + (HFloat y) = HFloat ((fromIntegral x) + y)
(HFloat x) + (HInt y) = HFloat (x + (fromIntegral y))
(HFloat x) + (HFloat y) = HFloat (x + y)
(HInt x) - (HInt y) = HInt (x - y)
(HInt x) - (HFloat y) = HFloat ((fromIntegral x) - y)
(HFloat x) - (HInt y) = HFloat (x - (fromIntegral y))
(HFloat x) - (HFloat y) = HFloat (x - y)
(HInt x) * (HInt y) = HInt (x * y)
(HInt x) * (HFloat y) = HFloat ((fromIntegral x) * y)
(HFloat x) * (HInt y) = HFloat (x * (fromIntegral y))
(HFloat x) * (HFloat y) = HFloat (x * y)
fromInteger = HInt
instance Show HNum where
show (HInt x) = show x
show (HFloat x) = show x
data HData = HN HNum
| HBool Bool
| HString String
| HList [HData]
| HQuote Expr
| HFunc Env (Env -> [HData] -> ThrowsError HData)
| HNothing -- For use in hasp interpreter (i.e. Haskell code) ONLY!!!
instance Eq HData where
(HFunc _ _) == _ = False
_ == (HFunc _ _) = False
(HN x) == (HN y) = x == y
x == y = show x == show y -- Kinda hacky but good enough for now.
instance Show HData where
show (HN num) = show num
show (HBool bool) = show bool
show (HString string) = string
show (HList list) = "(" ++ unwords (map show list) ++ ")"
show (HQuote expr) = "'" ++ (show expr)
show (HFunc _ _) = "procedure"
show HNothing = ""
data Env = Env (Map.Map Identifier HData)
emptyEnv :: Env
emptyEnv = Env (Map.empty)
toMap :: Env -> Map.Map Identifier HData
toMap (Env m) = m
|
aldld/hasp
|
src/DataTypes.hs
|
bsd-3-clause
| 2,600 | 0 | 10 | 722 | 1,200 | 612 | 588 | 65 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Data.Wavelets.Reconstruction where
import Prelude hiding (map,maximum,minimum,init)
import Data.Wavelets
import Numeric.Statistics
import Statistics.Sample
import Data.Vector.Storable -- hiding (map)
-- import Linear
-- |explicitly name a Fractional and Ord instance on the idwt function
fidwt :: Int -> WaveletFilter Double -> WaveletPacker Double c -> c -> [Double]
fidwt = idwt
-- | reconstruct the time series raw, without worrying about scaling
reconstructTimeSeries :: Int -> WaveletFilter Double -> WaveletPacker Double c -> c -> Vector Double
reconstructTimeSeries i wft wptc c = vRslt
where rslt = fidwt i wft wptc c
vRslt = init.fromList $ rslt
|
smurphy8/wavelets
|
src/Data/Wavelets/Reconstruction.hs
|
bsd-3-clause
| 722 | 0 | 9 | 125 | 161 | 90 | 71 | 13 | 1 |
{-# LANGUAGE TypeOperators #-}
module Dag.Render where
import Control.Monad.State
import Data.Foldable (Foldable)
import qualified Data.Foldable as Foldable
import Data.IntMap
import Data.Traversable (Traversable, traverse)
import Tree
import Dag.Internal
import Dot
numberNodesFree :: Traversable f
=> Maybe Int -- ^ Optional number for the root
-> Free f a
-> State Int (Free (f :&: Int) a)
numberNodesFree _ (Ret a) = return $ Ret a
numberNodesFree k (In f) = do
n <- case k of
Just k' -> return k'
_ -> do
k' <- get; put (k'+1)
return k'
f' <- traverse (numberNodesFree Nothing) f
return $ In (f' :&: n)
numberNodes :: Traversable f => Dag f -> Dag (f :&: Int)
numberNodes (Dag r es n) = flip evalState n $ do
r' <- (fmap out . numberNodesFree Nothing . In) r
es' <- traverseWithKey (\k -> fmap out . numberNodesFree (Just k) . In) es
return $ Dag r' es' n
where
out (In f) = f
class ShowConstr f where
showConstr :: f a -> String
arity :: Foldable f => f a -> Int
arity = length . Foldable.toList
nodeToGraph' :: (ShowConstr f, Functor f, Foldable f) =>
Free (f :&: Int) Node -> ExpGraph
nodeToGraph' (Ret _) = []
nodeToGraph' (In f) = nodeToGraph "white" f
nodeToGraph :: (ShowConstr f, Functor f, Foldable f) =>
Color -> (f :&: Int) (Free (f :&: Int) Node) -> ExpGraph
nodeToGraph col (f :&: x) = concat
$ [node x (showConstr f) col (arity f)]
++ [mkEdge x i inp | (i,inp) <- [0..] `zip` Foldable.toList f]
++ [Foldable.fold $ fmap nodeToGraph' f]
where
mkEdge x inp (Ret a) = edge x inp a
mkEdge x inp (In (_ :&: y)) = edge x inp y
dagToGraph :: (ShowConstr f, Traversable f) => Dag f -> ExpGraph
dagToGraph dag = concat $
[nodeToGraph "lightgrey" $ root dag']
++
[nodeToGraph "lightgrey" f | (n,f) <- assocs $ edges dag']
where
dag' = numberNodes dag
renderDag :: (ShowConstr f, Traversable f) => Dag f -> FilePath -> IO ()
renderDag dag file = renderGraph (dagToGraph dag) file
|
emilaxelsson/ag-graph
|
src/Dag/Render.hs
|
bsd-3-clause
| 2,074 | 0 | 16 | 535 | 895 | 450 | 445 | 53 | 2 |
-- | This module contains the parser for the MiniJava language
module Espresso.Parser(
identifier,
mainClass) where
import Text.Parser as P
import Text.Parser.Combinators
import Text.Parser.Char
import Espresso.AST
-- | 'token' represents a token in the MiniJava language
token :: Parser a -> Parser a
token p = do res <- p
many spaces
return res
-- | 'identifier' parses an identifier in the MiniJava language.
identifier :: Parser MJIdentifier
identifier = token p
where
p = do x <- (char '_' <|> letter)
xs <- many (alphaNum <|> char '_')
return $ MJIdentifier $ x:xs
-- | 'keyword' parses a keyword in MiniJava, which is string potentially
-- followed by white space.
keyword :: String -> Parser Char
keyword = token . string
-- | 'mainClass' parses the main class in the MiniJava language
mainClass :: Parser MJExpression
mainClass = do keyword "class"
classId <- identifier
keyword "{"
keyword "public"
keyword "static"
keyword "void"
keyword "main"
keyword "("
keyword "String"
argsId <- identifier
keyword ")"
keyword "{"
keyword "}"
keyword "}"
return (MJMainClass classId argsId [])
|
helino/espresso
|
src/Espresso/Parser.hs
|
bsd-3-clause
| 1,388 | 0 | 13 | 470 | 299 | 141 | 158 | 34 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Api.Session where
import Data.Text (Text)
import Control.Monad.Except
import Control.Monad.Reader (ReaderT, runReaderT)
import Control.Monad.Reader.Class
import GHC.Generics
import Data.Time (getCurrentTime, addUTCTime)
import Data.Aeson
import Data.Int (Int64)
import Database.Persist.Postgresql (Entity (..), fromSqlKey, insert,
selectFirst, selectList, (==.))
import Network.Wai (Application)
import Servant
import Config (Config (..), App(..))
import Models
import Password
import Session (encodeSession, Session(..))
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.ByteString (ByteString)
import Database.Persist.Sql
import Data.Maybe (listToMaybe, Maybe(..))
import Web.Cookie (SetCookie(..), renderSetCookie)
import Data.Default (def)
import qualified Blaze.ByteString.Builder as BB
data Creds = Creds {
username :: Text,
password :: Text
} deriving (Generic)
instance FromJSON Creds
type SetCookieResult = Headers '[Header "Set-Cookie" Text] ()
type AuthAPI =
"login" :> ReqBody '[JSON] Creds :> Post '[JSON] SetCookieResult
:<|> "logout" :> Post '[JSON] SetCookieResult
authServer :: ServerT AuthAPI App
authServer = login :<|> logout
sessionCookieName :: Text
sessionCookieName = "_SESSION"
setCookieToText :: SetCookie -> Text
setCookieToText = decodeUtf8 . BB.toByteString . renderSetCookie
login :: Creds -> App SetCookieResult
login c = do
mu <- runDB $ getBy $ UniqueUser $ username c
case mu of
Just (Entity uId u) -> do
key <- asks getKey
now <- liftIO getCurrentTime
if checkPassword (password c) u
then do
let et = addUTCTime sessionLength now
t <- liftIO $ encodeSession key $ Session uId et
let sc = def {
setCookieName = encodeUtf8 sessionCookieName,
setCookieValue = encodeUtf8 t,
setCookieExpires = Just et,
setCookieHttpOnly = True
}
return $ addHeader (setCookieToText sc) ()
else err
Nothing -> err
where
sessionLength = 365 * 86400
err = throwError $ err403 { errBody = "Invalid username or password" }
logout :: App SetCookieResult
logout = do
now <- liftIO getCurrentTime
return $ addHeader (setCookieToText $ sc now) ()
where
sc now = def {
setCookieName = encodeUtf8 sessionCookieName,
setCookieValue = encodeUtf8 "",
setCookieExpires = Just now,
setCookieHttpOnly = True
}
|
tlaitinen/servant-cookie-hmac-auth-example
|
src/Api/Session.hs
|
bsd-3-clause
| 3,264 | 0 | 20 | 1,188 | 747 | 417 | 330 | 74 | 3 |
module Text.HTML.Moe2.Element where
import Text.HTML.Moe2.Type
import Text.HTML.Moe2.Utils
import Data.Default
import Control.Monad.Writer
import Prelude hiding (id, span, div, head, (>), (.), (-))
import Air.Light ((-), first)
import Data.DList (singleton, toList)
import Data.Maybe (fromMaybe)
element :: String -> MoeCombinator
element x u = tell - singleton -
def
{
name = pack - escape x
, elements = toList - execWriter - u
}
(!) :: (MoeUnit -> MoeUnit) -> [Attribute] -> (MoeUnit -> MoeUnit)
(!) = add_attributes
infixl 1 !
add_attributes :: (MoeUnit -> MoeUnit) -> [Attribute] -> (MoeUnit -> MoeUnit)
add_attributes f xs = \u ->
let r = f u
in
tell - singleton - Attributes xs - fromMaybe def - first - toList - execWriter - r
e :: String -> MoeCombinator
e = element
no_indent_element :: String -> MoeCombinator
no_indent_element x u = tell - singleton -
def
{
name = pack - x
, elements = toList - execWriter u
, indent = False
}
ne :: String -> MoeCombinator
ne = no_indent_element
self_close_element :: String -> LightCombinator
self_close_element x _ = tell - singleton -
def
{
name = pack - escape x
, self_close = True
}
sc :: String -> LightCombinator
sc = self_close_element
no_escape_no_indent_str :: String -> MoeUnit
no_escape_no_indent_str = raw
escape_no_indent_str :: String -> MoeUnit
escape_no_indent_str = _pre
no_escape_indent_str :: String -> MoeUnit
no_escape_indent_str = prim
str, raw, _pre, prim :: String -> MoeUnit
str x = tell - singleton - Data (pack - escape x)
raw x = tell - singleton - Raw (pack x)
_pre x = tell - singleton - Pre (pack - escape x)
prim x = tell - singleton - Prim (pack x)
raw_bytestring, prim_bytestring :: Internal -> MoeUnit
raw_bytestring x = tell - singleton - Raw x
prim_bytestring x = tell - singleton - Prim x
|
nfjinjing/moe
|
src/Text/HTML/Moe2/Element.hs
|
bsd-3-clause
| 1,905 | 0 | 14 | 430 | 659 | 369 | 290 | 52 | 1 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{- |
A small module to perform optimization using Particle Swarm Optimization
(PSO), based on the so-called /Standard PSO/ defined in
Bratton, Daniel, and James Kennedy. \"Defining a standard for particle
swarm optimization.\" Swarm Intelligence Symposium, 2007. SIS 2007. IEEE.
IEEE, 2007.
I highly recommend that you find and read this paper if you are
interested in PSO at all. However, the wikipedia entry is also quite
good: <http://en.wikipedia.org/wiki/Particle_swarm_optimization>
Note that we are using a method with /constriction parameters/, while
the wikipedia article puts forward a method using /inertia weight/. The
two are similar, but not identical.
For an overview of how to use this module, see the README available at
<https://github.com/brianshourd/haskell-Calypso/blob/master/README.md>.
-}
module Calypso.Core
(
-- * Main Classes
-- $typeclasses
PsoVect(..),
Between(..),
Grade(..),
PsoSized(..),
-- * Easy Method
easyOptimize,
-- * Updaters
Updater(..),
-- ** Common Updaters
-- $updaters
upDefault,
upStandard,
upOriginal,
upInertiaWeight,
upInertiaWeightDynamic,
-- ** Building Blocks
-- $buildingUpdaters
upAddLocal,
upAddLocalDynamic,
upAddPrivate,
upAddPrivateDynamic,
upScale,
upScaleDynamic,
upVMax,
upVMaxDynamic,
-- * Swarm Operations
defaultSwarm,
randomSwarm,
createSwarm,
updateSwarm,
iterateSwarm,
iterateWhile,
-- * Helper functions
boundTo,
pSqMag,
-- * Data Structures
PsoGuide(..),
Particle(..),
Swarm(..),
-- * Analysis
center,
-- avgScore,
posVariance,
-- scoreVariance
) where
import Control.DeepSeq
import Data.Function (on)
import Data.List (foldl', genericIndex)
import Data.Monoid
import System.Random
{- $typeclasses
In general, to use this library, you will be optimizing a function @f ::
a -> b@. This library will work so long as
1. @a@ is a member of the @'PsoVect'@ type class, and
2. @b@ is a member of the @'Grade'@ type class.
Ex. You want to minimize the function @f (x,y) = x^2 + y^2@. Then @f@
has type @f :: (Double, Double) -> Double@, where lower scores are
better. Then you need to make sure that @(Double, Double)@ is an
instance of @PsoVect@ and that @Double@ is an instance of @Grade@ (with
@'betterThan'@ given by @(<)@). Good news - these are already included,
so you don't need to create these instances yourself.
For more examples, see the examples included with the code (which should
be available at <https://github.com/brianshourd/haskell-Calypso>).
-}
{- |
Represents the position and velocity of a particle.
Minimal complete definition: @'pAdd'@, @'pZero'@, @'pScale'@
Theoretically, a type belonging to the class @PsoVect@ should form a
/real vector space/
(<http://en.wikipedia.org/wiki/Vector_space#Definition>). That is, it
should satisfy the vector space laws:
Suppose that the type @a@ is an instance of @'PsoVect'@. for all @u@,
@v@, and @w@ of type @a@, and all @r@ and @s@ of type @Double@, we
should have:
1. @pAdd (pAdd u v) w = pAdd u (pAdd v w)@ [pAdd is associative]
2. @pAdd v pZero = pAdd pZero v = v@ [pZero is additive identity]
3. For every @v@ there is an additive inverse @v'@ such that @pAdd v
v' = pAdd v' v = pZero@
4. @pAdd v w = pAdd w v@ [pAdd is commutative]
5. @pScale r (pAdd v w) = pAdd (pScale r v) (pScale r w)@
[Distributivity]
6. @pScale (r + s) v = pAdd (pScale r v) (pScale s v)@
[Distributivity]
7. @pScale (r * s) v = pScale r (pScale s v)@ [Compatibility]
8. @pScale 1 v = v@ [Identity scalar]
Notice that the first 2 laws are the Monoid laws (mAppend = pAdd, mempty
= pZero) and the first 4 are the laws of an abelian group.
If these laws are satisfied, we can prove that the additive inverse of
@v@ is @pScale (-1) v@, so we can automatically define @'pSubtract'@.
However, you may provide a faster implementation if you wish.
-}
class (Between a) => PsoVect a
where
pAdd :: a -> a -> a
pZero :: a
pScale :: Double -> a -> a
pSubtract :: a -> a -> a
pSubtract v1 v2 = pAdd v1 $ pScale (-1) v2
{- |
This class encodes the meaning when we say something like "pick a point
between (-1, -1) and (1, 1)", meaning any point (x, y) where -1 <= x <=
1 and -1 <= y <= 1. Generally, it should be defined component-wise like
this (though I plan on experimenting with alternate notions, hence the
typeclass).
Notice that @randBetween@ is essentially the same as @randomR@. Why not
just require the @Random@ typeclass, then? Two reasons:
1. I want to make a bunch of standard types instances of @Between@, and
I'd rather not polllute the @Random@ typeclass.
2. @Random@ requires both @randomR@ and @random@ - for some types
@random@ doesn't make sense.
-}
class Between a
where
isBetween :: a -> (a, a) -> Bool
randBetween :: (a, a) -> StdGen -> (a, StdGen)
{- |
Often, we may want to restrict a function to some inputs (that is, bound
the function). This function does exactly that. Arguments are structured
to allow for infix notation: @f `boundTo` ((-1, -1), (1, 1))@.
-}
boundTo :: (Between a) => (a -> b) -> (a, a) -> a -> Maybe b
boundTo f bounds p = case p `isBetween` bounds of
True -> Just $ f p
False -> Nothing
{- |
The function that you wish to optimize should be of the form @f ::
(PsoVect a, Grade b) => a -> b@. That is, it should associate to each
point a grade.
Many different data structures could be considered grades. In
particular, the types of @Double@ and @Maybe Double@, both of which are
instanced below. In the case of @Double@, lower scores are better
(including negative numbers) - this is the usual scoring system for PSO.
In the @Maybe Double@ case, lower scores are better, but a score of
@Nothing@ is worst of all. This is principally used to create grading
functions which look only within given bounds. For example, if we wish
to find the lowest value of @f x y = 2 * x + 3 * y - 4@ within the
bounds @0 <= x <= 3@ and @0 <= y <= 4@, we would use as our grading
function
g :: (Double, Double) -> Maybe Double
g p\@(x,y)
| and [0 <= x, x <= 2, 0 <= y, y <= 3] = Just $ 2 * x + 3 * y - 4
| otherwise = Nothing
In practice, I don't think that anyone will need to instantiate this
typeclass, since I've already made instances for what I think are the
common situations. However, if you needed to, a minimal definition would
include either @betterThan@ or @worseThan@.
-}
class Grade a
where
betterThan :: a -> a -> Bool
x `betterThan` y = not $ x `worseThan` y
worseThan :: a -> a -> Bool
x `worseThan` y = not $ x `betterThan` y
-- Convenience function to determine the best grade from a list of
-- grades
bestGrade :: (Grade a) => [a] -> a
bestGrade (x:xs) = foldr go x xs
where
go y z
| y `betterThan` z = y
| otherwise = z
{- |
If @PsoVect@ means /real vector space/, then @PsoSized@ means /real
inner product space/
(<http://en.wikipedia.org/wiki/Inner_product_space>). In particular, we
should satisfy the following three axioms:
1. @x `dot` y == y `dot` x@ for all @x@ and @y@ (symmetric).
2. @(x `pAdd` (a `pScale` z)) `dot` y == (x `dot` y) + a * (z `dot y)@
for all @x@, @y@, @z@, and @a@ (linear in the first argument).
3. @x `dot` x >= 0@ for all @x@, with equality if and only if @x ==
pZero@ (positive-definite).
In practice, a @PsoVect@ is just an ordered collection of real numbers,
and we can define `dot` analagously to:
dot :: (Double, Double) -> (Double, Double) -> Double
(x1, y1) `dot` (x2, y2) = x1 * x2 + y1 * y2
In many cases, it is not necessary to make your data an instance of
@PsoSized@. Generally, this is only used if you wish to use @'upVMax'@.
-}
class (PsoVect a) => PsoSized a
where
dot :: a -> a -> Double
{-
If we have a @PsoSized@ element, then it has a length. This is the
square of that length.
-}
pSqMag :: (PsoSized a) => a -> Double
pSqMag x = x `dot` x
{- |
A guide for a particle. The term /guide/ originates from (as far as I
can tell) this paper on velocity adaptation.
Helwig, Sabine, Frank Neumann, and Rolf Wanka. \"Particle swarm
optimization with velocity adaptation.\" Adaptive and Intelligent
Systems, 2009. ICAIS'09. International Conference on. IEEE, 2009.
It stores both the location of the possible minimum, and the value of
the function to minimize at that point.
In use, the type @a@ should belong to the @'PsoVect'@ class and the type
@b@ should belong to the @'Grade'@ class.
-}
data PsoGuide a b = PsoGuide {
pt :: a,
val :: b
} deriving (Show)
bestGuide :: (Grade b) => [PsoGuide a b] -> PsoGuide a b
bestGuide (x:xs) = foldr go x xs
where
go y@(PsoGuide _ valy) z@(PsoGuide _ valz)
| valy `betterThan` valz = y
| otherwise = z
{- |
@Particles@ know their location, velocity, and the best location/value
they've visited. Individual @Particles@ do not know the global minimum,
but the @Swarm@ they belong to does
In use, the type @a@ should belong to the @'PsoVect'@ class and the type
@b@ should belong to the @'Grade'@ class.
-}
data Particle a b = Particle {
pos :: a, -- ^ Position of particle
vel :: a, -- ^ Velocity of particle
pGuide :: PsoGuide a b -- ^ Private guide
} deriving (Show)
{- |
Updater is the function which takes as arguments:
1. A @StdGen@, to do any necessary random calculations
2. A @Particle a b@, from which it can get position, velocity, and th
private guide
3. A @PsoGuide a b@, the local guide for the particle
4. An @Int@, the current iteration of the swarm. Useful for parameters
that adjust over time
It returns the new velocity of the particle.
Normally, updaters are not created through this constructor, but through
one of the @up*@ functions (e.g. @'upStandard'@,
@'upOriginal'@, etc.), or by combining some of the builder functions
through @<>@.
-}
data Updater a b = Updater {
newVel :: StdGen -> Particle a b -> PsoGuide a b -> Integer -> (a, StdGen)
}
{- |
Updaters form a @Monoid@ under (essentially) composition. An @Updater@
is just a wrapper on a function @f :: StdGen -> Particle a b -> PsoGuide
a b -> Integer -> (a, StdGen)@. A @Particle a b@ is really just a
position (type @a@), a velocity (type @a@), and a
private guide (type @PsoGuide a b@). If we regard the position, private
guide, local guide, and iteration to be constant, then an @Updater@ just
is just a function @StdGen -> a -> (a, StdGen)@ which takes a velocity
and a standard generator to produce a new velocity and a new standard
generator. In this way, we can think about composing @Updaters@ - this
composition forms a @Monoid@.
-}
instance (PsoVect a, Grade b) => Monoid (Updater a b)
where
mempty = Updater (\g (Particle _ v _) _ _ -> (v, g))
mappend (Updater f) (Updater g) = Updater h
where
h gen part@(Particle p v pg) lg i = f gen' (Particle p v' pg) lg i
where
(v', gen') = g gen part lg i
{- $buildingUpdaters
The following Updaters are simple building blocks for building more
complex Updaters. Ex. If you have an Updater @u@ and you wish to change
it so that it has a maximum velocity, you can use @upMaxVel <> u@.
-}
{- |
Add to the velocity a random vector between the particle's current
position and the location of the local guide, scaled by the given
@Double@.
-}
upAddLocal :: (PsoVect a, Grade b) => Double -> Updater a b
upAddLocal c = upAddLocalDynamic $ const c
{- |
Add to the velocity a random vector between the particle's current
position and the location of the local guide, scaled by the given
@Integer -> Double@ (fed by the current iteration).
-}
upAddLocalDynamic :: (PsoVect a, Grade b) => (Integer -> Double) -> Updater a b
upAddLocalDynamic c = Updater f
where
f gen (Particle p v _) (PsoGuide lg _) i = (v', gen')
where
v' = pAdd v $ pScale (c i) dl
(dl, gen') = randBetween (pZero, pSubtract lg p) gen
{- |
Add to the velocity a random vector between the particle's current
position and the location of the private guide, scaled by the given
@Double@.
-}
upAddPrivate :: (PsoVect a, Grade b) => Double -> Updater a b
upAddPrivate c = upAddPrivateDynamic $ const c
{- |
Add to the velocity a random vector between the particle's current
position and the location of the private guide, scaled by the given
@Integer -> Double@ (fed by the current iteration).
-}
upAddPrivateDynamic :: (PsoVect a, Grade b) => (Integer -> Double) -> Updater a b
upAddPrivateDynamic c = Updater f
where
f gen (Particle p v (PsoGuide pg _)) _ i = (v', gen')
where
v' = pAdd v $ pScale (c i) dp
(dp, gen') = randBetween (pZero, pSubtract pg p) gen
{- |
Scale the velocity by the given @Double@.
-}
upScale :: (PsoVect a, Grade b) => Double -> Updater a b
upScale c = upScaleDynamic $ const c
{- |
Scale the velocity by the given @Integer -> Double@ (fed by the current
iteration).
-}
upScaleDynamic :: (PsoVect a, Grade b) => (Integer -> Double) -> Updater a b
upScaleDynamic c = Updater f
where
f gen (Particle _ v _) _ i = (pScale (c i) v, gen)
{- |
Cap the velocity at the magnitude of the given @a@.
-}
upVMax :: (PsoSized a, Grade b) => Double -> Updater a b
upVMax max = upVMaxDynamic $ const max
{- |
Cap the velocity at the magnitude of the given @Integer -> a@ (fed by
the current iteration).
-}
upVMaxDynamic :: (PsoSized a, Grade b) => (Integer -> Double) -> Updater a b
upVMaxDynamic max = Updater f
where
f gen (Particle _ v _) _ i = case compare (pSqMag v) ((max i)^2) of
GT -> (pScale (max i) (unitV v), gen)
_ -> (v, gen)
unitV v = pScale ((/) 1 . sqrt . pSqMag $ v) v
{- $updaters
These updaters are some of the updaters that I could find in papers on
PSO. In particular, the @'upStandard'@ updater is recent and performs
well in a myriad of situations.
-}
{- |
Create an @'Updater'@ using the so-called /standard PSO/ parameters,
given in
Bratton, Daniel, and James Kennedy. \"Defining a standard for particle
swarm optimization.\" Swarm Intelligence Symposium, 2007. SIS 2007. IEEE.
IEEE, 2007.
If in doubt, the paper suggests that the constriction parameter be given
by the formula chi = 2 / abs(2 - phi - sqrt(phi^2 - 4 * phi)) where phi
= c1 + c2 and phi > 4.
-}
upStandard :: (PsoVect a, Grade b)
=> Double -- ^ Constriction parameter (chi)
-> Double -- ^ Tendancy toward private guide (c1)
-> Double -- ^ Tendancy toward local guide (c2)
-> Updater a b
upStandard chi c1 c2 = (upScale chi) <> (upAddLocal c2) <> (upAddPrivate c1)
{- |
The updater with parameters suggested as a starting point in
Bratton, Daniel, and James Kennedy. \"Defining a standard for particle
swarm optimization.\" Swarm Intelligence Symposium, 2007. SIS 2007. IEEE.
IEEE, 2007.
That is, the standard updater with constriction parameter 0.72984 and
both other constants 2.05.
Normally, one should search for better parameters, since parameter
choice dramatically influences algorithm performance.
-}
upDefault :: (PsoVect a, Grade b) => Updater a b
upDefault = upStandard 0.72984 2.05 2.05
{- |
The original updater function, defined in
Kennedy, James, and Russell Eberhart. \"Particle swarm optimization.\"
Neural Networks, 1995. Proceedings., IEEE International Conference on.
Vol. 4. IEEE, 1995.
This is (in the words of James Kennedy) obsolete now. However, it is still convenient for e.g. testing new versions of updaters. Plus, it's historical.
-}
upOriginal ::(PsoVect a, Grade b)
=> Double -- ^ Tendancy toward private guide (c1)
-> Double -- ^ Tendancy toward local guide (c2)
-> Updater a b
upOriginal c1 c2 = (upAddLocal c2) <> (upAddPrivate c1)
{- |
An updater using a constant inertia weight factor, as can be found in
Shi, Yuhui, and Russell Eberhart. \"Parameter selection in particle swarm
optimization.\" Evolutionary Programming VII. Springer Berlin/Heidelberg,
1998.
-}
upInertiaWeight :: (PsoVect a, Grade b)
=> Double -- ^ Inertia weight (omega)
-> Double -- ^ Tendancy toward private guide (c1)
-> Double -- ^ Tendancy toward local guide (c2)
-> Updater a b
upInertiaWeight omega c1 c2 = (upAddLocal c2) <> (upAddPrivate c1) <> (upScale omega)
{- |
An updater using a dynamic inertia weight factor, as can be found in
Shi, Yuhui, and Russell Eberhart. \"Parameter selection in particle swarm
optimization.\" Evolutionary Programming VII. Springer Berlin/Heidelberg,
1998.
-}
upInertiaWeightDynamic :: (PsoVect a, Grade b)
=> (Integer -> Double) -- ^ Inertia weight (omega)
-> Double -- ^ Tendancy toward private guide (c1)
-> Double -- ^ Tendancy toward local guide (c2)
-> Updater a b
upInertiaWeightDynamic omega c1 c2 = (upAddLocal c2) <> (upAddPrivate c1) <> (upScaleDynamic omega)
{- |
A @Swarm@ keeps track of all the particles in the swarm, the function
that the swarm seeks to minimize, the updater, the current iteration
(for dynamic updaters), and the best location/value found so far
In use, the type @a@ should belong to the @'PsoVect'@ class and the type
@b@ should belong to the @'Grade'@ class.
-}
data Swarm a b = Swarm {
parts :: [Particle a b], -- ^ Particles in the swarm
gGuide :: PsoGuide a b, -- ^ Global guide
func :: a -> b, -- ^ Function to minimize
updater :: Updater a b, -- ^ Updater
iteration :: Integer -- ^ Current iteration
}
instance (Show a, Show b) => Show (Swarm a b)
where
show (Swarm ps b _ _ _) = show ( map pGuide ps) ++ show b
{-
If you don't care about such things as the number of particles or the
particular Updater used, use this function to get a decent attempt at a
good swarm.
For reference, the swarm it creates has 50 particles and uses the
@'upDefault'@ updater.
-}
defaultSwarm :: (PsoVect a, Grade b)
=> (a -> b) -- ^ Function to optimize
-> (a, a) -- ^ Bounds to begin search
-> StdGen -- ^ Random generator
-> (Swarm a b, StdGen)
defaultSwarm f bounds gen = randomSwarm gen 50 bounds f upDefault
{- |
Create a swarm by randomly generating n points within the bounds, making
all the particles start at these points with velocity zero.
-}
randomSwarm :: (PsoVect a, Grade b)
=> StdGen -- ^ A random seed
-> Int -- ^ Number of particles
-> (a,a) -- ^ Bounds to create particles in
-> (a -> b) -- ^ Function to minimize
-> Updater a b -- ^ Updater
-> (Swarm a b, StdGen) -- ^ (Swarm returned, new seed)
randomSwarm g n bounds f up = (createSwarm ps f up, g')
where
(ps, g') = getSomeRands n g []
getSomeRands 0 gen acc = (acc,gen)
getSomeRands m gen acc = getSomeRands (m-1) gen' (next:acc)
where
(next, gen') = randBetween bounds gen
{- |
Create a swarm in initial state based on the positions of the particles.
Initial velocities are all zero.
-}
createSwarm :: (PsoVect a, Grade b)
=> [a] -- ^ Positions of of particles
-> (a -> b) -- ^ Function to minimize
-> Updater a b -- ^ Updater to use
-> Swarm a b
createSwarm ps f up = Swarm qs b f up 0
where
qs = map (createParticle f) ps
b = bestGuide $ map (pGuide) qs
createParticle f' p = Particle p pZero (PsoGuide p (f' p))
{- |
Update the swarm one step, updating every particle's position and
velocity, and the best values found so far. Returns the updated swarm as
well as a new generator to use.
Arguments ordered to allow @iterate (uncurry updateSwarm)@
-}
updateSwarm :: (PsoVect a, Grade b) => Swarm a b -> StdGen -> (Swarm a b, StdGen)
updateSwarm s@(Swarm ps b f up i) g = (Swarm qs b' f up (i+1), g')
where
(qs, g', b') = foldl' helper ([], g, b) ps
helper (acc, gen, best) p = (p':acc, gen', minBest)
where
(p',gen') = updateParticle p s gen
minBest = case (val best) `betterThan` (val $ pGuide p') of
True -> best
_ -> pGuide p'
{- |
Update a swarm repeatedly. Absorbs a @StdGen@.
If you have a large swarm, this fills up your space quickly, and often
unnecessarily, since you don't really want to keep all of this data
around. For example - if you are searching with 50 particles in 50
dimensional space, 1000 iterations will end up storing over 1000 * 50 *
50 * 3 = 7500000 doubles.
In such a case, you may be better off using iterateWhile, which doesn't
keep track of old swarms, and doesn't consume additional stack space (I
think).
-}
iterateSwarm :: (PsoVect a, Grade b) => Swarm a b -> StdGen -> [Swarm a b]
iterateSwarm s g = iterate' (s, g)
where
-- Trying to force strict evaluation
iterate' (s@(Swarm _ b _ _ _), g) = b `seq` s : iterate' (updateSwarm s g)
{- |
Continue iterating and searching until the condition is met. It
continues until the condition evaluates to @True@, then returns the
first @Swarm@ that evaluates to @False@. Absorbs a @StdGen@.
Typical uses:
Iterate until variance of particles is below 0.001:
iterateWhile ((> 0.001) . posVariance) s gen
Iterate until the grade of at least @good@ is reached:
iterateWhile ((`worseThan` good) . val . gGuide) s gen
Iterate @n@ times:
iterateWhile ((<n) . iteration) s gen
-}
iterateWhile :: (PsoVect a, Grade b)
=> (Swarm a b -> Bool) -- ^ Condition to meet
-> Swarm a b -- ^ Swarm to update
-> StdGen -- ^ Random seed
-> Swarm a b
iterateWhile f s gen = if f s
then iterateWhile f s' gen'
else s
where
(s', gen') = updateSwarm s gen
{- |
If you don't want to think about all of this stuff, don't worry. Just
use this function to get a nice, easy optimization for a give function -
none of this nonsense about creating swarms or what-not.
It returns a @PsoGuide@, which contains both the optimal value and the
point at which that optimal value is achieved.
For reference, the swarm it uses is just created by @'defaultSwarm'@.
-}
easyOptimize :: (PsoVect a, Grade b)
=> (a -> b) -- ^ Function to optimize
-> (a, a) -- ^ Bounds to create particles within
-> Integer -- ^ Number of iterations
-> StdGen -- ^ Generator to use
-> PsoGuide a b
easyOptimize f bounds n gen = gGuide $
iterateWhile ((<n) . iteration) swarm gen'
where
(swarm, gen') = defaultSwarm f bounds gen
{- |
Update a particle one step. Called by updateSwarm and requires the swarm
that the particle belongs to as a parameter
-}
updateParticle :: (PsoVect a, Grade b) => Particle a b -> Swarm a b -> StdGen -> (Particle a b, StdGen)
updateParticle part@(Particle p v pg) (Swarm ps lg f up i) g = (Particle p' v' pg', g')
where
p' = pAdd p v'
(v',g') = (newVel up) g part lg i
pg' = case (val pg) `betterThan` (f p') of
False -> PsoGuide p' (f p')
_ -> pg
-- ===============
-- Analysis
-- ===============
{- |
Find the center of the swarm.
-}
center :: (PsoVect a) => Swarm a b -> a
center (Swarm ps _ _ _ _) = avg sumPoints
where
avg = pScale (1 / (fromIntegral $ length ps))
sumPoints = foldr pAdd pZero $ map pos ps
{-
Each point has a personal best, what is the average?
-}
{-
avgScore :: (PsoVect a) => Swarm a -> Double
avgScore (Swarm ps _ f _ _) = avg $ map (val . pGuide) ps
where
avg xs = (sum xs) / (fromIntegral $ length xs)
-}
{- |
Total variance of the distance points are from the center of the swarm.
Measures how close the swarm is to converging, and can be used to
determine if a swarm has converged on a point or not.
-}
posVariance :: (PsoSized a) => Swarm a b -> Double
posVariance s@(Swarm ps _ _ _ _) = sum . map (pSqMag . pSubtract cen . pos) $ ps
where
cen = center s
{-
Total variance of the scores of the private guides. Measures how close
the swarm is to converging upon a score, even if it cannot decide on a
single best location for that score. Good if, say, your problem is
multi-modal.
-}
{-
scoreVariance :: (PsoVect a) => Swarm a -> Double
scoreVariance s@(Swarm ps b f _ _) = sum . map ((^2) . (-) avg . val . pGuide) $ ps
where
avg = avgScore s
-}
|
brianshourd/haskell-Calypso
|
Calypso/Core.hs
|
bsd-3-clause
| 24,330 | 0 | 13 | 5,573 | 3,637 | 1,972 | 1,665 | 219 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-|
Muster is a library that provides composable regular expressions implemented
using derivatives.
= References
* Janusz A. Brzozowski (1964). Derivatives of Regular Expressions
* Scott Owens, John Reppy, Aaron Turon (2009). Regular-expression derivatives reexamined
-}
module Muster (
Regex(Symbol),
fromString,
fromText,
(<.>),
(<|>),
(<&>),
many,
many1,
not,
derivative,
match
) where
import Prelude hiding (not)
import qualified Data.Bool as B
import Data.Text (Text)
import qualified Data.Text as T
import Muster.Internal.Regex
isNullable :: Regex -> Bool
isNullable None = False
isNullable Epsilon = True
isNullable (Symbol _) = False
isNullable (Concatenation l r) = isNullable l && isNullable r
isNullable (KleeneStar _) = True
isNullable (Or l r) = isNullable l || isNullable r
isNullable (And l r) = isNullable l && isNullable r
isNullable (Not o) = B.not $ isNullable o
-- | Produces an expression that matches all suffixes of the strings described
-- by the regular expression that start with the given character.
derivative :: Char -> Regex -> Regex
derivative _ None = None
derivative _ Epsilon = None
derivative x (Symbol y) = if x == y then Epsilon else None
derivative x (Concatenation l r)
| isNullable l = (derivative x l <.> r) <|> derivative x r
| otherwise = derivative x l <.> r
derivative x (KleeneStar o) = derivative x o <.> many o
derivative x (Or l r) = derivative x l <|> derivative x r
derivative x (And l r) = derivative x l <&> derivative x r
derivative x (Not o) = not (derivative x o)
-- | Tests whether the regular expression matches the string.
match :: Regex -> Text -> Bool
match r text = case T.uncons text of
Just (x, xs) -> match (derivative x r) xs
Nothing -> isNullable r
|
DasIch/haskell-muster
|
src/Muster.hs
|
bsd-3-clause
| 1,826 | 0 | 10 | 375 | 564 | 294 | 270 | 45 | 2 |
---------------------------------------------------------------------------------
-- |
-- Module : Data.SBV
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- (The sbv library is hosted at <http://github.com/LeventErkok/sbv>.
-- Comments, bug reports, and patches are always welcome.)
--
-- SBV: SMT Based Verification
--
-- Express properties about Haskell programs and automatically prove
-- them using SMT solvers.
--
-- >>> prove $ \x -> x `shiftL` 2 .== 4 * (x :: SWord8)
-- Q.E.D.
--
-- >>> prove $ forAll ["x"] $ \x -> x `shiftL` 2 .== (x :: SWord8)
-- Falsifiable. Counter-example:
-- x = 51 :: SWord8
--
-- The function 'prove' has the following type:
--
-- @
-- 'prove' :: 'Provable' a => a -> 'IO' 'ThmResult'
-- @
--
-- The class 'Provable' comes with instances for n-ary predicates, for arbitrary n.
-- The predicates are just regular Haskell functions over symbolic signed and unsigned
-- bit-vectors. Functions for checking satisfiability ('sat' and 'allSat') are also
-- provided.
--
-- In particular, the sbv library introduces the types:
--
-- * 'SBool': Symbolic Booleans (bits).
--
-- * 'SWord8', 'SWord16', 'SWord32', 'SWord64': Symbolic Words (unsigned).
--
-- * 'SInt8', 'SInt16', 'SInt32', 'SInt64': Symbolic Ints (signed).
--
-- * 'SInteger': Unbounded signed integers.
--
-- * 'SReal': Algebraic-real numbers
--
-- * 'SFloat': IEEE-754 single-precision floating point values
--
-- * 'SDouble': IEEE-754 double-precision floating point values
--
-- * 'SArray', 'SFunArray': Flat arrays of symbolic values.
--
-- * Symbolic polynomials over GF(2^n), polynomial arithmetic, and CRCs.
--
-- * Uninterpreted constants and functions over symbolic values, with user
-- defined SMT-Lib axioms.
--
-- * Uninterpreted sorts, and proofs over such sorts, potentially with axioms.
--
-- The user can construct ordinary Haskell programs using these types, which behave
-- very similar to their concrete counterparts. In particular these types belong to the
-- standard classes 'Num', 'Bits', custom versions of 'Eq' ('EqSymbolic')
-- and 'Ord' ('OrdSymbolic'), along with several other custom classes for simplifying
-- programming with symbolic values. The framework takes full advantage of Haskell's type
-- inference to avoid many common mistakes.
--
-- Furthermore, predicates (i.e., functions that return 'SBool') built out of
-- these types can also be:
--
-- * proven correct via an external SMT solver (the 'prove' function)
--
-- * checked for satisfiability (the 'sat', 'allSat' functions)
--
-- * used in synthesis (the `sat` function with existentials)
--
-- * quick-checked
--
-- If a predicate is not valid, 'prove' will return a counterexample: An
-- assignment to inputs such that the predicate fails. The 'sat' function will
-- return a satisfying assignment, if there is one. The 'allSat' function returns
-- all satisfying assignments, lazily.
--
-- The sbv library uses third-party SMT solvers via the standard SMT-Lib interface:
-- <http://goedel.cs.uiowa.edu/smtlib/>.
--
-- The SBV library is designed to work with any SMT-Lib compliant SMT-solver.
-- Currently, we support the following SMT-Solvers out-of-the box:
--
-- * Z3 from Microsoft: <http://research.microsoft.com/en-us/um/redmond/projects/z3/>
--
-- * Yices from SRI: <http://yices.csl.sri.com/>
--
-- * CVC4 from New York University and University of Iowa: <http://cvc4.cs.nyu.edu/>
--
-- * Boolector from Johannes Kepler University: <http://fmv.jku.at/boolector/>
--
-- * MathSAT from Fondazione Bruno Kessler and DISI-University of Trento: <http://mathsat.fbk.eu/>
--
-- SBV also allows calling these solvers in parallel, either getting results from multiple solvers
-- or returning the fastest one. (See 'proveWithAll', 'proveWithAny', etc.)
--
-- Support for other compliant solvers can be added relatively easily, please
-- get in touch if there is a solver you'd like to see included.
---------------------------------------------------------------------------------
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
module Data.SBV (
-- * Programming with symbolic values
-- $progIntro
-- ** Symbolic types
-- *** Symbolic bit
SBool
-- *** Unsigned symbolic bit-vectors
, SWord8, SWord16, SWord32, SWord64
-- *** Signed symbolic bit-vectors
, SInt8, SInt16, SInt32, SInt64
-- *** Signed unbounded integers
-- $unboundedLimitations
, SInteger
-- *** IEEE-floating point numbers
-- $floatingPoints
, SFloat, SDouble, RoundingMode(..), nan, infinity, sNaN, sInfinity, fusedMA, isSNaN, isFPPoint
-- *** Signed algebraic reals
-- $algReals
, SReal, AlgReal, toSReal
-- ** Creating a symbolic variable
-- $createSym
, sBool, sWord8, sWord16, sWord32, sWord64, sInt8, sInt16, sInt32, sInt64, sInteger, sReal, sFloat, sDouble
-- ** Creating a list of symbolic variables
-- $createSyms
, sBools, sWord8s, sWord16s, sWord32s, sWord64s, sInt8s, sInt16s, sInt32s, sInt64s, sIntegers, sReals, sFloats, sDoubles
-- *** Abstract SBV type
, SBV
-- *** Arrays of symbolic values
, SymArray(..), SArray, SFunArray, mkSFunArray
-- *** Full binary trees
, STree, readSTree, writeSTree, mkSTree
-- ** Operations on symbolic values
-- *** Word level
, sbvTestBit, sbvPopCount, sbvShiftLeft, sbvShiftRight, sbvSignedShiftArithRight, setBitTo, oneIf, lsb, msb
, sbvRotateLeft, sbvRotateRight
-- *** Predicates
, allEqual, allDifferent, inRange, sElem
-- *** Addition and Multiplication with high-bits
, fullAdder, fullMultiplier
-- *** Blasting/Unblasting
, blastBE, blastLE, FromBits(..)
-- *** Splitting, joining, and extending
, Splittable(..)
-- *** Sign-casting
, SignCast(..)
-- ** Polynomial arithmetic and CRCs
, Polynomial(..), crcBV, crc
-- ** Conditionals: Mergeable values
, Mergeable(..), ite, iteLazy, sBranch
-- ** Symbolic equality
, EqSymbolic(..)
-- ** Symbolic ordering
, OrdSymbolic(..)
-- ** Symbolic integral numbers
, SIntegral
-- ** Division
, SDivisible(..)
-- ** The Boolean class
, Boolean(..)
-- *** Generalizations of boolean operations
, bAnd, bOr, bAny, bAll
-- ** Pretty-printing and reading numbers in Hex & Binary
, PrettyNum(..), readBin
-- * Uninterpreted sorts, constants, and functions
-- $uninterpreted
, Uninterpreted(..), addAxiom
-- * Properties, proofs, and satisfiability
-- $proveIntro
-- ** Predicates
, Predicate, Provable(..), Equality(..)
-- ** Proving properties
, prove, proveWith, isTheorem, isTheoremWith
-- ** Checking satisfiability
, sat, satWith, isSatisfiable, isSatisfiableWith
-- ** Finding all satisfying assignments
, allSat, allSatWith
-- ** Satisfying a sequence of boolean conditions
, solve
-- ** Adding constraints
-- $constrainIntro
, constrain, pConstrain
-- ** Checking constraint vacuity
, isVacuous, isVacuousWith
-- * Proving properties using multiple solvers
-- $multiIntro
, proveWithAll, proveWithAny, satWithAll, satWithAny, allSatWithAll, allSatWithAny
-- * Optimization
-- $optimizeIntro
, minimize, maximize, optimize
, minimizeWith, maximizeWith, optimizeWith
-- * Computing expected values
, expectedValue, expectedValueWith
-- * Model extraction
-- $modelExtraction
-- ** Inspecting proof results
-- $resultTypes
, ThmResult(..), SatResult(..), AllSatResult(..), SMTResult(..)
-- ** Programmable model extraction
-- $programmableExtraction
, SatModel(..), Modelable(..), displayModels, extractModels
, getModelDictionaries, getModelValues, getModelUninterpretedValues
-- * SMT Interface: Configurations and solvers
, SMTConfig(..), SMTLibLogic(..), Logic(..), OptimizeOpts(..), Solver(..), SMTSolver(..), boolector, cvc4, yices, z3, mathSAT, defaultSolverConfig, sbvCurrentSolver, defaultSMTCfg, sbvCheckSolverInstallation, sbvAvailableSolvers
-- * Symbolic computations
, Symbolic, output, SymWord(..)
-- * Getting SMT-Lib output (for offline analysis)
, compileToSMTLib, generateSMTBenchmarks
-- * Test case generation
, genTest, getTestValues, TestVectors, TestStyle(..), renderTest, CW(..), HasKind(..), Kind(..), cwToBool
-- * Code generation from symbolic programs
-- $cCodeGeneration
, SBVCodeGen
-- ** Setting code-generation options
, cgPerformRTCs, cgSetDriverValues, cgGenerateDriver, cgGenerateMakefile
-- ** Designating inputs
, cgInput, cgInputArr
-- ** Designating outputs
, cgOutput, cgOutputArr
-- ** Designating return values
, cgReturn, cgReturnArr
-- ** Code generation with uninterpreted functions
, cgAddPrototype, cgAddDecl, cgAddLDFlags
-- ** Code generation with 'SInteger' and 'SReal' types
-- $unboundedCGen
, cgIntegerSize, cgSRealType, CgSRealType(..)
-- ** Compilation to C
, compileToC, compileToCLib
-- * Module exports
-- $moduleExportIntro
, module Data.Bits
, module Data.Word
, module Data.Int
, module Data.Ratio
) where
import Control.Monad (filterM)
import Control.Concurrent.Async (async, waitAny, waitAnyCancel)
import System.IO.Unsafe (unsafeInterleaveIO) -- only used safely!
import Data.SBV.BitVectors.AlgReals
import Data.SBV.BitVectors.Data
import Data.SBV.BitVectors.Model
import Data.SBV.BitVectors.PrettyNum
import Data.SBV.BitVectors.SignCast
import Data.SBV.BitVectors.Splittable
import Data.SBV.BitVectors.STree
import Data.SBV.Compilers.C
import Data.SBV.Compilers.CodeGen
import Data.SBV.Provers.Prover
import Data.SBV.Tools.GenTest
import Data.SBV.Tools.ExpectedValue
import Data.SBV.Tools.Optimize
import Data.SBV.Tools.Polynomial
import Data.SBV.Utils.Boolean
import Data.Bits
import Data.Int
import Data.Ratio
import Data.Word
-- | The currently active solver, obtained by importing "Data.SBV".
-- To have other solvers /current/, import one of the bridge
-- modules "Data.SBV.Bridge.CVC4", "Data.SBV.Bridge.Yices", or
-- "Data.SBV.Bridge.Z3" directly.
sbvCurrentSolver :: SMTConfig
sbvCurrentSolver = z3
-- | Note that the floating point value NaN does not compare equal to itself,
-- so we need a special recognizer for that. Haskell provides the isNaN predicate
-- with the `RealFrac` class, which unfortunately is not currently implementable for
-- symbolic cases. (Requires trigonometric functions etc.) Thus, we provide this
-- recognizer separately. Note that the definition simply tests equality against
-- itself, which fails for NaN. Who said equality for floating point was reflexive?
isSNaN :: (Floating a, SymWord a) => SBV a -> SBool
isSNaN x = x ./= x
-- | We call a FP number FPPoint if it is neither NaN, nor +/- infinity.
isFPPoint :: (Floating a, SymWord a) => SBV a -> SBool
isFPPoint x = x .== x -- gets rid of NaN's
&&& x .< sInfinity -- gets rid of +inf
&&& x .> -sInfinity -- gets rid of -inf
-- | Form the symbolic conjunction of a given list of boolean conditions. Useful in expressing
-- problems with constraints, like the following:
--
-- @
-- do [x, y, z] <- sIntegers [\"x\", \"y\", \"z\"]
-- solve [x .> 5, y + z .< x]
-- @
solve :: [SBool] -> Symbolic SBool
solve = return . bAnd
-- | Check whether the given solver is installed and is ready to go. This call does a
-- simple call to the solver to ensure all is well.
sbvCheckSolverInstallation :: SMTConfig -> IO Bool
sbvCheckSolverInstallation cfg = do ThmResult r <- proveWith cfg $ \x -> (x+x) .== ((x*2) :: SWord8)
case r of
Unsatisfiable _ -> return True
_ -> return False
-- | The default configs corresponding to supported SMT solvers
defaultSolverConfig :: Solver -> SMTConfig
defaultSolverConfig Z3 = z3
defaultSolverConfig Yices = yices
defaultSolverConfig Boolector = boolector
defaultSolverConfig CVC4 = cvc4
defaultSolverConfig MathSAT = mathSAT
-- | Return the known available solver configs, installed on your machine.
sbvAvailableSolvers :: IO [SMTConfig]
sbvAvailableSolvers = filterM sbvCheckSolverInstallation (map defaultSolverConfig [minBound .. maxBound])
sbvWithAny :: Provable a => [SMTConfig] -> (SMTConfig -> a -> IO b) -> a -> IO (Solver, b)
sbvWithAny [] _ _ = error "SBV.withAny: No solvers given!"
sbvWithAny solvers what a = snd `fmap` (mapM try solvers >>= waitAnyCancel)
where try s = async $ what s a >>= \r -> return (name (solver s), r)
sbvWithAll :: Provable a => [SMTConfig] -> (SMTConfig -> a -> IO b) -> a -> IO [(Solver, b)]
sbvWithAll solvers what a = mapM try solvers >>= (unsafeInterleaveIO . go)
where try s = async $ what s a >>= \r -> return (name (solver s), r)
go [] = return []
go as = do (d, r) <- waitAny as
rs <- unsafeInterleaveIO $ go (filter (/= d) as)
return (r : rs)
-- | Prove a property with multiple solvers, running them in separate threads. The
-- results will be returned in the order produced.
proveWithAll :: Provable a => [SMTConfig] -> a -> IO [(Solver, ThmResult)]
proveWithAll = (`sbvWithAll` proveWith)
-- | Prove a property with multiple solvers, running them in separate threads. Only
-- the result of the first one to finish will be returned, remaining threads will be killed.
proveWithAny :: Provable a => [SMTConfig] -> a -> IO (Solver, ThmResult)
proveWithAny = (`sbvWithAny` proveWith)
-- | Find a satisfying assignment to a property with multiple solvers, running them in separate threads. The
-- results will be returned in the order produced.
satWithAll :: Provable a => [SMTConfig] -> a -> IO [(Solver, SatResult)]
satWithAll = (`sbvWithAll` satWith)
-- | Find a satisfying assignment to a property with multiple solvers, running them in separate threads. Only
-- the result of the first one to finish will be returned, remaining threads will be killed.
satWithAny :: Provable a => [SMTConfig] -> a -> IO (Solver, SatResult)
satWithAny = (`sbvWithAny` satWith)
-- | Find all satisfying assignments to a property with multiple solvers, running them in separate threads. Only
-- the result of the first one to finish will be returned, remaining threads will be killed.
allSatWithAll :: Provable a => [SMTConfig] -> a -> IO [(Solver, AllSatResult)]
allSatWithAll = (`sbvWithAll` allSatWith)
-- | Find all satisfying assignments to a property with multiple solvers, running them in separate threads. Only
-- the result of the first one to finish will be returned, remaining threads will be killed.
allSatWithAny :: Provable a => [SMTConfig] -> a -> IO (Solver, AllSatResult)
allSatWithAny = (`sbvWithAny` allSatWith)
-- | Equality as a proof method. Allows for
-- very concise construction of equivalence proofs, which is very typical in
-- bit-precise proofs.
infix 4 ===
class Equality a where
(===) :: a -> a -> IO ThmResult
instance (SymWord a, EqSymbolic z) => Equality (SBV a -> z) where
k === l = prove $ \a -> k a .== l a
instance (SymWord a, SymWord b, EqSymbolic z) => Equality (SBV a -> SBV b -> z) where
k === l = prove $ \a b -> k a b .== l a b
instance (SymWord a, SymWord b, EqSymbolic z) => Equality ((SBV a, SBV b) -> z) where
k === l = prove $ \a b -> k (a, b) .== l (a, b)
instance (SymWord a, SymWord b, SymWord c, EqSymbolic z) => Equality (SBV a -> SBV b -> SBV c -> z) where
k === l = prove $ \a b c -> k a b c .== l a b c
instance (SymWord a, SymWord b, SymWord c, EqSymbolic z) => Equality ((SBV a, SBV b, SBV c) -> z) where
k === l = prove $ \a b c -> k (a, b, c) .== l (a, b, c)
instance (SymWord a, SymWord b, SymWord c, SymWord d, EqSymbolic z) => Equality (SBV a -> SBV b -> SBV c -> SBV d -> z) where
k === l = prove $ \a b c d -> k a b c d .== l a b c d
instance (SymWord a, SymWord b, SymWord c, SymWord d, EqSymbolic z) => Equality ((SBV a, SBV b, SBV c, SBV d) -> z) where
k === l = prove $ \a b c d -> k (a, b, c, d) .== l (a, b, c, d)
instance (SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, EqSymbolic z) => Equality (SBV a -> SBV b -> SBV c -> SBV d -> SBV e -> z) where
k === l = prove $ \a b c d e -> k a b c d e .== l a b c d e
instance (SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, EqSymbolic z) => Equality ((SBV a, SBV b, SBV c, SBV d, SBV e) -> z) where
k === l = prove $ \a b c d e -> k (a, b, c, d, e) .== l (a, b, c, d, e)
instance (SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, SymWord f, EqSymbolic z) => Equality (SBV a -> SBV b -> SBV c -> SBV d -> SBV e -> SBV f -> z) where
k === l = prove $ \a b c d e f -> k a b c d e f .== l a b c d e f
instance (SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, SymWord f, EqSymbolic z) => Equality ((SBV a, SBV b, SBV c, SBV d, SBV e, SBV f) -> z) where
k === l = prove $ \a b c d e f -> k (a, b, c, d, e, f) .== l (a, b, c, d, e, f)
instance (SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, SymWord f, SymWord g, EqSymbolic z) => Equality (SBV a -> SBV b -> SBV c -> SBV d -> SBV e -> SBV f -> SBV g -> z) where
k === l = prove $ \a b c d e f g -> k a b c d e f g .== l a b c d e f g
instance (SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, SymWord f, SymWord g, EqSymbolic z) => Equality ((SBV a, SBV b, SBV c, SBV d, SBV e, SBV f, SBV g) -> z) where
k === l = prove $ \a b c d e f g -> k (a, b, c, d, e, f, g) .== l (a, b, c, d, e, f, g)
-- Haddock section documentation
{- $progIntro
The SBV library is really two things:
* A framework for writing symbolic programs in Haskell, i.e., programs operating on
symbolic values along with the usual concrete counterparts.
* A framework for proving properties of such programs using SMT solvers.
The programming goal of SBV is to provide a /seamless/ experience, i.e., let people program
in the usual Haskell style without distractions of symbolic coding. While Haskell helps
in some aspects (the 'Num' and 'Bits' classes simplify coding), it makes life harder
in others. For instance, @if-then-else@ only takes 'Bool' as a test in Haskell, and
comparisons ('>' etc.) only return 'Bool's. Clearly we would like these values to be
symbolic (i.e., 'SBool'), thus stopping us from using some native Haskell constructs.
When symbolic versions of operators are needed, they are typically obtained by prepending a dot,
for instance '==' becomes '.=='. Care has been taken to make the transition painless. In
particular, any Haskell program you build out of symbolic components is fully concretely
executable within Haskell, without the need for any custom interpreters. (They are truly
Haskell programs, not AST's built out of pieces of syntax.) This provides for an integrated
feel of the system, one of the original design goals for SBV.
-}
{- $proveIntro
The SBV library provides a "push-button" verification system via automated SMT solving. The
design goal is to let SMT solvers be used without any knowledge of how SMT solvers work
or how different logics operate. The details are hidden behind the SBV framework, providing
Haskell programmers with a clean API that is unencumbered by the details of individual solvers.
To that end, we use the SMT-Lib standard (<http://goedel.cs.uiowa.edu/smtlib/>)
to communicate with arbitrary SMT solvers.
-}
{- $multiIntro
On a multi-core machine, it might be desirable to try a given property using multiple SMT solvers,
using parallel threads. Even with machines with single-cores, threading can be helpful if you
want to try out multiple-solvers but do not know which one would work the best
for the problem at hand ahead of time.
The functions in this section allow proving/satisfiability-checking with multiple
backends at the same time. Each function comes in two variants, one that
returns the results from all solvers, the other that returns the fastest one.
The @All@ variants, (i.e., 'proveWithAll', 'satWithAll', 'allSatWithAll') run all solvers and
return all the results. SBV internally makes sure that the result is lazily generated; so,
the order of solvers given does not matter. In other words, the order of results will follow
the order of the solvers as they finish, not as given by the user. These variants are useful when you
want to make sure multiple-solvers agree (or disagree!) on a given problem.
The @Any@ variants, (i.e., 'proveWithAny', 'satWithAny', 'allSatWithAny') will run all the solvers
in parallel, and return the results of the first one finishing. The other threads will then be killed. These variants
are useful when you do not care if the solvers produce the same result, but rather want to get the
solution as quickly as possible, taking advantage of modern many-core machines.
Note that the function 'sbvAvailableSolvers' will return all the installed solvers, which can be
used as the first argument to all these functions, if you simply want to try all available solvers on a machine.
-}
{- $optimizeIntro
Symbolic optimization. A call of the form:
@minimize Quantified cost n valid@
returns @Just xs@, such that:
* @xs@ has precisely @n@ elements
* @valid xs@ holds
* @cost xs@ is minimal. That is, for all sequences @ys@ that satisfy the first two criteria above, @cost xs .<= cost ys@ holds.
If there is no such sequence, then 'minimize' will return 'Nothing'.
The function 'maximize' is similar, except the comparator is '.>='. So the value returned has the largest cost (or value, in that case).
The function 'optimize' allows the user to give a custom comparison function.
The 'OptimizeOpts' argument controls how the optimization is done. If 'Quantified' is used, then the SBV optimization engine satisfies the following predicate:
@exists xs. forall ys. valid xs && (valid ys ``implies`` (cost xs ``cmp`` cost ys))@
Note that this may cause efficiency problems as it involves alternating quantifiers.
If 'OptimizeOpts' is set to 'Iterative' 'True', then SBV will programmatically
search for an optimal solution, by repeatedly calling the solver appropriately. (The boolean argument controls whether progress reports are given. Use
'False' for quiet operation.) Note that the quantified and iterative versions are two different optimization approaches and may not necessarily yield the same
results. In particular, the quantified version can find solutions where there is no global optimum value, while the iterative version would simply loop forever
in such cases. On the other hand, the iterative version might be more suitable if the quantified version of the problem is too hard to deal with by the SMT solver.
-}
{- $modelExtraction
The default 'Show' instances for prover calls provide all the counter-example information in a
human-readable form and should be sufficient for most casual uses of sbv. However, tools built
on top of sbv will inevitably need to look into the constructed models more deeply, programmatically
extracting their results and performing actions based on them. The API provided in this section
aims at simplifying this task.
-}
{- $resultTypes
'ThmResult', 'SatResult', and 'AllSatResult' are simple newtype wrappers over 'SMTResult'. Their
main purpose is so that we can provide custom 'Show' instances to print results accordingly.
-}
{- $programmableExtraction
While default 'Show' instances are sufficient for most use cases, it is sometimes desirable (especially
for library construction) that the SMT-models are reinterpreted in terms of domain types. Programmable
extraction allows getting arbitrarily typed models out of SMT models.
-}
{- $cCodeGeneration
The SBV library can generate straight-line executable code in C. (While other target languages are
certainly possible, currently only C is supported.) The generated code will perform no run-time memory-allocations,
(no calls to @malloc@), so its memory usage can be predicted ahead of time. Also, the functions will execute precisely the
same instructions in all calls, so they have predictable timing properties as well. The generated code
has no loops or jumps, and is typically quite fast. While the generated code can be large due to complete unrolling,
these characteristics make them suitable for use in hard real-time systems, as well as in traditional computing.
-}
{- $unboundedCGen
The types 'SInteger' and 'SReal' are unbounded quantities that have no direct counterparts in the C language. Therefore,
it is not possible to generate standard C code for SBV programs using these types, unless custom libraries are available. To
overcome this, SBV allows the user to explicitly set what the corresponding types should be for these two cases, using
the functions below. Note that while these mappings will produce valid C code, the resulting code will be subject to
overflow/underflows for 'SInteger', and rounding for 'SReal', so there is an implicit loss of precision.
If the user does /not/ specify these mappings, then SBV will
refuse to compile programs that involve these types.
-}
{- $moduleExportIntro
The SBV library exports the following modules wholesale, as user programs will have to import these
modules to make any sensible use of the SBV functionality.
-}
{- $createSym
These functions simplify declaring symbolic variables of various types. Strictly speaking, they are just synonyms
for 'free' (specialized at the given type), but they might be easier to use.
-}
{- $createSyms
These functions simplify declaring a sequence symbolic variables of various types. Strictly speaking, they are just synonyms
for 'mapM' 'free' (specialized at the given type), but they might be easier to use.
-}
{- $unboundedLimitations
The SBV library supports unbounded signed integers with the type 'SInteger', which are not subject to
overflow/underflow as it is the case with the bounded types, such as 'SWord8', 'SInt16', etc. However,
some bit-vector based operations are /not/ supported for the 'SInteger' type while in the verification mode. That
is, you can use these operations on 'SInteger' values during normal programming/simulation.
but the SMT translation will not support these operations since there corresponding operations are not supported in SMT-Lib.
Note that this should rarely be a problem in practice, as these operations are mostly meaningful on fixed-size
bit-vectors. The operations that are restricted to bounded word/int sizes are:
* Rotations and shifts: 'rotateL', 'rotateR', 'shiftL', 'shiftR'
* Bitwise logical ops: '.&.', '.|.', 'xor', 'complement'
* Extraction and concatenation: 'split', '#', and 'extend' (see the 'Splittable' class)
Usual arithmetic ('+', '-', '*', 'sQuotRem', 'sQuot', 'sRem', 'sDivMod', 'sDiv', 'sMod') and logical operations ('.<', '.<=', '.>', '.>=', '.==', './=') operations are
supported for 'SInteger' fully, both in programming and verification modes.
-}
{- $algReals
Algebraic reals are roots of single-variable polynomials with rational coefficients. (See
<http://en.wikipedia.org/wiki/Algebraic_number>.) Note that algebraic reals are infinite
precision numbers, but they do not cover all /real/ numbers. (In particular, they cannot
represent transcendentals.) Some irrational numbers are algebraic (such as @sqrt 2@), while
others are not (such as pi and e).
SBV can deal with real numbers just fine, since the theory of reals is decidable. (See
<http://goedel.cs.uiowa.edu/smtlib/theories/Reals.smt2>.) In addition, by leveraging backend
solver capabilities, SBV can also represent and solve non-linear equations involving real-variables.
(For instance, the Z3 SMT solver, supports polynomial constraints on reals starting with v4.0.)
-}
{- $floatingPoints
Floating point numbers are defined by the IEEE-754 standard; and correspond to Haskell's
'Float' and 'Double' types. For SMT support with floating-point numbers, see the paper
by Rummer and Wahl: <http://www.philipp.ruemmer.org/publications/smt-fpa.pdf>.
-}
{- $constrainIntro
A constraint is a means for restricting the input domain of a formula. Here's a simple
example:
@
do x <- 'exists' \"x\"
y <- 'exists' \"y\"
'constrain' $ x .> y
'constrain' $ x + y .>= 12
'constrain' $ y .>= 3
...
@
The first constraint requires @x@ to be larger than @y@. The scond one says that
sum of @x@ and @y@ must be at least @12@, and the final one says that @y@ to be at least @3@.
Constraints provide an easy way to assert additional properties on the input domain, right at the point of
the introduction of variables.
Note that the proper reading of a constraint
depends on the context:
* In a 'sat' (or 'allSat') call: The constraint added is asserted
conjunctively. That is, the resulting satisfying model (if any) will
always satisfy all the constraints given.
* In a 'prove' call: In this case, the constraint acts as an implication.
The property is proved under the assumption that the constraint
holds. In other words, the constraint says that we only care about
the input space that satisfies the constraint.
* In a 'quickCheck' call: The constraint acts as a filter for 'quickCheck';
if the constraint does not hold, then the input value is considered to be irrelevant
and is skipped. Note that this is similar to 'prove', but is stronger: We do not
accept a test case to be valid just because the constraints fail on them, although
semantically the implication does hold. We simply skip that test case as a /bad/
test vector.
* In a 'genTest' call: Similar to 'quickCheck' and 'prove': If a constraint
does not hold, the input value is ignored and is not included in the test
set.
A good use case (in fact the motivating use case) for 'constrain' is attaching a
constraint to a 'forall' or 'exists' variable at the time of its creation.
Also, the conjunctive semantics for 'sat' and the implicative
semantics for 'prove' simplify programming by choosing the correct interpretation
automatically. However, one should be aware of the semantic difference. For instance, in
the presence of constraints, formulas that are /provable/ are not necessarily
/satisfiable/. To wit, consider:
@
do x <- 'exists' \"x\"
'constrain' $ x .< x
return $ x .< (x :: 'SWord8')
@
This predicate is unsatisfiable since no element of 'SWord8' is less than itself. But
it's (vacuously) true, since it excludes the entire domain of values, thus making the proof
trivial. Hence, this predicate is provable, but is not satisfiable. To make sure the given
constraints are not vacuous, the functions 'isVacuous' (and 'isVacuousWith') can be used.
Also note that this semantics imply that test case generation ('genTest') and quick-check
can take arbitrarily long in the presence of constraints, if the random input values generated
rarely satisfy the constraints. (As an extreme case, consider @'constrain' 'false'@.)
A probabilistic constraint (see 'pConstrain') attaches a probability threshold for the
constraint to be considered. For instance:
@
'pConstrain' 0.8 c
@
will make sure that the condition @c@ is satisfied 80% of the time (and correspondingly, falsified 20%
of the time), in expectation. This variant is useful for 'genTest' and 'quickCheck' functions, where we
want to filter the test cases according to some probability distribution, to make sure that the test-vectors
are drawn from interesting subsets of the input space. For instance, if we were to generate 100 test cases
with the above constraint, we'd expect about 80 of them to satisfy the condition @c@, while about 20 of them
will fail it.
The following properties hold:
@
'constrain' = 'pConstrain' 1
'pConstrain' t c = 'pConstrain' (1-t) (not c)
@
Note that while 'constrain' can be used freely, 'pConstrain' is only allowed in the contexts of
'genTest' or 'quickCheck'. Calls to 'pConstrain' in a prove/sat call will be rejected as SBV does not
deal with probabilistic constraints when it comes to satisfiability and proofs.
Also, both 'constrain' and 'pConstrain' calls during code-generation will also be rejected, for similar reasons.
-}
{- $uninterpreted
Users can introduce new uninterpreted sorts simply by defining a data-type in Haskell and registering it as such. The
following example demonstrates:
@
data B = B deriving (Eq, Ord, Data, Typeable)
instance SymWord B
instance HasKind B
@
(Note that you'll also need to use the language pragma @DeriveDataTypeable@, and import @Data.Generics@ for the above to work.)
Once GHC implements derivable user classes (<http://hackage.haskell.org/trac/ghc/ticket/5462>), we will be able to simplify this to:
@
data B = B deriving (Eq, Ord, Data, Typeable, SymWord, HasKind)
@
This is all it takes to introduce 'B' as an uninterpreted sort in SBV, which makes the type @SBV B@ automagically become available as the type
of symbolic values that ranges over 'B' values.
Uninterpreted functions over both uninterpreted and regular sorts can be declared using the facilities introduced by
the 'Uninterpreted' class.
-}
{-# ANN module "HLint: ignore Use import/export shortcut" #-}
|
TomMD/cryptol
|
sbv/Data/SBV.hs
|
bsd-3-clause
| 33,155 | 0 | 14 | 6,133 | 3,790 | 2,221 | 1,569 | 159 | 2 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, DeriveFunctor #-}
{-| TT is the core language of Idris. The language has:
* Full dependent types
* A hierarchy of universes, with cumulativity: Type : Type1, Type1 : Type2, ...
* Pattern matching letrec binding
* (primitive types defined externally)
Some technical stuff:
* Typechecker is kept as simple as possible - no unification, just a checker for incomplete terms.
* We have a simple collection of tactics which we use to elaborate source
programs with implicit syntax into fully explicit terms.
-}
module Idris.Core.TT(module Idris.Core.TT, module Idris.Core.TC) where
import Idris.Core.TC
import Control.Monad.State.Strict
import Control.Monad.Trans.Error (Error(..))
import Debug.Trace
import qualified Data.Map.Strict as Map
import Data.Char
import qualified Data.Text as T
import Data.List
import Data.Maybe (listToMaybe)
import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed as V
import qualified Data.Binary as B
import Data.Binary hiding (get, put)
import Foreign.Storable (sizeOf)
import Util.Pretty hiding (Str)
data Option = TTypeInTType
| CheckConv
deriving Eq
-- | Source location. These are typically produced by the parser 'Idris.Parser.getFC'
data FC = FC { fc_fname :: String, -- ^ Filename
fc_line :: Int, -- ^ Line number
fc_column :: Int -- ^ Column number
}
-- | Ignore source location equality (so deriving classes do not compare FCs)
instance Eq FC where
_ == _ = True
-- | FC with equality
newtype FC' = FC' { unwrapFC :: FC }
instance Eq FC' where
FC' fc == FC' fc' = fcEq fc fc'
where fcEq (FC n l c) (FC n' l' c') = n == n' && l == l' && c == c'
-- | Empty source location
emptyFC :: FC
emptyFC = fileFC ""
-- | Source location with file only
fileFC :: String -> FC
fileFC s = FC s 0 0
{-!
deriving instance Binary FC
deriving instance NFData FC
!-}
instance Sized FC where
size (FC f l c) = 1 + length f
instance Show FC where
show (FC f l c) = f ++ ":" ++ show l ++ ":" ++ show c
-- | Output annotation for pretty-printed name - decides colour
data NameOutput = TypeOutput | FunOutput | DataOutput
-- | Output annotations for pretty-printing
data OutputAnnotation = AnnName Name (Maybe NameOutput) (Maybe Type)
| AnnBoundName Name Bool
| AnnConstData
| AnnConstType
| AnnFC FC
-- | Used for error reflection
data ErrorReportPart = TextPart String
| NamePart Name
| TermPart Term
| SubReport [ErrorReportPart]
deriving (Show, Eq)
-- Please remember to keep Err synchronised with
-- Language.Reflection.Errors.Err in the stdlib!
-- | Idris errors. Used as exceptions in the compiler, but reported to users
-- if they reach the top level.
data Err' t
= Msg String
| InternalMsg String
| CantUnify Bool t t (Err' t) [(Name, t)] Int
-- Int is 'score' - how much we did unify
-- Bool indicates recoverability, True indicates more info may make
-- unification succeed
| InfiniteUnify Name t [(Name, t)]
| CantConvert t t [(Name, t)]
| CantSolveGoal t [(Name, t)]
| UnifyScope Name Name t [(Name, t)]
| CantInferType String
| NonFunctionType t t
| NotEquality t t
| TooManyArguments Name
| CantIntroduce t
| NoSuchVariable Name
| NoTypeDecl Name
| NotInjective t t t
| CantResolve t
| CantResolveAlts [String]
| IncompleteTerm t
| UniverseError
| ProgramLineComment
| Inaccessible Name
| NonCollapsiblePostulate Name
| AlreadyDefined Name
| ProofSearchFail (Err' t)
| NoRewriting t
| At FC (Err' t)
| Elaborating String Name (Err' t)
| ProviderError String
| LoadingFailed String (Err' t)
| ReflectionError [[ErrorReportPart]] (Err' t)
| ReflectionFailed String (Err' t)
deriving (Eq, Functor)
type Err = Err' Term
{-!
deriving instance NFData Err
!-}
instance Sized Err where
size (Msg msg) = length msg
size (InternalMsg msg) = length msg
size (CantUnify _ left right err _ score) = size left + size right + size err
size (InfiniteUnify _ right _) = size right
size (CantConvert left right _) = size left + size right
size (UnifyScope _ _ right _) = size right
size (NoSuchVariable name) = size name
size (NoTypeDecl name) = size name
size (NotInjective l c r) = size l + size c + size r
size (CantResolve trm) = size trm
size (NoRewriting trm) = size trm
size (CantResolveAlts _) = 1
size (IncompleteTerm trm) = size trm
size UniverseError = 1
size ProgramLineComment = 1
size (At fc err) = size fc + size err
size (Elaborating _ n err) = size err
size (ProviderError msg) = length msg
size (LoadingFailed fn e) = 1 + length fn + size e
size _ = 1
score :: Err -> Int
score (CantUnify _ _ _ m _ s) = s + score m
score (CantResolve _) = 20
score (NoSuchVariable _) = 1000
score (ProofSearchFail _) = 10000
score (CantSolveGoal _ _) = 10000
score (InternalMsg _) = -1
score _ = 0
instance Show Err where
show (Msg s) = s
show (InternalMsg s) = "Internal error: " ++ show s
show (CantUnify _ l r e sc i) = "CantUnify " ++ show l ++ " " ++ show r ++ " "
++ show e ++ " in " ++ show sc ++ " " ++ show i
show (CantSolveGoal g _) = "CantSolve " ++ show g
show (Inaccessible n) = show n ++ " is not an accessible pattern variable"
show (ProviderError msg) = "Type provider error: " ++ msg
show (LoadingFailed fn e) = "Loading " ++ fn ++ " failed: (TT) " ++ show e
show ProgramLineComment = "Program line next to comment"
show (At f e) = show f ++ ":" ++ show e
show _ = "Error"
instance Pretty Err OutputAnnotation where
pretty (Msg m) = text m
pretty (CantUnify _ l r e _ i) =
if size l + size r > breakingSize then
text "Cannot unify" <+> colon <+>
nest nestingSize (pretty l <+> text "and" <+> pretty r) <+>
nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
else
text "Cannot unify" <+> colon <+> pretty l <+> text "and" <+> pretty r <+>
nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
pretty (ProviderError msg) = text msg
pretty err@(LoadingFailed _ _) = text (show err)
pretty _ = text "Error"
instance Error Err where
strMsg = InternalMsg
type TC = TC' Err
instance (Pretty a OutputAnnotation) => Pretty (TC a) OutputAnnotation where
pretty (OK ok) = pretty ok
pretty (Error err) =
if size err > breakingSize then
text "Error" <+> colon <+> (nest nestingSize $ pretty err)
else
text "Error" <+> colon <+> pretty err
instance Show a => Show (TC a) where
show (OK x) = show x
show (Error str) = "Error: " ++ show str
tfail :: Err -> TC a
tfail e = Error e
failMsg :: String -> TC a
failMsg str = Error (Msg str)
trun :: FC -> TC a -> TC a
trun fc (OK a) = OK a
trun fc (Error e) = Error (At fc e)
discard :: Monad m => m a -> m ()
discard f = f >> return ()
showSep :: String -> [String] -> String
showSep sep [] = ""
showSep sep [x] = x
showSep sep (x:xs) = x ++ sep ++ showSep sep xs
pmap f (x, y) = (f x, f y)
traceWhen True msg a = trace msg a
traceWhen False _ a = a
-- RAW TERMS ----------------------------------------------------------------
-- | Names are hierarchies of strings, describing scope (so no danger of
-- duplicate names, but need to be careful on lookup).
data Name = UN T.Text -- ^ User-provided name
| NS Name [T.Text] -- ^ Root, namespaces
| MN Int T.Text -- ^ Machine chosen names
| NErased -- ^ Name of somethng which is never used in scope
| SN SpecialName -- ^ Decorated function names
| SymRef Int -- ^ Reference to IBC file symbol table (used during serialisation)
deriving (Eq, Ord)
txt :: String -> T.Text
txt = T.pack
str :: T.Text -> String
str = T.unpack
tnull :: T.Text -> Bool
tnull = T.null
thead :: T.Text -> Char
thead = T.head
-- Smart constructors for names, using old String style
sUN :: String -> Name
sUN s = UN (txt s)
sNS :: Name -> [String] -> Name
sNS n ss = NS n (map txt ss)
sMN :: Int -> String -> Name
sMN i s = MN i (txt s)
{-!
deriving instance Binary Name
deriving instance NFData Name
!-}
data SpecialName = WhereN Int Name Name
| InstanceN Name [T.Text]
| ParentN Name T.Text
| MethodN Name
| CaseN Name
| ElimN Name
deriving (Eq, Ord)
{-!
deriving instance Binary SpecialName
deriving instance NFData SpecialName
!-}
sInstanceN :: Name -> [String] -> SpecialName
sInstanceN n ss = InstanceN n (map T.pack ss)
sParentN :: Name -> String -> SpecialName
sParentN n s = ParentN n (T.pack s)
instance Sized Name where
size (UN n) = 1
size (NS n els) = 1 + length els
size (MN i n) = 1
size _ = 1
instance Pretty Name OutputAnnotation where
pretty n@(UN n') = annotate (AnnName n Nothing Nothing) $ text (T.unpack n')
pretty n@(NS un s) = annotate (AnnName n Nothing Nothing) . noAnnotate $ pretty un
pretty n@(MN i s) = annotate (AnnName n Nothing Nothing) $
lbrace <+> text (T.unpack s) <+> (text . show $ i) <+> rbrace
pretty n@(SN s) = annotate (AnnName n Nothing Nothing) $ text (show s)
instance Pretty [Name] OutputAnnotation where
pretty = encloseSep empty empty comma . map pretty
instance Show Name where
show (UN n) = str n
show (NS n s) = showSep "." (map T.unpack (reverse s)) ++ "." ++ show n
show (MN _ u) | u == txt "underscore" = "_"
show (MN i s) = "{" ++ str s ++ show i ++ "}"
show (SN s) = show s
show NErased = "_"
instance Show SpecialName where
show (WhereN i p c) = show p ++ ", " ++ show c
show (InstanceN cl inst) = showSep ", " (map T.unpack inst) ++ " instance of " ++ show cl
show (MethodN m) = "method " ++ show m
show (ParentN p c) = show p ++ "#" ++ T.unpack c
show (CaseN n) = "case block in " ++ show n
show (ElimN n) = "<<" ++ show n ++ " eliminator>>"
-- Show a name in a way decorated for code generation, not human reading
showCG :: Name -> String
showCG (UN n) = T.unpack n
showCG (NS n s) = showSep "." (map T.unpack (reverse s)) ++ "." ++ showCG n
showCG (MN _ u) | u == txt "underscore" = "_"
showCG (MN i s) = "{" ++ T.unpack s ++ show i ++ "}"
showCG (SN s) = showCG' s
where showCG' (WhereN i p c) = showCG p ++ ":" ++ showCG c ++ ":" ++ show i
showCG' (InstanceN cl inst) = '@':showCG cl ++ '$':showSep ":" (map T.unpack inst)
showCG' (MethodN m) = '!':showCG m
showCG' (ParentN p c) = showCG p ++ "#" ++ show c
showCG' (CaseN c) = showCG c ++ "_case"
showCG' (ElimN sn) = showCG sn ++ "_elim"
showCG NErased = "_"
-- |Contexts allow us to map names to things. A root name maps to a collection
-- of things in different namespaces with that name.
type Ctxt a = Map.Map Name (Map.Map Name a)
emptyContext = Map.empty
mapCtxt :: (a -> b) -> Ctxt a -> Ctxt b
mapCtxt = fmap . fmap
-- |Return True if the argument 'Name' should be interpreted as the name of a
-- typeclass.
tcname (UN xs) | T.null xs = False
| otherwise = T.head xs == '@'
tcname (NS n _) = tcname n
tcname (SN (InstanceN _ _)) = True
tcname (SN (MethodN _)) = True
tcname (SN (ParentN _ _)) = True
tcname _ = False
implicitable (NS n _) = implicitable n
implicitable (UN xs) | T.null xs = False
| otherwise = isLower (T.head xs)
implicitable (MN _ _) = True
implicitable _ = False
nsroot (NS n _) = n
nsroot n = n
addDef :: Name -> a -> Ctxt a -> Ctxt a
addDef n v ctxt = case Map.lookup (nsroot n) ctxt of
Nothing -> Map.insert (nsroot n)
(Map.insert n v Map.empty) ctxt
Just xs -> Map.insert (nsroot n)
(Map.insert n v xs) ctxt
{-| Look up a name in the context, given an optional namespace.
The name (n) may itself have a (partial) namespace given.
Rules for resolution:
- if an explicit namespace is given, return the names which match it. If none
match, return all names.
- if the name has has explicit namespace given, return the names which match it
and ignore the given namespace.
- otherwise, return all names.
-}
lookupCtxtName :: Name -> Ctxt a -> [(Name, a)]
lookupCtxtName n ctxt = case Map.lookup (nsroot n) ctxt of
Just xs -> filterNS (Map.toList xs)
Nothing -> []
where
filterNS [] = []
filterNS ((found, v) : xs)
| nsmatch n found = (found, v) : filterNS xs
| otherwise = filterNS xs
nsmatch (NS n ns) (NS p ps) = ns `isPrefixOf` ps
nsmatch (NS _ _) _ = False
nsmatch looking found = True
lookupCtxt :: Name -> Ctxt a -> [a]
lookupCtxt n ctxt = map snd (lookupCtxtName n ctxt)
lookupCtxtExact :: Name -> Ctxt a -> Maybe a
lookupCtxtExact n ctxt = listToMaybe [ v | (nm, v) <- lookupCtxtName n ctxt, nm == n]
updateDef :: Name -> (a -> a) -> Ctxt a -> Ctxt a
updateDef n f ctxt
= let ds = lookupCtxtName n ctxt in
foldr (\ (n, t) c -> addDef n (f t) c) ctxt ds
toAlist :: Ctxt a -> [(Name, a)]
toAlist ctxt = let allns = map snd (Map.toList ctxt) in
concat (map (Map.toList) allns)
addAlist :: Show a => [(Name, a)] -> Ctxt a -> Ctxt a
addAlist [] ctxt = ctxt
addAlist ((n, tm) : ds) ctxt = addDef n tm (addAlist ds ctxt)
data NativeTy = IT8 | IT16 | IT32 | IT64
deriving (Show, Eq, Ord, Enum)
instance Pretty NativeTy OutputAnnotation where
pretty IT8 = text "Bits8"
pretty IT16 = text "Bits16"
pretty IT32 = text "Bits32"
pretty IT64 = text "Bits64"
data IntTy = ITFixed NativeTy | ITNative | ITBig | ITChar
| ITVec NativeTy Int
deriving (Show, Eq, Ord)
data ArithTy = ATInt IntTy | ATFloat -- TODO: Float vectors
deriving (Show, Eq, Ord)
{-!
deriving instance NFData IntTy
deriving instance NFData NativeTy
deriving instance NFData ArithTy
!-}
instance Pretty ArithTy OutputAnnotation where
pretty (ATInt ITNative) = text "Int"
pretty (ATInt ITBig) = text "BigInt"
pretty (ATInt ITChar) = text "Char"
pretty (ATInt (ITFixed n)) = pretty n
pretty (ATInt (ITVec e c)) = pretty e <> text "x" <> (text . show $ c)
pretty ATFloat = text "Float"
nativeTyWidth :: NativeTy -> Int
nativeTyWidth IT8 = 8
nativeTyWidth IT16 = 16
nativeTyWidth IT32 = 32
nativeTyWidth IT64 = 64
{-# DEPRECATED intTyWidth "Non-total function, use nativeTyWidth and appropriate casing" #-}
intTyWidth :: IntTy -> Int
intTyWidth (ITFixed n) = nativeTyWidth n
intTyWidth ITNative = 8 * sizeOf (0 :: Int)
intTyWidth ITChar = error "IRTS.Lang.intTyWidth: Characters have platform and backend dependent width"
intTyWidth ITBig = error "IRTS.Lang.intTyWidth: Big integers have variable width"
data Const = I Int | BI Integer | Fl Double | Ch Char | Str String
| B8 Word8 | B16 Word16 | B32 Word32 | B64 Word64
| B8V (Vector Word8) | B16V (Vector Word16)
| B32V (Vector Word32) | B64V (Vector Word64)
| AType ArithTy | StrType
| PtrType | VoidType | Forgot
deriving (Eq, Ord)
{-!
deriving instance Binary Const
deriving instance NFData Const
!-}
instance Sized Const where
size _ = 1
instance Pretty Const OutputAnnotation where
pretty (I i) = text . show $ i
pretty (BI i) = text . show $ i
pretty (Fl f) = text . show $ f
pretty (Ch c) = text . show $ c
pretty (Str s) = text s
pretty (AType a) = pretty a
pretty StrType = text "String"
pretty PtrType = text "Ptr"
pretty VoidType = text "Void"
pretty Forgot = text "Forgot"
pretty (B8 w) = text . show $ w
pretty (B16 w) = text . show $ w
pretty (B32 w) = text . show $ w
pretty (B64 w) = text . show $ w
data Raw = Var Name
| RBind Name (Binder Raw) Raw
| RApp Raw Raw
| RType
| RForce Raw
| RConstant Const
deriving (Show, Eq)
instance Sized Raw where
size (Var name) = 1
size (RBind name bind right) = 1 + size bind + size right
size (RApp left right) = 1 + size left + size right
size RType = 1
size (RForce raw) = 1 + size raw
size (RConstant const) = size const
instance Pretty Raw OutputAnnotation where
pretty = text . show
{-!
deriving instance Binary Raw
deriving instance NFData Raw
!-}
-- The type parameter `b` will normally be something like `TT Name` or just
-- `Raw`. We do not make a type-level distinction between TT terms that happen
-- to be TT types and TT terms that are not TT types.
-- | All binding forms are represented in a uniform fashion. This type only represents
-- the types of bindings (and their values, if any); the attached identifiers are part
-- of the 'Bind' constructor for the 'TT' type.
data Binder b = Lam { binderTy :: !b {-^ type annotation for bound variable-}}
| Pi { binderTy :: !b }
{-^ A binding that occurs in a function type expression, e.g. @(x:Int) -> ...@ -}
| Let { binderTy :: !b,
binderVal :: b {-^ value for bound variable-}}
-- ^ A binding that occurs in a @let@ expression
| NLet { binderTy :: !b,
binderVal :: b }
| Hole { binderTy :: !b}
| GHole { envlen :: Int,
binderTy :: !b}
| Guess { binderTy :: !b,
binderVal :: b }
| PVar { binderTy :: !b }
-- ^ A pattern variable
| PVTy { binderTy :: !b }
deriving (Show, Eq, Ord, Functor)
{-!
deriving instance Binary Binder
deriving instance NFData Binder
!-}
instance Sized a => Sized (Binder a) where
size (Lam ty) = 1 + size ty
size (Pi ty) = 1 + size ty
size (Let ty val) = 1 + size ty + size val
size (NLet ty val) = 1 + size ty + size val
size (Hole ty) = 1 + size ty
size (GHole _ ty) = 1 + size ty
size (Guess ty val) = 1 + size ty + size val
size (PVar ty) = 1 + size ty
size (PVTy ty) = 1 + size ty
fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b)
fmapMB f (Let t v) = liftM2 Let (f t) (f v)
fmapMB f (NLet t v) = liftM2 NLet (f t) (f v)
fmapMB f (Guess t v) = liftM2 Guess (f t) (f v)
fmapMB f (Lam t) = liftM Lam (f t)
fmapMB f (Pi t) = liftM Pi (f t)
fmapMB f (Hole t) = liftM Hole (f t)
fmapMB f (GHole i t) = liftM (GHole i) (f t)
fmapMB f (PVar t) = liftM PVar (f t)
fmapMB f (PVTy t) = liftM PVTy (f t)
raw_apply :: Raw -> [Raw] -> Raw
raw_apply f [] = f
raw_apply f (a : as) = raw_apply (RApp f a) as
raw_unapply :: Raw -> (Raw, [Raw])
raw_unapply t = ua [] t where
ua args (RApp f a) = ua (a:args) f
ua args t = (t, args)
-- WELL TYPED TERMS ---------------------------------------------------------
-- | Universe expressions for universe checking
data UExp = UVar Int -- ^ universe variable
| UVal Int -- ^ explicit universe level
deriving (Eq, Ord)
{-!
deriving instance NFData UExp
!-}
instance Sized UExp where
size _ = 1
-- We assume that universe levels have been checked, so anything external
-- can just have the same universe variable and we won't get any new
-- cycles.
instance Binary UExp where
put x = return ()
get = return (UVar (-1))
instance Show UExp where
show (UVar x) | x < 26 = [toEnum (x + fromEnum 'a')]
| otherwise = toEnum ((x `mod` 26) + fromEnum 'a') : show (x `div` 26)
show (UVal x) = show x
-- show (UMax l r) = "max(" ++ show l ++ ", " ++ show r ++")"
-- | Universe constraints
data UConstraint = ULT UExp UExp -- ^ Strictly less than
| ULE UExp UExp -- ^ Less than or equal to
deriving Eq
instance Show UConstraint where
show (ULT x y) = show x ++ " < " ++ show y
show (ULE x y) = show x ++ " <= " ++ show y
type UCs = (Int, [UConstraint])
data NameType = Bound
| Ref
| DCon {nt_tag :: Int, nt_arity :: Int} -- ^ Data constructor
| TCon {nt_tag :: Int, nt_arity :: Int} -- ^ Type constructor
deriving (Show, Ord)
{-!
deriving instance Binary NameType
deriving instance NFData NameType
!-}
instance Sized NameType where
size _ = 1
instance Pretty NameType OutputAnnotation where
pretty = text . show
instance Eq NameType where
Bound == Bound = True
Ref == Ref = True
DCon _ a == DCon _ b = (a == b) -- ignore tag
TCon _ a == TCon _ b = (a == b) -- ignore tag
_ == _ = False
-- | Terms in the core language. The type parameter is the type of
-- identifiers used for bindings and explicit named references;
-- usually we use @TT 'Name'@.
data TT n = P NameType n (TT n) -- ^ named references with type
-- (P for "Parameter", motivated by McKinna and Pollack's
-- Pure Type Systems Formalized)
| V !Int -- ^ a resolved de Bruijn-indexed variable
| Bind n !(Binder (TT n)) (TT n) -- ^ a binding
| App !(TT n) (TT n) -- ^ function, function type, arg
| Constant Const -- ^ constant
| Proj (TT n) !Int -- ^ argument projection; runtime only
-- (-1) is a special case for 'subtract one from BI'
| Erased -- ^ an erased term
| Impossible -- ^ special case for totality checking
| TType UExp -- ^ the type of types at some level
deriving (Ord, Functor)
{-!
deriving instance Binary TT
deriving instance NFData TT
!-}
class TermSize a where
termsize :: Name -> a -> Int
instance TermSize a => TermSize [a] where
termsize n [] = 0
termsize n (x : xs) = termsize n x + termsize n xs
instance TermSize (TT Name) where
termsize n (P _ n' _)
| n' == n = 1000000 -- recursive => really big
| otherwise = 1
termsize n (V _) = 1
-- for `Bind` terms, we can erroneously declare a term
-- "recursive => really big" if the name of the bound
-- variable is the same as the name we're using
-- So generate a different name in that case.
termsize n (Bind n' (Let t v) sc)
= let rn = if n == n' then sMN 0 "noname" else n in
termsize rn v + termsize rn sc
termsize n (Bind n' b sc)
= let rn = if n == n' then sMN 0 "noname" else n in
termsize rn sc
termsize n (App f a) = termsize n f + termsize n a
termsize n (Proj t i) = termsize n t
termsize n _ = 1
instance Sized a => Sized (TT a) where
size (P name n trm) = 1 + size name + size n + size trm
size (V v) = 1
size (Bind nm binder bdy) = 1 + size nm + size binder + size bdy
size (App l r) = 1 + size l + size r
size (Constant c) = size c
size Erased = 1
size (TType u) = 1 + size u
instance Pretty a o => Pretty (TT a) o where
pretty _ = text "test"
type EnvTT n = [(n, Binder (TT n))]
data Datatype n = Data { d_typename :: n,
d_typetag :: Int,
d_type :: (TT n),
d_cons :: [(n, TT n)] }
deriving (Show, Functor, Eq)
instance Eq n => Eq (TT n) where
(==) (P xt x _) (P yt y _) = x == y
(==) (V x) (V y) = x == y
(==) (Bind _ xb xs) (Bind _ yb ys) = xs == ys && xb == yb
(==) (App fx ax) (App fy ay) = ax == ay && fx == fy
(==) (TType _) (TType _) = True -- deal with constraints later
(==) (Constant x) (Constant y) = x == y
(==) (Proj x i) (Proj y j) = x == y && i == j
(==) Erased _ = True
(==) _ Erased = True
(==) _ _ = False
-- * A few handy operations on well typed terms:
-- | A term is injective iff it is a data constructor, type constructor,
-- constant, the type Type, pi-binding, or an application of an injective
-- term.
isInjective :: TT n -> Bool
isInjective (P (DCon _ _) _ _) = True
isInjective (P (TCon _ _) _ _) = True
isInjective (Constant _) = True
isInjective (TType x) = True
isInjective (Bind _ (Pi _) sc) = True
isInjective (App f a) = isInjective f
isInjective _ = False
-- | Count the number of instances of a de Bruijn index in a term
vinstances :: Int -> TT n -> Int
vinstances i (V x) | i == x = 1
vinstances i (App f a) = vinstances i f + vinstances i a
vinstances i (Bind x b sc) = instancesB b + vinstances (i + 1) sc
where instancesB (Let t v) = vinstances i v
instancesB _ = 0
vinstances i t = 0
-- | Replace the outermost (index 0) de Bruijn variable with the given term
instantiate :: TT n -> TT n -> TT n
instantiate e = subst 0 where
subst i (V x) | i == x = e
subst i (Bind x b sc) = Bind x (fmap (subst i) b) (subst (i+1) sc)
subst i (App f a) = App (subst i f) (subst i a)
subst i (Proj x idx) = Proj (subst i x) idx
subst i t = t
-- | As 'instantiate', but also decrement the indices of all de Bruijn variables
-- remaining in the term, so that there are no more references to the variable
-- that has been substituted.
substV :: TT n -> TT n -> TT n
substV x tm = dropV 0 (instantiate x tm) where
dropV i (V x) | x > i = V (x - 1)
| otherwise = V x
dropV i (Bind x b sc) = Bind x (fmap (dropV i) b) (dropV (i+1) sc)
dropV i (App f a) = App (dropV i f) (dropV i a)
dropV i (Proj x idx) = Proj (dropV i x) idx
dropV i t = t
-- | Replace all non-free de Bruijn references in the given term with references
-- to the name of their binding.
explicitNames :: TT n -> TT n
explicitNames (Bind x b sc) = let b' = fmap explicitNames b in
Bind x b'
(explicitNames (instantiate
(P Bound x (binderTy b')) sc))
explicitNames (App f a) = App (explicitNames f) (explicitNames a)
explicitNames (Proj x idx) = Proj (explicitNames x) idx
explicitNames t = t
-- | Replace references to the given 'Name'-like id with references to
-- de Bruijn index 0.
pToV :: Eq n => n -> TT n -> TT n
pToV n = pToV' n 0
pToV' n i (P _ x _) | n == x = V i
pToV' n i (Bind x b sc)
-- We can assume the inner scope has been pToVed already, so continue to
-- resolve names from the *outer* scope which may happen to have the same id.
| n == x = Bind x (fmap (pToV' n i) b) sc
| otherwise = Bind x (fmap (pToV' n i) b) (pToV' n (i+1) sc)
pToV' n i (App f a) = App (pToV' n i f) (pToV' n i a)
pToV' n i (Proj t idx) = Proj (pToV' n i t) idx
pToV' n i t = t
-- increase de Bruijn indices, as if a binder has been added
addBinder :: TT n -> TT n
addBinder t = ab 0 t
where
ab top (V i) | i >= top = V (i + 1)
| otherwise = V i
ab top (Bind x b sc) = Bind x (fmap (ab top) b) (ab (top + 1) sc)
ab top (App f a) = App (ab top f) (ab top a)
ab top (Proj t idx) = Proj (ab top t) idx
ab top t = t
-- | Convert several names. First in the list comes out as V 0
pToVs :: Eq n => [n] -> TT n -> TT n
pToVs ns tm = pToVs' ns tm 0 where
pToVs' [] tm i = tm
pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1))
-- | Replace de Bruijn indices in the given term with explicit references to
-- the names of the bindings they refer to. It is an error if the given term
-- contains free de Bruijn indices.
vToP :: TT n -> TT n
vToP = vToP' [] where
vToP' env (V i) = let (n, b) = (env !! i) in
P Bound n (binderTy b)
vToP' env (Bind n b sc) = let b' = fmap (vToP' env) b in
Bind n b' (vToP' ((n, b'):env) sc)
vToP' env (App f a) = App (vToP' env f) (vToP' env a)
vToP' env t = t
-- | Replace every non-free reference to the name of a binding in
-- the given term with a de Bruijn index.
finalise :: Eq n => TT n -> TT n
finalise (Bind x b sc) = Bind x (fmap finalise b) (pToV x (finalise sc))
finalise (App f a) = App (finalise f) (finalise a)
finalise t = t
-- Once we've finished checking everything about a term we no longer need
-- the type on the 'P' so erase it so save memory
pEraseType :: TT n -> TT n
pEraseType (P nt t _) = P nt t Erased
pEraseType (App f a) = App (pEraseType f) (pEraseType a)
pEraseType (Bind n b sc) = Bind n (fmap pEraseType b) (pEraseType sc)
pEraseType t = t
-- | As 'instantiate', but in addition to replacing @'V' 0@,
-- replace references to the given 'Name'-like id.
subst :: Eq n => n {-^ The id to replace -} ->
TT n {-^ The replacement term -} ->
TT n {-^ The term to replace in -} ->
TT n
subst n v tm = instantiate v (pToV n tm)
-- If there are no Vs in the term (i.e. in proof state)
psubst :: Eq n => n -> TT n -> TT n -> TT n
psubst n v tm = s' tm where
s' (P _ x _) | n == x = v
s' (Bind x b sc) | n == x = Bind x (fmap s' b) sc
| otherwise = Bind x (fmap s' b) (s' sc)
s' (App f a) = App (s' f) (s' a)
s' (Proj t idx) = Proj (s' t) idx
s' t = t
-- | As 'subst', but takes a list of (name, substitution) pairs instead
-- of a single name and substitution
substNames :: Eq n => [(n, TT n)] -> TT n -> TT n
substNames [] t = t
substNames ((n, tm) : xs) t = subst n tm (substNames xs t)
-- | Replaces all terms equal (in the sense of @(==)@) to
-- the old term with the new term.
substTerm :: Eq n => TT n {-^ Old term -} ->
TT n {-^ New term -} ->
TT n {-^ template term -}
-> TT n
substTerm old new = st where
st t | t == old = new
st (App f a) = App (st f) (st a)
st (Bind x b sc) = Bind x (fmap st b) (st sc)
st t = t
-- | Returns true if V 0 and bound name n do not occur in the term
noOccurrence :: Eq n => n -> TT n -> Bool
noOccurrence n t = no' 0 t
where
no' i (V x) = not (i == x)
no' i (P Bound x _) = not (n == x)
no' i (Bind n b sc) = noB' i b && no' (i+1) sc
where noB' i (Let t v) = no' i t && no' i v
noB' i (Guess t v) = no' i t && no' i v
noB' i b = no' i (binderTy b)
no' i (App f a) = no' i f && no' i a
no' i (Proj x _) = no' i x
no' i _ = True
-- | Returns all names used free in the term
freeNames :: Eq n => TT n -> [n]
freeNames (P _ n _) = [n]
freeNames (Bind n (Let t v) sc) = nub $ freeNames v ++ (freeNames sc \\ [n])
++ freeNames t
freeNames (Bind n b sc) = nub $ freeNames (binderTy b) ++ (freeNames sc \\ [n])
freeNames (App f a) = nub $ freeNames f ++ freeNames a
freeNames (Proj x i) = nub $ freeNames x
freeNames _ = []
-- | Return the arity of a (normalised) type
arity :: TT n -> Int
arity (Bind n (Pi t) sc) = 1 + arity sc
arity _ = 0
-- | Deconstruct an application; returns the function and a list of arguments
unApply :: TT n -> (TT n, [TT n])
unApply t = ua [] t where
ua args (App f a) = ua (a:args) f
ua args t = (t, args)
-- | Returns a term representing the application of the first argument
-- (a function) to every element of the second argument.
mkApp :: TT n -> [TT n] -> TT n
mkApp f [] = f
mkApp f (a:as) = mkApp (App f a) as
unList :: Term -> Maybe [Term]
unList tm = case unApply tm of
(nil, [_]) -> Just []
(cons, ([_, x, xs])) ->
do rest <- unList xs
return $ x:rest
(f, args) -> Nothing
-- | Cast a 'TT' term to a 'Raw' value, discarding universe information and
-- the types of named references and replacing all de Bruijn indices
-- with the corresponding name. It is an error if there are free de
-- Bruijn indices.
forget :: TT Name -> Raw
forget tm = fe [] tm
where
fe env (P _ n _) = Var n
fe env (V i) = Var (env !! i)
fe env (Bind n b sc) = let n' = uniqueName n env in
RBind n' (fmap (fe env) b)
(fe (n':env) sc)
fe env (App f a) = RApp (fe env f) (fe env a)
fe env (Constant c)
= RConstant c
fe env (TType i) = RType
fe env Erased = RConstant Forgot
-- | Introduce a 'Bind' into the given term for each element of the
-- given list of (name, binder) pairs.
bindAll :: [(n, Binder (TT n))] -> TT n -> TT n
bindAll [] t = t
bindAll ((n, b) : bs) t = Bind n b (bindAll bs t)
-- | Like 'bindAll', but the 'Binder's are 'TT' terms instead.
-- The first argument is a function to map @TT@ terms to @Binder@s.
-- This function might often be something like 'Lam', which directly
-- constructs a @Binder@ from a @TT@ term.
bindTyArgs :: (TT n -> Binder (TT n)) -> [(n, TT n)] -> TT n -> TT n
bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs)
-- | Return a list of pairs of the names of the outermost 'Pi'-bound
-- variables in the given term, together with their types.
getArgTys :: TT n -> [(n, TT n)]
getArgTys (Bind n (Pi t) sc) = (n, t) : getArgTys sc
getArgTys _ = []
getRetTy :: TT n -> TT n
getRetTy (Bind n (PVar _) sc) = getRetTy sc
getRetTy (Bind n (PVTy _) sc) = getRetTy sc
getRetTy (Bind n (Pi _) sc) = getRetTy sc
getRetTy sc = sc
uniqueNameFrom :: [Name] -> [Name] -> Name
uniqueNameFrom (s : supply) hs
| s `elem` hs = uniqueNameFrom supply hs
| otherwise = s
uniqueName :: Name -> [Name] -> Name
uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs
| otherwise = n
uniqueBinders :: [Name] -> TT Name -> TT Name
uniqueBinders ns (Bind n b sc)
= let n' = uniqueName n ns in
Bind n' (fmap (uniqueBinders (n':ns)) b) (uniqueBinders ns sc)
uniqueBinders ns (App f a) = App (uniqueBinders ns f) (uniqueBinders ns a)
uniqueBinders ns t = t
nextName (NS x s) = NS (nextName x) s
nextName (MN i n) = MN (i+1) n
nextName (UN x) = let (num', nm') = T.span isDigit (T.reverse x)
nm = T.reverse nm'
num = readN (T.reverse num') in
UN (nm `T.append` txt (show (num+1)))
where
readN x | not (T.null x) = read (T.unpack x)
readN x = 0
nextName (SN x) = SN (nextName' x)
where
nextName' (WhereN i f x) = WhereN i f (nextName x)
nextName' (CaseN n) = CaseN (nextName n)
nextName' (MethodN n) = MethodN (nextName n)
type Term = TT Name
type Type = Term
type Env = EnvTT Name
-- | an environment with de Bruijn indices 'normalised' so that they all refer to
-- this environment
newtype WkEnvTT n = Wk (EnvTT n)
type WkEnv = WkEnvTT Name
instance (Eq n, Show n) => Show (TT n) where
show t = showEnv [] t
itBitsName IT8 = "Bits8"
itBitsName IT16 = "Bits16"
itBitsName IT32 = "Bits32"
itBitsName IT64 = "Bits64"
instance Show Const where
show (I i) = show i
show (BI i) = show i
show (Fl f) = show f
show (Ch c) = show c
show (Str s) = show s
show (B8 x) = show x
show (B16 x) = show x
show (B32 x) = show x
show (B64 x) = show x
show (B8V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">"
show (B16V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">"
show (B32V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">"
show (B64V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">"
show (AType ATFloat) = "Float"
show (AType (ATInt ITBig)) = "Integer"
show (AType (ATInt ITNative)) = "Int"
show (AType (ATInt ITChar)) = "Char"
show (AType (ATInt (ITFixed it))) = itBitsName it
show (AType (ATInt (ITVec it c))) = itBitsName it ++ "x" ++ show c
show StrType = "String"
show PtrType = "Ptr"
show VoidType = "Void"
showEnv :: (Eq n, Show n) => EnvTT n -> TT n -> String
showEnv env t = showEnv' env t False
showEnvDbg env t = showEnv' env t True
prettyEnv env t = prettyEnv' env t False
where
prettyEnv' env t dbg = prettySe 10 env t dbg
bracket outer inner p
| inner > outer = lparen <> p <> rparen
| otherwise = p
prettySe p env (P nt n t) debug =
pretty n <+>
if debug then
lbracket <+> pretty nt <+> colon <+> prettySe 10 env t debug <+> rbracket
else
empty
prettySe p env (V i) debug
| i < length env =
if debug then
text . show . fst $ env!!i
else
lbracket <+> text (show i) <+> rbracket
| otherwise = text "unbound" <+> text (show i) <+> text "!"
prettySe p env (Bind n b@(Pi t) sc) debug
| noOccurrence n sc && not debug =
bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
prettySe p env (Bind n b sc) debug =
bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
prettySe p env (App f a) debug =
bracket p 1 $ prettySe 1 env f debug <+> prettySe 0 env a debug
prettySe p env (Proj x i) debug =
prettySe 1 env x debug <+> text ("!" ++ show i)
prettySe p env (Constant c) debug = pretty c
prettySe p env Erased debug = text "[_]"
prettySe p env (TType i) debug = text "Type" <+> (text . show $ i)
-- Render a `Binder` and its name
prettySb env n (Lam t) = prettyB env "λ" "=>" n t
prettySb env n (Hole t) = prettyB env "?defer" "." n t
prettySb env n (Pi t) = prettyB env "(" ") ->" n t
prettySb env n (PVar t) = prettyB env "pat" "." n t
prettySb env n (PVTy t) = prettyB env "pty" "." n t
prettySb env n (Let t v) = prettyBv env "let" "in" n t v
prettySb env n (Guess t v) = prettyBv env "??" "in" n t v
-- Use `op` and `sc` to delimit `n` (a binding name) and its type
-- declaration
-- e.g. "λx : Int =>" for the Lam case
prettyB env op sc n t debug =
text op <> pretty n <+> colon <+> prettySe 10 env t debug <> text sc
-- Like `prettyB`, but handle the bindings that have values in addition
-- to names and types
prettyBv env op sc n t v debug =
text op <> pretty n <+> colon <+> prettySe 10 env t debug <+> text "=" <+>
prettySe 10 env v debug <> text sc
showEnv' env t dbg = se 10 env t where
se p env (P nt n t) = show n
++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else ""
se p env (V i) | i < length env && i >= 0
= (show $ fst $ env!!i) ++
if dbg then "{" ++ show i ++ "}" else ""
| otherwise = "!!V " ++ show i ++ "!!"
se p env (Bind n b@(Pi t) sc)
| noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ " -> " ++ se 10 ((n,b):env) sc
se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc
se p env (App f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a
se p env (Proj x i) = se 1 env x ++ "!" ++ show i
se p env (Constant c) = show c
se p env Erased = "[__]"
se p env Impossible = "[impossible]"
se p env (TType i) = "Type " ++ show i
sb env n (Lam t) = showb env "\\ " " => " n t
sb env n (Hole t) = showb env "? " ". " n t
sb env n (GHole i t) = showb env "?defer " ". " n t
sb env n (Pi t) = showb env "(" ") -> " n t
sb env n (PVar t) = showb env "pat " ". " n t
sb env n (PVTy t) = showb env "pty " ". " n t
sb env n (Let t v) = showbv env "let " " in " n t v
sb env n (Guess t v) = showbv env "?? " " in " n t v
showb env op sc n t = op ++ show n ++ " : " ++ se 10 env t ++ sc
showbv env op sc n t v = op ++ show n ++ " : " ++ se 10 env t ++ " = " ++
se 10 env v ++ sc
bracket outer inner str | inner > outer = "(" ++ str ++ ")"
| otherwise = str
-- | Check whether a term has any holes in it - impure if so
pureTerm :: TT Name -> Bool
pureTerm (App f a) = pureTerm f && pureTerm a
pureTerm (Bind n b sc) = notClassName n && pureBinder b && pureTerm sc where
pureBinder (Hole _) = False
pureBinder (Guess _ _) = False
pureBinder (Let t v) = pureTerm t && pureTerm v
pureBinder t = pureTerm (binderTy t)
notClassName (MN _ c) | c == txt "class" = False
notClassName _ = True
pureTerm _ = True
-- | Weaken a term by adding i to each de Bruijn index (i.e. lift it over i bindings)
weakenTm :: Int -> TT n -> TT n
weakenTm i t = wk i 0 t
where wk i min (V x) | x >= min = V (i + x)
wk i m (App f a) = App (wk i m f) (wk i m a)
wk i m (Bind x b sc) = Bind x (wkb i m b) (wk i (m + 1) sc)
wk i m t = t
wkb i m t = fmap (wk i m) t
-- | Weaken an environment so that all the de Bruijn indices are correct according
-- to the latest bound variable
weakenEnv :: EnvTT n -> EnvTT n
weakenEnv env = wk (length env - 1) env
where wk i [] = []
wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i - 1) bs
weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v)
weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v)
weakenTmB i t = t { binderTy = weakenTm i (binderTy t) }
-- | Weaken every term in the environment by the given amount
weakenTmEnv :: Int -> EnvTT n -> EnvTT n
weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b))
-- | Gather up all the outer 'PVar's and 'Hole's in an expression and reintroduce
-- them in a canonical order
orderPats :: Term -> Term
orderPats tm = op [] tm
where
op ps (Bind n (PVar t) sc) = op ((n, PVar t) : ps) sc
op ps (Bind n (Hole t) sc) = op ((n, Hole t) : ps) sc
op ps sc = bindAll (sortP ps) sc
sortP ps = pick [] (reverse ps)
namesIn (P _ n _) = [n]
namesIn (Bind n b t) = nub $ nb b ++ (namesIn t \\ [n])
where nb (Let t v) = nub (namesIn t) ++ nub (namesIn v)
nb (Guess t v) = nub (namesIn t) ++ nub (namesIn v)
nb t = namesIn (binderTy t)
namesIn (App f a) = nub (namesIn f ++ namesIn a)
namesIn _ = []
pick acc [] = reverse acc
pick acc ((n, t) : ps) = pick (insert n t acc) ps
insert n t [] = [(n, t)]
insert n t ((n',t') : ps)
| n `elem` (namesIn (binderTy t') ++
concatMap namesIn (map (binderTy . snd) ps))
= (n', t') : insert n t ps
| otherwise = (n,t):(n',t'):ps
|
ctford/Idris-Elba-dev
|
src/Idris/Core/TT.hs
|
bsd-3-clause
| 42,471 | 0 | 17 | 12,812 | 16,469 | 8,281 | 8,188 | -1 | -1 |
module SNMPTrapType
( SNMPTrap (..)
) where
import Data.ASN1.Types (ASN1)
import Data.ConfigFile (SectionSpec)
import Data.Default
import Data.Word (Word8)
data SNMPTrap = SNMPTrap { takeSection :: SectionSpec
, takeVersion :: String
, takeCommunity :: String
, takeAgentAddress :: [Word8]
, takeEnterpriseId :: [Integer]
, takeGenericTrap :: Integer
, takeSpecificTrap :: Integer
, takeTrapOid :: [Integer]
, takeVarBind :: [ASN1]
}
instance Default SNMPTrap where
def = SNMPTrap { takeSection = undefined
, takeVersion = undefined
, takeCommunity = undefined
, takeAgentAddress = undefined
, takeEnterpriseId = undefined
, takeGenericTrap = undefined
, takeSpecificTrap = undefined
, takeTrapOid = undefined
, takeVarBind = undefined
}
|
IMOKURI/bulk-snmptrap-tool
|
src/SNMPTrapType.hs
|
mit
| 1,124 | 0 | 9 | 489 | 193 | 124 | 69 | 25 | 0 |
{-# LANGUAGE RecordWildCards #-}
module Graphics.GL.Pal.Geometries.Octahedron where
import Graphics.GL
import Graphics.GL.Pal.Types
import Graphics.GL.Pal.Geometry
import Linear hiding (trace)
import Control.Lens hiding (indices)
import Data.Foldable
import Control.Arrow
import Control.Monad.Trans
octahedronData :: GLfloat -> GLuint -> GeometryData
octahedronData size subdivisions = GeometryData{..}
where
-- The base Array of vertices
vertList = [ V3 1 0 0
, V3 0 1 0
, V3 0 0 1
, V3 (-1) 0 0
, V3 0 (-1) 0
, V3 0 0 (-1)
]
faceList = [ V3 2 0 1
, V3 0 5 1
, V3 5 3 1
, V3 3 2 1
, V3 0 2 4
, V3 5 0 4
, V3 3 5 4
, V3 2 3 4
]
(newVertList, newFaceList) = subdivide (vertList, faceList) subdivisions
gdPositions = makeOctahedronPositions size newVertList
gdUVs = makeOctahedronUVs newVertList
gdIndices = makeOctahedronIndices newFaceList
gdNormals = makeOctahedronNormals newVertList
gdTangents = makeOctahedronTangents newVertList
makeOctahedronPositions :: GLfloat -> [V3 GLfloat] -> [V3 GLfloat]
makeOctahedronPositions size vertList = map (realToFrac size *) vertList
makeOctahedronIndices :: (Foldable t, Foldable t1) => t (t1 b) -> [b]
makeOctahedronIndices indexList = concatMap toList indexList
makeOctahedronNormals :: [V3 GLfloat] -> [V3 GLfloat]
makeOctahedronNormals positionList = map normalize positionList
makeOctahedronUVs :: [V3 GLfloat] -> [V2 GLfloat]
makeOctahedronUVs positionList = uvs
where
uvs = map getUV positionList
getUV p =
let u = asin (p^._x)/pi + 0.5
v = asin (p^._y)/pi + 0.5
in V2 u (1 - v)
makeOctahedronTangents :: [V3 GLfloat] -> [V3 GLfloat]
makeOctahedronTangents positionList = tangents
where
tangents = map getTangent [0..length positionList]
getTangent _ = V3 0 0 0
octahedronGeometry :: MonadIO m => GLfloat -> GLuint -> m Geometry
octahedronGeometry size subdivisions = geometryFromData $ octahedronData size subdivisions
subdivide :: ([V3 GLfloat] , [V3 GLuint]) -> GLuint -> ([V3 GLfloat] , [V3 GLuint])
subdivide (vertList, faceList) 0 = (vertList , faceList)
subdivide (vertList, faceList) n = subdivide vertsAndFaces (n - 1)
where
vertsAndFaces = first concat . second concat . unzip $ map getNewVerts (zip [0..] faceList)
getNewVerts (i, face) =
let v1 = vertList !! fromIntegral (face ^. _x)
v2 = vertList !! fromIntegral (face ^. _y)
v3 = vertList !! fromIntegral (face ^. _z)
m1 = getMidpoint v1 v2
m2 = getMidpoint v2 v3
m3 = getMidpoint v3 v1
newVertList = [ v1 , v2 , v3 , m1 , m2 , m3 ]
newFaceList = [ V3 0 3 5
, V3 3 1 4
, V3 5 3 4
, V3 5 4 2
]
faceListOffset = fmap (fmap (+ (i * 6))) newFaceList
vertListNormal = fmap normalize newVertList
in (vertListNormal, faceListOffset)
getMidpoint :: V3 GLfloat -> V3 GLfloat -> V3 GLfloat
getMidpoint v1 v2 = v2 + ((v1 - v2) / 2)
|
lukexi/gl-pal
|
src/Graphics/GL/Pal/Geometries/Octahedron.hs
|
bsd-3-clause
| 3,499 | 0 | 16 | 1,217 | 1,083 | 572 | 511 | 72 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
-- | This package uses "Data.Generics.PlateData", so
--
-- * when Cabal package format changes, we don't have to rewrite anything
--
-- * all queries are statically typed
--
-- * as a disadvantage, we may suffer some performance loss when doing very complex queries,
-- anyway most of processing goes while we read package descriptions, not querying them
--
-- Example of enduser querying code:
--
-- @
--module Main where
--
-- import qualified Data.ByteString.Lazy as B
--import System.Environment
--import Distribution.Query
--import Distribution.Compiler
--import Distribution.License
--import Distribution.ModuleName hiding (main)
--import Distribution.Package
--import Distribution.PackageDescription
--import Distribution.Version
--import Distribution.Text
--import Language.Haskell.Extension
--
-- main = (head \`fmap\` getArgs) >>=
-- B.readFile >>=
-- mapM_ (putStrLn . show . (\x -> (display $ package x, display $ license x))) .
-- queryIndex (Not (Id (== GPL)) :& Not (Id (== BSD3)))
-- @
--
-- You can query any field of 'PackageDescription' no matter how deep it is.
-- You don't need to provide any type signature for comparison functions,
-- which are wrapped in 'Id', as long as you use data constructors for which type can be inferred.
--
-- See 'PackageDescription' fields for details.
module Distribution.Query
( queryFiles
, queryIndex
, module Distribution.Query.Types ) where
import Codec.Archive.Tar as T hiding (unpack)
import Data.ByteString.Internal (w2c)
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as B
import Data.Generics.PlateData
import Data.Maybe
import Distribution.PackageDescription
import Distribution.PackageDescription.Parse
import Distribution.Query.Types
-- | Queries an index file, which is commonly located at
-- <~/.cabal/packages/hackage.haskell.org/00-index.tar> in POSIX systems.
queryIndex :: Query
-> ByteString -- ^ The index file must be read as lazy ByteString
-> [PackageDescription] -- ^ Returns a list of package descriptions which satisfy the query
queryIndex q = procQuery q . foldEntries foldF [] (const []) . T.read
where
foldF :: Entry -> [PackageDescription] -> [PackageDescription]
foldF c rest =
case entryContent c of
NormalFile s _ -> maybe rest (:rest) $ parsePD s
_ -> rest
parsePD :: ByteString -> Maybe PackageDescription
parsePD s =
case (parsePackageDescription $ map w2c $ B.unpack s) of
ParseOk _ x -> Just $ packageDescription x
_ -> Nothing
-- | Queries .cabal files.
queryFiles :: Query
-> [ByteString] -- ^ All files must be read as lazy ByteStrings
-> [PackageDescription] -- ^ Returns a list of package descriptions which satisfy the query
queryFiles q = procQuery q . catMaybes . map parsePD
procQuery :: Query -> [PackageDescription] -> [PackageDescription]
procQuery q = filter (doQuery q)
doQuery :: Query -> PackageDescription -> Bool
doQuery (Id f) pd = or [f x | x <- universeBi pd]
doQuery (Not q) pd = not $ doQuery q pd
doQuery (q1 :& q2) pd = doQuery q1 pd && doQuery q2 pd
doQuery (q1 :| q2) pd = doQuery q1 pd || doQuery q2 pd
|
explicitcall/cabal-query
|
src/Distribution/Query.hs
|
bsd-3-clause
| 3,293 | 0 | 12 | 668 | 544 | 309 | 235 | 39 | 2 |
module Core.Data where
import Core.Type
import Name
import Utilities
type Arity = Int
type DataCon = String
dataTypes :: [(TyCon, [TyVar], [(DataCon, [Type])])]
dataTypes = [
("()" , [],
[("()" , [])]),
("(,)" , [name "a", name "b"],
[("(,)" , [TyVar (name "a"), TyVar (name "b")])]),
("(,,)" , [name "a", name "b", name "c"],
[("(,,)" , [TyVar (name "a"), TyVar (name "b"), TyVar (name "c")])]),
("(,,,)" , [name "a", name "b", name "c", name "d"],
[("(,,,)" , [TyVar (name "a"), TyVar (name "b"), TyVar (name "c"), TyVar (name "d")])]),
("[]" , [name "a"],
[("[]" , []),
("(:)" , [TyVar (name "a"), TyTyCon "[]" `TyApp` TyVar (name "a")])]),
("Either" , [name "a", name "b"],
[("Left" , [TyVar (name "a")]),
("Right" , [TyVar (name "b")])]),
("Bool" , [],
[("True" , []),
("False" , [])]),
("Maybe" , [name "a"],
[("Just" , [TyVar (name "a")]),
("Nothing", [])])
]
dataConFriendlyName :: DataCon -> Maybe String
dataConFriendlyName dc = case dc of
"()" -> Just "Tup0"
"(,)" -> Just "Tup2"
"(,,)" -> Just "Tup3"
"(,,,)" -> Just "Tup4"
"[]" -> Just "Nil"
"(:)" -> Just "Cons"
_ -> Nothing
dataConFields :: DataCon -> (TyCon, [TyVar], [Type])
dataConFields have_dc = case [(tc, tvs, tys) | (tc, tvs, dt) <- dataTypes, (dc, tys) <- dt, dc == have_dc] of
[res] -> res
_ -> panic "dataConFields" (text have_dc)
dataConArity :: DataCon -> Arity
dataConArity = length . thd3 . dataConFields
dataConSiblings :: DataCon -> [(DataCon, Arity)]
dataConSiblings have_dc = case [[(dc, length tys) | (dc, tys) <- dt] | (_tc, _tvs, dt) <- dataTypes, Just _ <- [lookup have_dc dt]] of
[dt] -> dt
_ -> panic "dataConSiblings" (text have_dc)
|
batterseapower/mini-ghc
|
Core/Data.hs
|
bsd-3-clause
| 1,849 | 0 | 13 | 497 | 879 | 495 | 384 | 47 | 7 |
module Main ( main ) where
import qualified Bot.Test.TestIntegration
import qualified Bot.Test.TestParser
import Test.Framework ( defaultMain )
main = defaultMain [ Bot.Test.TestIntegration.tests
, Bot.Test.TestParser.tests
]
|
andregr/bot
|
test/src/Main.hs
|
bsd-3-clause
| 282 | 0 | 7 | 81 | 55 | 36 | 19 | 6 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Kalium.Nucleus.Scalar.Atomize (atomize) where
import Kalium.Prelude
import Kalium.Util
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.Rename
import qualified Data.Map as M
import Kalium.Nucleus.Scalar.Program
import Kalium.Nucleus.Scalar.Build (statement, follow)
import Kalium.Nucleus.Scalar.Typecheck
atomize a = runReaderT (atomizeProgram a) mempty
type T e m = (TypeEnv e m, MonadNameGen m)
type Atomize a = forall e m param . (Typing param, T e m)
=> Kleisli' m
(a (Configuration param Pattern Expression))
(a (Configuration param Pattern Atom))
atomizeProgram :: Atomize Program
atomizeProgram = typeIntro $ programFuncs (traverse atomizeFunc)
atomizeFunc :: Atomize Func
atomizeFunc = funcScope (atomizeScope atomizeBodyScope)
atomizeBodyScope :: Atomize (Scope Vars Body)
atomizeBodyScope = typeIntro $ \(Scope vars (Body stmt expr)) -> do
(atom, (vardecls, statements)) <- runWriterT (atomizeExpression expr)
statement <- atomizeStatement stmt
return $ Scope
(M.fromList vardecls <> vars)
(Body (follow (statement:statements)) atom)
atomizeScope atomize = typeIntro $ scopeElem atomize
atomizeStatement :: Atomize Statement
atomizeStatement = \case
Execute (Exec mname op tyArgs exprs) -> atomizeStatementW
$ Exec mname op tyArgs <$> traverse atomizeExpression exprs
ForStatement (ForCycle name range body) -> atomizeStatementW
$ ForCycle name <$> atomizeExpression range <*> atomizeStatement body
IfStatement (If cond thenb elseb) -> atomizeStatementW
$ If <$> atomizeExpression cond
<*> atomizeStatement thenb
<*> atomizeStatement elseb
ScopeStatement scope
-> ScopeStatement
<$> atomizeScope atomizeStatement scope
Follow st1 st2
-> Follow
<$> atomizeStatement st1
<*> atomizeStatement st2
Pass -> pure Pass
atomizeStatementW w = do
(a, (vardecls, statements)) <- runWriterT w
return $ ScopeStatement
$ Scope (scoping vardecls) (follow (statements `snoc` statement a))
atomizeExpression
:: T e m
=> Expression
-> WriterT
( Pairs Name Type
, [Statement (Configuration param Pattern Atom)]
) m Atom
atomizeExpression = \case
Atom atom -> return atom
e@(Call op tyArgs args) -> do
eArgs <- traverse atomizeExpression args
name <- NameGen <$> mkname Nothing
ty <- typecheck e
let vardecl = (name, ty)
tell ([vardecl], [Execute $ Exec (PAccess name) op tyArgs eArgs])
return (Access name)
|
rscprof/kalium
|
src/Kalium/Nucleus/Scalar/Atomize.hs
|
bsd-3-clause
| 2,661 | 0 | 16 | 607 | 834 | 426 | 408 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
--------------------------------------------------------------------------------
-- |
-- Module : HEP.Data.HepMC.Type
-- Copyright : (c) 2017 Chan Beom Park
-- License : BSD-style
-- Maintainer : Chan Beom Park <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-- Parsers for HepMC event data. See "HEP.Data.HepMC.PipesUtil" for functions
-- using pipes.
--
--------------------------------------------------------------------------------
module HEP.Data.HepMC.Parser (hepmcHeader, hepmcEvent) where
import Control.Applicative ((<|>))
import Control.Monad (replicateM, void)
import Data.Attoparsec.ByteString.Char8
import Data.Maybe (isJust)
import Data.Monoid (All (..))
import Prelude hiding (takeWhile)
import HEP.Data.HepMC.Type
import HEP.Data.ParserUtil (skipTillEnd)
-- | Parsing the HepMC Header.
-- This returns the 'Version'.
hepmcHeader :: Parser Version
hepmcHeader = do
skipSpace
v <- hepmcVersion <* skipSpace
_ <- beginBlock <* skipSpace
return v
where
hepmcVersion =
string "HepMC::Version" >> skipSpace >> takeWhile (not . isSpace)
beginBlock = void (string "HepMC::IO_GenEvent-START_EVENT_LISTING")
-- | Parsing the 'GenEvent'.
-- It has 'GenVertex', which contains 'GenParticle'.
hepmcEvent :: Parser GenEvent
hepmcEvent = lineE
<*> header (EventHeader Nothing Nothing Nothing Nothing Nothing)
<*> many1' vertexParticles
where
vertexParticles :: Parser GenVertex
vertexParticles = lineV <*> many1' lineP
header :: EventHeader -> Parser EventHeader
header h@EventHeader {..} =
if isFilled
then return h
else do s <- satisfy (inClass "NUCHF")
case s of
'N' -> lineN >>= \r -> header (h { weightInfo = Just r })
'U' -> lineU >>= \r -> header (h { unitInfo = Just r })
'C' -> lineC >>= \r -> header (h { crossSectionInfo = Just r })
'H' -> lineH >>= \r -> header (h { heavyIonInfo = Just r })
'F' -> lineF >>= \r -> header (h { pdfInfo = Just r })
_ -> return h
<|> return h
where
isFilled = (getAll . mconcat . map All) [ isJust weightInfo
, isJust unitInfo
, isJust crossSectionInfo
, isJust heavyIonInfo
, isJust pdfInfo
]
lineE :: Parser (EventHeader -> [GenVertex] -> GenEvent)
lineE = do
char 'E' >> skipSpace
evnum <- decimal <* skipSpace
nmint <- signed decimal <* skipSpace
esc <- double <* skipSpace
aqcd <- double <* skipSpace
aqed <- double <* skipSpace
sid <- decimal <* skipSpace
bcd <- signed decimal <* skipSpace
nvtx <- decimal <* skipSpace
bcdbm1 <- decimal <* skipSpace
bcdbm2 <- decimal <* skipSpace
rnum <- decimal <* skipSpace
rList' <- replicateM rnum (skipSpace *> decimal)
wgtnum <- decimal
wList' <- replicateM wgtnum (skipSpace *> double)
skipTillEnd
return $ \h vs -> GenEvent { eventNumber = evnum
, numMultiParticleInt = nmint
, eventScale = esc
, alphaQCD = aqcd
, alphaQED = aqed
, signalProcId = sid
, signalProcVertex = bcd
, numVertex = nvtx
, beamParticles = (bcdbm1, bcdbm2)
, randomStateList = mkList rnum rList'
, weightList = mkList wgtnum wList'
, eventHeader = h
, vertices = vs }
lineN :: Parser WeightNames
lineN = do
skipSpace
n <- decimal <* skipSpace
wstrs <- replicateM n (skipSpace *> weightStrings)
skipTillEnd
return (WeightNames n wstrs)
where
weightStrings = char '"' *> takeWhile (/= '"') <* char '"'
lineU :: Parser MomentumPositionUnit
lineU = do
skipSpace
mUnit <- (string "GEV" >> return GeV) <|> (string "MEV" >> return MeV)
skipSpace
lUnit <- (string "MM" >> return MM) <|> (string "CM" >> return CM)
skipTillEnd
return (MomentumPositionUnit mUnit lUnit)
lineC :: Parser GenCrossSection
lineC = do
skipSpace
xs <- double <* skipSpace
err <- double
skipTillEnd
return (GenCrossSection xs err)
lineH :: Parser HeavyIon
lineH = do
skipSpace
nhsc <- decimal <* skipSpace
npp <- decimal <* skipSpace
ntp <- decimal <* skipSpace
nnn <- decimal <* skipSpace
nsn <- decimal <* skipSpace
nsp <- decimal <* skipSpace
nnnw <- decimal <* skipSpace
nnwn <- decimal <* skipSpace
nnwnw <- decimal <* skipSpace
impct <- double <* skipSpace
epangle <- double <* skipSpace
ecc <- double <* skipSpace
inelstcxsec <- double
skipTillEnd
return HeavyIon { numHardScattering = nhsc
, numProjectileParticipants = npp
, numTargetParticipants = ntp
, numNNCollisions = nnn
, numSpectatorNeutrons = nsn
, numSpectatorProtons = nsp
, numNNwoundedCollisions = nnnw
, numNwoundedNCollisions = nnwn
, numNwoundedNwoundedCollisions = nnwnw
, impactParamCollision = impct
, eventPlaneAngle = epangle
, eccentricity = ecc
, inelasticXsecNN = inelstcxsec }
lineF :: Parser PdfInfo
lineF = do
skipSpace
f1 <- signed decimal <* skipSpace
f2 <- signed decimal <* skipSpace
bx1 <- double <* skipSpace
bx2 <- double <* skipSpace
sqpdf <- double <* skipSpace
xfx1 <- double <* skipSpace
xfx2 <- double <* skipSpace
id1 <- signed decimal <* skipSpace
id2 <- signed decimal
skipTillEnd
return PdfInfo { flavor = (f1, f2)
, beamMomentumFrac = (bx1, bx2)
, scaleQPDF = sqpdf
, xfx = (xfx1, xfx2)
, idLHAPDF = (id1, id2) }
lineV :: Parser ([GenParticle] -> GenVertex)
lineV = do
char 'V' >> skipSpace
vbcd <- signed decimal <* skipSpace
vid' <- signed decimal <* skipSpace
vx <- double <* skipSpace
vy <- double <* skipSpace
vz <- double <* skipSpace
vctau <- double <* skipSpace
norphans <- decimal <* skipSpace
nouts <- decimal <* skipSpace
nwgts <- decimal
wgts <- replicateM nwgts (skipSpace *> double)
skipTillEnd
return $ \ps -> GenVertex { vbarcode = vbcd
, vid = vid'
, vposition = (vx, vy, vz, vctau)
, numOrphan = norphans
, numOutgoing = nouts
, vWeightList = mkList nwgts wgts
, particles = ps }
lineP :: Parser GenParticle
lineP = do
char 'P' >> skipSpace
pbcd <- decimal <* skipSpace
pid' <- signed decimal <* skipSpace
px <- double <* skipSpace
py <- double <* skipSpace
pz <- double <* skipSpace
pe <- double <* skipSpace
gmass <- double <* skipSpace
scode <- decimal <* skipSpace
polTh <- double <* skipSpace
polPh <- double <* skipSpace
vbcd <- signed decimal <* skipSpace
nflows <- decimal
fList' <- replicateM nflows
((,) <$> (skipSpace *> signed decimal <* skipSpace)
<*> signed decimal)
finalLine >> skipTillEnd
return GenParticle { pbarcode = pbcd
, pdgID = pid'
, pMomentum = (px, py, pz, pe)
, pMass = gmass
, statusCode = scode
, polarization = (polTh, polPh)
, vbarcodeThisIncoming = vbcd
, flows = mkList nflows fList' }
where finalLine = many' $ string "HepMC::IO_GenEvent-END_EVENT_LISTING"
mkList :: Int -> [a] -> Maybe (Int, [a])
mkList n ls = if n > 0 then Just (n, ls) else Nothing
|
cbpark/hep-kinematics
|
src/HEP/Data/HepMC/Parser.hs
|
bsd-3-clause
| 9,249 | 0 | 18 | 3,846 | 2,154 | 1,111 | 1,043 | 197 | 7 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
module IHaskell.Display.Widgets.Selection.SelectMultiple (
-- * The SelectMultiple Widget
SelectMultiple,
-- * Constructor
mkSelectMultiple) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Control.Monad (fmap, join, sequence, void)
import Data.Aeson
import qualified Data.HashMap.Strict as HM
import Data.IORef (newIORef)
import Data.Text (Text)
import qualified Data.Vector as V
import Data.Vinyl (Rec(..), (<+>))
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
import IHaskell.Display.Widgets.Common
-- | A 'SelectMultiple' represents a SelectMultiple widget from IPython.html.widgets.
type SelectMultiple = IPythonWidget SelectMultipleType
-- | Create a new SelectMultiple widget
mkSelectMultiple :: IO SelectMultiple
mkSelectMultiple = do
-- Default properties, with a random uuid
uuid <- U.random
let widgetState = WidgetState $ defaultMultipleSelectionWidget "SelectMultipleView"
stateIO <- newIORef widgetState
let widget = IPythonWidget uuid stateIO
initData = object
[ "model_name" .= str "WidgetModel"
, "widget_class" .= str "IPython.SelectMultiple"
]
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen widget initData $ toJSON widgetState
-- Return the widget
return widget
instance IHaskellDisplay SelectMultiple where
display b = do
widgetSendView b
return $ Display []
instance IHaskellWidget SelectMultiple where
getCommUUID = uuid
comm widget (Object dict1) _ = do
let key1 = "sync_data" :: Text
key2 = "selected_labels" :: Text
Just (Object dict2) = HM.lookup key1 dict1
Just (Array labels) = HM.lookup key2 dict2
labelList = map (\(String x) -> x) $ V.toList labels
opts <- getField widget Options
case opts of
OptionLabels _ -> void $ do
setField' widget SelectedLabels labelList
setField' widget SelectedValues labelList
OptionDict ps ->
case sequence $ map (`lookup` ps) labelList of
Nothing -> return ()
Just valueList -> void $ do
setField' widget SelectedLabels labelList
setField' widget SelectedValues valueList
triggerSelection widget
|
FranklinChen/IHaskell
|
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Selection/SelectMultiple.hs
|
mit
| 2,637 | 0 | 17 | 675 | 556 | 294 | 262 | 56 | 1 |
-- Echo Test Example for Push Notifications.
-- This is a simple example of a Yesod server, where devices can register to receive
-- messages and every time they send a message to the server, they receive an echo response.
{-# LANGUAGE OverloadedStrings, TypeFamilies, TemplateHaskell, FlexibleInstances,
QuasiQuotes, MultiParamTypeClasses, GeneralizedNewtypeDeriving, FlexibleContexts, GADTs #-}
import Yesod
import Database.Persist.Sqlite
import Database.Persist
import Data.Aeson.Types
import Data.Conduit.Pool
import Data.Default
import Data.Functor
import Data.IORef
import Data.Text (Text,pack)
import qualified Data.Map as M
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
import Text.Hamlet.XML
import Text.XML
import Control.Applicative
import Control.Monad (mzero)
import Control.Monad.Trans.Resource (runResourceT)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger
import Network.TLS.Extra (fileReadCertificate,fileReadPrivateKey)
import Network.PushNotify.Gcm
import Network.PushNotify.Apns
import Network.PushNotify.Mpns
import Network.PushNotify.General
import Extra
-- Data Base:
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Devices
identifier Device
UniqueDevice identifier
deriving Show
|]
-- Yesod App:
data Echo = Echo { connectionPool :: ConnectionPool
, pushManager :: PushManager -- Yesod Subsite.
}
mkYesod "Echo" [parseRoutes|
/ PushManagerR PushManager pushManager
|]
-- Instances:
instance Yesod Echo
instance YesodPersist Echo where
type YesodPersistBackend Echo = SqlPersistT
runDB action = do
Echo pool _ <- getYesod
runSqlPool action pool
instance RenderMessage Echo FormMessage where
renderMessage _ _ = defaultFormMessage
main :: IO ()
main = do
runResourceT . runNoLoggingT $ withSqlitePool "DevicesDateBase.db3" 10 $ \pool -> do
runSqlPool (runMigration migrateAll) pool
liftIO $ do
ref <- newIORef Nothing
-- cert <- fileReadCertificate "public-cert.pem" -- your APNS Certificate
-- key <- fileReadPrivateKey "private-key.pem" -- your APNS PrivateKey
man <- startPushService $ PushServiceConfig{
pushConfig = def{
gcmConfig = Just $ Http $ def{apiKey = "apikey"} -- Here you must complete with the
-- correct Api Key.
-- , apnsConfig = Just $ def{environment = Local , apnsCertificate = cert , apnsPrivateKey = key }
, mpnsConfig = Just def
}
, newMessageCallback = handleNewMessage pool ref
, newDeviceCallback = handleNewDevice pool
, unRegisteredCallback = handleUnregistered pool
, newIdCallback = handleNewId pool
}
writeIORef ref $ Just man
warp 3000 $ Echo pool man
where
parsMsg :: Value -> Parser Text
parsMsg (Object v) = v .: "message"
parsMsg _ = mzero
runDBAct p a = runResourceT . runNoLoggingT $ runSqlPool a p
handleNewDevice pool d v = do
device <- runDBAct pool $ getBy $ UniqueDevice d
case device of
Nothing -> do
runDBAct pool $ insert $ Devices d
return SuccessfulReg
Just a -> return $ ErrorReg "User has registered before."
handleNewMessage pool ref d v = do
Just man <- readIORef ref
device <- runDBAct pool $ getBy $ UniqueDevice d
case device of
Nothing -> return ()
Just a -> do
m <- return $ parseMaybe parsMsg v
case m of
Nothing -> return ()
Just msg -> do
let message = def {
gcmNotif = Just $ def {data_object = Just (HM.fromList
[(pack "Message" .= msg)]) }
, mpnsNotif = Just $ def {target = Toast , restXML =
Document (Prologue [] Nothing []) (xmlMessage msg) [] }
, apnsNotif = Just $ def {rest = Just (HM.fromList
[(pack "Message" .= msg)]) } }
sendPush man message $ HS.singleton d
return ()
handleNewId pool (old,new) = do
dev <- runDBAct pool $ getBy $ UniqueDevice old
case dev of
Just x -> runDBAct pool $ update (entityKey (x)) [DevicesIdentifier =. new ]
Nothing -> return ()
handleUnregistered pool d = runDBAct pool $ deleteBy $ UniqueDevice d
xmlMessage msg = Element (Name "Notification" (Just "WPNotification") (Just "wp")) (M.singleton "xmlns:wp" "WPNotification") [xml|
<wp:Toast>
<wp:Text1>New message:
<wp:Text2>#{msg}
<wp:Param>?msg=#{msg}
|]
|
jimpeak/GSoC-Communicating-with-mobile-devices
|
push-notify-general/test/yesodAppEcho.hs
|
mit
| 5,592 | 4 | 33 | 2,159 | 1,118 | 584 | 534 | 92 | 6 |
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.Win32
-- Copyright : (c) Alastair Reid, 1997-2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : Esa Ilari Vuokko <[email protected]>
-- Stability : provisional
-- Portability : portable
--
-- An interface to the Microsoft Windows user interface.
-- See <http://msdn.microsoft.com/library/> under /User Interface Design
-- and Development/ and then /Windows User Interface/ for more details
-- of the underlying library.
--
-----------------------------------------------------------------------------
module Graphics.Win32 (
module System.Win32.Types,
module Graphics.Win32.Control,
module Graphics.Win32.Dialogue,
module Graphics.Win32.GDI,
module Graphics.Win32.Icon,
module Graphics.Win32.Key,
module Graphics.Win32.Menu,
module Graphics.Win32.Message,
module Graphics.Win32.Misc,
module Graphics.Win32.Resource,
module Graphics.Win32.Window
) where
import System.Win32.Types
import Graphics.Win32.Control
import Graphics.Win32.Dialogue
import Graphics.Win32.GDI
import Graphics.Win32.Icon
import Graphics.Win32.Key
import Graphics.Win32.Menu
import Graphics.Win32.Message
import Graphics.Win32.Misc
import Graphics.Win32.Resource
import Graphics.Win32.Window
|
jwiegley/ghc-release
|
libraries/Win32/Graphics/Win32.hs
|
gpl-3.0
| 1,399 | 24 | 5 | 165 | 194 | 135 | 59 | 23 | 0 |
module Main where
-- this is a simple example where lambdas only bind a single variable at a time
-- this directly corresponds to the usual de bruijn presentation
import Data.List (elemIndex)
import Data.Foldable hiding (notElem)
import Data.Maybe (fromJust)
import Data.Traversable
import Control.Monad
import Control.Monad.Trans.Class
import Control.Applicative
import Prelude hiding (foldr,abs)
import Prelude.Extras
import Bound
import System.Exit
infixl 9 :@
data Exp a
= V a
| Exp a :@ Exp a
| Lam (Scope () Exp a)
| Let [Scope Int Exp a] (Scope Int Exp a)
deriving (Eq,Ord,Show,Read)
-- | A smart constructor for Lam
--
-- >>> lam "y" (lam "x" (V "x" :@ V "y"))
-- Lam (Scope (Lam (Scope (V (B ()) :@ V (F (V (B ())))))))
lam :: Eq a => a -> Exp a -> Exp a
lam v b = Lam (abstract1 v b)
-- | A smart constructor for Let bindings
let_ :: Eq a => [(a,Exp a)] -> Exp a -> Exp a
let_ [] b = b
let_ bs b = Let (map (abstr . snd) bs) (abstr b)
where abstr = abstract (`elemIndex` map fst bs)
instance Functor Exp where fmap = fmapDefault
instance Foldable Exp where foldMap = foldMapDefault
instance Applicative Exp where
pure = V
(<*>) = ap
instance Traversable Exp where
traverse f (V a) = V <$> f a
traverse f (x :@ y) = (:@) <$> traverse f x <*> traverse f y
traverse f (Lam e) = Lam <$> traverse f e
traverse f (Let bs b) = Let <$> traverse (traverse f) bs <*> traverse f b
instance Monad Exp where
return = V
V a >>= f = f a
(x :@ y) >>= f = (x >>= f) :@ (y >>= f)
Lam e >>= f = Lam (e >>>= f)
Let bs b >>= f = Let (map (>>>= f) bs) (b >>>= f)
-- these 4 classes are needed to help Eq, Ord, Show and Read pass through Scope
instance Eq1 Exp where (==#) = (==)
instance Ord1 Exp where compare1 = compare
instance Show1 Exp where showsPrec1 = showsPrec
instance Read1 Exp where readsPrec1 = readsPrec
-- | Compute the normal form of an expression
nf :: Exp a -> Exp a
nf e@V{} = e
nf (Lam b) = Lam $ toScope $ nf $ fromScope b
nf (f :@ a) = case whnf f of
Lam b -> nf (instantiate1 a b)
f' -> nf f' :@ nf a
nf (Let bs b) = nf (inst b)
where es = map inst bs
inst = instantiate (es !!)
-- | Reduce a term to weak head normal form
whnf :: Exp a -> Exp a
whnf e@V{} = e
whnf e@Lam{} = e
whnf (f :@ a) = case whnf f of
Lam b -> whnf (instantiate1 a b)
f' -> f' :@ a
whnf (Let bs b) = whnf (inst b)
where es = map inst bs
inst = instantiate (es !!)
infixr 0 !
(!) :: Eq a => a -> Exp a -> Exp a
(!) = lam
-- | Lennart Augustsson's example from "The Lambda Calculus Cooked 4 Ways"
--
-- Modified to use recursive let, because we can.
--
-- >>> nf cooked == true
-- True
true :: Exp String
true = lam "F" $ lam "T" $ V"T"
cooked :: Exp a
cooked = fromJust $ closed $ let_
[ ("False", "f" ! "t" ! V"f")
, ("True", "f" ! "t" ! V"t")
, ("if", "b" ! "t" ! "f" ! V"b" :@ V"f" :@ V"t")
, ("Zero", "z" ! "s" ! V"z")
, ("Succ", "n" ! "z" ! "s" ! V"s" :@ V"n")
, ("one", V"Succ" :@ V"Zero")
, ("two", V"Succ" :@ V"one")
, ("three", V"Succ" :@ V"two")
, ("isZero", "n" ! V"n" :@ V"True" :@ ("m" ! V"False"))
, ("const", "x" ! "y" ! V"x")
, ("Pair", "a" ! "b" ! "p" ! V"p" :@ V"a" :@ V"b")
, ("fst", "ab" ! V"ab" :@ ("a" ! "b" ! V"a"))
, ("snd", "ab" ! V"ab" :@ ("a" ! "b" ! V"b"))
-- we have a lambda calculus extended with recursive bindings, so we don't need to use fix
, ("add", "x" ! "y" ! V"x" :@ V"y" :@ ("n" ! V"Succ" :@ (V"add" :@ V"n" :@ V"y")))
, ("mul", "x" ! "y" ! V"x" :@ V"Zero" :@ ("n" ! V"add" :@ V"y" :@ (V"mul" :@ V"n" :@ V"y")))
, ("fac", "x" ! V"x" :@ V"one" :@ ("n" ! V"mul" :@ V"x" :@ (V"fac" :@ V"n")))
, ("eqnat", "x" ! "y" ! V"x" :@ (V"y" :@ V"True" :@ (V"const" :@ V"False")) :@ ("x1" ! V"y" :@ V"False" :@ ("y1" ! V"eqnat" :@ V"x1" :@ V"y1")))
, ("sumto", "x" ! V"x" :@ V"Zero" :@ ("n" ! V"add" :@ V"x" :@ (V"sumto" :@ V"n")))
-- but we could if we wanted to
-- , ("fix", "g" ! ("x" ! V"g":@ (V"x":@V"x")) :@ ("x" ! V"g":@ (V"x":@V"x")))
-- , ("add", V"fix" :@ ("radd" ! "x" ! "y" ! V"x" :@ V"y" :@ ("n" ! V"Succ" :@ (V"radd" :@ V"n" :@ V"y"))))
-- , ("mul", V"fix" :@ ("rmul" ! "x" ! "y" ! V"x" :@ V"Zero" :@ ("n" ! V"add" :@ V"y" :@ (V"rmul" :@ V"n" :@ V"y"))))
-- , ("fac", V"fix" :@ ("rfac" ! "x" ! V"x" :@ V"one" :@ ("n" ! V"mul" :@ V"x" :@ (V"rfac" :@ V"n"))))
-- , ("eqnat", V"fix" :@ ("reqnat" ! "x" ! "y" ! V"x" :@ (V"y" :@ V"True" :@ (V"const" :@ V"False")) :@ ("x1" ! V"y" :@ V"False" :@ ("y1" ! V"reqnat" :@ V"x1" :@ V"y1"))))
-- , ("sumto", V"fix" :@ ("rsumto" ! "x" ! V"x" :@ V"Zero" :@ ("n" ! V"add" :@ V"x" :@ (V"rsumto" :@ V"n"))))
, ("n5", V"add" :@ V"two" :@ V"three")
, ("n6", V"add" :@ V"three" :@ V"three")
, ("n17", V"add" :@ V"n6" :@ (V"add" :@ V"n6" :@ V"n5"))
, ("n37", V"Succ" :@ (V"mul" :@ V"n6" :@ V"n6"))
, ("n703", V"sumto" :@ V"n37")
, ("n720", V"fac" :@ V"n6")
] (V"eqnat" :@ V"n720" :@ (V"add" :@ V"n703" :@ V"n17"))
-- TODO: use a real pretty printer
prettyPrec :: [String] -> Bool -> Int -> Exp String -> ShowS
prettyPrec _ d n (V a) = showString a
prettyPrec vs d n (x :@ y) = showParen d $
prettyPrec vs False n x . showChar ' ' . prettyPrec vs True n y
prettyPrec (v:vs) d n (Lam b) = showParen d $
showString v . showString ". " . prettyPrec vs False n (instantiate1 (V v) b)
prettyPrec vs d n (Let bs b) = showParen d $
showString "let" . foldr (.) id (zipWith showBinding xs bs) .
showString " in " . indent . prettyPrec ys False n (inst b)
where (xs,ys) = splitAt (length bs) vs
inst = instantiate (\n -> V (xs !! n))
indent = showString ('\n' : replicate (n + 4) ' ')
showBinding x b = indent . showString x . showString " = " . prettyPrec ys False (n + 4) (inst b)
prettyWith :: [String] -> Exp String -> String
prettyWith vs t = prettyPrec (filter (`notElem` toList t) vs) False 0 t ""
pretty :: Exp String -> String
pretty = prettyWith $ [ [i] | i <- ['a'..'z']] ++ [i : show j | j <- [1..], i <- ['a'..'z'] ]
pp :: Exp String -> IO ()
pp = putStrLn . pretty
main = do
pp cooked
let result = nf cooked
if result == true
then putStrLn "Result correct."
else do
putStrLn "Unexpected result:"
pp result
exitFailure
|
bixuanzju/bound
|
examples/Simple.hs
|
bsd-3-clause
| 6,353 | 0 | 16 | 1,641 | 2,651 | 1,356 | 1,295 | 123 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Keymap.Vim.Ex.Commands.Tag
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
module Yi.Keymap.Vim.Ex.Commands.Tag (parse) where
import Control.Applicative (Alternative ((<|>)), (<$>))
import Control.Monad (void)
import Data.Monoid ((<>))
import qualified Data.Text as T (pack)
import qualified Text.ParserCombinators.Parsec as P (GenParser, anyChar, eof,
many1, optionMaybe,
space, string)
import Yi.Keymap (Action (YiA))
import Yi.Keymap.Vim.Common (EventString)
import qualified Yi.Keymap.Vim.Ex.Commands.Common as Common (impureExCommand, parse)
import Yi.Keymap.Vim.Ex.Types (ExCommand (cmdAction, cmdComplete, cmdShow))
import Yi.Keymap.Vim.Tag (completeVimTag, gotoTag, nextTag, unpopTag)
import Yi.Tag (Tag (Tag))
parse :: EventString -> Maybe ExCommand
parse = Common.parse $ do
void $ P.string "t"
parseTag <|> parseNext
parseTag :: P.GenParser Char () ExCommand
parseTag = do
void $ P.string "a"
void . P.optionMaybe $ P.string "g"
t <- P.optionMaybe $ do
void $ P.many1 P.space
P.many1 P.anyChar
case t of
Nothing -> P.eof >> return (tag Nothing)
Just t' -> return $! tag (Just (Tag (T.pack t')))
parseNext :: P.GenParser Char () ExCommand
parseNext = do
void $ P.string "next"
return next
tag :: Maybe Tag -> ExCommand
tag Nothing = Common.impureExCommand {
cmdShow = "tag"
, cmdAction = YiA unpopTag
, cmdComplete = return ["tag"]
}
tag (Just (Tag t)) = Common.impureExCommand {
cmdShow = "tag " <> t
, cmdAction = YiA $ gotoTag (Tag t) 0 Nothing
, cmdComplete = map ("tag " <>) <$> completeVimTag t
}
next :: ExCommand
next = Common.impureExCommand {
cmdShow = "tnext"
, cmdAction = YiA nextTag
, cmdComplete = return ["tnext"]
}
|
TOSPIO/yi
|
src/library/Yi/Keymap/Vim/Ex/Commands/Tag.hs
|
gpl-2.0
| 2,256 | 0 | 18 | 708 | 615 | 351 | 264 | 48 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.