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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
-- cribbed from https://github.com/pyr/apotiki/blob/master/System/Apotiki/Logger.hs
module Soundwave.Logger (start, info, Log) where
import System.IO (openFile, hPutStrLn, hFlush, hClose,
IOMode (AppendMode), Handle)
import Control.Concurrent (forkIO)
import Control.Monad (void, forever)
import Control.Monad.STM (atomically)
import Control.Concurrent.STM.TChan (writeTChan, readTChan, newTChanIO, TChan)
type Log = TChan String
logstdout :: TChan String -> IO ()
logstdout chan = do
line <- atomically $ readTChan chan
putStrLn line
start :: IO (TChan String)
start = do
chan <- newTChanIO
void $ forkIO $ forever $ logstdout chan
return chan
info :: TChan String -> String -> IO ()
info chan msg = do
let info_msg = "[info] " ++ msg
atomically $ writeTChan chan info_msg
|
mrb/soundwave
|
Soundwave/Logger.hs
|
mit
| 811
| 0
| 10
| 143
| 262
| 140
| 122
| 21
| 1
|
-- The result of the problem is: euler6 100 = 25164150
euler6 :: Integer -> Integer
euler6 n = sum [1..n] ** 2 - sum [ x ** 2 | x <- [1..100] ]
|
albertoblaz/ProjectEuler
|
euler6.hs
|
mit
| 143
| 0
| 10
| 33
| 58
| 30
| 28
| 2
| 1
|
module GreetIfCool1 where
greetIfCool :: String -> IO ()
greetIfCool coolness =
if cool
then putStrLn "eyyyyy. What's shakin'?"
else
putStrLn "pshhh."
where cool = coolness == "downright frosty yo"
|
curtisalexander/learning
|
haskell/haskell-book/ch4/ch4-greetIfCool1.hs
|
mit
| 226
| 0
| 7
| 58
| 51
| 27
| 24
| 7
| 2
|
module Language.Lua.Lint.Env where
import Control.Monad.ST (ST)
import Data.STRef
import Control.Applicative
import qualified Data.Map as M
import Data.Maybe (fromJust)
import qualified Data.Graph.Inductive.Graph as G
import qualified Data.Graph.Inductive.PatriciaTree
import Text.Parsec.Pos (SourcePos)
import Language.Lua.AST
import Language.Lua.Type
import Language.Lua.Semantics
import Language.Lua.Lint.Report
data Env = Env {
lintConf :: LintConf,
scopeGraph :: ScopeGraph,
depGraph :: DepGraph,
scratchNodes :: [G.Node],
currentScope :: ScopeGraphNode,
reports :: [Report]}
data LintConf = LintConf { lintConfFunctionThreshold :: Int }
type ScopeGraphNode = G.Node
type ScopeGraph = Data.Graph.Inductive.PatriciaTree.Gr ScopeNode ScopeEdge
type ScopeNode = M.Map ScopeNodeKey ScopeNodeItem
type ScopeNodeKey = String
type ScopeNodeItem = (DepGraphNode, SourcePos, UsageType, [EvalSpec]) -- (depgraph node, type of variable)
type ScopeEdge = ()
type DepGraphNode = G.Node
type DepGraph = Data.Graph.Inductive.PatriciaTree.Gr DepNode DepEdge
type DepNode = (Name, (UsageType, LuaType)) -- (scopegraph node, use|define, type)
type DepEdge = ()
class Inspect a where
inspect :: STRef s Env -> a -> ST s ()
inspectMany :: STRef s Env -> [a] -> ST s ()
inspectMany r = mapM_ (inspect r)
-- initializer
scopeNodeEnv = 0 :: G.Node
scopeNodeGlobal = succ scopeNodeEnv :: G.Node
initialEnv :: Env
initialEnv = Env initialConf initialScopeGraph initialDepGraph [(succ scopeNodeGlobal)..] scopeNodeGlobal []
initialConf :: LintConf
initialConf = LintConf 150
initialScopeGraph :: ScopeGraph
initialScopeGraph = G.mkGraph [(scopeNodeEnv, M.empty), (scopeNodeGlobal, M.empty)] []
initialDepGraph :: DepGraph
initialDepGraph = G.mkGraph [] []
-- conf helper
getConf r = readSTRef r >>= return . lintConf
-- graph helpers: scope graph
readCurrentNode r = readSTRef r >>= return . currentScope
getNodeLabelHere r = readCurrentNode r >>= getNodeLabel r
getNodeLabel r node = readSTRef r >>= \env ->
return . snd . G.labNode' . fromJust $ fst (G.match node (scopeGraph env))
getNodeParent r node = readSTRef r >>= \env ->
case G.pre' . fromJust $ fst (G.match node (scopeGraph env)) of
[] -> return Nothing
[x] -> return (Just x)
_ -> error "multiple parents"
modifyNodeLabelHere r f = readCurrentNode r >>= modifyNodeLabel r f
modifyNodeLabel :: STRef s Env -> (ScopeNode -> ScopeNode) -> G.Node -> ST s ()
modifyNodeLabel r f node =
readSTRef r >>= \env ->
case G.match node (scopeGraph env) of
(Just (pre,node,label,suc), rest) -> modifySTRef r $ \env ->
env {scopeGraph = (pre, node, f label, suc) G.& rest}
_ -> error "target node not found"
inNewScope :: STRef s Env -> ST s () -> ST s ()
inNewScope r c = pushScope r >> c >> popScope r
pushScope r =
createScope r >>= \newNode ->
modifySTRef r (\env ->
env { currentScope = newNode,
scopeGraph = G.insEdge (currentScope env, newNode, ()) (scopeGraph env)}) >>
return newNode
popScope r =
modifySTRef r $ \env ->
case G.pre (scopeGraph env) (currentScope env) of
[parent] -> env { currentScope = parent }
[] -> error "reverting root"
_ -> error "multiple parent"
createScope r = readSTRef r >>= \env ->
let (newNode:restNodes) = scratchNodes env in
writeSTRef r (env {
scopeGraph = G.insNode (newNode, M.empty) (scopeGraph env),
scratchNodes = restNodes}) >>
return newNode
-- graph helpers: dependent graph
addDepNode :: STRef s Env -> Name -> UsageType -> EvalSpec -> ST s DepGraphNode
addDepNode r name usage spec = -- TODO: maybe spec is not necessary
readSTRef r >>= \env ->
let (newNode:restNodes) = scratchNodes env in
writeSTRef r (env {
depGraph = G.insNode (newNode, (name, (usage, fst spec))) (depGraph env),
scratchNodes = restNodes}) >>
return newNode
linkDepNode :: STRef s Env -> G.Node -> Name -> EvalSpec -> ST s ()
linkDepNode r src name spec = addDepNode r name Use spec >>= \newNode ->
modifySTRef r $ \env ->
env { depGraph = G.insEdge (src, newNode, ()) (depGraph env)}
|
ykst/llint
|
Language/Lua/Lint/Env.hs
|
mit
| 4,242
| 0
| 18
| 903
| 1,457
| 785
| 672
| 95
| 3
|
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
-- /Users/evxyz/Library/Haskell/bin/yesod
import Yesod
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET
|]
instance Yesod App
getHomeR = return $ object ["msg" .= "Hello, JsonWorld"]
main = warp 3000 App
|
HaskellForCats/HaskellForCats
|
WarpFunctorOne/warpFunctorJ.hs
|
mit
| 411
| 0
| 8
| 88
| 65
| 37
| 28
| 11
| 1
|
-- delay and combLoop interact appropriately.
module T where
import Prelude hiding ( id )
import Tests.Basis
-- screwed: initialisation is a combinational cycle.
c0 = proc () ->
(| combLoop (\x ->
do x' <- (| delayAC (returnA -< x) (trueA -< ()) |)
dupA -< x' ) |)
prop_correct_c0 = property (\xs -> simulate c0 xs == take (length xs) (bottom : repeat true))
test_constructive_c0 = isNothing (isConstructive c0)
ok_netlist_c0 = runNL c0
-- screwed
c1 = proc () ->
(| combLoop (\x ->
do x' <- (| delayAC (returnA -< x) (trueA -< ()) |)
y' <- (| delayAC (returnA -< x') (trueA -< ()) |)
returnA -< (x', y') ) |)
prop_correct_c1 = property (\xs -> simulate c1 xs == take (length xs) (bottom : repeat true))
test_constructive_c1 = isNothing (isConstructive c1)
ok_netlist_c1 = runNL c1
-- OK
c2 = proc () ->
(| combLoop (\y ->
do x' <- (| delayAC (returnA -< y) (trueA -< ()) |)
y' <- (| delayAC (falseA -< ()) (trueA -< ()) |)
returnA -< (x', y') ) |)
prop_correct_c2 = property (\xs -> simulate c2 xs == take (length xs) (false : repeat true))
test_constructive_c2 = isJust (isConstructive c2)
ok_netlist_c2 = runNL c2
-- OK
c3 = proc () ->
(| combLoop (\x ->
do x' <- (| delayAC (orA <<< id *** trueA -< (x, ())) (trueA -< ()) |)
returnA -< (x', x') ) |)
prop_correct_c3 = property (\xs -> simulate c3 xs == take (length xs) (repeat true))
test_constructive_c3 = isJust (isConstructive c3)
ok_netlist_c3 = runNL c3
-- OK
c4 = proc () ->
do rec x <- (| delayAC (returnA -< y) (trueA -< ()) |)
y <- (| delayAC (falseA -< ()) (trueA -< ()) |)
returnA -< x
prop_correct_c4 = property (\xs -> simulate c4 xs == take (length xs) (false : repeat true))
test_constructive_c4 = isJust (isConstructive c4)
ok_netlist_c4 = runNL c4
-- screwed
c5 = proc () ->
(| combLoop (\x ->
do x' <- (| delayAC (falseA -< ()) (trueA -< ()) |)
y' <- (| delayAC (orA -< (x, x')) (trueA -< ()) |)
returnA -< (x', y') ) |)
prop_correct_c5 = property (\xs -> simulate c5 xs == take (length xs) (false : repeat true))
test_constructive_c5 = isNothing (isConstructive c5)
ok_netlist_c5 = runNL c5
-- screwed: the initialiser blows up.
c6 = proc () ->
(| delayAC (| combLoop (\x -> dupA -< x) |) (trueA -< ()) |)
prop_correct_c6 = property (\xs -> simulate c6 xs == take (length xs) (bottom : repeat true))
test_constructive_c6 = isNothing (isConstructive c6)
ok_netlist_c6 = runNL c6
-- OK: c4 with x initially not y.
c7 = proc () ->
do rec x <- (| delayAC (notA -< y) (trueA -< ()) |)
y <- (| delayAC (falseA -< ()) (trueA -< ()) |)
returnA -< x
prop_correct_c7 = property (\xs -> simulate c7 xs == take (length xs) (repeat true))
test_constructive_c7 = isJust (isConstructive c7)
ok_netlist_c7 = runNL c7
|
peteg/ADHOC
|
Tests/02_SequentialCircuits/005_delay_init_combLoop_nonconstructive.hs
|
gpl-2.0
| 2,941
| 46
| 18
| 766
| 1,337
| 690
| 647
| -1
| -1
|
module Cashlog.Cli.Output where
import Text.Printf
import Cashlog.Data.Connection
import Cashlog.Data.Access
import Cashlog.Cli.Utility
printArticles :: DataHandle
-> IO ()
printArticles handle = do
articles <- prettySelectArticles handle
printf "%24s | %24s | %24s\n" "Bezeichnung" "Vorgabepreis" "Kategorie"
putStrLn $ replicate 80 '-'
mapM_ (\(name, price, catName) -> printf "%24s | %24.2f | %24s\n" name price catName)
articles
printCategories :: DataHandle
-> IO ()
printCategories handle = do
categories <- prettySelectCategories handle
printf "%24s | %24s\n" "Nummer" "Bezeichnung"
putStrLn $ replicate 80 '-'
mapM_ (\(id, name) -> printf "%24d | %24s\n" id name) categories
printShops :: DataHandle
-> IO ()
printShops handle = do
shops <- prettySelectShops handle
printf "%24s | %24s\n" "Geschäft" "Ort"
putStrLn $ replicate 80 '-'
mapM_ (\(name, city) -> printf "%24s | %24s\n" name city) shops
printVouchers :: DataHandle
-> String
-> IO ()
printVouchers handle date = do
vouchers <- prettySelectVouchers handle dateFormat date
printf "%24s | %24s\n" "Datum / Zeit" "Geschäft"
putStrLn $ replicate 80 '-'
mapM_ (\(timestamp, shopName) -> printf "%24s | %24s\n" timestamp shopName)
vouchers
printVoucherPositions :: DataHandle
-> Int
-> IO ()
printVoucherPositions handle key = do
positions <- prettySelectVoucherPositions handle key
let sumPrices = foldl (\a (_, _, p) -> a + p) 0 positions
printf "%24s | %24s | %24s\n" "Artikel" "Menge" "Preis"
putStrLn $ replicate 80 '-'
mapM_ (\(artName, posQuantity, posPrice) ->
printf "%24s | %24.2f | %24.2f\n"
artName
posQuantity
posPrice)
positions
putStrLn ("Gesamtpreis: " ++ (show sumPrices))
|
pads-fhs/Cashlog
|
src/Cashlog/Cli/Output.hs
|
gpl-2.0
| 1,971
| 0
| 13
| 553
| 535
| 262
| 273
| 51
| 1
|
module Core.Scene where
import Core.Types
import Core.Geometry as G
import Core.Geometry (BBox, Ray)
import Core.Light (Light)
import Core.Volume as V
import Core.Volume (VolumeRegion)
import Core.Intersection
import Core.Primitive as P
import Core.Primitive (Aggregate)
data Scene = Scene {
aggregate :: Aggregate,
lights :: [Light],
volumeRegion :: Maybe VolumeRegion,
bound :: BBox
}
create :: Aggregate -> [Light] -> Maybe VolumeRegion -> Scene
create a l vr = Scene {
aggregate = a,
lights = l,
volumeRegion = vr,
bound = b'
}
where b = P.worldBound a
b' = case vr of
Nothing -> b
Just r -> G.union b (V.worldBound r)
intersect :: Scene -> Ray -> Maybe Intersection
intersect (Scene agg _ _ _) = P.intersect agg
intersectP :: Scene -> Ray -> Bool
intersectP (Scene agg _ _ _) = P.intersectP agg
worldBound :: Scene -> BBox
worldBound s = (bound s)
|
dsj36/dropray
|
src/Core/Scene.hs
|
gpl-3.0
| 939
| 0
| 13
| 230
| 333
| 186
| 147
| 31
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Slackware.VersionSpec (spec) where
import qualified Data.Map.Strict as Map
import Slackware.Version
import Test.Hspec (Spec, describe, it)
import Test.Hspec.Megaparsec ( parseSatisfies
, shouldFailOn
, shouldParse
, shouldSucceedOn
)
import Text.Megaparsec (parse)
spec :: Spec
spec
= describe "parse" $ do
it "parses into a valid Version structure" $
let actual = parse versions "" "core:gdm:3.33.92:\n\n"
expected = Map.singleton "gdm" "3.33.92"
in actual `shouldParse` expected
it "parses multiple entries" $
let actual = parse versions "" "core:gdm:3.33.92:\n\
\core:gedit:3.33.92:\n\n"
in actual `parseSatisfies` ((== 2) . length)
it "skips comment line" $
let actual = parse versions "" "core:gdm:3.33.92:\n\n"
expected = Map.singleton "gdm" "3.33.92"
in actual `shouldParse` expected
it "fails on invalid lines" $
let content = "CORE\n\
\core:gdm:3.33.92:\n\n"
in parse versions "" `shouldFailOn` content
it "skips leading comment" $
let content = "## CORE\n\
\core:gdm:3.33.92:\n\n"
in parse versions "" `shouldSucceedOn` content
it "doesn't expect a trailing newline" $
let content = "core:gdm:3.33.92:\n"
in parse versions "" `shouldSucceedOn` content
it "forces parsing till the end of file" $
let content = "core:gdm:3.33.92:\ninvalid-entry\n"
in parse versions "" `shouldFailOn` content
|
Dlackware/dlackware
|
test/Slackware/VersionSpec.hs
|
gpl-3.0
| 1,822
| 0
| 14
| 658
| 354
| 183
| 171
| 36
| 1
|
-- | Channel used for communication between entities within Explorer.
module RSCoin.Explorer.Channel
( ChannelItem (..)
, Channel
, newChannel
, newDummyChannel
, readChannel
, writeChannel
) where
import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)
import Control.Monad.Trans (MonadIO (liftIO))
import qualified RSCoin.Core as C
data ChannelItem = ChannelItem
{ ciTransactions :: ![C.Transaction]
} deriving (Show)
data Channel
= Channel (Chan ChannelItem)
| DummyChannel
newChannel
:: MonadIO m
=> m Channel
newChannel = Channel <$> liftIO newChan
newDummyChannel
:: MonadIO m
=> m Channel
newDummyChannel = pure DummyChannel
readChannel
:: MonadIO m
=> Channel -> m ChannelItem
readChannel (Channel ch) = liftIO $ readChan ch
readChannel DummyChannel =
error "Attempt to use readChannel on DummyChannel is illegal"
writeChannel
:: MonadIO m
=> Channel -> ChannelItem -> m ()
writeChannel (Channel ch) = liftIO . writeChan ch
writeChannel DummyChannel = const $ return ()
|
input-output-hk/rscoin-haskell
|
src/RSCoin/Explorer/Channel.hs
|
gpl-3.0
| 1,136
| 0
| 11
| 286
| 285
| 155
| 130
| 37
| 1
|
{-# LANGUAGE Haskell2010 #-}
module Simplex.ConfigData (
Config (..), defaultConfig
) where
data Config = Config {
doNumberSections :: Bool,
doSectionsCutColumns :: Bool,
doNewPageOnTopLevelHeading :: Bool,
oColumns :: Int,
oFigure :: Bool,
oStandalone :: Bool,
oLetter :: Bool,
oLetterClosing :: String,
oImageWidth :: Maybe String,
oImageHeight :: Maybe String,
oImageScale :: Maybe String,
oImageAngle :: Maybe String,
oImagePage :: Maybe String,
oImageTrim :: Maybe (String, String, String, String)
}
defaultConfig = Config {
doNumberSections = False,
doSectionsCutColumns = True,
doNewPageOnTopLevelHeading = False,
oColumns = 0,
oFigure = False,
oStandalone = False,
oLetter = False,
oLetterClosing = "",
oImageWidth = Nothing,
oImageHeight = Nothing,
oImageScale = Nothing,
oImageAngle = Nothing,
oImagePage = Nothing,
oImageTrim = Nothing
}
|
scravy/simplex
|
src/Simplex/ConfigData.hs
|
gpl-3.0
| 987
| 0
| 10
| 254
| 233
| 148
| 85
| 33
| 1
|
{-# LANGUAGE ScopedTypeVariables #-}
module Math.Structure.Tasty.Ring where
import Prelude hiding ( (+), (-), negate, subtract
, (*), (/), recip, (^), (^^)
, gcd
, quotRem, quot, rem
)
import Data.Maybe
import Data.Proxy
import Numeric.Natural ( Natural(..) )
import Test.Tasty
import Test.Tasty.HUnit
import Test.Natural
import Test.QuickCheck.Arbitrary ()
import Math.Structure.Ring
import Math.Structure.Utility.Tasty
import Math.Structure.Tasty.Additive
import Math.Structure.Tasty.Multiplicative
import Math.Structure.Tasty.NonZero
isSemiring ::
( Testable r, Semiring r )
=> Proxy r -> TestR [TestTree]
isSemiring p = fmap concat $ sequence
[ isAbelianSemigroup p
, isMultiplicativeSemigroup p
, sequence [ isDistributive' p ]
]
isRng ::
( Testable r, Rng r )
=> Proxy r -> TestR [TestTree]
isRng p = fmap concat $ sequence
[ isAbelianGroup p
, isMultiplicativeSemigroup p
, sequence [ isDistributive' p ]
]
isRing ::
( Testable r, Ring r )
=> Proxy r -> TestR [TestTree]
isRing p = fmap concat $ sequence
[ isAbelianGroup p
, isMultiplicativeMonoid p
, sequence [ isDistributive' p ]
]
isEuclideanDomain :: ( Testable a, Testable (NonZero a)
, EuclideanDomain a, DecidableZero a )
=> Proxy a -> TestR [TestTree]
isEuclideanDomain p = fmap concat $ sequence
[ isAbelianGroup p
, isCommutativeMonoid p
, sequence
[ isDistributive' p
, isIntegralDomain' p
, isPIDomain' p
, isEuclideanDomain' p
]
]
isField :: forall a .
( Testable a, Testable (NonZero a)
, Field a, DecidableZero a )
=> Proxy a -> TestR [TestTree]
isField p = fmap concat $ sequence
[ isAbelianGroup p
, isCommutativeGroup (Proxy::Proxy (NonZero a))
, sequence
[ isDistributive' p
, isIntegralDomain' p
]
]
isDistributive' :: forall a .
( Testable a, Distributive a )
=> Proxy a -> TestR TestTree
isDistributive' p = withTestProperty $ \testProperty ->
testProperty "Distributive Magmas" $
\a b c -> (a::a) * ((b::a) + (c::a)) == a*b + a*c &&
(a + b) * c == a*c + b*c
isIntegralDomain' :: forall a .
( Testable a, IntegralDomain a )
=> Proxy a -> TestR TestTree
isIntegralDomain' p = withTestProperty $ \testProperty ->
testProperty "IntegralDomain" $
\a b -> ((a::a)*(b::a)==zero) == (a==zero || b==zero)
isPIDomain' :: forall a .
( Testable a, PIDomain a )
=> Proxy a -> TestR TestTree
isPIDomain' p = withTestProperty $ \testProperty ->
testGroup "PID"
[ testProperty "fst . xgcd = gcd" $
\a b -> let (d,_,_) = xgcd (a::a) (b::a)
in gcd a b == d
, testProperty "xgcd" $
\a b -> let (d,s,t) = xgcd (a::a) (b::a)
in d == a*s + b*t
]
isEuclideanDomain' :: forall a .
( Testable a, Testable (NonZero a)
, EuclideanDomain a, DecidableZero a )
=> Proxy a -> TestR TestTree
isEuclideanDomain' p = withTestProperty $ \testProperty ->
testGroup "Euclidean Domain"
[ testProperty "quotRem" $
\a b -> let b' = fromNonZero (b :: NonZero a)
(q,r) = quotRem (a::a) b'
in r + q*b' == a
, testProperty "quot & rem" $
\a b -> let b' = fromNonZero b :: a
in (quot a b', rem a b') == quotRem (a::a) b'
, testProperty "euclNorm" $
\a -> (isNothing $ euclNorm (a::a)) == (a==zero)
, testProperty "euclNorm for quotRem" $
\a b -> let b' = fromNonZero b :: a
(q,r) = quotRem (a::a) b'
in maybe True (fromJust (euclNorm b') >)
(euclNorm r)
]
|
martinra/algebraic-structures
|
src/Math/Structure/Tasty/Ring.hs
|
gpl-3.0
| 3,830
| 2
| 22
| 1,176
| 1,388
| 742
| 646
| -1
| -1
|
{-
Copyright 2012-2015 Vidar Holen
This file is part of ShellCheck.
http://www.vidarholen.net/contents/shellcheck
ShellCheck 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.
ShellCheck is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module ShellCheck.ASTLib where
import ShellCheck.AST
import Control.Monad
import Data.List
import Data.Maybe
-- Is this a type of loop?
isLoop t = case t of
T_WhileExpression {} -> True
T_UntilExpression {} -> True
T_ForIn {} -> True
T_ForArithmetic {} -> True
T_SelectIn {} -> True
_ -> False
-- Will this split into multiple words when used as an argument?
willSplit x =
case x of
T_DollarBraced {} -> True
T_DollarExpansion {} -> True
T_Backticked {} -> True
T_BraceExpansion {} -> True
T_Glob {} -> True
T_Extglob {} -> True
T_NormalWord _ l -> any willSplit l
_ -> False
isGlob (T_Extglob {}) = True
isGlob (T_Glob {}) = True
isGlob (T_NormalWord _ l) = any isGlob l
isGlob _ = False
-- Is this shell word a constant?
isConstant token =
case token of
T_NormalWord _ l -> all isConstant l
T_DoubleQuoted _ l -> all isConstant l
T_SingleQuoted _ _ -> True
T_Literal _ _ -> True
_ -> False
-- Is this an empty literal?
isEmpty token =
case token of
T_NormalWord _ l -> all isEmpty l
T_DoubleQuoted _ l -> all isEmpty l
T_SingleQuoted _ "" -> True
T_Literal _ "" -> True
_ -> False
-- Quick&lazy oversimplification of commands, throwing away details
-- and returning a list like ["find", ".", "-name", "${VAR}*" ].
oversimplify token =
case token of
(T_NormalWord _ l) -> [concat (concatMap oversimplify l)]
(T_DoubleQuoted _ l) -> [concat (concatMap oversimplify l)]
(T_SingleQuoted _ s) -> [s]
(T_DollarBraced _ _) -> ["${VAR}"]
(T_DollarArithmetic _ _) -> ["${VAR}"]
(T_DollarExpansion _ _) -> ["${VAR}"]
(T_Backticked _ _) -> ["${VAR}"]
(T_Glob _ s) -> [s]
(T_Pipeline _ _ [x]) -> oversimplify x
(T_Literal _ x) -> [x]
(T_SimpleCommand _ vars words) -> concatMap oversimplify words
(T_Redirecting _ _ foo) -> oversimplify foo
(T_DollarSingleQuoted _ s) -> [s]
(T_Annotation _ _ s) -> oversimplify s
-- Workaround for let "foo = bar" parsing
(TA_Sequence _ [TA_Expansion _ v]) -> concatMap oversimplify v
otherwise -> []
-- Turn a SimpleCommand foo -avz --bar=baz into args "a", "v", "z", "bar",
-- each in a tuple of (token, stringFlag).
getFlagsUntil stopCondition (T_SimpleCommand _ _ (_:args)) =
let textArgs = takeWhile (not . stopCondition . snd) $ map (\x -> (x, concat $ oversimplify x)) args in
concatMap flag textArgs
where
flag (x, '-':'-':arg) = [ (x, takeWhile (/= '=') arg) ]
flag (x, '-':args) = map (\v -> (x, [v])) args
flag _ = []
getFlagsUntil _ _ = error "Internal shellcheck error, please report! (getFlags on non-command)"
-- Get all flags in a GNU way, up until --
getAllFlags = getFlagsUntil (== "--")
-- Get all flags in a BSD way, up until first non-flag argument
getLeadingFlags = getFlagsUntil (not . ("-" `isPrefixOf`))
-- Given a T_DollarBraced, return a simplified version of the string contents.
bracedString (T_DollarBraced _ l) = concat $ oversimplify l
bracedString _ = error "Internal shellcheck error, please report! (bracedString on non-variable)"
-- Is this an expansion of multiple items of an array?
isArrayExpansion t@(T_DollarBraced _ _) =
let string = bracedString t in
"@" `isPrefixOf` string ||
not ("#" `isPrefixOf` string) && "[@]" `isInfixOf` string
isArrayExpansion _ = False
-- Is it possible that this arg becomes multiple args?
mayBecomeMultipleArgs t = willBecomeMultipleArgs t || f t
where
f t@(T_DollarBraced _ _) =
let string = bracedString t in
"!" `isPrefixOf` string
f (T_DoubleQuoted _ parts) = any f parts
f (T_NormalWord _ parts) = any f parts
f _ = False
-- Is it certain that this word will becomes multiple words?
willBecomeMultipleArgs t = willConcatInAssignment t || f t
where
f (T_Extglob {}) = True
f (T_Glob {}) = True
f (T_BraceExpansion {}) = True
f (T_DoubleQuoted _ parts) = any f parts
f (T_NormalWord _ parts) = any f parts
f _ = False
-- This does token cause implicit concatenation in assignments?
willConcatInAssignment token =
case token of
t@(T_DollarBraced {}) -> isArrayExpansion t
(T_DoubleQuoted _ parts) -> any willConcatInAssignment parts
(T_NormalWord _ parts) -> any willConcatInAssignment parts
_ -> False
-- Maybe get the literal string corresponding to this token
getLiteralString :: Token -> Maybe String
getLiteralString = getLiteralStringExt (const Nothing)
-- Definitely get a literal string, skipping over all non-literals
onlyLiteralString :: Token -> String
onlyLiteralString = fromJust . getLiteralStringExt (const $ return "")
-- Maybe get a literal string, but only if it's an unquoted argument.
getUnquotedLiteral (T_NormalWord _ list) =
liftM concat $ mapM str list
where
str (T_Literal _ s) = return s
str _ = Nothing
getUnquotedLiteral _ = Nothing
-- Maybe get the literal string of this token and any globs in it.
getGlobOrLiteralString = getLiteralStringExt f
where
f (T_Glob _ str) = return str
f _ = Nothing
-- Maybe get the literal value of a token, using a custom function
-- to map unrecognized Tokens into strings.
getLiteralStringExt :: (Token -> Maybe String) -> Token -> Maybe String
getLiteralStringExt more = g
where
allInList = liftM concat . mapM g
g (T_DoubleQuoted _ l) = allInList l
g (T_DollarDoubleQuoted _ l) = allInList l
g (T_NormalWord _ l) = allInList l
g (TA_Expansion _ l) = allInList l
g (T_SingleQuoted _ s) = return s
g (T_Literal _ s) = return s
g x = more x
-- Is this token a string literal?
isLiteral t = isJust $ getLiteralString t
-- Turn a NormalWord like foo="bar $baz" into a series of constituent elements like [foo=,bar ,$baz]
getWordParts (T_NormalWord _ l) = concatMap getWordParts l
getWordParts (T_DoubleQuoted _ l) = l
getWordParts other = [other]
-- Return a list of NormalWords that would result from brace expansion
braceExpand (T_NormalWord id list) = take 1000 $ do
items <- mapM part list
return $ T_NormalWord id items
where
part (T_BraceExpansion id items) = do
item <- items
braceExpand item
part x = return x
-- Maybe get the command name of a token representing a command
getCommandName t =
case t of
T_Redirecting _ _ w -> getCommandName w
T_SimpleCommand _ _ (w:_) -> getLiteralString w
T_Annotation _ _ t -> getCommandName t
otherwise -> Nothing
-- Get the basename of a token representing a command
getCommandBasename = liftM basename . getCommandName
where
basename = reverse . takeWhile (/= '/') . reverse
isAssignment t =
case t of
T_Redirecting _ _ w -> isAssignment w
T_SimpleCommand _ (w:_) [] -> True
T_Assignment {} -> True
T_Annotation _ _ w -> isAssignment w
otherwise -> False
isFunction t = case t of T_Function {} -> True; _ -> False
-- Get the list of commands from tokens that contain them, such as
-- the body of while loops and if statements.
getCommandSequences t =
case t of
T_Script _ _ cmds -> [cmds]
T_BraceGroup _ cmds -> [cmds]
T_Subshell _ cmds -> [cmds]
T_WhileExpression _ _ cmds -> [cmds]
T_UntilExpression _ _ cmds -> [cmds]
T_ForIn _ _ _ cmds -> [cmds]
T_ForArithmetic _ _ _ _ cmds -> [cmds]
T_IfExpression _ thens elses -> map snd thens ++ [elses]
otherwise -> []
|
david-caro/shellcheck
|
ShellCheck/ASTLib.hs
|
gpl-3.0
| 8,415
| 0
| 15
| 2,108
| 2,236
| 1,126
| 1,110
| 154
| 16
|
-- * base
import Control.Monad (when)
-- import Debug.Trace (trace)
import System.Environment (getArgs, getProgName)
-- * gloss
import Graphics.Gloss (Display(InWindow), white)
import Graphics.Gloss.Interface.Pure.Simulate (ViewPort, simulate)
-- * elevators
import Elevators.Building
import Elevators.Graphics
import Elevators.Logic
--------------------------------------------------------------------------------
nFloors :: Int
nFloors = 14
nElevators :: Int
nElevators = 2
--------------------------------------------------------------------------------
main :: IO ()
main = do
args <- getArgs
progName <- getProgName
when (null args) (error $ "usage: " ++ progName ++ " filename")
orders <- readOrders (head args)
putStrLn "orders:\n"
mapM_ (putStrLn . show) orders
let
els = map (\i -> MkElevator i 1 []) [1 .. nElevators]
b0 = MkBuilding nFloors els orders [] [] 0.1 0 0 :: Building
simulate (InWindow "Building"
(windowWidthInt, windowHtInt)
(windowWidthInt `div` 2, windowHtInt `div` 2)
)
white
4
b0
drawBuilding
simulateBuilding
simulateBuilding :: ViewPort -> Float -> Building -> Building
simulateBuilding _ time b0
-- If enough time has passed then it's time to step the world.
-- | trace ("simulateBuilding: \n" ++ show b0 ++ "\n") False = undefined
| bElapsedStepTime b0 >= (bSimPeriod b0)
= let b1 = stepBuilding b0
in b1 { bElapsedStepTime = 0
, bElapsedTotalTime = bElapsedTotalTime b0 + time}
-- Wait some more.
| otherwise
= b0 { bElapsedStepTime = bElapsedStepTime b0 + time
, bElapsedTotalTime = bElapsedTotalTime b0 + time
}
|
tdox/elevators
|
elevators.hs
|
gpl-3.0
| 1,843
| 4
| 14
| 510
| 436
| 234
| 202
| 39
| 1
|
module Rewrite (rewrite, rewrite', match, Rule) where
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Monad (liftM2, mplus, msum, guard)
import Data.Maybe (isJust)
import Arbitrary
import Parser
import Syntax
import Util
type Rule = (Term, Term)
type Binding = Map String Term
rewrite :: [Rule] -> Term -> Term
rewrite rules t = case msum matches of
Just t' -> rewrite rules t'
Nothing -> t
where matches = map (\rule -> matchbind rule t) rules
rewrite' :: [Rule] -> Term -> Term
rewrite' rules t = rewrite rules (recur (rewrite rules t))
where walk t = rewrite' rules t
recur a@(Atom _) = a
recur (Not t) = Not $ walk t
recur (OfCourse t) = OfCourse $ walk t
recur (WhyNot t) = WhyNot $ walk t
recur (a :*: b) = walk a :*: walk b
recur (a :$: b) = walk a :$: walk b
--recur (a :-@: b) = walk a :-@: walk b
recur ((:-@:) a b d) = (:-@:) (walk a) (walk b) d
recur (a :&: b) = walk a :&: walk b
recur (a :+: b) = walk a :+: walk b
recur t = t
matchbind :: (Term, Term) -> Term -> Maybe Term
matchbind (pattern, replace) t =
do binding <- match pattern t
return (bind binding replace)
merge :: (Ord a, Eq b) => Maybe (Map a b) -> Maybe (Map a b) -> Maybe (Map a b)
merge mx my = do x <- mx
y <- my
guard (compatible x y)
return (x `Map.union` y)
compatible x y = allTrue (Map.intersectionWith (==) x y)
where allTrue = Map.fold (&&) True
crossMatch (a, b) (c, d) = x `mplus` y
where
x = match a c `merge` match b d
y = match a d `merge` match b c
match :: Term -> Term -> Maybe Binding
match (Atom s) t = Just (Map.singleton s t)
match (Not a) (Not b) = match a b
match (OfCourse a) (OfCourse b) = match a b
match (WhyNot a) (WhyNot b) = match a b
match (a :*: b) (c :*: d) = crossMatch (a, b) (c, d)
match (a :$: b) (c :$: d) = crossMatch (a, b) (c, d)
match (a :&: b) (c :&: d) = crossMatch (a, b) (c, d)
match (a :+: b) (c :+: d) = crossMatch (a, b) (c, d)
--match (a :-@: b) (c :-@: d) = match a c `merge` match b d
match ((:-@:) a b _) ((:-@:) c d _) = match a c `merge` match b d
match Top Top = Just Map.empty
match Bottom Bottom = Just Map.empty
match One One = Just Map.empty
match Zero Zero = Just Map.empty
match _ _ = Nothing
prop_match_reflixish t = isJust (match t t)
bind :: Binding -> Term -> Term
bind b t = termMap binding t
where binding a@(Atom s) =
case Map.lookup s b of
Just t -> t
Nothing -> a
|
jff/TeLLer
|
src/Rewrite.hs
|
gpl-3.0
| 2,695
| 0
| 10
| 856
| 1,266
| 657
| 609
| 65
| 10
|
-- Copyright 2014 by Mark Watson. All rights reserved. The software and data in this project can be used under the terms of the GPL version 3 license.
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
import Yesod
import qualified Data.Text as T
import Text.Read (readMaybe)
import Data.Maybe (fromMaybe)
--import Control.Monad (liftM)
--import Control.Monad.Exception.Synchronous (catch, runExceptionalT, Exceptional(Exception), Exceptional(Success))
import Yesod.Core.Types (Logger)
import System.IO (readLn)
import Utils (splitWordsKeepCase, cleanText)
import Categorize
import Entities
import Summarize
--import OpenCalais
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET POST
|]
instance Yesod App
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
readSession :: Read a => T.Text -> Handler (Maybe a)
readSession name = do
textValue <- lookupSession name
return (readMaybe . T.unpack =<< textValue)
getHomeR :: Handler Html
getHomeR = defaultLayout $ do
setTitle "Haskell Categorization Demo"
categories <- lookupSession "categories"
humanNames <- lookupSession "humanNames"
countryNames <- lookupSession "countryNames"
cityNames <- lookupSession "cityNames"
companyNames <- lookupSession "companyNames"
broadcastNetworkNames <- lookupSession "broadcastNetworkNames"
musicGroupNames <- lookupSession "musicGroupNames"
politicalPartyNames <- lookupSession "politicalPartyNames"
tradeUnionNames <- lookupSession "tradeUnionNames"
universityNames <- lookupSession "universityNames"
summary <- lookupSession "summary"
summary_s <- lookupSession "summary_s"
--calais <- lookupSession "calais"
the_text <- lookupSession "the_text"
deleteSession "categories"
deleteSession "humanNames"
deleteSession "countryNames"
deleteSession "cityNames"
deleteSession "companyNames"
deleteSession "broadcastNetworkNames"
deleteSession "musicGroupNames"
deleteSession "politicalPartyNames"
deleteSession "tradeUnionNames"
deleteSession "universityNames"
deleteSession "summary"
deleteSession "summary_s"
--deleteSession "calais"
deleteSession "the_text"
toWidget [lucius|
body { margin:0.7cm 1cm 1cm 1cm; }
|]
[whamlet|
<h2>This is a test of an initial port of KnowledgeBooks Natural Language Processing (NLP) code to Haskell
<p>This system attempts to resolve entity references to Wikipedia/DBPedia subject URIs.
<h4>Enter plain text (no special characters):
<form method=post>
<textarea type=text name=name rows="6" cols="70">
<br>
<br>
<input type=submit value="Process text">
<br>
<p>
<i>Note: if you don't see any results the cause is special characters (e.g., fancy quotes and other unicode characters) in the input text.
<p>#{fromMaybe "" the_text}
<h4>Summary of text:
<p>#{fromMaybe "" summary_s}
<h4>Category results from combined 1gram and 2gram analysis:
<p>#{fromMaybe "" categories}
<h4>Human names found in text:
<p>#{fromMaybe "" humanNames}
<h4>Country names found in text:
<p>#{fromMaybe "" countryNames}
<h4>City names found in text:
<p>#{fromMaybe "" cityNames}
<h4>Company names found in text:
<p>#{fromMaybe "" companyNames}
<h4>Braodcast network names found in text:
<p>#{fromMaybe "" broadcastNetworkNames}
<h4>Music group names found in text:
<p>#{fromMaybe "" musicGroupNames}
<h4>Political party names found in text:
<p>#{fromMaybe "" politicalPartyNames}
<h4>Trade union names found in text:
<p>#{fromMaybe "" tradeUnionNames}
<h4>University names found in text:
<p>#{fromMaybe "" universityNames}
<h4>Summary of text, with scoring:
<p>#{fromMaybe "" summary}
<br>
<br>
<div>
<p>Compared to previous versions written in Common Lisp, Scheme, Java, and Clojure the code is very compact. The current code size is:
<ul>
<li>Yesod web app: 110 lines
<li>NLP code: 550 lines
<p>
<i>Copyright 2014 Mark Watson.
|]
postHomeR :: Handler ()
postHomeR = do
name <- runInputPost $ ireq textField "name"
--calais <- lift $ calaisResults $ T.unpack name
setSession "categories" $ T.pack $ (show $ bestCategories $ splitWords $ cleanText $ T.unpack name)
setSession "humanNames" $ T.pack $ (show $ peopleNames $ splitWordsKeepCase $ cleanText $ T.unpack name)
setSession "countryNames" $ T.pack $ (show $ countryNames $ splitWordsKeepCase $ cleanText $ T.unpack name)
setSession "cityNames" $ T.pack $ (show $ cityNames $ splitWordsKeepCase $ cleanText $ T.unpack name)
setSession "companyNames" $ T.pack $ (show $ companyNames $ splitWordsKeepCase $ cleanText $ T.unpack name)
setSession "broadcastNetworkNames" $ T.pack $ (show $ broadcastNetworkNames $ splitWordsKeepCase $ cleanText $ T.unpack name)
setSession "musicGroupNames" $ T.pack $ (show $ musicGroupNames $ splitWordsKeepCase $ cleanText $ T.unpack name)
setSession "politicalPartyNames" $ T.pack $ (show $ politicalPartyNames $ splitWordsKeepCase $ cleanText $ T.unpack name)
setSession "tradeUnionNames" $ T.pack $ (show $ tradeUnionNames $ splitWordsKeepCase $ cleanText $ T.unpack name)
setSession "universityNames" $ T.pack $ (show $ universityNames $ splitWordsKeepCase $ cleanText $ T.unpack name)
setSession "summary" $ T.pack $ (show $ summarize $ cleanText $ T.unpack name)
--setSession "calais" $ T.pack calais
setSession "summary_s" $ T.pack $ (show $ summarize_s $ cleanText $ T.unpack name)
setSession "the_text" name
redirectUltDest HomeR
main :: IO ()
main = warp 3000 App
|
mark-watson/kbnlp.hs
|
WebApp.hs
|
agpl-3.0
| 5,901
| 0
| 12
| 1,175
| 981
| 467
| 514
| 74
| 1
|
{-# LANGUAGE DoAndIfThenElse #-}
module Main where
import System.Environment
import System.Console.Readline
import System.IO
import Control.Monad
import Parse
import Eval
import AST
import Error
main :: IO ()
main = do
args <- getArgs
if null args then runRepl else runOne $ args
flushStr :: String -> IO ()
flushStr str = putStr str >> hFlush stdout
readPrompt :: String -> IO String
-- readPrompt prompt = flushStr prompt >> getLine
readPrompt prompt = do l <- readline prompt
case l of
Just line -> do addHistory line
return line
Nothing -> readPrompt prompt
evalString :: Env -> String -> IO String
evalString env expr = runIOThrows $ liftM show $ (liftThrows $ readExpr expr) >>=
eval env
evalAndPrint :: Env -> String -> IO ()
evalAndPrint env expr = evalString env expr >>= putStrLn
until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m ()
until_ p prompt action = do
result <- prompt
if p result
then return ()
else action result >> until_ p prompt action
runOne :: [String] -> IO ()
runOne args = do
env <- primitiveBindings >>= flip bindVars [("args", List $ map String $ drop 1 args)]
(runIOThrows $ liftM show $ eval env (List [Atom "load", String (args !! 0)]))
>>= hPutStrLn stderr
runRepl :: IO ()
runRepl = primitiveBindings >>= until_ (== "quit") (readPrompt "Lisp>>> ") . evalAndPrint
|
kkspeed/SICP-Practise
|
Interpreter/code/Main.hs
|
lgpl-3.0
| 1,472
| 0
| 16
| 397
| 530
| 262
| 268
| 40
| 2
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-
Copyright 2019 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module CodeWorld.Picture where
import CodeWorld.Color
import Control.DeepSeq
import Data.List
import Data.Monoid ((<>))
import Data.Text (Text)
import GHC.Generics (Generic)
import GHC.Stack
import Util.EmbedAsUrl
-- | A point in two dimensions. A point is written with the x coordinate
-- first, and the y coordinate second. For example, (3, -2) is the point
-- with x coordinate 3 a y coordinate -2.
type Point = (Double, Double)
-- | Moves a given point by given x and y offsets
--
-- >>> translatedPoint 1 2 (10, 10)
-- (11.0, 12.0)
-- >>> translatedPoint (-1) (-2) (0, 0)
-- (-1.0, -2.0)
translatedPoint :: Double -> Double -> Point -> Point
translatedPoint tx ty (x, y) = (x + tx, y + ty)
-- | Rotates a given point by given angle, in radians
--
-- >>> rotatedPoint 45 (10, 0)
-- (7.071, 7.071)
rotatedPoint :: Double -> Point -> Point
rotatedPoint = rotatedVector
-- | Reflects a given point across a line through the origin at this
-- angle, in radians. For example, an angle of 0 reflects the point
-- vertically across the x axis, while an angle of @pi / 2@ reflects the
-- point horizontally across the y axis.
reflectedPoint :: Double -> Point -> Point
reflectedPoint th (x, y) = (x * cos a + y * sin a, x * sin a - y * cos a)
where a = 2 * th
-- | Scales a given point by given x and y scaling factor. Scaling by a
-- negative factor also reflects across that axis.
--
-- >>> scaledPoint 2 3 (10, 10)
-- (20, 30)
scaledPoint :: Double -> Double -> Point -> Point
scaledPoint kx ky (x, y) = (kx * x, ky * y)
-- | Dilates a given point by given uniform scaling factor. Dilating by a
-- negative factor also reflects across the origin.
--
-- >>> dilatedPoint 2 (10, 10)
-- (20, 20)
dilatedPoint :: Double -> Point -> Point
dilatedPoint k (x, y) = (k * x, k * y)
-- | A two-dimensional vector
type Vector = (Double, Double)
-- | The length of the given vector.
--
-- >>> vectorLength (10, 10)
-- 14.14
vectorLength :: Vector -> Double
vectorLength (x, y) = sqrt (x*x + y*y)
-- | The counter-clockwise angle, in radians, that a given vector make with the X-axis
--
-- >>> vectorDirection (1,0)
-- 0.0
-- >>> vectorDirection (1,1)
-- 0.7853981633974483
-- >>> vectorDirection (0,1)
-- 1.5707963267948966
vectorDirection :: Vector -> Double
vectorDirection (x, y) = atan2 y x
-- | The sum of two vectors
vectorSum :: Vector -> Vector -> Vector
vectorSum (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
-- | The difference of two vectors
vectorDifference :: Vector -> Vector -> Vector
vectorDifference (x1, y1) (x2, y2) = (x1 - x2, y1 - y2)
-- | Scales a given vector by a given scalar multiplier.
--
-- >>> scaledPoint 2 (10, 10)
-- (20, 20)
scaledVector :: Double -> Vector -> Vector
scaledVector k (x, y) = (k * x, k * y)
-- | Rotates a given vector by a given angle in radians
--
-- >>> rotatedVector pi (1.0, 0.0)
-- (-1.0, 1.2246467991473532e-16)
-- >>> rotatedVector (pi / 2) (1.0, 0.0)
-- (6.123233995736766e-17, 1.0)
rotatedVector :: Double -> Vector -> Vector
rotatedVector angle (x, y) =
(x * cos angle - y * sin angle, x * sin angle + y * cos angle)
-- | The dot product of two vectors
dotProduct :: Vector -> Vector -> Double
dotProduct (x1, y1) (x2, y2) = x1 * x2 + y1 * y2
-- | A design, diagram, or drawing that can be displayed and seen.
-- In technical terms, a picture is an assignment of a color to
-- every point of the coordinate plane. CodeWorld contains functions
-- to create pictures from simple geometry primitives, to transform
-- existing pictures, and to combine simpler pictures into more
-- complex compositions.
--
-- Ultimately, a picture can be drawn on the screen using one of the
-- CodeWorld entry points such as 'drawingOf'.
data Picture
= SolidPolygon (Maybe SrcLoc) [Point]
| SolidClosedCurve (Maybe SrcLoc) [Point]
| Polygon (Maybe SrcLoc) [Point]
| ThickPolygon (Maybe SrcLoc) [Point] !Double
| Rectangle (Maybe SrcLoc) !Double !Double
| SolidRectangle (Maybe SrcLoc) !Double !Double
| ThickRectangle (Maybe SrcLoc) !Double !Double !Double
| ClosedCurve (Maybe SrcLoc) [Point]
| ThickClosedCurve (Maybe SrcLoc) [Point] !Double
| Polyline (Maybe SrcLoc) [Point]
| ThickPolyline (Maybe SrcLoc) [Point] !Double
| Curve (Maybe SrcLoc) [Point]
| ThickCurve (Maybe SrcLoc) [Point] !Double
| Circle (Maybe SrcLoc) !Double
| SolidCircle (Maybe SrcLoc) !Double
| ThickCircle (Maybe SrcLoc) !Double !Double
| Sector (Maybe SrcLoc) !Double !Double !Double
| Arc (Maybe SrcLoc) !Double !Double !Double
| ThickArc (Maybe SrcLoc) !Double !Double !Double !Double
| StyledLettering (Maybe SrcLoc) !TextStyle !Font !Text
| Lettering (Maybe SrcLoc) !Text
| Color (Maybe SrcLoc) !Color !Picture
| Translate (Maybe SrcLoc) !Double !Double !Picture
| Scale (Maybe SrcLoc) !Double !Double !Picture
| Dilate (Maybe SrcLoc) !Double !Picture
| Rotate (Maybe SrcLoc) !Double !Picture
| Reflect (Maybe SrcLoc) !Double !Picture
| Clip (Maybe SrcLoc) !Double !Double !Picture
| CoordinatePlane (Maybe SrcLoc)
| Sketch (Maybe SrcLoc) !Text !Text !Double !Double
| Pictures (Maybe SrcLoc) [Picture]
| PictureAnd (Maybe SrcLoc) [Picture]
| Blank (Maybe SrcLoc)
deriving (Generic)
instance NFData Picture
-- A style in which to draw lettering. Either 'Plain', 'Bold', or
-- 'Italic'
data TextStyle
= Plain -- ^ Plain letters with no style
| Bold -- ^ Heavy, thick lettering used for emphasis
| Italic -- ^ Slanted script-like lettering used for emphasis
deriving (Generic, Show)
instance NFData TextStyle
-- A font in which to draw lettering. There are several built-in
-- font families ('SansSerif', 'Serif', 'Monospace', 'Handwriting',
-- and 'Fancy') that can look different on each screen. 'NamedFont'
-- can be used for a specific font. However, if the font is not
-- installed on the computer running your program, a different font
-- may be used instead.
data Font
= SansSerif
| Serif
| Monospace
| Handwriting
| Fancy
| NamedFont !Text
deriving (Generic, Show)
instance NFData Font
-- | A blank picture
blank :: HasCallStack => Picture
blank = Blank (getDebugSrcLoc callStack)
-- | A thin sequence of line segments, with these points as endpoints
polyline :: HasCallStack => [Point] -> Picture
polyline ps = Polyline (getDebugSrcLoc callStack) ps
-- | A thin sequence of line segments, with these points as endpoints
path :: HasCallStack => [Point] -> Picture
path ps = Polyline (getDebugSrcLoc callStack) ps
{-# WARNING path ["Please use polyline instead of path.",
"path may be removed July 2020."] #-}
-- | A thick sequence of line segments, with given line width and endpoints
thickPolyline :: HasCallStack => Double -> [Point] -> Picture
thickPolyline n ps = ThickPolyline (getDebugSrcLoc callStack) ps n
-- | A thick sequence of line segments, with given line width and endpoints
thickPath :: HasCallStack => Double -> [Point] -> Picture
thickPath n ps = ThickPolyline (getDebugSrcLoc callStack) ps n
{-# WARNING thickPath ["Please used thickPolyline instead of thickPath.",
"thickPath may be removed July 2020."] #-}
-- | A thin polygon with these points as vertices
polygon :: HasCallStack => [Point] -> Picture
polygon ps = Polygon (getDebugSrcLoc callStack) ps
-- | A thick polygon with this line width and these points as
-- vertices
thickPolygon :: HasCallStack => Double -> [Point] -> Picture
thickPolygon n ps = ThickPolygon (getDebugSrcLoc callStack) ps n
-- | A solid polygon with these points as vertices
solidPolygon :: HasCallStack => [Point] -> Picture
solidPolygon ps = SolidPolygon (getDebugSrcLoc callStack) ps
-- | A smooth curve passing through these points.
curve :: HasCallStack => [Point] -> Picture
curve ps = Curve (getDebugSrcLoc callStack) ps
-- | A thick smooth curve with this line width, passing through these points.
thickCurve :: HasCallStack => Double -> [Point] -> Picture
thickCurve n ps = ThickCurve (getDebugSrcLoc callStack) ps n
-- | A smooth closed curve passing through these points.
closedCurve :: HasCallStack => [Point] -> Picture
closedCurve ps = ClosedCurve (getDebugSrcLoc callStack) ps
-- | A thick smooth closed curve with this line width, passing through these points.
thickClosedCurve :: HasCallStack => Double -> [Point] -> Picture
thickClosedCurve n ps = ThickClosedCurve (getDebugSrcLoc callStack) ps n
-- | A solid smooth closed curve passing through these points.
solidClosedCurve :: HasCallStack => [Point] -> Picture
solidClosedCurve ps = SolidClosedCurve (getDebugSrcLoc callStack) ps
rectangleVertices :: Double -> Double -> [Point]
rectangleVertices w h = [ (w / 2, h / 2), (w / 2, -h / 2), (-w / 2, -h / 2), (-w / 2, h / 2) ]
-- | A thin rectangle, with this width and height
rectangle :: HasCallStack => Double -> Double -> Picture
rectangle w h = Rectangle (getDebugSrcLoc callStack) w h
-- | A solid rectangle, with this width and height
solidRectangle :: HasCallStack => Double -> Double -> Picture
solidRectangle w h = SolidRectangle (getDebugSrcLoc callStack) w h
-- | A thick rectangle, with this line width, and width and height
thickRectangle :: HasCallStack => Double -> Double -> Double -> Picture
thickRectangle lw w h = ThickRectangle (getDebugSrcLoc callStack) lw w h
-- | A thin circle, with this radius
circle :: HasCallStack => Double -> Picture
circle = Circle (getDebugSrcLoc callStack)
-- | A thick circle, with this line width and radius
thickCircle :: HasCallStack => Double -> Double -> Picture
thickCircle = ThickCircle (getDebugSrcLoc callStack)
-- | A thin arc, starting and ending at these angles, with this radius
--
-- Angles are in radians.
arc :: HasCallStack => Double -> Double -> Double -> Picture
arc b e r = Arc (getDebugSrcLoc callStack) b e r
-- | A thick arc with this line width, starting and ending at these angles,
-- with this radius.
--
-- Angles are in radians.
thickArc :: HasCallStack => Double -> Double -> Double -> Double -> Picture
thickArc w b e r = ThickArc (getDebugSrcLoc callStack) b e r w
-- | A solid circle, with this radius
solidCircle :: HasCallStack => Double -> Picture
solidCircle = SolidCircle (getDebugSrcLoc callStack)
-- | A solid sector of a circle (i.e., a pie slice) starting and ending at these
-- angles, with this radius
--
-- Angles are in radians.
sector :: HasCallStack => Double -> Double -> Double -> Picture
sector = Sector (getDebugSrcLoc callStack)
-- | A rendering of text characters.
text :: HasCallStack => Text -> Picture
text = Lettering (getDebugSrcLoc callStack)
{-# WARNING text ["Please used lettering instead of text.",
"text may be removed July 2020."] #-}
-- | A rendering of text characters.
lettering :: HasCallStack => Text -> Picture
lettering = Lettering (getDebugSrcLoc callStack)
-- | A rendering of text characters, with a specific choice of font and style.
styledText :: HasCallStack => TextStyle -> Font -> Text -> Picture
styledText = StyledLettering (getDebugSrcLoc callStack)
{-# WARNING styledText ["Please used styledLettering instead of styledText.",
"styledText may be removed July 2020."] #-}
-- | A rendering of text characters onto a Picture, with a specific
-- choice of font and style.
styledLettering :: HasCallStack => TextStyle -> Font -> Text -> Picture
styledLettering = StyledLettering (getDebugSrcLoc callStack)
-- | A picture drawn entirely in this color.
colored :: HasCallStack => Color -> Picture -> Picture
colored = Color (getDebugSrcLoc callStack)
-- | A picture drawn entirely in this colour.
coloured :: HasCallStack => Color -> Picture -> Picture
coloured = colored
-- | A picture drawn translated in these directions.
translated :: HasCallStack => Double -> Double -> Picture -> Picture
translated = Translate (getDebugSrcLoc callStack)
-- | A picture scaled by these factors in the x and y directions. Scaling
-- by a negative factoralso reflects across that axis.
scaled :: HasCallStack => Double -> Double -> Picture -> Picture
scaled = Scale (getDebugSrcLoc callStack)
-- | A picture scaled uniformly in all directions by this scale factor.
-- Dilating by a negative factor also reflects across the origin.
dilated :: HasCallStack => Double -> Picture -> Picture
dilated = Dilate (getDebugSrcLoc callStack)
-- | A picture rotated by this angle about the origin.
--
-- Angles are in radians.
rotated :: HasCallStack => Double -> Picture -> Picture
rotated = Rotate (getDebugSrcLoc callStack)
-- | A picture reflected across a line through the origin at this angle, in
-- radians. For example, an angle of 0 reflects the picture vertically
-- across the x axis, while an angle of @pi / 2@ reflects the picture
-- horizontally across the y axis.
reflected :: HasCallStack => Double -> Picture -> Picture
reflected = Reflect (getDebugSrcLoc callStack)
-- | A picture clipped to a rectangle around the origin with this width and height.
clipped :: HasCallStack => Double -> Double -> Picture -> Picture
clipped = Clip (getDebugSrcLoc callStack)
-- A picture made by drawing these pictures, ordered from top to bottom.
pictures :: HasCallStack => [Picture] -> Picture
pictures = Pictures (getDebugSrcLoc callStack)
-- | Binary composition of pictures.
(&) :: HasCallStack => Picture -> Picture -> Picture
infixr 0 &
a & PictureAnd loc2 bs
| srcContains loc1 loc2 = PictureAnd loc1 (a:bs)
where loc1 = getDebugSrcLoc callStack
a & b = PictureAnd (getDebugSrcLoc callStack) [a, b]
instance Monoid Picture where
mempty = blank
mappend = (&)
mconcat = pictures
#if MIN_VERSION_base(4,11,0)
instance Semigroup Picture where
(<>) = (&)
#endif
-- | A coordinate plane. Adding this to your pictures can help you measure distances
-- more accurately.
--
-- Example:
-- @
-- main = drawingOf (myPicture <> coordinatePlane)
-- myPicture = ...
-- @
coordinatePlane :: HasCallStack => Picture
coordinatePlane = CoordinatePlane (getDebugSrcLoc callStack)
-- | The CodeWorld logo.
codeWorldLogo :: HasCallStack => Picture
codeWorldLogo =
Sketch
(getDebugSrcLoc callStack)
"codeWorldLogo"
$(embedAsUrl "image/svg+xml" "data/codeworld.svg")
17.68 7.28
-- | An image from a standard image format. The image can be any universally
-- supported format, including SVG, PNG, JPG, etc. SVG should be preferred, as
-- it behaves better with transformations.
image
:: HasCallStack
=> Text -- ^ Name for the picture, used for debugging
-> Text -- ^ Data-scheme URI for the image data
-> Double -- ^ Width, in CodeWorld screen units
-> Double -- ^ Height, in CodeWorld screen units
-> Picture
image = Sketch (getDebugSrcLoc callStack)
getDebugSrcLoc :: CallStack -> Maybe SrcLoc
getDebugSrcLoc cs = Data.List.find ((== "main") . srcLocPackage) locs
where
locs = map snd (getCallStack cs)
srcContains :: Maybe SrcLoc -> Maybe SrcLoc -> Bool
srcContains Nothing _ = False
srcContains _ Nothing = True
srcContains (Just a) (Just b) =
srcLocFile a == srcLocFile b && srcLocStartLine a < srcLocStartLine b ||
(srcLocStartLine a == srcLocStartLine b &&
srcLocStartCol a <= srcLocStartCol b) &&
srcLocEndLine a > srcLocEndLine b ||
(srcLocEndLine a == srcLocEndLine b && srcLocEndCol a >= srcLocEndCol b)
|
alphalambda/codeworld
|
codeworld-api/src/CodeWorld/Picture.hs
|
apache-2.0
| 16,076
| 0
| 13
| 3,067
| 3,318
| 1,777
| 1,541
| -1
| -1
|
-- |
-- Definitions of each FFI type that can be used in Rust. These are
-- standardized accross the Rust and Haskell Curryrs library for easy
-- translation of function headers between the two.
module Curryrs.Types (
module Foreign.C.Types
, module Foreign.C.String
, Chr
, Str
, U8
, U16
, U32
, U64
, I8
, I16
, I32
, I64
, F32
, F64
, Boolean
) where
import Data.Int
import Data.Word
import Foreign.C.Types
import Foreign.C.String
-- We are only defining types that map to Rust types here
-- We don't need the full array of C types in Rust
-- |
-- Used to represent Char in both languages
type Chr = CChar
-- |
-- Used to represent Strings in both languages
type Str = CString
-- |
-- Used to represent 8 bit unsigned numbers in both languages
type U8 = Word8
-- |
-- Used to represent 16 bit unsigned numbers in both languages
type U16 = Word16
-- |
-- Used to represent 32 bit unsigned numbers in both languages
type U32 = Word32
-- |
-- Used to represent 64 bit unsigned numbers in both languages
type U64 = Word64
-- |
-- Used to represent 8 bit signed numbers in both languages
type I8 = Int8
-- |
-- Used to represent 16 bit signed numbers in both languages
type I16 = Int16
-- |
-- Used to represent 32 bit signed numbers in both languages
type I32 = Int32
-- |
-- Used to represent 64 bit signed numbers in both languages
type I64 = Int64
-- |
-- Used to represent 32 bit floating point numbers in both languages
type F32 = CFloat
-- |
-- Used to represent 64 bit floating point numbers in both languages
type F64 = CDouble
-- |
-- Used to represent Booleans in both languages
type Boolean = Word8
|
mgattozzi/curryrs
|
haskell/src/Curryrs/Types.hs
|
apache-2.0
| 1,661
| 0
| 5
| 368
| 193
| 139
| 54
| 33
| 0
|
module Vector(
Vector(Vector),
(/+),
(/-),
(/*),
(//),
neg,
dot,
cross,
norm,
len,
orthogonal,
rot,
toNorm,
toVertex,
toGLVector,
v0,
(~||)
) where
-- For conversion to Vertex3 and Normal3
import Graphics.Rendering.OpenGL
-- As I'm only dealing with 3D vectors here, I am being a bit lazy and not
-- generalizing.
-- I realize there are types for vectors and classes for them which I could
-- use, but I'd have to get aquianted with them first and it seems too much
-- of a hassle.
data Vector a = Vector a a a deriving(Eq, Ord)
x :: Vector a -> a
x (Vector a _ _) = a
y :: Vector a -> a
y (Vector _ a _) = a
z :: Vector a -> a
z (Vector _ _ a) = a
instance Show a => Show (Vector a) where
show (Vector a b c) = "(" ++ show a ++ "," ++ show b ++ "," ++ show c ++ ")"
(/+) :: Num a => Vector a -> Vector a -> Vector a
(Vector a b c) /+ (Vector a' b' c') = Vector (a + a') (b + b') (c + c')
(/-) :: Num a => Vector a -> Vector a -> Vector a
v1 /- v2 = v1 /+ neg v2
(/*) :: Num a => Vector a -> a -> Vector a
(Vector a b c) /* x = Vector (a * x) (b * x) (c * x)
(//) :: Fractional a => Vector a -> a -> Vector a
v // x = v /* (1 / x)
neg :: Num a => Vector a -> Vector a
neg (Vector a b c) = Vector (-a) (-b) (-c)
dot :: Num a => Vector a -> Vector a -> a
(Vector a b c) `dot` (Vector a' b' c') = a * a' + b * b' + c * c'
cross :: Num a => Vector a -> Vector a -> Vector a
(Vector a b c) `cross` (Vector a' b' c') = Vector
(b * c' - c * b')
(c * a' - a * c')
(a * b' - b * a')
norm :: Floating a => Vector a -> Vector a
norm v = v // len v
len :: Floating a => Vector a -> a
len v = sqrt $ v `dot` v
-- Finds a vector orthogonal to the given vector.
-- Note that the "almost parallel" check is required, as vectors almost
-- parallel to 1 0 0 will have a length of "0", due to floating point error.
orthogonal :: (Floating a, Ord a) => Vector a -> Vector a
orthogonal v
| v ~|| Vector 1 0 0 = v `cross` Vector 0 1 0
| otherwise = v `cross` Vector 1 0 0
(~||) :: (Floating a, Ord a) => Vector a -> Vector a -> Bool
v1 ~|| v2 = almostParallel (norm v1) (norm v2)
where
almostParallel (Vector a b c) (Vector a' b' c') =
(a ~= a' && b ~= b' && c ~= c') ||
((-a) ~= a' && (-b) ~= b' && (-c) ~= c')
a ~= b = abs (a - b) <= 1.0 / (10 ^ 5)
-- A bit ugly, but it works. And no, I'm not making a matrix type just for a
-- few rotations.
-- axis -> angle -> vector -> new vector
rot :: Floating a => Vector a -> a -> Vector a -> Vector a
rot u a v = Vector
(
(cos' + ux * ux * cos'') * vx +
(ux * uy * cos'' - uz * sin') * vy +
(ux * uz * cos'' + uy * sin') * vz
)
(
(uy * ux * cos'' + uz * sin') * vx +
(cos' + uy * uy * cos'') * vy +
(uy * uz * cos'' - ux * sin') * vz
)
(
(uz * ux * cos'' - uy * sin') * vx +
(uz * uy * cos'' + ux * sin') * vy +
(cos' + uz * uz * cos'') * vz
)
where
u' = norm u
ux = x u'
uy = y u'
uz = z u'
vx = x v
vy = y v
vz = z v
sin' = sin a
cos' = cos a
cos'' = 1 - cos a
toNorm :: Vector a -> Normal3 a
toNorm (Vector a b c) = Normal3 a b c
toVertex :: Vector a -> Vertex3 a
toVertex (Vector a b c) = Vertex3 a b c
toGLVector :: Vector a -> Vector3 a
toGLVector (Vector a b c) = Vector3 a b c
v0 :: Num a => Vector a
v0 = Vector 0 0 0
|
tkerber/-abandoned-3dlsystem-
|
Vector.hs
|
apache-2.0
| 3,342
| 0
| 16
| 1,000
| 1,671
| 857
| 814
| -1
| -1
|
{-# LANGUAGE FlexibleContexts, TypeSynonymInstances, FlexibleInstances #-}
-- | Docker support for propellor
--
-- The existance of a docker container is just another Property of a system,
-- which propellor can set up. See config.hs for an example.
module Propellor.Property.Docker (
-- * Host properties
installed,
configured,
container,
docked,
imageBuilt,
imagePulled,
memoryLimited,
garbageCollected,
tweaked,
Image(..),
ImageID(..),
latestImage,
ContainerName,
Container(..),
HasImage(..),
-- * Container configuration
dns,
hostname,
Publishable,
publish,
expose,
user,
Mountable,
volume,
volumes_from,
workdir,
memory,
cpuShares,
link,
environment,
ContainerAlias,
restartAlways,
restartOnFailure,
restartNever,
-- * Internal use
init,
chain,
listImages,
listContainers,
) where
import Propellor.Base hiding (init)
import Propellor.Types.Docker
import Propellor.Types.Container
import Propellor.Types.CmdLine
import Propellor.Types.Info
import qualified Propellor.Property.File as File
import qualified Propellor.Property.Apt as Apt
import qualified Propellor.Property.Cmd as Cmd
import qualified Propellor.Shim as Shim
import Utility.Path
import Utility.ThreadScheduler
import Control.Concurrent.Async hiding (link)
import System.Posix.Directory
import System.Posix.Process
import Prelude hiding (init)
import Data.List hiding (init)
import Data.List.Utils
import qualified Data.Map as M
import System.Console.Concurrent
installed :: Property NoInfo
installed = Apt.installed ["docker.io"]
-- | Configures docker with an authentication file, so that images can be
-- pushed to index.docker.io. Optional.
configured :: Property HasInfo
configured = prop `requires` installed
where
prop = withPrivData src anyContext $ \getcfg ->
property "docker configured" $ getcfg $ \cfg -> ensureProperty $
"/root/.dockercfg" `File.hasContent` privDataLines cfg
src = PrivDataSourceFileFromCommand DockerAuthentication
"/root/.dockercfg" "docker login"
-- | A short descriptive name for a container.
-- Should not contain whitespace or other unusual characters,
-- only [a-zA-Z0-9_-] are allowed
type ContainerName = String
-- | A docker container.
data Container = Container Image Host
class HasImage a where
getImageName :: a -> Image
instance HasImage Image where
getImageName = id
instance HasImage Container where
getImageName (Container i _) = i
instance PropAccum Container where
(Container i h) `addProp` p = Container i (h `addProp` p)
(Container i h) `addPropFront` p = Container i (h `addPropFront` p)
getProperties (Container _ h) = hostProperties h
-- | Defines a Container with a given name, image, and properties.
-- Properties can be added to configure the Container.
--
-- > container "web-server" "debian"
-- > & publish "80:80"
-- > & Apt.installed {"apache2"]
-- > & ...
container :: ContainerName -> Image -> Container
container cn image = Container image (Host cn [] info)
where
info = dockerInfo mempty
-- | Ensures that a docker container is set up and running.
--
-- The container has its own Properties which are handled by running
-- propellor inside the container.
--
-- When the container's Properties include DNS info, such as a CNAME,
-- that is propagated to the Info of the Host it's docked in.
--
-- Reverting this property ensures that the container is stopped and
-- removed.
docked :: Container -> RevertableProperty HasInfo
docked ctr@(Container _ h) =
(propagateContainerInfo ctr (go "docked" setup))
<!>
(go "undocked" teardown)
where
cn = hostName h
go desc a = property (desc ++ " " ++ cn) $ do
hn <- asks hostName
let cid = ContainerId hn cn
ensureProperties [a cid (mkContainerInfo cid ctr)]
setup cid (ContainerInfo image runparams) =
provisionContainer cid
`requires`
runningContainer cid image runparams
`requires`
installed
teardown cid (ContainerInfo image _runparams) =
combineProperties ("undocked " ++ fromContainerId cid)
[ stoppedContainer cid
, property ("cleaned up " ++ fromContainerId cid) $
liftIO $ report <$> mapM id
[ removeContainer cid
, removeImage image
]
]
-- | Build the image from a directory containing a Dockerfile.
imageBuilt :: HasImage c => FilePath -> c -> Property NoInfo
imageBuilt directory ctr = describe built msg
where
msg = "docker image " ++ (imageIdentifier image) ++ " built from " ++ directory
built = Cmd.cmdProperty' dockercmd ["build", "--tag", imageIdentifier image, "./"] workDir
workDir p = p { cwd = Just directory }
image = getImageName ctr
-- | Pull the image from the standard Docker Hub registry.
imagePulled :: HasImage c => c -> Property NoInfo
imagePulled ctr = describe pulled msg
where
msg = "docker image " ++ (imageIdentifier image) ++ " pulled"
pulled = Cmd.cmdProperty dockercmd ["pull", imageIdentifier image]
image = getImageName ctr
propagateContainerInfo :: (IsProp (Property i)) => Container -> Property i -> Property HasInfo
propagateContainerInfo ctr@(Container _ h) p = propagateContainer cn ctr p'
where
p' = infoProperty
(propertyDesc p)
(propertySatisfy p)
(propertyInfo p <> dockerinfo)
(propertyChildren p)
dockerinfo = dockerInfo $
mempty { _dockerContainers = M.singleton cn h }
cn = hostName h
mkContainerInfo :: ContainerId -> Container -> ContainerInfo
mkContainerInfo cid@(ContainerId hn _cn) (Container img h) =
ContainerInfo img runparams
where
runparams = map (\(DockerRunParam mkparam) -> mkparam hn)
(_dockerRunParams info)
info = getInfo $ hostInfo h'
h' = h
-- Restart by default so container comes up on
-- boot or when docker is upgraded.
&^ restartAlways
-- Expose propellor directory inside the container.
& volume (localdir++":"++localdir)
-- Name the container in a predictable way so we
-- and the user can easily find it later. This property
-- comes last, so it cannot be overridden.
& name (fromContainerId cid)
-- | Causes *any* docker images that are not in use by running containers to
-- be deleted. And deletes any containers that propellor has set up
-- before that are not currently running. Does not delete any containers
-- that were not set up using propellor.
--
-- Generally, should come after the properties for the desired containers.
garbageCollected :: Property NoInfo
garbageCollected = propertyList "docker garbage collected"
[ gccontainers
, gcimages
]
where
gccontainers = property "docker containers garbage collected" $
liftIO $ report <$> (mapM removeContainer =<< listContainers AllContainers)
gcimages = property "docker images garbage collected" $
liftIO $ report <$> (mapM removeImage =<< listImages)
-- | Tweaks a container to work well with docker.
--
-- Currently, this consists of making pam_loginuid lines optional in
-- the pam config, to work around <https://github.com/docker/docker/issues/5663>
-- which affects docker 1.2.0.
tweaked :: Property NoInfo
tweaked = trivial $
cmdProperty "sh" ["-c", "sed -ri 's/^session\\s+required\\s+pam_loginuid.so$/session optional pam_loginuid.so/' /etc/pam.d/*"]
`describe` "tweaked for docker"
-- | Configures the kernel to respect docker memory limits.
--
-- This assumes the system boots using grub 2. And that you don't need any
-- other GRUB_CMDLINE_LINUX_DEFAULT settings.
--
-- Only takes effect after reboot. (Not automated.)
memoryLimited :: Property NoInfo
memoryLimited = "/etc/default/grub" `File.containsLine` cfg
`describe` "docker memory limited"
`onChange` cmdProperty "update-grub" []
where
cmdline = "cgroup_enable=memory swapaccount=1"
cfg = "GRUB_CMDLINE_LINUX_DEFAULT=\""++cmdline++"\""
data ContainerInfo = ContainerInfo Image [RunParam]
-- | Parameters to pass to `docker run` when creating a container.
type RunParam = String
-- | ImageID is an image identifier to perform action on images. An
-- ImageID can be the name of an container image, a UID, etc.
--
-- It just encapsulates a String to avoid the definition of a String
-- instance of ImageIdentifier.
newtype ImageID = ImageID String
-- | Used to perform Docker action on an image.
--
-- Minimal complete definition: `imageIdentifier`
class ImageIdentifier i where
-- | For internal purposes only.
toImageID :: i -> ImageID
toImageID = ImageID . imageIdentifier
-- | A string that Docker can use as an image identifier.
imageIdentifier :: i -> String
instance ImageIdentifier ImageID where
imageIdentifier (ImageID i) = i
toImageID = id
-- | A docker image, that can be used to run a container. The user has
-- to specify a name and can provide an optional tag.
-- See <http://docs.docker.com/userguide/dockerimages/ Docker Image Documention>
-- for more information.
data Image = Image
{ repository :: String
, tag :: Maybe String
}
deriving (Eq, Read, Show)
-- | Defines a Docker image without any tag. This is considered by
-- Docker as the latest image of the provided repository.
latestImage :: String -> Image
latestImage repo = Image repo Nothing
instance ImageIdentifier Image where
-- | The format of the imageIdentifier of an `Image` is:
-- repository | repository:tag
imageIdentifier i = repository i ++ (maybe "" ((++) ":") $ tag i)
-- | The UID of an image. This UID is generated by Docker.
newtype ImageUID = ImageUID String
instance ImageIdentifier ImageUID where
imageIdentifier (ImageUID uid) = uid
-- | Set custom dns server for container.
dns :: String -> Property HasInfo
dns = runProp "dns"
-- | Set container host name.
hostname :: String -> Property HasInfo
hostname = runProp "hostname"
-- | Set name of container.
name :: String -> Property HasInfo
name = runProp "name"
class Publishable p where
toPublish :: p -> String
instance Publishable (Bound Port) where
toPublish p = show (hostSide p) ++ ":" ++ show (containerSide p)
-- | string format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort
instance Publishable String where
toPublish = id
-- | Publish a container's port to the host
publish :: Publishable p => p -> Property HasInfo
publish = runProp "publish" . toPublish
-- | Expose a container's port without publishing it.
expose :: String -> Property HasInfo
expose = runProp "expose"
-- | Username or UID for container.
user :: String -> Property HasInfo
user = runProp "user"
class Mountable p where
toMount :: p -> String
instance Mountable (Bound FilePath) where
toMount p = hostSide p ++ ":" ++ containerSide p
-- | string format: [host-dir]:[container-dir]:[rw|ro]
--
-- With just a directory, creates a volume in the container.
instance Mountable String where
toMount = id
-- | Mount a volume
volume :: Mountable v => v -> Property HasInfo
volume = runProp "volume" . toMount
-- | Mount a volume from the specified container into the current
-- container.
volumes_from :: ContainerName -> Property HasInfo
volumes_from cn = genProp "volumes-from" $ \hn ->
fromContainerId (ContainerId hn cn)
-- | Work dir inside the container.
workdir :: String -> Property HasInfo
workdir = runProp "workdir"
-- | Memory limit for container.
-- Format: <number><optional unit>, where unit = b, k, m or g
--
-- Note: Only takes effect when the host has the memoryLimited property
-- enabled.
memory :: String -> Property HasInfo
memory = runProp "memory"
-- | CPU shares (relative weight).
--
-- By default, all containers run at the same priority, but you can tell
-- the kernel to give more CPU time to a container using this property.
cpuShares :: Int -> Property HasInfo
cpuShares = runProp "cpu-shares" . show
-- | Link with another container on the same host.
link :: ContainerName -> ContainerAlias -> Property HasInfo
link linkwith calias = genProp "link" $ \hn ->
fromContainerId (ContainerId hn linkwith) ++ ":" ++ calias
-- | A short alias for a linked container.
-- Each container has its own alias namespace.
type ContainerAlias = String
-- | This property is enabled by default for docker containers configured by
-- propellor; as well as keeping badly behaved containers running,
-- it ensures that containers get started back up after reboot or
-- after docker is upgraded.
restartAlways :: Property HasInfo
restartAlways = runProp "restart" "always"
-- | Docker will restart the container if it exits nonzero.
-- If a number is provided, it will be restarted only up to that many
-- times.
restartOnFailure :: Maybe Int -> Property HasInfo
restartOnFailure Nothing = runProp "restart" "on-failure"
restartOnFailure (Just n) = runProp "restart" ("on-failure:" ++ show n)
-- | Makes docker not restart a container when it exits
-- Note that this includes not restarting it on boot!
restartNever :: Property HasInfo
restartNever = runProp "restart" "no"
-- | Set environment variable with a tuple composed by the environment
-- variable name and its value.
environment :: (String, String) -> Property HasInfo
environment (k, v) = runProp "env" $ k ++ "=" ++ v
-- | A container is identified by its name, and the host
-- on which it's deployed.
data ContainerId = ContainerId
{ containerHostName :: HostName
, containerName :: ContainerName
}
deriving (Eq, Read, Show)
-- | Two containers with the same ContainerIdent were started from
-- the same base image (possibly a different version though), and
-- with the same RunParams.
data ContainerIdent = ContainerIdent Image HostName ContainerName [RunParam]
deriving (Read, Show, Eq)
toContainerId :: String -> Maybe ContainerId
toContainerId s
| myContainerSuffix `isSuffixOf` s = case separate (== '.') (desuffix s) of
(cn, hn)
| null hn || null cn -> Nothing
| otherwise -> Just $ ContainerId hn cn
| otherwise = Nothing
where
desuffix = reverse . drop len . reverse
len = length myContainerSuffix
fromContainerId :: ContainerId -> String
fromContainerId (ContainerId hn cn) = cn++"."++hn++myContainerSuffix
myContainerSuffix :: String
myContainerSuffix = ".propellor"
containerDesc :: (IsProp (Property i)) => ContainerId -> Property i -> Property i
containerDesc cid p = p `describe` desc
where
desc = "container " ++ fromContainerId cid ++ " " ++ propertyDesc p
runningContainer :: ContainerId -> Image -> [RunParam] -> Property NoInfo
runningContainer cid@(ContainerId hn cn) image runps = containerDesc cid $ property "running" $ do
l <- liftIO $ listContainers RunningContainers
if cid `elem` l
then checkident =<< liftIO getrunningident
else ifM (liftIO $ elem cid <$> listContainers AllContainers)
( do
-- The container exists, but is not
-- running. Its parameters may have
-- changed, but we cannot tell without
-- starting it up first.
void $ liftIO $ startContainer cid
-- It can take a while for the container to
-- start up enough for its ident file to be
-- written, so retry for up to 60 seconds.
checkident =<< liftIO (retry 60 $ getrunningident)
, go image
)
where
ident = ContainerIdent image hn cn runps
-- Check if the ident has changed; if so the
-- parameters of the container differ and it must
-- be restarted.
checkident (Right runningident)
| runningident == Just ident = noChange
| otherwise = do
void $ liftIO $ stopContainer cid
restartcontainer
checkident (Left errmsg) = do
warningMessage errmsg
return FailedChange
restartcontainer = do
oldimage <- liftIO $
maybe (toImageID image) toImageID <$> commitContainer cid
void $ liftIO $ removeContainer cid
go oldimage
getrunningident = withTmpFile "dockerrunsane" $ \t h -> do
-- detect #774376 which caused docker exec to not enter
-- the container namespace, and be able to access files
-- outside
hClose h
void . checkSuccessProcess . processHandle =<<
createProcess (inContainerProcess cid []
["rm", "-f", t])
ifM (doesFileExist t)
( Right . readish <$>
readProcess' (inContainerProcess cid []
["cat", propellorIdent])
, return $ Left "docker exec failed to enter chroot properly (maybe an old kernel version?)"
)
retry :: Int -> IO (Either e (Maybe a)) -> IO (Either e (Maybe a))
retry 0 _ = return (Right Nothing)
retry n a = do
v <- a
case v of
Right Nothing -> do
threadDelaySeconds (Seconds 1)
retry (n-1) a
_ -> return v
go img = liftIO $ do
clearProvisionedFlag cid
createDirectoryIfMissing True (takeDirectory $ identFile cid)
shim <- Shim.setup (localdir </> "propellor") Nothing (localdir </> shimdir cid)
writeFile (identFile cid) (show ident)
toResult <$> runContainer img
(runps ++ ["-i", "-d", "-t"])
[shim, "--continue", show (DockerInit (fromContainerId cid))]
-- | Called when propellor is running inside a docker container.
-- The string should be the container's ContainerId.
--
-- This process is effectively init inside the container.
-- It even needs to wait on zombie processes!
--
-- In the foreground, run an interactive bash (or sh) shell,
-- so that the user can interact with it when attached to the container.
--
-- When the system reboots, docker restarts the container, and this is run
-- again. So, to make the necessary services get started on boot, this needs
-- to provision the container then. However, if the container is already
-- being provisioned by the calling propellor, it would be redundant and
-- problimatic to also provisoon it here, when not booting up.
--
-- The solution is a flag file. If the flag file exists, then the container
-- was already provisioned. So, it must be a reboot, and time to provision
-- again. If the flag file doesn't exist, don't provision here.
init :: String -> IO ()
init s = case toContainerId s of
Nothing -> error $ "Invalid ContainerId: " ++ s
Just cid -> do
changeWorkingDirectory localdir
writeFile propellorIdent . show =<< readIdentFile cid
whenM (checkProvisionedFlag cid) $ do
let shim = Shim.file (localdir </> "propellor") (localdir </> shimdir cid)
unlessM (boolSystem shim [Param "--continue", Param $ show $ toChain cid]) $
warningMessage "Boot provision failed!"
void $ async $ job reapzombies
job $ do
flushConcurrentOutput
void $ tryIO $ ifM (inPath "bash")
( boolSystem "bash" [Param "-l"]
, boolSystem "/bin/sh" []
)
putStrLn "Container is still running. Press ^P^Q to detach."
where
job = forever . void . tryIO
reapzombies = void $ getAnyProcessStatus True False
-- | Once a container is running, propellor can be run inside
-- it to provision it.
provisionContainer :: ContainerId -> Property NoInfo
provisionContainer cid = containerDesc cid $ property "provisioned" $ liftIO $ do
let shim = Shim.file (localdir </> "propellor") (localdir </> shimdir cid)
let params = ["--continue", show $ toChain cid]
msgh <- getMessageHandle
let p = inContainerProcess cid
(if isConsole msgh then ["-it"] else [])
(shim : params)
r <- withHandle StdoutHandle createProcessSuccess p $
processChainOutput
when (r /= FailedChange) $
setProvisionedFlag cid
return r
toChain :: ContainerId -> CmdLine
toChain cid = DockerChain (containerHostName cid) (fromContainerId cid)
chain :: [Host] -> HostName -> String -> IO ()
chain hostlist hn s = case toContainerId s of
Nothing -> errorMessage "bad container id"
Just cid -> case findHostNoAlias hostlist hn of
Nothing -> errorMessage ("cannot find host " ++ hn)
Just parenthost -> case M.lookup (containerName cid) (_dockerContainers $ getInfo $ hostInfo parenthost) of
Nothing -> errorMessage ("cannot find container " ++ containerName cid ++ " docked on host " ++ hn)
Just h -> go cid h
where
go cid h = do
changeWorkingDirectory localdir
onlyProcess (provisioningLock cid) $ do
r <- runPropellor h $ ensureProperties $
map ignoreInfo $
hostProperties h
flushConcurrentOutput
putStrLn $ "\n" ++ show r
stopContainer :: ContainerId -> IO Bool
stopContainer cid = boolSystem dockercmd [Param "stop", Param $ fromContainerId cid ]
startContainer :: ContainerId -> IO Bool
startContainer cid = boolSystem dockercmd [Param "start", Param $ fromContainerId cid ]
stoppedContainer :: ContainerId -> Property NoInfo
stoppedContainer cid = containerDesc cid $ property desc $
ifM (liftIO $ elem cid <$> listContainers RunningContainers)
( liftIO cleanup `after` ensureProperty
(property desc $ liftIO $ toResult <$> stopContainer cid)
, return NoChange
)
where
desc = "stopped"
cleanup = do
nukeFile $ identFile cid
removeDirectoryRecursive $ shimdir cid
clearProvisionedFlag cid
removeContainer :: ContainerId -> IO Bool
removeContainer cid = catchBoolIO $
snd <$> processTranscript dockercmd ["rm", fromContainerId cid ] Nothing
removeImage :: ImageIdentifier i => i -> IO Bool
removeImage image = catchBoolIO $
snd <$> processTranscript dockercmd ["rmi", imageIdentifier image] Nothing
runContainer :: ImageIdentifier i => i -> [RunParam] -> [String] -> IO Bool
runContainer image ps cmd = boolSystem dockercmd $ map Param $
"run" : (ps ++ (imageIdentifier image) : cmd)
inContainerProcess :: ContainerId -> [String] -> [String] -> CreateProcess
inContainerProcess cid ps cmd = proc dockercmd ("exec" : ps ++ [fromContainerId cid] ++ cmd)
commitContainer :: ContainerId -> IO (Maybe ImageUID)
commitContainer cid = catchMaybeIO $
ImageUID . takeWhile (/= '\n')
<$> readProcess dockercmd ["commit", fromContainerId cid]
data ContainerFilter = RunningContainers | AllContainers
deriving (Eq)
-- | Only lists propellor managed containers.
listContainers :: ContainerFilter -> IO [ContainerId]
listContainers status =
mapMaybe toContainerId . concatMap (split ",")
. mapMaybe (lastMaybe . words) . lines
<$> readProcess dockercmd ps
where
ps
| status == AllContainers = baseps ++ ["--all"]
| otherwise = baseps
baseps = ["ps", "--no-trunc"]
listImages :: IO [ImageUID]
listImages = map ImageUID . lines <$> readProcess dockercmd ["images", "--all", "--quiet"]
runProp :: String -> RunParam -> Property HasInfo
runProp field val = pureInfoProperty (param) $
mempty { _dockerRunParams = [DockerRunParam (\_ -> "--"++param)] }
where
param = field++"="++val
genProp :: String -> (HostName -> RunParam) -> Property HasInfo
genProp field mkval = pureInfoProperty field $
mempty { _dockerRunParams = [DockerRunParam (\hn -> "--"++field++"=" ++ mkval hn)] }
dockerInfo :: DockerInfo -> Info
dockerInfo i = mempty `addInfo` i
-- | The ContainerIdent of a container is written to
-- </.propellor-ident> inside it. This can be checked to see if
-- the container has the same ident later.
propellorIdent :: FilePath
propellorIdent = "/.propellor-ident"
provisionedFlag :: ContainerId -> FilePath
provisionedFlag cid = "docker" </> fromContainerId cid ++ ".provisioned"
clearProvisionedFlag :: ContainerId -> IO ()
clearProvisionedFlag = nukeFile . provisionedFlag
setProvisionedFlag :: ContainerId -> IO ()
setProvisionedFlag cid = do
createDirectoryIfMissing True (takeDirectory (provisionedFlag cid))
writeFile (provisionedFlag cid) "1"
checkProvisionedFlag :: ContainerId -> IO Bool
checkProvisionedFlag = doesFileExist . provisionedFlag
provisioningLock :: ContainerId -> FilePath
provisioningLock cid = "docker" </> fromContainerId cid ++ ".lock"
shimdir :: ContainerId -> FilePath
shimdir cid = "docker" </> fromContainerId cid ++ ".shim"
identFile :: ContainerId -> FilePath
identFile cid = "docker" </> fromContainerId cid ++ ".ident"
readIdentFile :: ContainerId -> IO ContainerIdent
readIdentFile cid = fromMaybe (error "bad ident in identFile")
. readish <$> readFile (identFile cid)
dockercmd :: String
dockercmd = "docker"
report :: [Bool] -> Result
report rmed
| or rmed = MadeChange
| otherwise = NoChange
|
np/propellor
|
src/Propellor/Property/Docker.hs
|
bsd-2-clause
| 23,584
| 820
| 15
| 4,165
| 5,639
| 3,065
| 2,574
| 425
| 5
|
module YesodDsl.Generator.Client where
import YesodDsl.AST
import Data.Maybe
import YesodDsl.Generator.Input
import YesodDsl.Generator.Common
data InputField = InputField Field
| InputUnknown FieldName OptionalFlag
| InputSort
| InputFilter
handlerInputFields :: Handler -> [InputField]
handlerInputFields h = (if handlerType h == GetHandler then [
InputField $ mkField "start" (True, NormalField FTInt32),
InputField $ mkField "limit" (True, NormalField FTInt32)
] else []) ++ (map trAttr $ nubAttrs $ concatMap requestAttrs $ handlerStmts h) ++ (if DefaultFilterSort `elem` handlerStmts h then [ InputSort, InputFilter ] else [])
where
trAttr (fn, Left o) = InputUnknown fn o
trAttr (_, Right f) = InputField f
handlerOutputFields :: Module -> Handler -> [Field]
handlerOutputFields m h = concatMap stmtOutputs $ handlerStmts h
where
stmtOutputs s = case s of
Select sq -> mapMaybe selectFieldToField $ sqFields sq
Return ofs -> mapMaybe (\(pn,fr,_) -> fieldRefToContent fr >>= Just . (mkField pn)) ofs
_ -> []
selectFieldToField sf = case sf of
SelectField (Var _ (Right e) mf) fn mvn -> do
f <- lookupField e fn
let f' = f { fieldOptional = fieldOptional f || mf }
Just $ case mvn of
Just vn -> f' { fieldOptions = [ FieldJsonName vn ] ++ fieldOptions f' }
Nothing -> f'
SelectIdField (Var _ (Right e) mf) mvn -> Just $
mkField (fromMaybe "id" mvn) (mf, EntityField $ entityName e)
SelectExpr ve vn -> do
fc <- case ve of
FieldExpr fr -> fieldRefToContent fr
BinOpExpr _ op _ -> Just $ if op `elem` [Add,Sub,Div,Mul]
then (False, NormalField FTDouble)
else (False, NormalField FTText)
UnOpExpr Floor _ -> Just (False, NormalField FTDouble)
UnOpExpr Ceiling _ -> Just (False, NormalField FTDouble)
UnOpExpr (Extract _) _ -> Just (False, NormalField FTDouble)
UnOpExpr Not _ -> Just (False, NormalField FTBool)
ConcatManyExpr _ -> Just (False, NormalField FTText)
_ -> Nothing
Just $ mkField vn fc
_ -> Nothing
fieldRefToContent fr = case fr of
SqlId (Var _ (Right e) mf) -> Just (mf, EntityField $ entityName e)
SqlField (Var _ (Right e) mf) fn -> do
f <- lookupField e fn
Just $ (fieldOptional f || mf, fieldContent f)
AuthId -> Just (False, EntityField "User")
AuthField fn -> listToMaybe [ (fieldOptional f, fieldContent f)
| e <- modEntities m,
f <- entityFields e,
entityName e == "User",
fieldName f == fn ]
LocalParamField (Var _ (Right e) mf) fn -> do
f <- lookupField e fn
Just $ (fieldOptional f || mf, fieldContent f)
_ -> Nothing
|
tlaitinen/yesod-dsl
|
YesodDsl/Generator/Client.hs
|
bsd-2-clause
| 3,325
| 0
| 20
| 1,283
| 1,053
| 527
| 526
| 60
| 20
|
{-# LANGUAGE RecordWildCards #-}
-- | Library for spawning and working with Ghci sessions.
module Language.Haskell.Ghcid(
Ghci, GhciError(..), Stream(..),
Load(..), Severity(..),
startGhci, stopGhci, interrupt, process, execStream,
showModules, reload, exec, quit
) where
import System.IO
import System.IO.Error
import System.Process
import System.Time.Extra
import Control.Concurrent.Extra
import Control.Exception.Extra
import Control.Monad.Extra
import Data.Function
import Data.List.Extra
import Data.Maybe
import Data.IORef
import Control.Applicative
import System.Console.CmdArgs.Verbosity
import Language.Haskell.Ghcid.Parser
import Language.Haskell.Ghcid.Types as T
import Language.Haskell.Ghcid.Util
import Prelude
-- | A GHCi session. Created with 'startGhci', closed with 'stopGhci'.
--
-- The interactions with a 'Ghci' session must all occur single-threaded,
-- or an error will be raised. The only exception is 'interrupt', which aborts
-- a running computation, or does nothing if no computation is running.
data Ghci = Ghci
{ghciProcess :: ProcessHandle
,ghciInterrupt :: IO ()
,ghciExec :: String -> (Stream -> String -> IO ()) -> IO ()}
-- | Start GHCi, returning a function to perform further operation, as well as the result of the initial loading.
-- If you do not call 'stopGhci' then the underlying process may be leaked.
-- The callback will be given the messages produced while loading, useful if invoking something like "cabal repl"
-- which might compile dependent packages before really loading.
startGhci :: String -> Maybe FilePath -> (Stream -> String -> IO ()) -> IO (Ghci, [Load])
startGhci cmd directory echo0 = do
(Just inp, Just out, Just err, ghciProcess) <-
createProcess (shell cmd){std_in=CreatePipe, std_out=CreatePipe, std_err=CreatePipe, cwd=directory, create_group=True}
hSetBuffering out LineBuffering
hSetBuffering err LineBuffering
hSetBuffering inp LineBuffering
let writeInp x = do
whenLoud $ outStrLn $ "%STDIN: " ++ x
hPutStrLn inp x
-- Some programs (e.g. stack) might use stdin before starting ghci (see #57)
-- Send them an empty line
hPutStrLn inp ""
-- I'd like the GHCi prompt to go away, but that's not possible, so I set it to a special
-- string and filter that out.
let ghcid_prefix = "#~GHCID-START~#"
let removePrefix = dropPrefixRepeatedly ghcid_prefix
-- At various points I need to ensure everything the user is waiting for has completed
-- So I send messages on stdout/stderr and wait for them to arrive
syncCount <- newVar 0
let syncReplay = do
i <- readVar syncCount
let msg = "#~GHCID-FINISH-" ++ show i ++ "~#"
writeInp $ "INTERNAL_GHCID.putStrLn " ++ show msg ++ "\n" ++
"INTERNAL_GHCID.hPutStrLn INTERNAL_GHCID.stderr " ++ show msg
return $ isInfixOf msg
let syncFresh = do
modifyVar_ syncCount $ return . succ
syncReplay
-- Consume from a stream until EOF (return Nothing) or some predicate returns Just
let consume :: Stream -> (String -> IO (Maybe a)) -> IO (Maybe a)
consume name finish = do
let h = if name == Stdout then out else err
fix $ \rec -> do
el <- tryBool isEOFError $ hGetLine h
case el of
Left _ -> return Nothing
Right l -> do
whenLoud $ outStrLn $ "%" ++ upper (show name) ++ ": " ++ l
res <- finish $ removePrefix l
case res of
Nothing -> rec
Just a -> return $ Just a
let consume2 :: String -> (Stream -> String -> IO (Maybe a)) -> IO (a,a)
consume2 msg finish = do
res1 <- onceFork $ consume Stdout (finish Stdout)
res2 <- consume Stderr (finish Stderr)
res1 <- res1
case liftM2 (,) res1 res2 of
Nothing -> throwIO $ UnexpectedExit cmd msg
Just v -> return v
-- held while interrupting, and briefly held when starting an exec
-- ensures exec values queue up behind an ongoing interrupt and no two interrupts run at once
isInterrupting <- newLock
-- is anyone running running an exec statement, ensure only one person talks to ghci at a time
isRunning <- newLock
let ghciExec command echo = do
withLock isInterrupting $ return ()
res <- withLockTry isRunning $ do
writeInp command
stop <- syncFresh
void $ consume2 command $ \strm s ->
if stop s then return $ Just () else do echo strm s; return Nothing
when (isNothing res) $
fail "Ghcid.exec, computation is already running, must be used single-threaded"
let ghciInterrupt = withLock isInterrupting $ do
whenM (fmap isNothing $ withLockTry isRunning $ return ()) $ do
whenLoud $ outStrLn "%INTERRUPT"
interruptProcessGroupOf ghciProcess
-- let the person running ghciExec finish, since their sync messages
-- may have been the ones that got interrupted
syncReplay
-- now wait for the person doing ghciExec to have actually left the lock
withLock isRunning $ return ()
-- there may have been two syncs sent, so now do a fresh sync to clear everything
stop <- syncFresh
void $ consume2 "Interrupt" $ \_ s -> return $ if stop s then Just () else Nothing
let ghci = Ghci{..}
-- Now wait for 'GHCi, version' to appear before sending anything real, required for #57
stdout <- newIORef []
stderr <- newIORef []
sync <- newIORef $ const False
consume2 "" $ \strm s -> do
stop <- readIORef sync
if stop s then
return $ Just ()
else do
-- there may be some initial prompts on stdout before I set the prompt properly
s <- return $ maybe s (removePrefix . snd) $ stripInfix ghcid_prefix s
whenLoud $ outStrLn $ "%STDOUT2: " ++ s
modifyIORef (if strm == Stdout then stdout else stderr) (s:)
when ("GHCi, version " `isPrefixOf` s) $ do
-- the thing before me may have done its own Haskell compiling
writeIORef stdout []
writeIORef stderr []
writeInp "import qualified System.IO as INTERNAL_GHCID"
writeInp $ ":set prompt " ++ ghcid_prefix
writeInp ":set -fno-break-on-exception -fno-break-on-error" -- see #43
writeIORef sync =<< syncFresh
echo0 strm s
return Nothing
r <- parseLoad . reverse <$> ((++) <$> readIORef stderr <*> readIORef stdout)
execStream ghci "" echo0
return (ghci, r)
-- | Execute a command, calling a callback on each response.
-- The callback will be called single threaded.
execStream :: Ghci -> String -> (Stream -> String -> IO ()) -> IO ()
execStream = ghciExec
-- | Interrupt Ghci, stopping the current computation (if any),
-- but leaving the process open to new input.
interrupt :: Ghci -> IO ()
interrupt = ghciInterrupt
-- | Obtain the progress handle behind a GHCi instance.
process :: Ghci -> ProcessHandle
process = ghciProcess
---------------------------------------------------------------------
-- SUGAR HELPERS
-- | Execute a command, calling a callback on each response.
-- The callback will be called single threaded.
execBuffer :: Ghci -> String -> (Stream -> String -> IO ()) -> IO [String]
execBuffer ghci cmd echo = do
stdout <- newIORef []
stderr <- newIORef []
execStream ghci cmd $ \strm s -> do
modifyIORef (if strm == Stdout then stdout else stderr) (s:)
echo strm s
reverse <$> ((++) <$> readIORef stderr <*> readIORef stdout)
-- | Send a command, get lines of result. Must be called single-threaded.
exec :: Ghci -> String -> IO [String]
exec ghci cmd = execBuffer ghci cmd $ \_ _ -> return ()
-- | List the modules currently loaded, with module name and source file.
showModules :: Ghci -> IO [(String,FilePath)]
showModules ghci = parseShowModules <$> exec ghci ":show modules"
-- | Perform a reload, list the messages that reload generated.
reload :: Ghci -> IO [Load]
reload ghci = parseLoad <$> exec ghci ":reload"
-- | Send @:quit@ and wait for the process to quit.
quit :: Ghci -> IO ()
quit ghci = do
interrupt ghci
handle (\UnexpectedExit{} -> return ()) $ void $ exec ghci ":quit"
-- Be aware that waitForProcess has a race condition, see https://github.com/haskell/process/issues/46.
-- Therefore just ignore the exception anyway, its probably already terminated.
ignore $
void $ waitForProcess $ process ghci
-- | Stop GHCi. Attempts to interrupt and execute @:quit:@, but if that doesn't complete
-- within 5 seconds it just terminates the process.
stopGhci :: Ghci -> IO ()
stopGhci ghci = do
forkIO $ do
-- if nicely doesn't work, kill ghci as the process level
sleep 5
terminateProcess $ process ghci
quit ghci
|
JPMoresmau/ghcid
|
src/Language/Haskell/Ghcid.hs
|
bsd-3-clause
| 9,304
| 0
| 26
| 2,613
| 2,034
| 1,014
| 1,020
| 146
| 9
|
module Data.Povray.Texture where
import Data.Povray.Base
import Data.Povray.Colour
import Data.Povray.Pigment
import Data.Povray.Types
import Data.Maybe
data Finish = Phong Double
| Ambient Double -- TODO
instance Povray Finish where
toPov (Phong x) = "finish { phong " `mappend` toPov x `mappend` " }"
toPov (Ambient x) = "finish { ambient " `mappend` toPov x `mappend` " }"
data Texture = Texture { _pigment :: Maybe Pigment,
_finish :: Maybe Finish }
| NamedTexture {textureName :: Str}
emptyTexture :: Texture
emptyTexture = Texture Nothing Nothing
instance Povray Texture where
toPov (Texture p f) =
join [
"texture {",
maybeToPov p,
maybeToPov f,
"}"
]
toPov (NamedTexture n) = "texture {" `mappend` n `mappend` "}"
|
lesguillemets/hspov_proto
|
src/Data/Povray/Texture.hs
|
bsd-3-clause
| 864
| 0
| 9
| 253
| 241
| 137
| 104
| 24
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Apps.Juno.Client
( main
) where
import Control.Concurrent.MVar
import Control.Concurrent.Lifted (threadDelay)
import qualified Control.Concurrent.Lifted as CL
import Control.Concurrent.Chan.Unagi
import Control.Monad.Reader
import qualified Data.ByteString.Char8 as BSC
import Data.Either ()
import qualified Data.Map as Map
import Text.Read (readMaybe)
import System.IO
import GHC.Int (Int64)
import Juno.Spec.Simple
import Juno.Types
import Apps.Juno.Parser
prompt :: String
prompt = "\ESC[0;31mhopper>> \ESC[0m"
promptGreen :: String
promptGreen = "\ESC[0;32mresult>> \ESC[0m"
flushStr :: String -> IO ()
flushStr str = putStr str >> hFlush stdout
readPrompt :: IO String
readPrompt = flushStr prompt >> getLine
-- should we poll here till we get a result?
showResult :: CommandMVarMap -> RequestId -> Maybe Int64 -> IO ()
showResult cmdStatusMap' rId Nothing =
threadDelay 1000 >> do
(CommandMap _ m) <- readMVar cmdStatusMap'
case Map.lookup rId m of
Nothing -> print $ "RequestId [" ++ show rId ++ "] not found."
Just (CmdApplied (CommandResult x) _) -> putStrLn $ promptGreen ++ BSC.unpack x
Just _ -> -- not applied yet, loop and wait
showResult cmdStatusMap' rId Nothing
showResult cmdStatusMap' rId pgm@(Just cnt) =
threadDelay 1000 >> do
(CommandMap _ m) <- readMVar cmdStatusMap'
case Map.lookup rId m of
Nothing -> print $ "RequestId [" ++ show rId ++ "] not found."
Just (CmdApplied (CommandResult _x) lat) -> do
putStrLn $ intervalOfNumerous cnt lat
Just _ -> -- not applied yet, loop and wait
showResult cmdStatusMap' rId pgm
-- -> OutChan CommandResult
runREPL :: InChan (RequestId, [CommandEntry]) -> CommandMVarMap -> IO ()
runREPL toCommands' cmdStatusMap' = do
cmd <- readPrompt
case cmd of
"" -> runREPL toCommands' cmdStatusMap'
_ -> do
cmd' <- return $ BSC.pack cmd
if take 11 cmd == "batch test:"
then case readMaybe $ drop 11 cmd of
Just n -> do
rId <- liftIO $ setNextCmdRequestId cmdStatusMap'
writeChan toCommands' (rId, [CommandEntry cmd'])
--- this is the tracer round for timing purposes
putStrLn $ "Sending " ++ show n ++ " 'transfer(Acct1->Acct2, 1%1)' transactions batched"
showResult cmdStatusMap' (rId + RequestId n) (Just n)
runREPL toCommands' cmdStatusMap'
Nothing -> runREPL toCommands' cmdStatusMap'
else if take 10 cmd == "many test:"
then
case readMaybe $ drop 10 cmd of
Just n -> do
cmds <- replicateM n
(do rid <- setNextCmdRequestId cmdStatusMap'; return (rid, [CommandEntry "transfer(Acct1->Acct2, 1%1)"]))
writeList2Chan toCommands' cmds
--- this is the tracer round for timing purposes
putStrLn $ "Sending " ++ show n ++ " 'transfer(Acct1->Acct2, 1%1)' transactions individually"
showResult cmdStatusMap' (fst $ last cmds) (Just $ fromIntegral n)
runREPL toCommands' cmdStatusMap'
Nothing -> runREPL toCommands' cmdStatusMap'
else
case readHopper cmd' of
Left err -> putStrLn cmd >> putStrLn err >> runREPL toCommands' cmdStatusMap'
Right _ -> do
rId <- liftIO $ setNextCmdRequestId cmdStatusMap'
writeChan toCommands' (rId, [CommandEntry cmd'])
showResult cmdStatusMap' rId Nothing
runREPL toCommands' cmdStatusMap'
intervalOfNumerous :: Int64 -> Int64 -> String
intervalOfNumerous cnt mics = let
interval = fromIntegral mics / 1000000
perSec = ceiling (fromIntegral cnt / interval)
in "Completed in " ++ show (interval :: Double) ++ "sec (" ++ show (perSec::Integer) ++ " per sec)"
-- | Runs a 'Raft nt String String mt'.
-- Simple fixes nt to 'HostPort' and mt to 'String'.
main :: IO ()
main = do
(toCommands, fromCommands) <- newChan
-- `toResult` is unused. There seem to be API's that use/block on fromResult.
-- Either we need to kill this channel full stop or `toResult` needs to be used.
cmdStatusMap' <- initCommandMap
let -- getEntry :: (IO et)
getEntries :: IO (RequestId, [CommandEntry])
getEntries = readChan fromCommands
-- applyFn :: et -> IO rt
applyFn :: Command -> IO CommandResult
applyFn _x = return $ CommandResult "Failure"
void $ CL.fork $ runClient applyFn getEntries cmdStatusMap'
threadDelay 100000
runREPL toCommands cmdStatusMap'
|
buckie/juno
|
src/Apps/Juno/Client.hs
|
bsd-3-clause
| 4,523
| 0
| 27
| 1,077
| 1,182
| 587
| 595
| 93
| 7
|
module Foo (foo) where
import Language.Haskell.TH
foo :: ExpQ
foo = stringE "foo"
|
eagletmt/ghc-mod
|
test/data/Foo.hs
|
bsd-3-clause
| 83
| 0
| 5
| 14
| 28
| 17
| 11
| 4
| 1
|
{-# LANGUAGE PatternGuards, FlexibleContexts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.CSL.Eval.Names
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Andrea Rossato <andrea.rossato@unitn.it>
-- Stability : unstable
-- Portability : unportable
--
-- The CSL implementation
--
-----------------------------------------------------------------------------
module Text.CSL.Eval.Names where
import Control.Monad.State
import Data.Char ( isLower, isUpper, isLetter )
import Data.List ( nub, intersperse )
import Data.List.Split ( wordsBy )
import Data.Maybe ( isJust )
import Text.CSL.Eval.Common
import Text.CSL.Eval.Output
import Text.CSL.Util ( headInline, lastInline, readNum, (<^>), query, toRead,
splitStrWhen, isRange )
import Text.CSL.Style
import Text.Pandoc.Definition
import Text.Pandoc.Shared ( stringify )
import qualified Text.Pandoc.Builder as B
evalNames :: Bool -> [String] -> [Name] -> String -> State EvalState [Output]
evalNames skipEdTrans ns nl d
| [sa,sb] <- ns, not skipEdTrans
, (sa == "editor" && sb == "translator") ||
(sb == "editor" && sa == "translator") = do
aa <- getAgents' sa
ab <- getAgents' sb
if not (null aa) && aa == ab
then modify (\s -> s { edtrans = True }) >>
evalNames True [sa] nl d
else evalNames True ns nl d
| (s:xs) <- ns = do
resetEtal
ags <- getAgents s
k <- getStringVar "ref-id"
p <- gets (citePosition . cite . env)
ops <- gets (options . env)
aus <- gets authSub
r <- do res <- agents p s ags
st <- get
fb <- agents "subsequent" s ags
put st
if null res
then return []
else let role = if aus == ["author"] then "authorsub" else s
in return . return . OContrib k role res fb =<< gets etal
r' <- evalNames skipEdTrans xs nl d
num <- gets contNum
return $ if r /= [] && r' /= []
then count num (r ++ [ODel $ delim ops] ++ r')
else count num $ cleanOutput (r ++ r')
| otherwise = return []
where
agents p s a = concatMapM (formatNames (hasEtAl nl) d p s a) nl
delim ops = if d == [] then getOptionVal "names-delimiter" ops else d
resetEtal = modify (\s -> s { etal = [] })
count num x = if hasCount nl && num /= [] -- FIXME!! le zero!!
then [OContrib [] [] [ONum (length num) emptyFormatting] [] []]
else x
hasCount = or . query hasCount'
hasCount' n
| Name Count _ _ _ _ <- n = [True]
| otherwise = [False]
-- | The 'Bool' is 'True' when formatting a name with a final "et-al".
-- The first 'String' represents the position and the second the role
-- (e.i. editor, translator, etc.).
formatNames :: Bool -> Delimiter -> String -> String -> [Agent] -> Name -> State EvalState [Output]
formatNames ea del p s as n
| Name f _ ns _ _ <- n, Count <- f = do
b <- isBib <$> gets mode
o <- gets (options . env) >>= return . mergeOptions ns
modify $ \st -> st { contNum = nub $ (++) (take (snd $ isEtAl b o p as) as) $ contNum st }
return []
| Name f fm ns d np <- n = do
b <- isBib <$> gets mode
o <- gets (options . env) >>= return . mergeOptions ns
m <- gets mode
let odel = if del /= [] then del else getOptionVal "name-delimiter" o
del' = if d /= [] then d else if odel == [] then ", " else odel
(_,i) = isEtAl b o p as
form = case f of
NotSet -> case getOptionVal "name-form" o of
[] -> Long
x -> read $ toRead x
_ -> f
genName x = do etal' <- formatEtAl o ea "et-al" fm del' x
if null etal'
then do t <- getTerm False Long "and"
return $ delim t o del' $ format m o form fm np x
else return $ (addDelim del' $ format m o form fm np x) ++ etal'
setLastName o $ formatName m False f fm o np (last as)
updateEtal =<< mapM genName [1 + i .. length as]
genName i
| NameLabel f fm pl <- n = when' (isVarSet s) $ do
b <- gets edtrans
res <- formatLabel f fm (isPlural pl $ length as) $
if b then "editortranslator" else s
modify $ \st -> st { edtrans = False }
-- Note: the following line was here previously.
-- It produces spurious 'et al's and seems to have no function,
-- so I have commented it out:
-- updateEtal [tr' "res" res]
return res
| EtAl fm t <- n = do
o <- gets (options . env)
if (getOptionVal "et-al-min" o == [])
then return []
else do
et <- gets etal
let i = length as - length et
t' = if null t then "et-al" else t
r <- mapM (et_al o False t' fm del) [i .. length as]
let (r',r'') = case r of
(x:xs) -> (x, xs)
[] -> ([],[])
updateEtal r''
return r'
| otherwise = return []
where
isBib (EvalBiblio _) = True
isBib _ = False
updateEtal x = modify $ \st ->
let x' = if length x == 1 then repeat $ head x else x
in st { etal = case etal st of
[] -> x
ys -> zipWith (++) ys x'
}
isWithLastName os
| "true" <- getOptionVal "et-al-use-last" os
, em <- readNum $ getOptionVal "et-al-min" os
, uf <- readNum $ getOptionVal "et-al-use-first" os
, em - uf > 1 = True
| otherwise = False
setLastName os x
| as /= []
, isWithLastName os = modify $ \st -> st { lastName = x}
| otherwise = return ()
format m os f fm np i
| (a:xs) <- take i as = formatName m True f fm os np a ++
concatMap (formatName m False f fm os np) xs
| otherwise = concatMap (formatName m True f fm os np) . take i $ as
delim t os d x
| "always" <- getOptionVal "delimiter-precedes-last" os
, length x == 2 = addDelim d (init x) ++ ODel (d <^> andStr t os) : [last x]
| length x == 2 = addDelim d (init x) ++ ODel (andStr' t d os) : [last x]
| "never" <- getOptionVal "delimiter-precedes-last" os
, length x > 2 = addDelim d (init x) ++ ODel (andStr' t d os) : [last x]
| length x > 2 = addDelim d (init x) ++ ODel (d <^> andStr t os) : [last x]
| otherwise = addDelim d x
andStr t os
| "text" <- getOptionVal "and" os = " " ++ t ++ " "
| "symbol" <- getOptionVal "and" os = " & "
| otherwise = []
andStr' t d os = if andStr t os == [] then d else andStr t os
formatEtAl o b t fm d i = do
ln <- gets lastName
if isWithLastName o
then case () of
_ | (length as - i) == 1 -> et_al o b t fm d i -- is that correct? FIXME later
| (length as - i) > 1 -> return $ [ODel d, OPan [Str "\x2026"], OSpace] ++ ln
| otherwise -> return []
else et_al o b t fm d i
et_al o b t fm d i
= when' (gets mode >>= return . not . isSorting) $
if (b || length as <= i)
then return []
else do x <- getTerm False Long t
when' (return $ x /= []) $
case getOptionVal "delimiter-precedes-et-al" o of
"never" -> return . (++) [OSpace] $ output fm x
"always" -> return . (++) [ODel d] $ output fm x
_ -> if i > 1 && not (null d)
then return . (++) [ODel d] $ output fm x
else return . (++) [OSpace] $ output fm x
-- | The first 'Bool' is 'True' if we are evaluating the bibliography.
-- The 'String' is the cite position. The function also returns the
-- number of contributors to be displayed.
isEtAl :: Bool -> [Option] -> String -> [Agent] -> (Bool, Int)
isEtAl b os p as
| p /= "first"
, isOptionSet "et-al-subsequent-min" os
, isOptionSet "et-al-subsequent-use-first" os
, le <- etAlMin "et-al-subsequent-min"
, le' <- etAlMin "et-al-subsequent-use-first"
, length as >= le
, length as > le' = (,) True le'
| isOptionSet' "et-al-min" "et-al-subsequent-min"
, isOptionSet' "et-al-use-first" "et-al-subsequent-use-first"
, le <- etAlMin' "et-al-min" "et-al-subsequent-min"
, le' <- etAlMin' "et-al-use-first" "et-al-subsequent-use-first"
, length as >= le
, length as > le' = (,) True le'
| isOptionSet' "et-al-min" "et-al-subsequent-min"
, le <- etAlMin' "et-al-min" "et-al-subsequent-min"
, length as >= le
, length as > 1 = (,) True getUseFirst
| otherwise = (,) False $ length as
where
etAlMin x = read $ getOptionVal x os
etAlMin' x y = if b then etAlMin x else read $ getOptionVal' x y
isOptionSet' s1 s2 = if b
then isOptionSet s1 os
else or $ (isOptionSet s1 os) : [(isOptionSet s2 os)]
getOptionVal' s1 s2 = if null (getOptionVal s1 os)
then getOptionVal s2 os
else getOptionVal s1 os
getUseFirst = let u = if b
then getOptionVal "et-al-use-first" os
else getOptionVal' "et-al-use-first" "et-al-subsequent-min"
in if null u then 1 else read u
-- | Generate the 'Agent's names applying et-al options, with all
-- possible permutations to disambiguate colliding citations. The
-- 'Bool' indicate whether we are formatting the first name or not.
formatName :: EvalMode -> Bool -> Form -> Formatting -> [Option] -> [NamePart] -> Agent -> [Output]
formatName m b f fm ops np n
| literal n /= mempty = return $ OName n institution [] fm
| Short <- f = return $ OName n shortName disambdata fm
| otherwise = return $ OName n (longName given) disambdata fm
where
institution = oPan' (unFormatted $ literal n) (form "family")
when_ c o = if c /= mempty then o else mempty
addAffixes (Formatted []) _ [] = []
addAffixes s sf ns = [Output (Output [OPan (unFormatted s)]
(form sf){ prefix = mempty, suffix = mempty} : ns)
emptyFormatting { prefix = prefix (form sf)
, suffix = suffix (form sf)}]
form s = case filter (\(NamePart n' _) -> n' == s) np of
NamePart _ fm':_ -> fm'
_ -> emptyFormatting
hyphenate new [] = new
hyphenate new accum =
if getOptionVal "initialize-with-hyphen" ops == "false"
then new ++ accum
else trimsp new ++ [Str "-"] ++ accum
isInit [Str [c]] = isUpper c
isInit _ = False
initial (Formatted x) =
case lookup "initialize-with" ops of
Just iw
| getOptionVal "initialize" ops == "false"
, isInit x -> addIn x $ B.toList $ B.text iw
| getOptionVal "initialize" ops /= "false"
, not (all isLower $ query (:[]) x) -> addIn x $ B.toList $ B.text iw
Nothing
| isInit x -> addIn x [Space] -- default
_ -> Space : x ++ [Space]
addIn x i = foldr hyphenate []
$ map (\z -> Str (headInline z) : i)
$ wordsBy (== Str "-")
$ splitStrWhen (=='-') x
sortSep g s = when_ g $ separator ++ addAffixes (g <+> s) "given" mempty
separator = if null (getOptionVal "sort-separator" ops)
then [OPan [Str ",", Space]]
else [OPan $ B.toList $ B.text $ getOptionVal "sort-separator" ops]
suff = if commaSuffix n && nameSuffix n /= mempty
then suffCom
else suffNoCom
suffCom = when_ (nameSuffix n) $ separator ++
oPan' (unFormatted $ nameSuffix n) fm
suffNoCom = when_ (nameSuffix n) $ OSpace : oPan' (unFormatted $ nameSuffix n) fm
onlyGiven = not (givenName n == mempty) && family == mempty
given = if onlyGiven
then givenLong
else when_ (givenName n) . Formatted . trimsp . fixsp . concatMap initial $ givenName n
fixsp (Space:Space:xs) = fixsp (Space:xs)
fixsp (x:xs) = x : fixsp xs
fixsp [] = []
trimsp = reverse . dropWhile (==Space) . reverse . dropWhile (==Space)
givenLong = when_ (givenName n) . mconcat . intersperse (Formatted [Space]) $ givenName n
family = familyName n
dropping = droppingPart n
nondropping = nonDroppingPart n
-- see src/load.js ROMANESQUE_REGEX in citeproc-js:
isByzantine c = not (isLetter c) ||
c <= '\x5FF' ||
(c >= '\x1e00' && c <= '\x1fff')
shortName = oPan' (unFormatted $ nondropping <+> family) (form "family")
longName g = if isSorting m
then let firstPart = case getOptionVal "demote-non-dropping-particle" ops of
"never" -> nondropping <+> family <+> dropping
_ -> family <+> dropping <+> nondropping
in oPan' (unFormatted firstPart) (form "family") <++> oPan' (unFormatted g) (form "given") <> suffCom
else if (b && getOptionVal "name-as-sort-order" ops == "first") ||
getOptionVal "name-as-sort-order" ops == "all"
then let (fam,par) = case getOptionVal "demote-non-dropping-particle" ops of
"never" -> (nondropping <+> family, dropping)
"sort-only" -> (nondropping <+> family, dropping)
_ -> (family, dropping <+> nondropping)
in oPan' (unFormatted fam) (form "family") <> sortSep g par <> suffCom
else let fam = addAffixes (dropping <+> nondropping <+> family) "family" suff
gvn = oPan' (unFormatted g) (form "given")
in if all isByzantine $ stringify $ unFormatted family
then gvn <++> fam
else fam <> gvn
disWithGiven = getOptionVal "disambiguate-add-givenname" ops == "true"
initialize = isJust (lookup "initialize-with" ops) && not onlyGiven
isLong = f /= Short && initialize
givenRule = let gr = getOptionVal "givenname-disambiguation-rule" ops
in if null gr then "by-cite" else gr
disambdata = case () of
_ | "all-names-with-initials" <- givenRule
, disWithGiven, Short <- f, initialize -> [longName given]
| "primary-name-with-initials" <- givenRule
, disWithGiven, Short <- f, initialize, b -> [longName given]
| disWithGiven, Short <- f, b
, "primary-name" <- givenRule -> [longName given, longName givenLong]
| disWithGiven, Short <- f
, "all-names" <- givenRule -> [longName given, longName givenLong]
| disWithGiven, Short <- f
, "by-cite" <- givenRule -> [longName given, longName givenLong]
| disWithGiven, isLong -> [longName givenLong]
| otherwise -> []
formatTerm :: Form -> Formatting -> Bool -> String -> State EvalState [Output]
formatTerm f fm p s = do
t <- getTerm p f s
return $ oStr' t fm
formatLabel :: Form -> Formatting -> Bool -> String -> State EvalState [Output]
formatLabel f fm p s
| "locator" <- s = when' (gets (citeLocator . cite . env) >>= return . (/=) []) $ do
(l,v) <- getLocVar
form (\fm' -> return . flip OLoc emptyFormatting . output fm') id l (isRange v)
| "page" <- s = checkPlural
| "volume" <- s = checkPlural
| "ibid" <- s = format s p
| isRole s = do a <- getAgents' (if s == "editortranslator"
then "editor"
else s)
if null a
then return []
else form (\fm' x -> [OLabel x fm']) id s p
| otherwise = format s p
where
isRole = flip elem ["author", "collection-editor", "composer", "container-author"
,"director", "editor", "editorial-director", "editortranslator"
,"illustrator", "interviewer", "original-author", "recipient"
,"reviewed-author", "translator"]
checkPlural = when' (isVarSet s) $ do
v <- getStringVar s
format s (isRange v)
format = form output id
form o g t b = return . o fm =<< g . period <$> getTerm (b && p) f t
period = if stripPeriods fm then filter (/= '.') else id
(<+>) :: Formatted -> Formatted -> Formatted
Formatted [] <+> ss = ss
s <+> Formatted [] = s
Formatted xs <+> Formatted ys =
case lastInline xs of
"’" -> Formatted (xs ++ ys)
"-" -> Formatted (xs ++ ys)
_ -> Formatted (xs ++ [Space] ++ ys)
(<++>) :: [Output] -> [Output] -> [Output]
[] <++> o = o
o <++> [] = o
o1 <++> o2 = o1 ++ [OSpace] ++ o2
|
jkr/pandoc-citeproc
|
src/Text/CSL/Eval/Names.hs
|
bsd-3-clause
| 18,799
| 0
| 20
| 7,490
| 6,049
| 2,998
| 3,051
| 329
| 21
|
module Thread.Pool where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Concurrent.STM.TChan
import Control.Concurrent.STM.TVar
import Control.Monad
type ThreadPoolAction a = IO a
data ThreadPool a = ThreadPool
{ addJob :: ThreadPoolAction a -> IO ()
, workerThreads :: [ThreadId]
, getResult :: IO a
}
startPool :: Int -> IO (ThreadPool a)
startPool n = do
input <- newTChanIO :: IO (TChan (ThreadPoolAction a))
output <- newTChanIO :: IO (TChan a)
threads <-
forM [1 .. n] $ \n -> forkIO . forever $ do
job <- atomically $ readTChan input
result <- job
atomically $ writeTChan output result
return $
ThreadPool
{ addJob = \job -> atomically $ writeTChan input job
, getResult = atomically $ readTChan output
, workerThreads = threads
}
|
theNerd247/ariaRacer
|
src/Thread/Pool.hs
|
bsd-3-clause
| 840
| 0
| 15
| 199
| 276
| 147
| 129
| 25
| 1
|
{-# LANGUAGE ExistentialQuantification #-}
module Network.WebSockets.Protocol.Hybi10
( Hybi10
) where
import Data.Enumerator ((=$))
import Data.Enumerator.List as EL
import Network.WebSockets.Protocol
import Network.WebSockets.Protocol.Hybi10.Internal
import Network.WebSockets.Protocol.Unsafe
data Hybi10 = forall p. Protocol p => Hybi10 p
instance Protocol Hybi10 where
version (Hybi10 p) = version p
headerVersions (Hybi10 p) = headerVersions p
supported (Hybi10 p) h = supported p h
encodeMessages (Hybi10 p) = (EL.map castMessage =$) . encodeMessages p
decodeMessages (Hybi10 p) = (decodeMessages p =$) . EL.map castMessage
finishRequest (Hybi10 p) = finishRequest p
implementations = [Hybi10 Hybi10_]
instance TextProtocol Hybi10
instance BinaryProtocol Hybi10
|
0xfaded/websockets
|
src/Network/WebSockets/Protocol/Hybi10.hs
|
bsd-3-clause
| 842
| 0
| 9
| 168
| 241
| 130
| 111
| 19
| 0
|
{-# LANGUAGE ConstraintKinds, DeriveFoldable, DeriveFunctor, DeriveTraversable, TypeFamilies #-}
-- | This module provides the the type for (SMT)-Formula.
module SLogic.Logic.Formula where
import Control.Monad
import Control.Monad.Reader
import qualified Data.Foldable as F (toList)
import qualified Data.Set as S
import SLogic.Data.Decode
import SLogic.Data.Result
import SLogic.Data.Solver
import SLogic.Logic.Logic
-- TODO: MS: optimise; differentiate between user vars and generated vars or use just generated vars
-- | Formula. SMT Core + Int.
data Formula v
= BVar v
| Top
| Bot
| Not (Formula v)
| And (Formula v) (Formula v)
| Or (Formula v) (Formula v)
| Implies (Formula v) (Formula v)
-- atomic integer arithmetic constraints
| IEq (IExpr v) (IExpr v)
| IGt (IExpr v) (IExpr v)
| IGte (IExpr v) (IExpr v)
-- optimise
| Max (IExpr v)
| Min (IExpr v)
deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
-- | Integer Expressions.
data IExpr v
= IVar v
| IVal !Int
| INeg (IExpr v)
| IAdd (IExpr v) (IExpr v)
| IMul (IExpr v) (IExpr v)
| IIte (Formula v) (IExpr v) (IExpr v)
deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
type VarType = String
boolType, intType :: VarType
boolType = "Bool"
intType = "Int"
variables :: Ord v => Formula v -> S.Set (v, VarType)
variables f = case f of
BVar v -> S.singleton (v, boolType)
Top -> S.empty
Bot -> S.empty
Not f1 -> variables f1
And f1 f2 -> variables f1 `S.union` variables f2
Or f1 f2 -> variables f1 `S.union` variables f2
Implies f1 f2 -> variables f1 `S.union` variables f2
IEq e1 e2 -> variables' e1 `S.union` variables' e2
IGt e1 e2 -> variables' e1 `S.union` variables' e2
IGte e1 e2 -> variables' e1 `S.union` variables' e2
Max e -> variables' e
Min e -> variables' e
where
variables' :: Ord v => IExpr v -> S.Set (v, VarType)
variables' e = case e of
IVar v -> S.singleton (v,intType)
IVal _ -> S.empty
INeg e1 -> variables' e1
IAdd e1 e2 -> variables' e1 `S.union` variables' e2
IMul e1 e2 -> variables' e1 `S.union` variables' e2
IIte b e1 e2 -> variables b `S.union` variables' e1 `S.union` variables' e2
--- * Boolean --------------------------------------------------------------------------------------------------------
-- MS: Optimisations can be important. For matrices we want `0 .* e = 0` and `e .* 0`. This significantly improves the
-- generated formula (when identity/triangular matrices are used). But (`1 .+ a = a`) decreases the performance
-- significantly. So optimisations should be done domain specific. Further when optimisations are used variables may
-- vanish; this should be considered when decoding.
--
-- MS: Note that 'bigAnd [] = Top', and similar for other monoid instances. Whereas `(and )` is an invalid formula
-- according to the SMTv2 standard.
instance Boolean (Formula v) where
top = Top
bot = Bot
bnot = Not
(.&&) = And
(.||) = Or
(.=>) = Implies
bigAnd fs
| null (F.toList fs) = Top
| otherwise = foldr1 (.&&) fs
bigOr fs
| null (F.toList fs) = Bot
| otherwise = foldr1 (.||) fs
-- | Returns a Boolean variable with the given id.
bvar :: v -> Formula v
bvar = BVar
-- | Returns a Boolean value.
bool :: Bool -> Formula v
bool True = Top
bool _ = Bot
-- annihilate :: Formula v -> Formula v
-- annihilate = simplify f g where
-- f f1 = f1
-- g (IMul (IVal 0) _) = IVal 0
-- g (IMul _ (IVal 0)) = IVal 0
-- g e1 = e1
-- simplify :: (Formula v -> Formula v) -> (IExpr v -> IExpr v) -> Formula v -> Formula v
-- simplify f g (Not f1) = f $! Not (simplify f g f1)
-- simplify f g (And f1 f2) = f $! And (simplify f g f1) (simplify f g f2)
-- simplify f g (Or f1 f2) = f $! Or (simplify f g f1) (simplify f g f2)
-- simplify f g (Implies f1 f2) = f $! Implies (simplify f g f1) (simplify f g f2)
-- simplify f g (IEq e1 e2) = f $! IEq (simplify' f g e1) (simplify' f g e2)
-- simplify f g (IGt e1 e2) = f $! IGt (simplify' f g e1) (simplify' f g e2)
-- simplify f g (IGte e1 e2) = f $! IGte (simplify' f g e1) (simplify' f g e2)
-- simplify _ _ f1 = f1
-- simplify' :: (Formula v -> Formula v) -> (IExpr v -> IExpr v) -> IExpr v -> IExpr v
-- simplify' f g (INeg e1) = g $! INeg (simplify' f g e1)
-- simplify' f g (IAdd e1 e2) = g $! IAdd (simplify' f g e1) (simplify' f g e2)
-- simplify' f g (IMul e1 e2) = g $! IMul (simplify' f g e1) (simplify' f g e2)
-- simplify' f g (IIte f1 e1 e2) = g $! IIte (simplify f g f1) (simplify' f g e1) (simplify' f g e2)
-- simplify' _ _ e1 = e1
--- * Arithmetic -----------------------------------------------------------------------------------------------------
ivar :: v -> IExpr v
ivar = IVar
num :: Int -> IExpr v
num = IVal
instance AAdditive (IExpr v) where
(.+) = IAdd
zero = IVal 0
bigAdd es
| null (F.toList es) = zero
| otherwise = foldr1 (.+) es
instance AAdditiveGroup (IExpr v) where
neg = INeg
instance MMultiplicative (IExpr v) where
(.*) = IMul
one = IVal 1
bigMul es
| null (F.toList es) = one
| otherwise = foldr1 (.*) es
instance Equal (IExpr v) where
type B (IExpr v) = Formula v
(.==) = IEq
instance Order (IExpr v) where
(.>) = IGt
(.>=) = IGte
instance Ite (IExpr v) where
ite = IIte
maximize, minimize :: IExpr v -> Formula v
maximize = Max
minimize = Min
--- * monadic interface ----------------------------------------------------------------------------------------------
bvarM :: Monad m => v -> m (Formula v)
bvarM = return . bvar
boolM :: Monad m => Bool -> m (Formula v)
boolM = return . bool
topM, botM :: Monad m => m (Formula v)
topM = return top
botM = return bot
bnotM :: Monad m => m (Formula v) -> m (Formula v)
bnotM = fmap bnot
bandM, borM :: Monad m => m (Formula v) -> m (Formula v) -> m (Formula v)
bandM = liftM2 (.&&)
borM = liftM2 (.||)
bigAndM, bigOrM :: Monad m => [m (Formula v)] -> m (Formula v)
bigAndM es = bigAnd `liftM` sequence es
bigOrM es = bigOr `liftM` sequence es
impliesM :: Monad m => m (Formula v) -> m (Formula v) -> m (Formula v)
impliesM = liftM2 (.=>)
--- * decoding -------------------------------------------------------------------------------------------------------
-- NOTE: MS:
-- There are situations when a variable is not defined in the mapping.
-- The user asks for a variable which is not used; or a variable is removed by optimisations.
-- We handle this situations using Maybe and a default value (False, 0).
notLiteral :: String
notLiteral = "SLogic.Logic.Formula.decode: not a literal."
wrongArgument :: String
wrongArgument = "SLogic.Logic.Formula.decode: wrong argument number."
-- | standard environment
type Environment v = Reader (Store v)
-- TODO: MS: extend decode st. it decodes Formulas
instance Storing v => Decode (Environment v) (Formula v) (Maybe Bool) where
decode c = case c of
Top -> return (Just True)
Bot -> return (Just False)
BVar v -> get v
_ -> error notLiteral
where
get v = asks $ \m -> case find v m of
Just (BoolVal b) -> Just b
Just _ -> error notLiteral
_ -> Nothing
-- | Defaults to @False@.
instance Storing v => Decode (Environment v) (Formula v) Bool where
decode c = case c of
Top -> return True
Bot -> return False
BVar v -> get v
_ -> error notLiteral
where
get v = asks $ \m -> case find v m of
Just (BoolVal b) -> b
Just _ -> error notLiteral
_ -> False
instance Storing v => Decode (Environment v) (IExpr v) (Maybe Int) where
decode c = case c of
IVal i -> return (Just i)
IVar v -> get v
_ -> error "not a literal"
where
get v = asks $ \m -> case find v m of
Just (IntVal i) -> Just i
Just _ -> error notLiteral
_ -> Nothing
-- | Defaults to @0@.
instance Storing v => Decode (Environment v) (IExpr v) Int where
decode c = case c of
IVal i -> return i
IVar v -> get v
IMul e1 e2 -> (*) <$> decode e1 <*> decode e2
IAdd e1 e2 -> (+) <$> decode e1 <*> decode e2
INeg e -> negate <$> decode e
IIte eb e1 e2 -> do
b <- decode eb
if b then decode e1 else decode e2
where
get v = asks $ \m -> case find v m of
Just (IntVal i) -> i
Just _ -> error notLiteral
_ -> 0
|
ComputationWithBoundedResources/slogic
|
src/SLogic/Logic/Formula.hs
|
bsd-3-clause
| 8,766
| 0
| 15
| 2,435
| 2,447
| 1,259
| 1,188
| -1
| -1
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Generate haddocks
module Stack.Build.Haddock
( generateLocalHaddockIndex
, generateDepsHaddockIndex
, generateSnapHaddockIndex
, shouldHaddockPackage
, shouldHaddockDeps
) where
import Control.Exception (tryJust, onException)
import Control.Monad
import Control.Monad.Catch (MonadCatch)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Trans.Resource
import qualified Data.Foldable as F
import Data.Function
import qualified Data.HashSet as HS
import Data.List
import Data.List.Extra (nubOrd)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Maybe.Extra (mapMaybeM)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time (UTCTime)
import Path
import Path.Extra
import Path.IO
import Prelude
import Stack.Types.Build
import Stack.PackageDump
import Stack.Types
import qualified System.FilePath as FP
import System.IO.Error (isDoesNotExistError)
import System.Process.Read
-- | Determine whether we should haddock for a package.
shouldHaddockPackage :: BuildOpts
-> Set PackageName -- ^ Packages that we want to generate haddocks for
-- in any case (whether or not we are going to generate
-- haddocks for dependencies)
-> PackageName
-> Bool
shouldHaddockPackage bopts wanted name =
if Set.member name wanted
then boptsHaddock bopts
else shouldHaddockDeps bopts
-- | Determine whether to build haddocks for dependencies.
shouldHaddockDeps :: BuildOpts -> Bool
shouldHaddockDeps bopts = fromMaybe (boptsHaddock bopts) (boptsHaddockDeps bopts)
-- | Generate Haddock index and contents for local packages.
generateLocalHaddockIndex
:: (MonadIO m, MonadCatch m, MonadThrow m, MonadLogger m, MonadBaseControl IO m)
=> EnvOverride
-> WhichCompiler
-> BaseConfigOpts
-> Map GhcPkgId (DumpPackage () ()) -- ^ Local package dump
-> [LocalPackage]
-> m ()
generateLocalHaddockIndex envOverride wc bco localDumpPkgs locals = do
let dumpPackages =
mapMaybe
(\LocalPackage{lpPackage = Package{..}} ->
F.find
(\dp -> dpPackageIdent dp == PackageIdentifier packageName packageVersion)
localDumpPkgs)
locals
generateHaddockIndex
"local packages"
envOverride
wc
dumpPackages
"."
(localDocDir bco)
-- | Generate Haddock index and contents for local packages and their dependencies.
generateDepsHaddockIndex
:: (MonadIO m, MonadCatch m, MonadThrow m, MonadLogger m, MonadBaseControl IO m)
=> EnvOverride
-> WhichCompiler
-> BaseConfigOpts
-> Map GhcPkgId (DumpPackage () ()) -- ^ Global dump information
-> Map GhcPkgId (DumpPackage () ()) -- ^ Snapshot dump information
-> Map GhcPkgId (DumpPackage () ()) -- ^ Local dump information
-> [LocalPackage]
-> m ()
generateDepsHaddockIndex envOverride wc bco globalDumpPkgs snapshotDumpPkgs localDumpPkgs locals = do
let deps = (mapMaybe (`lookupDumpPackage` allDumpPkgs) . nubOrd . findTransitiveDepends . mapMaybe getGhcPkgId) locals
depDocDir = localDocDir bco </> $(mkRelDir "all")
generateHaddockIndex
"local packages and dependencies"
envOverride
wc
deps
".."
depDocDir
where
getGhcPkgId :: LocalPackage -> Maybe GhcPkgId
getGhcPkgId LocalPackage{lpPackage = Package{..}} =
let pkgId = PackageIdentifier packageName packageVersion
mdpPkg = F.find (\dp -> dpPackageIdent dp == pkgId) localDumpPkgs
in fmap dpGhcPkgId mdpPkg
findTransitiveDepends :: [GhcPkgId] -> [GhcPkgId]
findTransitiveDepends = (`go` HS.empty) . HS.fromList
where
go todo checked =
case HS.toList todo of
[] -> HS.toList checked
(ghcPkgId:_) ->
let deps =
case lookupDumpPackage ghcPkgId allDumpPkgs of
Nothing -> HS.empty
Just pkgDP -> HS.fromList (dpDepends pkgDP)
deps' = deps `HS.difference` checked
todo' = HS.delete ghcPkgId (deps' `HS.union` todo)
checked' = HS.insert ghcPkgId checked
in go todo' checked'
allDumpPkgs = [localDumpPkgs, snapshotDumpPkgs, globalDumpPkgs]
-- | Generate Haddock index and contents for all snapshot packages.
generateSnapHaddockIndex
:: (MonadIO m, MonadCatch m, MonadThrow m, MonadLogger m, MonadBaseControl IO m)
=> EnvOverride
-> WhichCompiler
-> BaseConfigOpts
-> Map GhcPkgId (DumpPackage () ()) -- ^ Global package dump
-> Map GhcPkgId (DumpPackage () ()) -- ^ Snapshot package dump
-> m ()
generateSnapHaddockIndex envOverride wc bco globalDumpPkgs snapshotDumpPkgs =
generateHaddockIndex
"snapshot packages"
envOverride
wc
(Map.elems snapshotDumpPkgs ++ Map.elems globalDumpPkgs)
"."
(snapDocDir bco)
-- | Generate Haddock index and contents for specified packages.
generateHaddockIndex
:: (MonadIO m, MonadCatch m, MonadLogger m, MonadBaseControl IO m)
=> Text
-> EnvOverride
-> WhichCompiler
-> [DumpPackage () ()]
-> FilePath
-> Path Abs Dir
-> m ()
generateHaddockIndex descr envOverride wc dumpPackages docRelFP destDir = do
ensureDir destDir
interfaceOpts <- (liftIO . fmap nubOrd . mapMaybeM toInterfaceOpt) dumpPackages
unless (null interfaceOpts) $ do
let destIndexFile = haddockIndexFile destDir
eindexModTime <- liftIO (tryGetModificationTime destIndexFile)
let needUpdate =
case eindexModTime of
Left _ -> True
Right indexModTime ->
or [mt > indexModTime | (_,mt,_,_) <- interfaceOpts]
when needUpdate $ do
$logInfo
(T.concat ["Updating Haddock index for ", descr, " in\n",
T.pack (toFilePath destIndexFile)])
liftIO (mapM_ copyPkgDocs interfaceOpts)
readProcessNull
(Just destDir)
envOverride
(haddockExeName wc)
(["--gen-contents", "--gen-index"] ++ [x | (xs,_,_,_) <- interfaceOpts, x <- xs])
where
toInterfaceOpt :: DumpPackage a b -> IO (Maybe ([String], UTCTime, Path Abs File, Path Abs File))
toInterfaceOpt DumpPackage {..} = do
case dpHaddockInterfaces of
[] -> return Nothing
srcInterfaceFP:_ -> do
srcInterfaceAbsFile <- parseCollapsedAbsFile srcInterfaceFP
let (PackageIdentifier name _) = dpPackageIdent
destInterfaceRelFP =
docRelFP FP.</>
packageIdentifierString dpPackageIdent FP.</>
(packageNameString name FP.<.> "haddock")
destInterfaceAbsFile <- parseCollapsedAbsFile (toFilePath destDir FP.</> destInterfaceRelFP)
esrcInterfaceModTime <- tryGetModificationTime srcInterfaceAbsFile
return $
case esrcInterfaceModTime of
Left _ -> Nothing
Right srcInterfaceModTime ->
Just
( [ "-i"
, concat
[ docRelFP FP.</> packageIdentifierString dpPackageIdent
, ","
, destInterfaceRelFP ]]
, srcInterfaceModTime
, srcInterfaceAbsFile
, destInterfaceAbsFile )
tryGetModificationTime :: Path Abs File -> IO (Either () UTCTime)
tryGetModificationTime = tryJust (guard . isDoesNotExistError) . getModificationTime
copyPkgDocs :: (a, UTCTime, Path Abs File, Path Abs File) -> IO ()
copyPkgDocs (_,srcInterfaceModTime,srcInterfaceAbsFile,destInterfaceAbsFile) = do
-- Copy dependencies' haddocks to documentation directory. This way, relative @../$pkg-$ver@
-- links work and it's easy to upload docs to a web server or otherwise view them in a
-- non-local-filesystem context. We copy instead of symlink for two reasons: (1) symlinks
-- aren't reliably supported on Windows, and (2) the filesystem containing dependencies'
-- docs may not be available where viewing the docs (e.g. if building in a Docker
-- container).
edestInterfaceModTime <- tryGetModificationTime destInterfaceAbsFile
case edestInterfaceModTime of
Left _ -> doCopy
Right destInterfaceModTime
| destInterfaceModTime < srcInterfaceModTime -> doCopy
| otherwise -> return ()
where
doCopy = do
ignoringAbsence (removeDirRecur destHtmlAbsDir)
ensureDir destHtmlAbsDir
onException
(copyDirRecur' (parent srcInterfaceAbsFile) destHtmlAbsDir)
(ignoringAbsence (removeDirRecur destHtmlAbsDir))
destHtmlAbsDir = parent destInterfaceAbsFile
-- | Find first DumpPackage matching the GhcPkgId
lookupDumpPackage :: GhcPkgId
-> [Map GhcPkgId (DumpPackage () ())]
-> Maybe (DumpPackage () ())
lookupDumpPackage ghcPkgId dumpPkgs =
listToMaybe $ mapMaybe (Map.lookup ghcPkgId) dumpPkgs
-- | Path of haddock index file.
haddockIndexFile :: Path Abs Dir -> Path Abs File
haddockIndexFile destDir = destDir </> $(mkRelFile "index.html")
-- | Path of local packages documentation directory.
localDocDir :: BaseConfigOpts -> Path Abs Dir
localDocDir bco = bcoLocalInstallRoot bco </> docDirSuffix
-- | Path of snapshot packages documentation directory.
snapDocDir :: BaseConfigOpts -> Path Abs Dir
snapDocDir bco = bcoSnapInstallRoot bco </> docDirSuffix
|
narrative/stack
|
src/Stack/Build/Haddock.hs
|
bsd-3-clause
| 11,044
| 0
| 24
| 3,649
| 2,229
| 1,159
| 1,070
| 216
| 5
|
{-# LANGUAGE OverloadedStrings #-}
module Cauterize.Dynamic.Common
( isNameOf
, lu
, fieldsToNameMap
, fieldsToIndexMap
, fieldNameSet
, isBuiltIn
, isSynonym
, isArray
, isVector
, isRecord
, isCombination
, isUnion
) where
import Cauterize.Dynamic.Types
import Control.Exception
import Data.Maybe
import qualified Data.Text.Lazy as T
import qualified Cauterize.Specification as S
import qualified Cauterize.Common.Types as C
import qualified Data.Map as M
import qualified Data.Set as Set
lu :: T.Text -> TyMap -> S.SpType
lu n m = fromMaybe (throw $ InvalidType n)
(n `M.lookup` m)
fieldsToNameMap :: [C.Field] -> M.Map T.Text C.Field
fieldsToNameMap fs = M.fromList $ map go fs
where
go f = (C.fName f, f)
fieldsToIndexMap :: [C.Field] -> M.Map Integer C.Field
fieldsToIndexMap fs = M.fromList $ map go fs
where
go f = (C.fIndex f, f)
fieldNameSet :: [C.Field] -> Set.Set T.Text
fieldNameSet fs = Set.fromList $ map C.fName fs
isNameOf :: T.Text -> BIDetails -> Bool
isNameOf "u8" (BDu8 _) = True
isNameOf "u16" (BDu16 _) = True
isNameOf "u32" (BDu32 _) = True
isNameOf "u64" (BDu64 _) = True
isNameOf "s8" (BDs8 _) = True
isNameOf "s16" (BDs16 _) = True
isNameOf "s32" (BDs32 _) = True
isNameOf "s64" (BDs64 _) = True
isNameOf "f32" (BDf32 _) = True
isNameOf "f64" (BDf64 _) = True
isNameOf "bool" (BDbool _) = True
isNameOf _ _ = False
isBuiltIn :: S.SpType -> Bool
isBuiltIn (S.BuiltIn {}) = True
isBuiltIn _ = False
isSynonym :: S.SpType -> Bool
isSynonym (S.Synonym {}) = True
isSynonym _ = False
isArray :: S.SpType -> Bool
isArray (S.Array {}) = True
isArray _ = False
isVector :: S.SpType -> Bool
isVector (S.Vector {}) = True
isVector _ = False
isRecord :: S.SpType -> Bool
isRecord (S.Record {}) = True
isRecord _ = False
isCombination :: S.SpType -> Bool
isCombination (S.Combination {}) = True
isCombination _ = False
isUnion :: S.SpType -> Bool
isUnion (S.Union {}) = True
isUnion _ = False
|
reiddraper/cauterize
|
src/Cauterize/Dynamic/Common.hs
|
bsd-3-clause
| 1,979
| 0
| 9
| 387
| 780
| 421
| 359
| 67
| 1
|
{-# LANGUAGE CPP #-}
module Import
( module X
-- * Utilities borrowed from 'errors'
, hush
, note
, fmapL
-- * Text-based string marshallers
, withTString
, withTStringLen
, withMaybeTString
, peekMaybeTString
-- * memory cleanup
, scrubbing
, scrubbing_
, scrubWith_
, scrubWith
) where
#if MIN_VERSION_base(4,8,0)
#else
import Control.Applicative as X
#endif
import Data.Char (chr)
import Data.Monoid as X
import Foreign as X
import Foreign.C.Types as X
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Foreign as T
import System.Win32.Error as X
import System.Win32.Error.Foreign as X
import System.Win32.Types as X
hiding ( ErrCode, failIfNull, failWith, failUnlessSuccess
, failIfFalse_, failIf, errorWin, withTString, withTStringLen)
import qualified System.Win32.Types as W32
-- |Peek a string that might be null. Null pointers become Nothing
peekMaybeTString :: LPTSTR -> IO (Maybe String)
peekMaybeTString ptr
| ptr == nullPtr = return Nothing
| otherwise = Just <$> peekTString ptr
-- |Temporarily marshal a Maybe String. A nothing becomes a null pointer.
withMaybeTString :: Maybe String -> (LPTSTR -> IO a) -> IO a
withMaybeTString Nothing f = f nullPtr
withMaybeTString (Just str) f = W32.withTString str f
withTStringLen :: Text -> (LPTSTR -> T.I16 -> IO a) -> IO a
withTStringLen text act = T.useAsPtr (T.snoc text (chr 0x0)) $ \ptr len ->
act (castPtr ptr) len
withTString :: Text -> (LPTSTR -> IO a) -> IO a
withTString text act = withTStringLen text $ \ptr _ -> act ptr
-- |Suppress the 'Left' value of an 'Either'
-- taken from the errors package
hush :: Either a b -> Maybe b
hush = either (const Nothing) Just
-- |taken from the errors package
note :: e -> Maybe a -> Either e a
note e Nothing = Left e
note _ (Just x) = Right x
-- |taken from the errors package
fmapL :: (a -> b) -> Either a r -> Either b r
fmapL f (Left x) = Left (f x)
fmapL _ (Right x) = (Right x)
-- | Perform an action over a double pointer, and then zero it out. If the
-- double pointer is already zeroed out, do nothing and return 'Nothing'.
scrubbing :: (Ptr a -> IO b) -> Ptr (Ptr a) -> IO (Maybe b)
scrubbing f pptr = do
ptr <- peek pptr
if ptr == nullPtr
then return Nothing
else do
ret <- f ptr
poke pptr nullPtr
return $ Just ret
-- |Perform a cleanup operation on memory.
scrubbing_ :: (Ptr a -> IO ()) -> Ptr (Ptr a) -> IO ()
scrubbing_ f pptr = do
_ <- scrubbing f pptr
return ()
scrubWith :: Ptr (Ptr a) -> (Ptr a -> IO b) -> IO (Maybe b)
scrubWith = flip scrubbing
scrubWith_ :: Ptr (Ptr a) -> (Ptr a -> IO ()) -> IO ()
scrubWith_ pptr f = do
_ <-scrubWith pptr f
return ()
|
mikesteele81/Win32-dhcp-server
|
src/Import.hs
|
bsd-3-clause
| 2,854
| 0
| 11
| 717
| 907
| 475
| 432
| 67
| 2
|
-- |
module BicomplexProperties where
import Control.Category.Constrained (id, (.))
import Control.Monad (forM_, unless)
import Math.Algebra.Combination
import Math.Algebra.ChainComplex
import Math.Algebra.Bicomplex
import Test.Hspec
import Prelude hiding (id, (.))
import ChainComplexProperties
checkChainConditions :: (Bicomplex a, Show (Bibasis a)) => a -> [Bibasis a] -> Spec
checkChainConditions a as = do
it "images under ∂v should be valid" $
forM_ as (\b -> vdiff a `onBasis` b `shouldSatisfy` validBicomb a)
it "images under ∂v should have the right dimension" $
forM_ as (\b -> let (h,v) = bidegree a b
in forM_ (coeffs $ vdiff a `onBasis` b) (\(_, c) -> bidegree a c `shouldBe` (h, v - 1)))
it "∂v ∘ ∂v = 0" $ (vdiff a . vdiff a) `isZeroOnAll` as
it "images under ∂h should be valid" $
forM_ as (\b -> hdiff a `onBasis` b `shouldSatisfy` validBicomb a)
it "images under ∂h should have the right dimension" $
forM_ as (\b -> let (h, v) = bidegree a b
in forM_ (coeffs $ hdiff a `onBasis` b) (\(_, c) -> bidegree a c `shouldBe` (h - 1, v)))
it "∂h ∘ ∂h = 0" $ (hdiff a . hdiff a) `isZeroOnAll` as
it "∂v ∘ ∂h = -∂h ∘ ∂v" $ (vdiff a . hdiff a, negate (hdiff a . vdiff a)) `isEqOnAll` as
-- checkChainMap :: (Bicomplex a, Bicomplex a', Show (Bibasis a'), Show (Bibasis a)) => a -> a' -> String -> [Bibasis a] -> Bimorphism a a' -> Spec
-- checkChainMap a a' name as m = do
-- it "images should be valid" $
-- forM_ as (\b -> m `onBibasis` b `shouldSatisfy` validComb a')
-- it ("∂ ∘ " ++ name ++ " = " ++ name ++ " ∘ ∂") $ (diff a' . m, m . diff a) `isEqOnAll` as
|
mvr/at
|
test/BicomplexProperties.hs
|
bsd-3-clause
| 1,685
| 0
| 18
| 371
| 521
| 282
| 239
| -1
| -1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Distributed.Process.Task.Pool.Internal.Types
-- Copyright : (c) Tim Watson 2017
-- License : BSD3 (see the file LICENSE)
--
-- Maintainer : Tim Watson <watson.timothy@gmail.com>
-- Stability : experimental
-- Portability : non-portable (requires concurrency)
--
-- = WARNING
--
-- This module is considered __internal__.
--
-- The Package Versioning Policy __does not apply__.
--
-- This contents of this module may change __in any way whatsoever__
-- and __without any warning__ between minor versions of this package.
--
-- Authors importing this module are expected to track development
-- closely.
--
-- [Process Pool (Types)]
--
-- This module contains types common to all pool implementations.
--
-----------------------------------------------------------------------------
module Control.Distributed.Process.Task.Pool.Internal.Types
( -- Client Handles & Command Messages
ResourcePool(..)
, AcquireResource(..)
, ReleaseResource(..)
, TransferRequest(..)
, TransferResponse(..)
, StatsReq(..)
-- Statistics
, PoolStats(..)
, PoolStatsInfo(..)
-- Policy, Strategy, and Internal
, ReclamationStrategy(..)
, Status(..)
, InitPolicy(..)
, RotationPolicy(..)
, Take(..)
, Ticket(..)
, baseErrorMessage
-- Resource Types, Pool Backends and the Pool monad.
, Referenced
, Resource(..)
, ResourceQueue(..)
, PoolBackend(..)
, PoolState(..)
, initialPoolState
, Pool(..)
-- Lenses
, resourceQueue
, queueRotationPolicy
, available
, busy
) where
import Control.DeepSeq (NFData)
import Control.Distributed.Process
( Process
, ProcessId
, Message
, SendPort
, link
)
import Control.Distributed.Process.Extras.Internal.Types
( Resolvable(..)
, Routable(..)
, Addressable
, Linkable(..)
, NFSerializable
, ExitReason(..)
)
-- import Control.Distributed.Process.Supervisor (SupervisorPid)
import Control.Distributed.Process.Serializable
import Control.Monad.IO.Class (MonadIO)
import qualified Control.Monad.State as ST
( StateT
, MonadState
)
import Data.Accessor (Accessor, accessor)
import Data.Binary
import Data.Hashable
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq (empty)
import Data.Set (Set)
import qualified Data.Set as Set (empty)
import Data.Rank1Typeable (TypeRep)
import Data.Typeable (Typeable)
import GHC.Generics
--------------------------------------------------------------------------------
-- Client Handles & Command Messages --
--------------------------------------------------------------------------------
data ResourcePool r = ResourcePool { poolAddr :: !ProcessId }
deriving (Typeable, Generic, Eq, Show)
instance (Serializable r) => Binary (ResourcePool r) where
instance (NFData r) => NFData (ResourcePool r) where
instance (Referenced r) => NFSerializable (ResourcePool r) where
instance Linkable (ResourcePool r) where
linkTo = link . poolAddr
instance Resolvable (ResourcePool r) where
resolve = return . Just . poolAddr
instance Routable (ResourcePool r) where
sendTo = sendTo . poolAddr
unsafeSendTo = unsafeSendTo . poolAddr
instance Addressable (ResourcePool r)
class (NFSerializable r, Hashable r, Eq r, Ord r, Show r) => Referenced r
instance (NFSerializable r, Hashable r, Eq r, Ord r, Show r) => Referenced r
data AcquireResource = AcquireResource ProcessId
deriving (Typeable, Generic, Eq, Show)
instance Binary AcquireResource where
instance NFData AcquireResource where
data ReleaseResource r = ReleaseResource r ProcessId
deriving (Typeable, Generic)
instance (Serializable r) => Binary (ReleaseResource r) where
instance (NFData r) => NFData (ReleaseResource r) where
data TransferRequest r = TransferRequest { resourceHandle :: r
, newOwner :: ProcessId
, currentOwner :: ProcessId
}
deriving (Typeable, Generic)
instance (Serializable r) => Binary (TransferRequest r) where
instance (NFData r) => NFData (TransferRequest r) where
data TransferResponse = Transfered { location :: ProcessId }
| InvalidResource
| InvalidOwner
deriving (Typeable, Generic, Eq, Show)
instance Binary TransferResponse where
instance NFData TransferResponse where
data StatsReq = StatsReq deriving (Typeable, Generic)
instance Binary StatsReq where
instance NFData StatsReq where
data Ticket r = Ticket { ticketOwner :: ProcessId
, ticketChan :: SendPort r
} deriving (Typeable)
baseErrorMessage :: String
baseErrorMessage = "Control.Distributed.Process.Task.Pool"
--------------------------------------------------------------------------------
-- Statistics --
--------------------------------------------------------------------------------
data PoolStatsInfo = PoolStatsInfo String String |
PoolStatsTypeInfo String TypeRep |
PoolStatsData String Message |
PoolStatsCounter String Integer |
PoolStatsDouble String Double
deriving (Typeable, Generic, Show)
instance Binary PoolStatsInfo where
data PoolStats = PoolStats { totalResources :: Integer
, activeResources :: Int
, inactiveResources :: Int
, lockedResources :: Int
, activeClients :: Int
, pendingClients :: Int
, backendStats :: [PoolStatsInfo]
} deriving (Typeable, Generic, Show)
instance Binary PoolStats where
--------------------------------------------------------------------------------
-- Resource Types, Pool Backends and the @Pool@ monad. --
--------------------------------------------------------------------------------
data ReclamationStrategy = Release | Destroy | PermLock deriving (Eq, Show)
data Status = Alive | Dead | Unknown
data InitPolicy = OnDemand | OnInit deriving (Typeable, Eq, Show)
-- We use 'RotationPolicy' to determine whether released resources are applied
-- to the head or tail of the ResourceQueue. We always dequeue the 'head'
-- element (i.e., the left side of the sequence).
data RotationPolicy s r = LRU
| MRU
| Custom (PoolState s r -> r -> PoolState s r)
data Take r = Block | Take r
instance (Eq r) => Eq (Take r) where
Block == Block = True
Block == _ = False
_ == Block = False
(Take a) == (Take b) = a == b
instance Show r => Show (Take r) where
show Block = "Block"
show (Take r) = "Take[" ++ (show r) ++ "]"
data Resource r =
Resource { create :: Process r
, destroy :: r -> Process ()
, checkRef :: Message -> r -> Process (Maybe Status)
, accept :: (Ticket r) -> r -> Process ()
}
data ResourceQueue r = ResourceQueue { _available :: Seq r
, _busy :: Set r
} deriving (Typeable)
data PoolBackend s r =
PoolBackend { acquire :: Pool s r (Take r)
, release :: r -> Pool s r ()
, dispose :: r -> Pool s r ()
, setup :: Pool s r ()
, teardown :: ExitReason -> Pool s r ()
, infoCall :: Message -> Pool s r ()
, getStats :: Pool s r [PoolStatsInfo]
}
data PoolState s r = PoolState { queue :: ResourceQueue r
, initPolicy :: InitPolicy
, rotationPolicy :: RotationPolicy s r
, internalState :: s
, resourceType :: Resource r
, isDirty :: Bool
} deriving (Typeable)
initialPoolState :: forall s r. (Referenced r)
=> Resource r
-> InitPolicy
-> RotationPolicy s r
-> s
-> PoolState s r
initialPoolState rt ip rp st =
PoolState { queue = ResourceQueue Seq.empty Set.empty
, initPolicy = ip
, rotationPolicy = rp
, internalState = st
, resourceType = rt
, isDirty = False
}
newtype Pool s r a = Pool { unPool :: ST.StateT (PoolState s r) Process a }
deriving ( Functor
, Monad
, MonadIO
, Typeable
, Applicative
, ST.MonadState (PoolState s r)
)
-- PoolState and ResourceQueue lenses
resourceQueue :: forall s r. Accessor (PoolState s r) (ResourceQueue r)
resourceQueue = accessor queue (\q' st -> st { queue = q' })
queueRotationPolicy :: forall s r . Accessor (PoolState s r) (RotationPolicy s r)
queueRotationPolicy = accessor rotationPolicy (\p' st -> st { rotationPolicy = p' })
available :: forall r. Accessor (ResourceQueue r) (Seq r)
available = accessor _available (\q' st -> st { _available = q' })
busy :: forall r. Accessor (ResourceQueue r) (Set r)
busy = accessor _busy (\s' st -> st { _busy = s' })
|
haskell-distributed/distributed-process-task
|
src/Control/Distributed/Process/Task/Pool/Internal/Types.hs
|
bsd-3-clause
| 9,894
| 0
| 13
| 2,826
| 2,162
| 1,256
| 906
| -1
| -1
|
module Main where
import Parser
import Core
import Typecheck
main = do
f <- readFile "test.hdep"
let Right defs = parseFile f
print defs
let ctxt = checkProgram [] defs
print ctxt
|
jxwr/hdep
|
src/Main.hs
|
bsd-3-clause
| 193
| 0
| 11
| 45
| 72
| 33
| 39
| 10
| 1
|
{-# LANGUAGE DeriveDataTypeable, CPP, MultiParamTypeClasses,
FlexibleContexts, ScopedTypeVariables, PatternGuards,
ViewPatterns #-}
{-
Copyright (C) 2006-2015 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Shared
Copyright : Copyright (C) 2006-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Utility functions and definitions used by the various Pandoc modules.
-}
module Text.Pandoc.Shared (
-- * List processing
splitBy,
splitByIndices,
splitStringByIndices,
substitute,
ordNub,
-- * Text processing
backslashEscapes,
escapeStringUsing,
stripTrailingNewlines,
trim,
triml,
trimr,
stripFirstAndLast,
camelCaseToHyphenated,
toRomanNumeral,
escapeURI,
tabFilter,
-- * Date/time
normalizeDate,
-- * Pandoc block and inline list processing
orderedListMarkers,
normalizeSpaces,
extractSpaces,
normalize,
normalizeInlines,
normalizeBlocks,
removeFormatting,
stringify,
capitalize,
compactify,
compactify',
compactify'DL,
Element (..),
hierarchicalize,
uniqueIdent,
isHeaderBlock,
headerShift,
isTightList,
addMetaField,
makeMeta,
-- * TagSoup HTML handling
renderTags',
-- * File handling
inDirectory,
getDefaultReferenceDocx,
getDefaultReferenceODT,
readDataFile,
readDataFileUTF8,
fetchItem,
fetchItem',
openURL,
collapseFilePath,
-- * Error handling
err,
warn,
mapLeft,
hush,
-- * Safe read
safeRead,
-- * Temp directory
withTempDir
) where
import Text.Pandoc.Definition
import Text.Pandoc.Walk
import Text.Pandoc.MediaBag (MediaBag, lookupMedia)
import Text.Pandoc.Builder (Inlines, Blocks, ToMetaValue(..))
import qualified Text.Pandoc.Builder as B
import qualified Text.Pandoc.UTF8 as UTF8
import System.Environment (getProgName)
import System.Exit (exitWith, ExitCode(..))
import Data.Char ( toLower, isLower, isUpper, isAlpha,
isLetter, isDigit, isSpace )
import Data.List ( find, stripPrefix, intercalate )
import qualified Data.Map as M
import Network.URI ( escapeURIString, isURI, nonStrictRelativeTo,
unEscapeString, parseURIReference, isAllowedInURI )
import qualified Data.Set as Set
import System.Directory
import System.FilePath (splitDirectories, isPathSeparator)
import qualified System.FilePath.Posix as Posix
import Text.Pandoc.MIME (MimeType, getMimeType)
import System.FilePath ( (</>), takeExtension, dropExtension)
import Data.Generics (Typeable, Data)
import qualified Control.Monad.State as S
import qualified Control.Exception as E
import Control.Applicative ((<$>))
import Control.Monad (msum, unless, MonadPlus(..))
import Text.Pandoc.Pretty (charWidth)
import Text.Pandoc.Compat.Locale (defaultTimeLocale)
import Data.Time
import Data.Time.Clock.POSIX
import System.IO (stderr)
import System.IO.Temp
import Text.HTML.TagSoup (renderTagsOptions, RenderOptions(..), Tag(..),
renderOptions)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B8
import Text.Pandoc.Compat.Monoid
import Data.ByteString.Base64 (decodeLenient)
import Data.Sequence (ViewR(..), ViewL(..), viewl, viewr)
import qualified Data.Text as T (toUpper, pack, unpack)
import Data.ByteString.Lazy (toChunks, fromChunks)
import qualified Data.ByteString.Lazy as BL
import Codec.Archive.Zip
#ifdef EMBED_DATA_FILES
import Text.Pandoc.Data (dataFiles)
#else
import Paths_pandoc (getDataFileName)
#endif
#ifdef HTTP_CLIENT
import Network.HTTP.Client (httpLbs, parseUrl,
responseBody, responseHeaders,
Request(port,host))
#if MIN_VERSION_http_client(0,4,18)
import Network.HTTP.Client (newManager)
#else
import Network.HTTP.Client (withManager)
#endif
import Network.HTTP.Client.Internal (addProxy)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import System.Environment (getEnv)
import Network.HTTP.Types.Header ( hContentType)
import Network (withSocketsDo)
#else
import Network.URI (parseURI)
import Network.HTTP (findHeader, rspBody,
RequestMethod(..), HeaderName(..), mkRequest)
import Network.Browser (browse, setAllowRedirects, setOutHandler, request)
#endif
--
-- List processing
--
-- | Split list by groups of one or more sep.
splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy _ [] = []
splitBy isSep lst =
let (first, rest) = break isSep lst
rest' = dropWhile isSep rest
in first:(splitBy isSep rest')
splitByIndices :: [Int] -> [a] -> [[a]]
splitByIndices [] lst = [lst]
splitByIndices (x:xs) lst = first:(splitByIndices (map (\y -> y - x) xs) rest)
where (first, rest) = splitAt x lst
-- | Split string into chunks divided at specified indices.
splitStringByIndices :: [Int] -> [Char] -> [[Char]]
splitStringByIndices [] lst = [lst]
splitStringByIndices (x:xs) lst =
let (first, rest) = splitAt' x lst in
first : (splitStringByIndices (map (\y -> y - x) xs) rest)
splitAt' :: Int -> [Char] -> ([Char],[Char])
splitAt' _ [] = ([],[])
splitAt' n xs | n <= 0 = ([],xs)
splitAt' n (x:xs) = (x:ys,zs)
where (ys,zs) = splitAt' (n - charWidth x) xs
-- | Replace each occurrence of one sublist in a list with another.
substitute :: (Eq a) => [a] -> [a] -> [a] -> [a]
substitute _ _ [] = []
substitute [] _ xs = xs
substitute target replacement lst@(x:xs) =
case stripPrefix target lst of
Just lst' -> replacement ++ substitute target replacement lst'
Nothing -> x : substitute target replacement xs
ordNub :: (Ord a) => [a] -> [a]
ordNub l = go Set.empty l
where
go _ [] = []
go s (x:xs) = if x `Set.member` s then go s xs
else x : go (Set.insert x s) xs
--
-- Text processing
--
-- | Returns an association list of backslash escapes for the
-- designated characters.
backslashEscapes :: [Char] -- ^ list of special characters to escape
-> [(Char, String)]
backslashEscapes = map (\ch -> (ch, ['\\',ch]))
-- | Escape a string of characters, using an association list of
-- characters and strings.
escapeStringUsing :: [(Char, String)] -> String -> String
escapeStringUsing _ [] = ""
escapeStringUsing escapeTable (x:xs) =
case (lookup x escapeTable) of
Just str -> str ++ rest
Nothing -> x:rest
where rest = escapeStringUsing escapeTable xs
-- | Strip trailing newlines from string.
stripTrailingNewlines :: String -> String
stripTrailingNewlines = reverse . dropWhile (== '\n') . reverse
-- | Remove leading and trailing space (including newlines) from string.
trim :: String -> String
trim = triml . trimr
-- | Remove leading space (including newlines) from string.
triml :: String -> String
triml = dropWhile (`elem` " \r\n\t")
-- | Remove trailing space (including newlines) from string.
trimr :: String -> String
trimr = reverse . triml . reverse
-- | Strip leading and trailing characters from string
stripFirstAndLast :: String -> String
stripFirstAndLast str =
drop 1 $ take ((length str) - 1) str
-- | Change CamelCase word to hyphenated lowercase (e.g., camel-case).
camelCaseToHyphenated :: String -> String
camelCaseToHyphenated [] = ""
camelCaseToHyphenated (a:b:rest) | isLower a && isUpper b =
a:'-':(toLower b):(camelCaseToHyphenated rest)
camelCaseToHyphenated (a:rest) = (toLower a):(camelCaseToHyphenated rest)
-- | Convert number < 4000 to uppercase roman numeral.
toRomanNumeral :: Int -> String
toRomanNumeral x =
if x >= 4000 || x < 0
then "?"
else case x of
_ | x >= 1000 -> "M" ++ toRomanNumeral (x - 1000)
_ | x >= 900 -> "CM" ++ toRomanNumeral (x - 900)
_ | x >= 500 -> "D" ++ toRomanNumeral (x - 500)
_ | x >= 400 -> "CD" ++ toRomanNumeral (x - 400)
_ | x >= 100 -> "C" ++ toRomanNumeral (x - 100)
_ | x >= 90 -> "XC" ++ toRomanNumeral (x - 90)
_ | x >= 50 -> "L" ++ toRomanNumeral (x - 50)
_ | x >= 40 -> "XL" ++ toRomanNumeral (x - 40)
_ | x >= 10 -> "X" ++ toRomanNumeral (x - 10)
_ | x == 9 -> "IX"
_ | x >= 5 -> "V" ++ toRomanNumeral (x - 5)
_ | x == 4 -> "IV"
_ | x >= 1 -> "I" ++ toRomanNumeral (x - 1)
_ -> ""
-- | Escape whitespace in URI.
escapeURI :: String -> String
escapeURI = escapeURIString (not . isSpace)
-- | Convert tabs to spaces and filter out DOS line endings.
-- Tabs will be preserved if tab stop is set to 0.
tabFilter :: Int -- ^ Tab stop
-> String -- ^ Input
-> String
tabFilter tabStop =
let go _ [] = ""
go _ ('\n':xs) = '\n' : go tabStop xs
go _ ('\r':'\n':xs) = '\n' : go tabStop xs
go _ ('\r':xs) = '\n' : go tabStop xs
go spsToNextStop ('\t':xs) =
if tabStop == 0
then '\t' : go tabStop xs
else replicate spsToNextStop ' ' ++ go tabStop xs
go 1 (x:xs) =
x : go tabStop xs
go spsToNextStop (x:xs) =
x : go (spsToNextStop - 1) xs
in go tabStop
--
-- Date/time
--
-- | Parse a date and convert (if possible) to "YYYY-MM-DD" format.
normalizeDate :: String -> Maybe String
normalizeDate s = fmap (formatTime defaultTimeLocale "%F")
(msum $ map (\fs -> parsetimeWith fs s) formats :: Maybe Day)
where parsetimeWith = parseTime defaultTimeLocale
formats = ["%x","%m/%d/%Y", "%D","%F", "%d %b %Y",
"%d %B %Y", "%b. %d, %Y", "%B %d, %Y", "%Y"]
--
-- Pandoc block and inline list processing
--
-- | Generate infinite lazy list of markers for an ordered list,
-- depending on list attributes.
orderedListMarkers :: (Int, ListNumberStyle, ListNumberDelim) -> [String]
orderedListMarkers (start, numstyle, numdelim) =
let singleton c = [c]
nums = case numstyle of
DefaultStyle -> map show [start..]
Example -> map show [start..]
Decimal -> map show [start..]
UpperAlpha -> drop (start - 1) $ cycle $
map singleton ['A'..'Z']
LowerAlpha -> drop (start - 1) $ cycle $
map singleton ['a'..'z']
UpperRoman -> map toRomanNumeral [start..]
LowerRoman -> map (map toLower . toRomanNumeral) [start..]
inDelim str = case numdelim of
DefaultDelim -> str ++ "."
Period -> str ++ "."
OneParen -> str ++ ")"
TwoParens -> "(" ++ str ++ ")"
in map inDelim nums
-- | Normalize a list of inline elements: remove leading and trailing
-- @Space@ elements, collapse double @Space@s into singles, and
-- remove empty Str elements.
normalizeSpaces :: [Inline] -> [Inline]
normalizeSpaces = cleanup . dropWhile isSpaceOrEmpty
where cleanup [] = []
cleanup (Space:rest) = case dropWhile isSpaceOrEmpty rest of
[] -> []
(x:xs) -> Space : x : cleanup xs
cleanup ((Str ""):rest) = cleanup rest
cleanup (x:rest) = x : cleanup rest
isSpaceOrEmpty :: Inline -> Bool
isSpaceOrEmpty Space = True
isSpaceOrEmpty (Str "") = True
isSpaceOrEmpty _ = False
-- | Extract the leading and trailing spaces from inside an inline element
-- and place them outside the element.
extractSpaces :: (Inlines -> Inlines) -> Inlines -> Inlines
extractSpaces f is =
let contents = B.unMany is
left = case viewl contents of
(Space :< _) -> B.space
_ -> mempty
right = case viewr contents of
(_ :> Space) -> B.space
_ -> mempty in
(left <> f (B.trimInlines . B.Many $ contents) <> right)
-- | Normalize @Pandoc@ document, consolidating doubled 'Space's,
-- combining adjacent 'Str's and 'Emph's, remove 'Null's and
-- empty elements, etc.
normalize :: Pandoc -> Pandoc
normalize (Pandoc (Meta meta) blocks) =
Pandoc (Meta $ M.map go meta) (normalizeBlocks blocks)
where go (MetaInlines xs) = MetaInlines $ normalizeInlines xs
go (MetaBlocks xs) = MetaBlocks $ normalizeBlocks xs
go (MetaList ms) = MetaList $ map go ms
go (MetaMap m) = MetaMap $ M.map go m
go x = x
normalizeBlocks :: [Block] -> [Block]
normalizeBlocks (Null : xs) = normalizeBlocks xs
normalizeBlocks (Div attr bs : xs) =
Div attr (normalizeBlocks bs) : normalizeBlocks xs
normalizeBlocks (BlockQuote bs : xs) =
case normalizeBlocks bs of
[] -> normalizeBlocks xs
bs' -> BlockQuote bs' : normalizeBlocks xs
normalizeBlocks (BulletList [] : xs) = normalizeBlocks xs
normalizeBlocks (BulletList items : xs) =
BulletList (map normalizeBlocks items) : normalizeBlocks xs
normalizeBlocks (OrderedList _ [] : xs) = normalizeBlocks xs
normalizeBlocks (OrderedList attr items : xs) =
OrderedList attr (map normalizeBlocks items) : normalizeBlocks xs
normalizeBlocks (DefinitionList [] : xs) = normalizeBlocks xs
normalizeBlocks (DefinitionList items : xs) =
DefinitionList (map go items) : normalizeBlocks xs
where go (ils, bs) = (normalizeInlines ils, map normalizeBlocks bs)
normalizeBlocks (RawBlock _ "" : xs) = normalizeBlocks xs
normalizeBlocks (RawBlock f x : xs) =
case normalizeBlocks xs of
(RawBlock f' x' : rest) | f' == f ->
RawBlock f (x ++ ('\n':x')) : rest
rest -> RawBlock f x : rest
normalizeBlocks (Para ils : xs) =
case normalizeInlines ils of
[] -> normalizeBlocks xs
ils' -> Para ils' : normalizeBlocks xs
normalizeBlocks (Plain ils : xs) =
case normalizeInlines ils of
[] -> normalizeBlocks xs
ils' -> Plain ils' : normalizeBlocks xs
normalizeBlocks (Header lev attr ils : xs) =
Header lev attr (normalizeInlines ils) : normalizeBlocks xs
normalizeBlocks (Table capt aligns widths hdrs rows : xs) =
Table (normalizeInlines capt) aligns widths
(map normalizeBlocks hdrs) (map (map normalizeBlocks) rows)
: normalizeBlocks xs
normalizeBlocks (x:xs) = x : normalizeBlocks xs
normalizeBlocks [] = []
normalizeInlines :: [Inline] -> [Inline]
normalizeInlines (Str x : ys) =
case concat (x : map fromStr strs) of
"" -> rest
n -> Str n : rest
where
(strs, rest) = span isStr $ normalizeInlines ys
isStr (Str _) = True
isStr _ = False
fromStr (Str z) = z
fromStr _ = error "normalizeInlines - fromStr - not a Str"
normalizeInlines (Space : ys) =
if null rest
then []
else Space : rest
where isSp Space = True
isSp _ = False
rest = dropWhile isSp $ normalizeInlines ys
normalizeInlines (Emph xs : zs) =
case normalizeInlines zs of
(Emph ys : rest) -> normalizeInlines $
Emph (normalizeInlines $ xs ++ ys) : rest
rest -> case normalizeInlines xs of
[] -> rest
xs' -> Emph xs' : rest
normalizeInlines (Strong xs : zs) =
case normalizeInlines zs of
(Strong ys : rest) -> normalizeInlines $
Strong (normalizeInlines $ xs ++ ys) : rest
rest -> case normalizeInlines xs of
[] -> rest
xs' -> Strong xs' : rest
normalizeInlines (Subscript xs : zs) =
case normalizeInlines zs of
(Subscript ys : rest) -> normalizeInlines $
Subscript (normalizeInlines $ xs ++ ys) : rest
rest -> case normalizeInlines xs of
[] -> rest
xs' -> Subscript xs' : rest
normalizeInlines (Superscript xs : zs) =
case normalizeInlines zs of
(Superscript ys : rest) -> normalizeInlines $
Superscript (normalizeInlines $ xs ++ ys) : rest
rest -> case normalizeInlines xs of
[] -> rest
xs' -> Superscript xs' : rest
normalizeInlines (SmallCaps xs : zs) =
case normalizeInlines zs of
(SmallCaps ys : rest) -> normalizeInlines $
SmallCaps (normalizeInlines $ xs ++ ys) : rest
rest -> case normalizeInlines xs of
[] -> rest
xs' -> SmallCaps xs' : rest
normalizeInlines (Strikeout xs : zs) =
case normalizeInlines zs of
(Strikeout ys : rest) -> normalizeInlines $
Strikeout (normalizeInlines $ xs ++ ys) : rest
rest -> case normalizeInlines xs of
[] -> rest
xs' -> Strikeout xs' : rest
normalizeInlines (RawInline _ [] : ys) = normalizeInlines ys
normalizeInlines (RawInline f xs : zs) =
case normalizeInlines zs of
(RawInline f' ys : rest) | f == f' -> normalizeInlines $
RawInline f (xs ++ ys) : rest
rest -> RawInline f xs : rest
normalizeInlines (Code _ "" : ys) = normalizeInlines ys
normalizeInlines (Code attr xs : zs) =
case normalizeInlines zs of
(Code attr' ys : rest) | attr == attr' -> normalizeInlines $
Code attr (xs ++ ys) : rest
rest -> Code attr xs : rest
-- allow empty spans, they may carry identifiers etc.
-- normalizeInlines (Span _ [] : ys) = normalizeInlines ys
normalizeInlines (Span attr xs : zs) =
case normalizeInlines zs of
(Span attr' ys : rest) | attr == attr' -> normalizeInlines $
Span attr (normalizeInlines $ xs ++ ys) : rest
rest -> Span attr (normalizeInlines xs) : rest
normalizeInlines (Note bs : ys) = Note (normalizeBlocks bs) :
normalizeInlines ys
normalizeInlines (Quoted qt ils : ys) =
Quoted qt (normalizeInlines ils) : normalizeInlines ys
normalizeInlines (Link ils t : ys) =
Link (normalizeInlines ils) t : normalizeInlines ys
normalizeInlines (Image ils t : ys) =
Image (normalizeInlines ils) t : normalizeInlines ys
normalizeInlines (Cite cs ils : ys) =
Cite cs (normalizeInlines ils) : normalizeInlines ys
normalizeInlines (x : xs) = x : normalizeInlines xs
normalizeInlines [] = []
-- | Extract inlines, removing formatting.
removeFormatting :: Walkable Inline a => a -> [Inline]
removeFormatting = query go . walk deNote
where go :: Inline -> [Inline]
go (Str xs) = [Str xs]
go Space = [Space]
go (Code _ x) = [Str x]
go (Math _ x) = [Str x]
go LineBreak = [Space]
go _ = []
deNote (Note _) = Str ""
deNote x = x
-- | Convert pandoc structure to a string with formatting removed.
-- Footnotes are skipped (since we don't want their contents in link
-- labels).
stringify :: Walkable Inline a => a -> String
stringify = query go . walk deNote
where go :: Inline -> [Char]
go Space = " "
go (Str x) = x
go (Code _ x) = x
go (Math _ x) = x
go (RawInline (Format "html") ('<':'b':'r':_)) = " " -- see #2105
go LineBreak = " "
go _ = ""
deNote (Note _) = Str ""
deNote x = x
-- | Bring all regular text in a pandoc structure to uppercase.
--
-- This function correctly handles cases where a lowercase character doesn't
-- match to a single uppercase character – e.g. “Straße” would be converted
-- to “STRASSE”, not “STRAßE”.
capitalize :: Walkable Inline a => a -> a
capitalize = walk go
where go :: Inline -> Inline
go (Str s) = Str (T.unpack $ T.toUpper $ T.pack s)
go x = x
-- | Change final list item from @Para@ to @Plain@ if the list contains
-- no other @Para@ blocks.
compactify :: [[Block]] -- ^ List of list items (each a list of blocks)
-> [[Block]]
compactify [] = []
compactify items =
case (init items, last items) of
(_,[]) -> items
(others, final) ->
case last final of
Para a -> case (filter isPara $ concat items) of
-- if this is only Para, change to Plain
[_] -> others ++ [init final ++ [Plain a]]
_ -> items
_ -> items
-- | Change final list item from @Para@ to @Plain@ if the list contains
-- no other @Para@ blocks. Like compactify, but operates on @Blocks@ rather
-- than @[Block]@.
compactify' :: [Blocks] -- ^ List of list items (each a list of blocks)
-> [Blocks]
compactify' [] = []
compactify' items =
let (others, final) = (init items, last items)
in case reverse (B.toList final) of
(Para a:xs) -> case [Para x | Para x <- concatMap B.toList items] of
-- if this is only Para, change to Plain
[_] -> others ++ [B.fromList (reverse $ Plain a : xs)]
_ -> items
_ -> items
-- | Like @compactify'@, but acts on items of definition lists.
compactify'DL :: [(Inlines, [Blocks])] -> [(Inlines, [Blocks])]
compactify'DL items =
let defs = concatMap snd items
in case reverse (concatMap B.toList defs) of
(Para x:xs)
| not (any isPara xs) ->
let (t,ds) = last items
lastDef = B.toList $ last ds
ds' = init ds ++
if null lastDef
then [B.fromList lastDef]
else [B.fromList $ init lastDef ++ [Plain x]]
in init items ++ [(t, ds')]
| otherwise -> items
_ -> items
isPara :: Block -> Bool
isPara (Para _) = True
isPara _ = False
-- | Data structure for defining hierarchical Pandoc documents
data Element = Blk Block
| Sec Int [Int] Attr [Inline] [Element]
-- lvl num attributes label contents
deriving (Eq, Read, Show, Typeable, Data)
instance Walkable Inline Element where
walk f (Blk x) = Blk (walk f x)
walk f (Sec lev nums attr ils elts) = Sec lev nums attr (walk f ils) (walk f elts)
walkM f (Blk x) = Blk `fmap` walkM f x
walkM f (Sec lev nums attr ils elts) = do
ils' <- walkM f ils
elts' <- walkM f elts
return $ Sec lev nums attr ils' elts'
query f (Blk x) = query f x
query f (Sec _ _ _ ils elts) = query f ils <> query f elts
instance Walkable Block Element where
walk f (Blk x) = Blk (walk f x)
walk f (Sec lev nums attr ils elts) = Sec lev nums attr (walk f ils) (walk f elts)
walkM f (Blk x) = Blk `fmap` walkM f x
walkM f (Sec lev nums attr ils elts) = do
ils' <- walkM f ils
elts' <- walkM f elts
return $ Sec lev nums attr ils' elts'
query f (Blk x) = query f x
query f (Sec _ _ _ ils elts) = query f ils <> query f elts
-- | Convert Pandoc inline list to plain text identifier. HTML
-- identifiers must start with a letter, and may contain only
-- letters, digits, and the characters _-.
inlineListToIdentifier :: [Inline] -> String
inlineListToIdentifier =
dropWhile (not . isAlpha) . intercalate "-" . words .
map (nbspToSp . toLower) .
filter (\c -> isLetter c || isDigit c || c `elem` "_-. ") .
stringify
where nbspToSp '\160' = ' '
nbspToSp x = x
-- | Convert list of Pandoc blocks into (hierarchical) list of Elements
hierarchicalize :: [Block] -> [Element]
hierarchicalize blocks = S.evalState (hierarchicalizeWithIds blocks) []
hierarchicalizeWithIds :: [Block] -> S.State [Int] [Element]
hierarchicalizeWithIds [] = return []
hierarchicalizeWithIds ((Header level attr@(_,classes,_) title'):xs) = do
lastnum <- S.get
let lastnum' = take level lastnum
let newnum = case length lastnum' of
x | "unnumbered" `elem` classes -> []
| x >= level -> init lastnum' ++ [last lastnum' + 1]
| otherwise -> lastnum ++
replicate (level - length lastnum - 1) 0 ++ [1]
unless (null newnum) $ S.put newnum
let (sectionContents, rest) = break (headerLtEq level) xs
sectionContents' <- hierarchicalizeWithIds sectionContents
rest' <- hierarchicalizeWithIds rest
return $ Sec level newnum attr title' sectionContents' : rest'
hierarchicalizeWithIds ((Div ("",["references"],[])
(Header level (ident,classes,kvs) title' : xs)):ys) =
hierarchicalizeWithIds ((Header level (ident,("references":classes),kvs)
title') : (xs ++ ys))
hierarchicalizeWithIds (x:rest) = do
rest' <- hierarchicalizeWithIds rest
return $ (Blk x) : rest'
headerLtEq :: Int -> Block -> Bool
headerLtEq level (Header l _ _) = l <= level
headerLtEq level (Div ("",["references"],[]) (Header l _ _ : _)) = l <= level
headerLtEq _ _ = False
-- | Generate a unique identifier from a list of inlines.
-- Second argument is a list of already used identifiers.
uniqueIdent :: [Inline] -> [String] -> String
uniqueIdent title' usedIdents
= let baseIdent = case inlineListToIdentifier title' of
"" -> "section"
x -> x
numIdent n = baseIdent ++ "-" ++ show n
in if baseIdent `elem` usedIdents
then case find (\x -> numIdent x `notElem` usedIdents) ([1..60000] :: [Int]) of
Just x -> numIdent x
Nothing -> baseIdent -- if we have more than 60,000, allow repeats
else baseIdent
-- | True if block is a Header block.
isHeaderBlock :: Block -> Bool
isHeaderBlock (Header _ _ _) = True
isHeaderBlock _ = False
-- | Shift header levels up or down.
headerShift :: Int -> Pandoc -> Pandoc
headerShift n = walk shift
where shift :: Block -> Block
shift (Header level attr inner) = Header (level + n) attr inner
shift x = x
-- | Detect if a list is tight.
isTightList :: [[Block]] -> Bool
isTightList = all firstIsPlain
where firstIsPlain (Plain _ : _) = True
firstIsPlain _ = False
-- | Set a field of a 'Meta' object. If the field already has a value,
-- convert it into a list with the new value appended to the old value(s).
addMetaField :: ToMetaValue a
=> String
-> a
-> Meta
-> Meta
addMetaField key val (Meta meta) =
Meta $ M.insertWith combine key (toMetaValue val) meta
where combine newval (MetaList xs) = MetaList (xs ++ tolist newval)
combine newval x = MetaList [x, newval]
tolist (MetaList ys) = ys
tolist y = [y]
-- | Create 'Meta' from old-style title, authors, date. This is
-- provided to ease the transition from the old API.
makeMeta :: [Inline] -> [[Inline]] -> [Inline] -> Meta
makeMeta title authors date =
addMetaField "title" (B.fromList title)
$ addMetaField "author" (map B.fromList authors)
$ addMetaField "date" (B.fromList date)
$ nullMeta
--
-- TagSoup HTML handling
--
-- | Render HTML tags.
renderTags' :: [Tag String] -> String
renderTags' = renderTagsOptions
renderOptions{ optMinimize = matchTags ["hr", "br", "img",
"meta", "link"]
, optRawTag = matchTags ["script", "style"] }
where matchTags = \tags -> flip elem tags . map toLower
--
-- File handling
--
-- | Perform an IO action in a directory, returning to starting directory.
inDirectory :: FilePath -> IO a -> IO a
inDirectory path action = E.bracket
getCurrentDirectory
setCurrentDirectory
(const $ setCurrentDirectory path >> action)
getDefaultReferenceDocx :: Maybe FilePath -> IO Archive
getDefaultReferenceDocx datadir = do
let paths = ["[Content_Types].xml",
"_rels/.rels",
"docProps/app.xml",
"docProps/core.xml",
"word/document.xml",
"word/fontTable.xml",
"word/footnotes.xml",
"word/numbering.xml",
"word/settings.xml",
"word/webSettings.xml",
"word/styles.xml",
"word/_rels/document.xml.rels",
"word/_rels/footnotes.xml.rels",
"word/theme/theme1.xml"]
let toLazy = fromChunks . (:[])
let pathToEntry path = do epochtime <- (floor . utcTimeToPOSIXSeconds) <$>
getCurrentTime
contents <- toLazy <$> readDataFile datadir
("docx/" ++ path)
return $ toEntry path epochtime contents
mbArchive <- case datadir of
Nothing -> return Nothing
Just d -> do
exists <- doesFileExist (d </> "reference.docx")
if exists
then return (Just (d </> "reference.docx"))
else return Nothing
case mbArchive of
Just arch -> toArchive <$> BL.readFile arch
Nothing -> foldr addEntryToArchive emptyArchive <$>
mapM pathToEntry paths
getDefaultReferenceODT :: Maybe FilePath -> IO Archive
getDefaultReferenceODT datadir = do
let paths = ["mimetype",
"manifest.rdf",
"styles.xml",
"content.xml",
"meta.xml",
"settings.xml",
"Configurations2/accelerator/current.xml",
"Thumbnails/thumbnail.png",
"META-INF/manifest.xml"]
let pathToEntry path = do epochtime <- floor `fmap` getPOSIXTime
contents <- (fromChunks . (:[])) `fmap`
readDataFile datadir ("odt/" ++ path)
return $ toEntry path epochtime contents
mbArchive <- case datadir of
Nothing -> return Nothing
Just d -> do
exists <- doesFileExist (d </> "reference.odt")
if exists
then return (Just (d </> "reference.odt"))
else return Nothing
case mbArchive of
Just arch -> toArchive <$> BL.readFile arch
Nothing -> foldr addEntryToArchive emptyArchive <$>
mapM pathToEntry paths
readDefaultDataFile :: FilePath -> IO BS.ByteString
readDefaultDataFile "reference.docx" =
(BS.concat . toChunks . fromArchive) <$> getDefaultReferenceDocx Nothing
readDefaultDataFile "reference.odt" =
(BS.concat . toChunks . fromArchive) <$> getDefaultReferenceODT Nothing
readDefaultDataFile fname =
#ifdef EMBED_DATA_FILES
case lookup (makeCanonical fname) dataFiles of
Nothing -> err 97 $ "Could not find data file " ++ fname
Just contents -> return contents
where makeCanonical = Posix.joinPath . transformPathParts . splitDirectories
transformPathParts = reverse . foldl go []
go as "." = as
go (_:as) ".." = as
go as x = x : as
#else
getDataFileName fname' >>= checkExistence >>= BS.readFile
where fname' = if fname == "README" then fname else "data" </> fname
#endif
checkExistence :: FilePath -> IO FilePath
checkExistence fn = do
exists <- doesFileExist fn
if exists
then return fn
else err 97 ("Could not find data file " ++ fn)
-- | Read file from specified user data directory or, if not found there, from
-- Cabal data directory.
readDataFile :: Maybe FilePath -> FilePath -> IO BS.ByteString
readDataFile Nothing fname = readDefaultDataFile fname
readDataFile (Just userDir) fname = do
exists <- doesFileExist (userDir </> fname)
if exists
then BS.readFile (userDir </> fname)
else readDefaultDataFile fname
-- | Same as 'readDataFile' but returns a String instead of a ByteString.
readDataFileUTF8 :: Maybe FilePath -> FilePath -> IO String
readDataFileUTF8 userDir fname =
UTF8.toString `fmap` readDataFile userDir fname
-- | Fetch an image or other item from the local filesystem or the net.
-- Returns raw content and maybe mime type.
fetchItem :: Maybe String -> String
-> IO (Either E.SomeException (BS.ByteString, Maybe MimeType))
fetchItem sourceURL s =
case (sourceURL >>= parseURIReference . ensureEscaped, ensureEscaped s) of
(_, s') | isURI s' -> openURL s'
(Just u, s') -> -- try fetching from relative path at source
case parseURIReference s' of
Just u' -> openURL $ show $ u' `nonStrictRelativeTo` u
Nothing -> openURL s' -- will throw error
(Nothing, _) -> E.try readLocalFile -- get from local file system
where readLocalFile = do
cont <- BS.readFile fp
return (cont, mime)
dropFragmentAndQuery = takeWhile (\c -> c /= '?' && c /= '#')
fp = unEscapeString $ dropFragmentAndQuery s
mime = case takeExtension fp of
".gz" -> getMimeType $ dropExtension fp
".svgz" -> getMimeType $ dropExtension fp ++ ".svg"
x -> getMimeType x
ensureEscaped x@(_:':':'\\':_) = x -- likely windows path
ensureEscaped x = escapeURIString isAllowedInURI x
-- | Like 'fetchItem', but also looks for items in a 'MediaBag'.
fetchItem' :: MediaBag -> Maybe String -> String
-> IO (Either E.SomeException (BS.ByteString, Maybe MimeType))
fetchItem' media sourceURL s = do
case lookupMedia s media of
Nothing -> fetchItem sourceURL s
Just (mime, bs) -> return $ Right (BS.concat $ toChunks bs, Just mime)
-- | Read from a URL and return raw data and maybe mime type.
openURL :: String -> IO (Either E.SomeException (BS.ByteString, Maybe MimeType))
openURL u
| Just u' <- stripPrefix "data:" u =
let mime = takeWhile (/=',') u'
contents = B8.pack $ unEscapeString $ drop 1 $ dropWhile (/=',') u'
in return $ Right (decodeLenient contents, Just mime)
#ifdef HTTP_CLIENT
| otherwise = withSocketsDo $ E.try $ do
req <- parseUrl u
(proxy :: Either E.SomeException String) <- E.try $ getEnv "http_proxy"
let req' = case proxy of
Left _ -> req
Right pr -> case parseUrl pr of
Just r -> addProxy (host r) (port r) req
Nothing -> req
#if MIN_VERSION_http_client(0,4,18)
resp <- newManager tlsManagerSettings >>= httpLbs req'
#else
resp <- withManager tlsManagerSettings $ httpLbs req'
#endif
return (BS.concat $ toChunks $ responseBody resp,
UTF8.toString `fmap` lookup hContentType (responseHeaders resp))
#else
| otherwise = E.try $ getBodyAndMimeType `fmap` browse
(do S.liftIO $ UTF8.hPutStrLn stderr $ "Fetching " ++ u ++ "..."
setOutHandler $ const (return ())
setAllowRedirects True
request (getRequest' u'))
where getBodyAndMimeType (_, r) = (rspBody r, findHeader HdrContentType r)
getRequest' uriString = case parseURI uriString of
Nothing -> error ("Not a valid URL: " ++
uriString)
Just v -> mkRequest GET v
u' = escapeURIString (/= '|') u -- pipes are rejected by Network.URI
#endif
--
-- Error reporting
--
err :: Int -> String -> IO a
err exitCode msg = do
name <- getProgName
UTF8.hPutStrLn stderr $ name ++ ": " ++ msg
exitWith $ ExitFailure exitCode
return undefined
warn :: String -> IO ()
warn msg = do
name <- getProgName
UTF8.hPutStrLn stderr $ name ++ ": " ++ msg
mapLeft :: (a -> b) -> Either a c -> Either b c
mapLeft f (Left x) = Left (f x)
mapLeft _ (Right x) = Right x
hush :: Either a b -> Maybe b
hush (Left _) = Nothing
hush (Right x) = Just x
-- | Remove intermediate "." and ".." directories from a path.
--
-- > collapseFilePath "./foo" == "foo"
-- > collapseFilePath "/bar/../baz" == "/baz"
-- > collapseFilePath "/../baz" == "/../baz"
-- > collapseFilePath "parent/foo/baz/../bar" == "parent/foo/bar"
-- > collapseFilePath "parent/foo/baz/../../bar" == "parent/bar"
-- > collapseFilePath "parent/foo/.." == "parent"
-- > collapseFilePath "/parent/foo/../../bar" == "/bar"
collapseFilePath :: FilePath -> FilePath
collapseFilePath = Posix.joinPath . reverse . foldl go [] . splitDirectories
where
go rs "." = rs
go r@(p:rs) ".." = case p of
".." -> ("..":r)
(checkPathSeperator -> Just True) -> ("..":r)
_ -> rs
go _ (checkPathSeperator -> Just True) = [[Posix.pathSeparator]]
go rs x = x:rs
isSingleton [] = Nothing
isSingleton [x] = Just x
isSingleton _ = Nothing
checkPathSeperator = fmap isPathSeparator . isSingleton
--
-- Safe read
--
safeRead :: (MonadPlus m, Read a) => String -> m a
safeRead s = case reads s of
(d,x):_
| all isSpace x -> return d
_ -> mzero
--
-- Temp directory
--
withTempDir :: String -> (FilePath -> IO a) -> IO a
withTempDir =
#ifdef _WINDOWS
withTempDirectory "."
#else
withSystemTempDirectory
#endif
|
ddssff/pandoc
|
src/Text/Pandoc/Shared.hs
|
gpl-2.0
| 39,263
| 687
| 16
| 12,233
| 10,278
| 5,544
| 4,734
| 725
| 21
|
-- Prime numbers example from chapter 15 of Programming in Haskell,
-- Graham Hutton, Cambridge University Press, 2016.
primes :: [Int]
primes = sieve [2..]
sieve :: [Int] -> [Int]
sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
|
thalerjonathan/phd
|
coding/learning/haskell/grahambook/Code_Solutions/primes.hs
|
gpl-3.0
| 238
| 0
| 10
| 48
| 88
| 48
| 40
| 4
| 1
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sk-SK">
<title>Active Scan Rules - Beta | 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>
|
veggiespam/zap-extensions
|
addOns/ascanrulesBeta/src/main/javahelp/org/zaproxy/zap/extension/ascanrulesBeta/resources/help_sk_SK/helpset_sk_SK.hs
|
apache-2.0
| 986
| 85
| 53
| 163
| 405
| 213
| 192
| -1
| -1
|
{-# LANGUAGE DeriveFunctor #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Tests.Matrix.Types
(
Mat(..)
, fromMat
, toMat
) where
import Control.Monad (join)
import Control.Applicative ((<$>), (<*>))
import Statistics.Matrix (Matrix(..), fromList)
import Test.QuickCheck
import Tests.Helpers (shrinkFixedList, small)
import qualified Data.Vector.Unboxed as U
data Mat a = Mat { mrows :: Int , mcols :: Int
, asList :: [[a]] }
deriving (Eq, Ord, Show, Functor)
fromMat :: Mat Double -> Matrix
fromMat (Mat r c xs) = fromList r c (concat xs)
toMat :: Matrix -> Mat Double
toMat (Matrix r c _ v) = Mat r c . split . U.toList $ v
where split xs@(_:_) = let (h,t) = splitAt c xs
in h : split t
split [] = []
instance (Arbitrary a) => Arbitrary (Mat a) where
arbitrary = small $ join (arbMat <$> arbitrary <*> arbitrary)
shrink (Mat r c xs) = Mat r c <$> shrinkFixedList (shrinkFixedList shrink) xs
arbMat :: (Arbitrary a) => Positive (Small Int) -> Positive (Small Int)
-> Gen (Mat a)
arbMat (Positive (Small r)) (Positive (Small c)) =
Mat r c <$> vectorOf r (vector c)
instance Arbitrary Matrix where
arbitrary = fromMat <$> arbitrary
-- shrink = map fromMat . shrink . toMat
|
fpco/statistics
|
tests/Tests/Matrix/Types.hs
|
bsd-2-clause
| 1,305
| 0
| 11
| 335
| 509
| 275
| 234
| 32
| 2
|
{-
Verified Red-Black Trees
Toon Nolten
Based on Chris Okasaki's "Red-Black Trees in a Functional Setting"
where he uses red-black trees to implement sets.
Invariants
----------
1. No red node has a red parent
2. Every Path from the root to an empty node contains the same number of
black nodes.
(Empty nodes are considered black)
-}
{-# LANGUAGE GADTs, DataKinds, KindSignatures #-}
module RedBlackTree where
data Nat = Z | S Nat deriving (Show, Eq, Ord)
data Color = R | B deriving (Show, Eq)
data Tree :: Color -> Nat -> * -> * where
ET :: Tree B Z a
RT :: Tree B h a -> a -> Tree B h a -> Tree R h a
BT :: Tree cl h a -> a -> Tree cr h a -> Tree B (S h) a
instance Eq a => Eq (Tree c h a) where
ET == ET = True
RT l a r == RT m b s = a == b && l == m && r == s
-- Black trees need further pattern matching because of cl and cr
BT ET a ET == BT ET b ET =
a == b
BT ET a r@(RT {}) == BT ET b s@(RT {}) =
a == b && r == s
--
BT l@(RT {}) a ET == BT m@(RT {}) b ET =
a == b && l == m
BT l@(RT {}) a r@(RT {}) == BT m@(RT {}) b s@(RT {}) =
a == b && l == m && r == s
BT l@(RT {}) a r@(BT {}) == BT m@(RT {}) b s@(BT {}) =
a == b && l == m && r == s
--
BT l@(BT {}) a r@(RT {}) == BT m@(BT {}) b s@(RT {}) =
a == b && l == m && r == s
BT l@(BT {}) a r@(BT {}) == BT m@(BT {}) b s@(BT {}) =
a == b && l == m && r == s
_ == _ = False
data IRTree :: Nat -> * -> * where
IRl :: Tree R h a -> a -> Tree B h a -> IRTree h a
IRr :: Tree B h a -> a -> Tree R h a -> IRTree h a
data OutOfBalance :: Nat -> * -> * where
(:<:) :: IRTree h a -> a -> Tree c h a -> OutOfBalance h a
(:>:) :: Tree c h a -> a -> IRTree h a -> OutOfBalance h a
data Treeish :: Color -> Nat -> * -> * where
RB :: Tree c h a -> Treeish c h a
IR :: IRTree h a -> Treeish R h a
--Insertion
balance :: OutOfBalance h a -> Tree R (S h) a
balance ((:<:) (IRl (RT a x b) y c) z d) = RT (BT a x b) y (BT c z d)
balance ((:<:) (IRr a x (RT b y c)) z d) = RT (BT a x b) y (BT c z d)
balance ((:>:) a x (IRl (RT b y c) z d)) = RT (BT a x b) y (BT c z d)
balance ((:>:) a x (IRr b y (RT c z d))) = RT (BT a x b) y (BT c z d)
blacken :: Treeish c h a -> Either (Tree B h a) (Tree B (S h) a)
blacken (RB ET) = Left ET
blacken (RB (RT l b r)) = Right (BT l b r)
blacken (RB (BT l b r)) = Left (BT l b r)
blacken (IR (IRl l b r)) = Right (BT l b r)
blacken (IR (IRr l b r)) = Right (BT l b r)
-- Surprisingly difficult to find the right formulation
-- (ins in a pattern guard)
ins :: Ord a => a -> Tree c h a -> Either (Treeish R h a) (Treeish B h a)
ins a ET = Left $ RB (RT ET a ET)
--
ins a (RT l b r)
| a < b , Left (RB t) <- ins a l = Left $ IR (IRl t b r)
| a < b , Right (RB t) <- ins a l = Left $ RB (RT t b r)
| a == b = Left $ RB (RT l b r)
| a > b , Left (RB t) <- ins a r = Left $ IR (IRr l b t)
| a > b , Right (RB t) <- ins a r = Left $ RB (RT l b t)
--
ins a (BT l b r)
| a < b , Left (RB t) <- ins a l = Right $ RB (BT t b r)
| a < b , Left (IR t) <- ins a l = Left $ RB (balance ((:<:) t b r))
| a < b , Right (RB t) <- ins a l = Right $ RB (BT t b r)
| a == b = Right $ RB (BT l b r)
| a > b , Left (RB t) <- ins a r = Right $ RB (BT l b t)
| a > b , Left (IR t) <- ins a r = Left $ RB (balance ((:>:) l b t))
| a > b , Right (RB t) <- ins a r = Right $ RB (BT l b t)
insert :: Ord a => a -> Tree c h a -> Either (Tree B h a) (Tree B (S h) a)
insert a t
| Left t' <- ins a t = blacken t'
| Right t' <- ins a t = blacken t'
-- Simple Set operations
-- Partial Type Signatures might allow 'hiding' the color and height
type Set c h a = Tree c h a
empty :: Set B Z a
empty = ET
member :: Ord a => a -> Set c h a -> Bool
member _ ET = False
member a (RT l b r)
| a < b = member a l
| a == b = True
| a > b = member a r
member a (BT l b r)
| a < b = member a l
| a == b = True
| a > b = member a r
-- Usage example
t0 :: Tree B (S (S Z)) Integer
t0 = BT (RT (BT ET 1 ET) 2 (BT (RT ET 3 ET) 5 (RT ET 7 ET)))
8
(BT ET 9 (RT ET 10 ET))
t1 :: Tree B (S (S (S Z))) Integer
t1 = BT (BT (BT ET 1 ET) 2 (BT ET 3 ET))
4
(BT (BT ET 5 (RT ET 7 ET)) 8 (BT ET 9 (RT ET 10 ET)))
t2 :: Tree B (S (S (S Z))) Integer
t2 = BT (BT (BT ET 1 ET) 2 (BT ET 3 ET))
4
(BT (RT (BT ET 5 ET) 6 (BT ET 7 ET)) 8 (BT ET 9 (RT ET 10 ET)))
-- Would a proof with refl and equality require the entire tree at type
-- level?
t1_is_t0_plus_4 :: Bool
t1_is_t0_plus_4 = t1 == t0_plus_4
where Right t0_plus_4 = insert 4 t0
t2_is_t1_plus_6 :: Bool
t2_is_t1_plus_6 = t2 == t1_plus_6
where Left t1_plus_6 = insert 6 t1
|
toonn/sciartt
|
RedBlackTree.hs
|
bsd-2-clause
| 4,664
| 0
| 12
| 1,464
| 2,943
| 1,457
| 1,486
| 97
| 1
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
import Control.Lens
import Control.Monad.Fix
import Data.Align
import qualified Data.AppendMap as AMap
import Data.Functor.Misc
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Map.Monoidal (MonoidalMap)
import Data.Semigroup
import Data.These
#if defined(MIN_VERSION_these_lens) || (MIN_VERSION_these(0,8,0) && !MIN_VERSION_these(0,9,0))
import Data.These.Lens
#endif
import Reflex
import Data.Patch.MapWithMove
import Test.Run
newtype MyQuery = MyQuery SelectedCount
deriving (Show, Read, Eq, Ord, Monoid, Semigroup, Additive, Group)
instance Query MyQuery where
type QueryResult MyQuery = ()
crop _ _ = ()
instance (Ord k, Query a, Eq (QueryResult a), Align (MonoidalMap k)) => Query (Selector k a) where
type QueryResult (Selector k a) = Selector k (QueryResult a)
crop q r = undefined
newtype Selector k a = Selector { unSelector :: MonoidalMap k a }
deriving (Show, Read, Eq, Ord, Functor)
#if !(MIN_VERSION_monoidal_containers(0,4,1))
deriving instance Ord k => Align (MonoidalMap k)
#endif
instance (Ord k, Eq a, Monoid a, Align (MonoidalMap k)) => Semigroup (Selector k a) where
(Selector a) <> (Selector b) = Selector $ fmapMaybe id $ f a b
where
f = alignWith $ \case
This x -> Just x
That y -> Just y
These x y ->
let z = x `mappend` y
in if z == mempty then Nothing else Just z
instance (Ord k, Eq a, Monoid a, Align (MonoidalMap k)) => Monoid (Selector k a) where
mempty = Selector AMap.empty
mappend = (<>)
instance (Eq a, Ord k, Group a, Align (MonoidalMap k)) => Group (Selector k a) where
negateG = fmap negateG
instance (Eq a, Ord k, Group a, Align (MonoidalMap k)) => Additive (Selector k a)
main :: IO ()
main = do
[0, 1, 1, 0] <- fmap (map fst . concat) $
runApp (testQueryT testRunWithReplace) () $ map (Just . That) $
[ That (), This (), That () ]
[0, 1, 1, 0] <- fmap (map fst . concat) $
runApp (testQueryT testSequenceDMapWithAdjust) () $ map (Just . That) $
[ That (), This (), That () ]
[0, 1, 1, 0] <- fmap (map fst . concat) $
runApp (testQueryT testSequenceDMapWithAdjustWithMove) () $ map (Just . That) $
[ That (), This (), That () ]
return ()
testQueryT :: (Reflex t, MonadFix m)
=> (Event t () -> Event t () -> QueryT t (Selector Int MyQuery) m ())
-> AppIn t () (These () ())
-> m (AppOut t Int Int)
testQueryT w (AppIn _ pulse) = do
let replace = fmapMaybe (^? here) pulse
increment = fmapMaybe (^? there) pulse
(_, q) <- runQueryT (w replace increment) $ pure mempty
let qDyn = head . AMap.keys . unSelector <$> incrementalToDynamic q
return $ AppOut
{ _appOut_behavior = current qDyn
, _appOut_event = updated qDyn
}
testRunWithReplace :: ( Reflex t
, Adjustable t m
, MonadHold t m
, MonadFix m
, MonadQuery t (Selector Int MyQuery) m)
=> Event t ()
-> Event t ()
-> m ()
testRunWithReplace replace increment = do
let w = do
n <- count increment
queryDyn $ zipDynWith (\x y -> Selector (AMap.singleton (x :: Int) y)) n $ pure $ MyQuery $ SelectedCount 1
_ <- runWithReplace w $ w <$ replace
return ()
testSequenceDMapWithAdjust :: ( Reflex t
, Adjustable t m
, MonadHold t m
, MonadFix m
, MonadQuery t (Selector Int MyQuery) m)
=> Event t ()
-> Event t ()
-> m ()
testSequenceDMapWithAdjust replace increment = do
_ <- listHoldWithKey (Map.singleton () ()) (Map.singleton () (Just ()) <$ replace) $ \_ _ -> do
n <- count increment
queryDyn $ zipDynWith (\x y -> Selector (AMap.singleton (x :: Int) y)) n $ pure $ MyQuery $ SelectedCount 1
return ()
testSequenceDMapWithAdjustWithMove :: ( Reflex t
, Adjustable t m
, MonadHold t m
, MonadFix m
, MonadQuery t (Selector Int MyQuery) m)
=> Event t ()
-> Event t ()
-> m ()
testSequenceDMapWithAdjustWithMove replace increment = do
_ <- listHoldWithKeyWithMove (Map.singleton () ()) (Map.singleton () (Just ()) <$ replace) $ \_ _ -> do
n <- count increment
queryDyn $ zipDynWith (\x y -> Selector (AMap.singleton (x :: Int) y)) n $ pure $ MyQuery $ SelectedCount 1
return ()
-- scam it out to test traverseDMapWithAdjustWithMove
listHoldWithKeyWithMove :: forall t m k v a. (Ord k, MonadHold t m, Adjustable t m) => Map k v -> Event t (Map k (Maybe v)) -> (k -> v -> m a) -> m (Dynamic t (Map k a))
listHoldWithKeyWithMove m0 m' f = do
(n0, n') <- mapMapWithAdjustWithMove f m0 $ ffor m' $ PatchMapWithMove . Map.map (\v -> NodeInfo (maybe From_Delete From_Insert v) Nothing)
incrementalToDynamic <$> holdIncremental n0 n'
-- -}
|
ryantrinkle/reflex
|
test/QueryT.hs
|
bsd-3-clause
| 5,468
| 3
| 22
| 1,644
| 2,042
| 1,041
| 1,001
| 115
| 1
|
{-# LANGUAGE FlexibleContexts #-}
module Opaleye.Table (module Opaleye.Table,
View,
Writer,
Table(Table, TableWithSchema),
TableProperties) where
import Opaleye.Internal.Column (Column(Column))
import qualified Opaleye.Internal.QueryArr as Q
import qualified Opaleye.Internal.Table as T
import Opaleye.Internal.Table (View(View), Table, Writer,
TableProperties)
import qualified Opaleye.Internal.TableMaker as TM
import qualified Opaleye.Internal.Tag as Tag
import qualified Data.Profunctor.Product.Default as D
import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ
-- | Example type specialization:
--
-- @
-- queryTable :: Table w (Column a, Column b) -> Query (Column a, Column b)
-- @
--
-- Assuming the @makeAdaptorAndInstance@ splice has been run for the
-- product type @Foo@:
--
-- @
-- queryTable :: Table w (Foo (Column a) (Column b) (Column c)) -> Query (Foo (Column a) (Column b) (Column c))
-- @
queryTable :: D.Default TM.ColumnMaker columns columns =>
Table a columns -> Q.Query columns
queryTable = queryTableExplicit D.def
queryTableExplicit :: TM.ColumnMaker tablecolumns columns ->
Table a tablecolumns -> Q.Query columns
queryTableExplicit cm table = Q.simpleQueryArr f where
f ((), t0) = (retwires, primQ, Tag.next t0) where
(retwires, primQ) = T.queryTable cm table t0
required :: String -> TableProperties (Column a) (Column a)
required columnName = T.TableProperties
(T.required columnName)
(View (Column (HPQ.BaseTableAttrExpr columnName)))
optional :: String -> TableProperties (Maybe (Column a)) (Column a)
optional columnName = T.TableProperties
(T.optional columnName)
(View (Column (HPQ.BaseTableAttrExpr columnName)))
|
benkolera/haskell-opaleye
|
src/Opaleye/Table.hs
|
bsd-3-clause
| 1,862
| 0
| 12
| 416
| 428
| 248
| 180
| 34
| 1
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Ord
-- Copyright : (c) The University of Glasgow 2005
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : stable
-- Portability : portable
--
-- Orderings
--
-----------------------------------------------------------------------------
module Data.Ord (
Ord(..),
Ordering(..),
Down(..),
comparing,
) where
import GHC.Base
import GHC.Show
import GHC.Read
import GHC.Num
-- |
-- > comparing p x y = compare (p x) (p y)
--
-- Useful combinator for use in conjunction with the @xxxBy@ family
-- of functions from "Data.List", for example:
--
-- > ... sortBy (comparing fst) ...
comparing :: (Ord a) => (b -> a) -> b -> b -> Ordering
comparing p x y = compare (p x) (p y)
-- | The 'Down' type allows you to reverse sort order conveniently. A value of type
-- @'Down' a@ contains a value of type @a@ (represented as @'Down' a@).
-- If @a@ has an @'Ord'@ instance associated with it then comparing two
-- values thus wrapped will give you the opposite of their normal sort order.
-- This is particularly useful when sorting in generalised list comprehensions,
-- as in: @then sortWith by 'Down' x@
--
-- @since 4.6.0.0
newtype Down a = Down a
deriving
( Eq
, Show -- ^ @since 4.7.0.0
, Read -- ^ @since 4.7.0.0
, Num -- ^ @since 4.11.0.0
, Semigroup -- ^ @since 4.11.0.0
, Monoid -- ^ @since 4.11.0.0
)
-- | @since 4.6.0.0
instance Ord a => Ord (Down a) where
compare (Down x) (Down y) = y `compare` x
-- | @since 4.11.0.0
instance Functor Down where
fmap = coerce
-- | @since 4.11.0.0
instance Applicative Down where
pure = Down
(<*>) = coerce
-- | @since 4.11.0.0
instance Monad Down where
Down a >>= k = k a
|
rahulmutt/ghcvm
|
libraries/base/Data/Ord.hs
|
bsd-3-clause
| 1,988
| 0
| 8
| 427
| 298
| 182
| 116
| 31
| 1
|
module Turbinado.Server.ErrorHandler where
import System.IO
import Prelude hiding (catch)
import Data.Dynamic ( fromDynamic )
import Network.FastCGI
import Network.Socket
import Turbinado.Controller.Monad
import Turbinado.Environment.Types
import Turbinado.Environment.Response
import Turbinado.Server.Exception
import Turbinado.Server.Network
import Turbinado.Server.StandardResponse
import Turbinado.Utility.Data
handleHTTPError :: Socket -> Exception -> Environment -> IO ()
handleHTTPError s ex e =
do runController (errorResponse err >> sendHTTPResponse s) e
return ()
where err = unlines [ "Error in server: " ++ show ex
," please report as a bug to alson@alsonkemp.com"]
handleCGIError :: Exception -> Environment -> IO ()
handleCGIError ex e =
do e' <- liftIO $ runController (errorResponse err) e
runFastCGIorCGI $ sendCGIResponse e'
where err = unlines [ "Error in server: " ++ show ex
," please report as a bug to alson@alsonkemp.com"]
handleHTTPTurbinado :: Socket -> TurbinadoException -> Environment -> IO ()
handleHTTPTurbinado s he e = do
e' <- buildResponse he e
runController (sendHTTPResponse s) e'
return ()
handleCGITurbinado :: TurbinadoException -> Environment -> IO ()
handleCGITurbinado he e = do
e' <- liftIO $ buildResponse he e
runFastCGIorCGI $ sendCGIResponse e'
buildResponse he e = runController (
case he of
CompilationFailed errs -> errorResponse err
where err = unlines $ "File did not compile:" : errs
FileNotFound file -> fileNotFoundResponse file
LoadApplicationFailed dir -> errorResponse err
where err = "Failed to load application file in directory " ++ dir
AppCompilationFailed errs -> errorResponse err
where err = unlines $ "Application file did not compile:" : errs
NoURISpecified -> badReqResponse
TimedOut -> errorResponse err
where err = "Evaluation timed out"
BadRequest _ -> badReqResponse
PageEvalFailed ex -> errorResponse err
where err = "An exception occured during page evaluation\n:" ++
case ex of
DynException dyn ->
case (fromDynamic dyn :: Maybe Exception) of
Nothing -> show ex
Just hspe -> show hspe
_ -> show ex) e
|
alsonkemp/turbinado
|
Turbinado/Server/ErrorHandler.hs
|
bsd-3-clause
| 2,959
| 0
| 19
| 1,179
| 598
| 297
| 301
| 55
| 10
|
{-# LANGUAGE RankNTypes, NoMonomorphismRestriction, BangPatterns #-}
{-# OPTIONS -W #-}
module Language.Hakaru.ImportanceSampler where
-- This is an interpreter that's like Interpreter except conditioning is
-- checked at run time rather than by static types. In other words, we allow
-- models to be compiled whose conditioned parts do not match the observation
-- inputs. In exchange, we get to make Measure an instance of Monad, and we
-- can express models whose number of observations is unknown at compile time.
import Language.Hakaru.Types
import Language.Hakaru.Mixture (Prob, empty, point, Mixture(..))
import Language.Hakaru.Sampler (Sampler, deterministic, smap, sbind)
import qualified System.Random.MWC as MWC
import Control.Applicative (Applicative(..))
import Control.Monad (liftM, ap)
import Control.Monad.Primitive
import Data.Monoid
import Data.Dynamic
import System.IO.Unsafe
import qualified Data.Map.Strict as M
import qualified Data.Number.LogFloat as LF
-- Conditioned sampling
newtype Measure a = Measure { unMeasure :: [Cond] -> Sampler (a, [Cond]) }
bind :: Measure a -> (a -> Measure b) -> Measure b
bind measure continuation =
Measure (\conds ->
sbind (unMeasure measure conds)
(\(a,cds) -> unMeasure (continuation a) cds))
instance Functor Measure where
fmap = liftM -- TODO: can we optimize this default definition?
instance Applicative Measure where
pure x = Measure (\conds -> deterministic (point (x,conds) 1))
(<*>) = ap -- TODO: can we optimize this default definition?
instance Monad Measure where
return = pure
(>>=) = bind
updateMixture :: Typeable a => Cond -> Dist a -> Sampler a
updateMixture (Just cond) dist =
case fromDynamic cond of
Just y -> deterministic (point (fromDensity y) density)
where density = LF.logToLogFloat $ logDensity dist y
Nothing -> error "did not get data from dynamic source"
updateMixture Nothing dist = \g -> do e <- distSample dist g
return $ point (fromDensity e) 1
conditioned, unconditioned :: Typeable a => Dist a -> Measure a
conditioned dist = Measure (\(cond:conds) -> smap (\a->(a,conds))
(updateMixture cond dist))
unconditioned dist = Measure (\ conds -> smap (\a->(a,conds))
(updateMixture Nothing dist))
factor :: Prob -> Measure ()
factor p = Measure (\conds -> deterministic (point ((), conds) p))
condition :: Eq b => Measure (a, b) -> b -> Measure a
condition m b' =
Measure (\ conds ->
sbind (unMeasure m conds)
(\ ((a,b), cds) ->
deterministic (if b==b' then point (a,cds) 1 else empty)))
-- Drivers for testing
finish :: Mixture (a, [Cond]) -> Mixture a
finish (Mixture m) = Mixture (M.mapKeysMonotonic (\(a,[]) -> a) m)
empiricalMeasure :: (PrimMonad m, Ord a) => Int -> Measure a -> [Cond] -> m (Mixture a)
empiricalMeasure !n measure conds = do
gen <- MWC.create
go n gen empty
where once = unMeasure measure conds
go 0 _ m = return m
go k g m = once g >>= \result -> go (k - 1) g $! mappend m (finish result)
sample :: Measure a -> [Cond] -> IO [(a, Prob)]
sample measure conds = do
gen <- MWC.create
unsafeInterleaveIO $ sampleNext gen
where once = unMeasure measure conds
mixToTuple = head . M.toList . unMixture
sampleNext g = do
u <- once g
let x = mixToTuple (finish u)
xs <- unsafeInterleaveIO $ sampleNext g
return (x : xs)
logit :: Floating a => a -> a
logit !x = 1 / (1 + exp (- x))
|
suhailshergill/hakaru
|
Language/Hakaru/ImportanceSampler.hs
|
bsd-3-clause
| 3,640
| 0
| 15
| 891
| 1,204
| 644
| 560
| 72
| 2
|
-- This is a Game of Score module that is not currently being used in JS-monads-stable
{-# LANGUAGE OverloadedStrings #-}
module Impossibles where
import Data.List
import System.CPUTime
notWhole :: Double -> Bool
notWhole x = fromIntegral (round x) /= x
cat :: Double -> Double -> Double
cat l m | m < 0 = 3.1
| l == 0 = 3.1
| notWhole l = 3.1
| notWhole m = 3.1
| otherwise = read (show (round l) ++ show (round m))
f :: Double -> String
f x = show (round x)
scoreDiv :: Double -> Double -> Double
scoreDiv az bz | bz == 0 = 99999
| otherwise = (/) az bz
ops :: [Double -> Double -> Double]
ops = [cat, (+), (-), (*), scoreDiv]
calc a b c d e = [ (a',b',c',d') |
[a',b',c',d'] <- nub(permutations [a,b,c,d]),
op1 <- ops,
op2 <- ops,
op2 (op1 a' b') c' == e]
calc2 a b c d e = [ (a',b',c',d') |
[a',b',c',d'] <- nub(permutations [a,b,c,d]),
op1 <- ops,
op2 <- ops,
op2 a' (op1 b' c') == e]
calc3 a b c d e = [ (a',b',c',d') |
[a',b',c',d'] <- nub(permutations [a,b,c,d]),
op1 <- ops,
op2 <- ops,
op3 <- ops,
op3 (op1 a' b') (op2 c' d') == e]
calc4 a b c d e = [ (a',b',c',d') |
[a',b',c',d'] <- nub(permutations [a,b,c,d]),
op1 <- ops,
op2 <- ops,
op3 <- ops,
op3 (op2 (op1 a' b') c') d' == e]
calc5 :: Double -> Double -> Double -> Double -> Double -> [(Double, Double, Double, Double)]
calc5 a b c d e = [ (a',b',c',d') |
[a',b',c',d'] <- nub(permutations [a,b,c,d]),
op1 <- ops,
op2 <- ops,
op3 <- ops,
op3 (op2 a' (op1 b' c')) d' == e]
calc6 a b c d e = [ (a',b',c',d') |
[a',b',c',d'] <- nub(permutations [a,b,c,d]),
op1 <- ops,
op2 <- ops,
op3 <- ops,
op3 a' (op2 (op1 b' c') d') == e]
calc7 a b c d e = [ (a',b',c',d') |
[a',b',c',d'] <- nub(permutations [a,b,c,d]),
op1 <- ops,
op2 <- ops,
op3 <- ops,
op3 a' (op2 b' (op1 c' d')) == e]
impossibles :: Double -> Double -> Double -> Double -> Double -> [[Double]]
impossibles v w x y z = [ [a, b, c, d] | a <- [1..v], b <- [1..w], c <- [1..x], d <- [1..y],
a <= b, b <= c, c <= d,
null $ calc a b c d z, null $ calc2 a b c d z, null $ calc3 a b c d z,
null $ calc4 a b c d z, null $ calc5 a b c d z, null $ calc6 a b c d z,
null $ calc7 a b c d z ]
main = do
t1 <- getCPUTime
let imp = impossibles 6 6 12 20 20
print $ length imp
mapM_ print imp
t2 <- getCPUTime
let t = fromIntegral (t2-t1) * 1e-12
print t
|
dschalk/monads-for-functional-javascript
|
Impossibles.hs
|
mit
| 3,353
| 0
| 13
| 1,587
| 1,510
| 799
| 711
| 74
| 1
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-
Copyright 2017 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
import CodeWorld.Message
import System.Clock
import Data.List
import Text.Read
import Control.Monad
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as BS
import qualified Network.WebSockets as WS
import Control.Concurrent
import Control.Concurrent.Async
import Control.Exception
import Options.Applicative
connect :: Config -> WS.ClientApp a -> IO a
connect Config {..} = WS.runClient hostname port path
sendClientMessage :: ClientMessage -> WS.Connection -> IO ()
sendClientMessage msg conn = WS.sendTextData conn (T.pack (show msg))
getServerMessage :: WS.Connection -> IO ServerMessage
getServerMessage conn = do
msg <- WS.receiveData conn
case readMaybe (T.unpack msg) of
Just msg -> return msg
Nothing -> fail "Invalid server message"
joinGame :: Config -> GameId -> IO [ServerMessage]
joinGame config gid = do
connect config $ \conn -> do
sendClientMessage (JoinGame gid sig) conn
JoinedAs _ _ <- getServerMessage conn
waitForStart config conn
waitForStart :: Config -> WS.Connection -> IO [ServerMessage]
waitForStart config conn = go
where
go = do
m <- getServerMessage conn
case m of
Started {} -> playGame config conn
_ -> go
playGame :: Config -> WS.Connection -> IO [ServerMessage]
playGame config conn = do
forkIO $ sendMessages config conn
getAllMessages config conn
sendMessages :: Config -> WS.Connection -> IO ()
sendMessages config conn = do
forM_ [1..events config] $ \n -> do
sendClientMessage (InEvent (show n)) conn
getAllMessages :: Config -> WS.Connection -> IO [ServerMessage]
getAllMessages config conn =
replicateM (nrequests config) (getServerMessage conn) <*
WS.sendClose conn BS.empty
timeSpecToS ts = fromIntegral (sec ts) + fromIntegral (nsec ts) * 1E-9
data Config = Config
{ clients :: Int
, events :: Int
, hostname :: String
, port :: Int
, path :: String
}
opts = info (helper <*> config)
( fullDesc
<> progDesc "CodeWorld gameserver stresstest client"
<> header "codeword-game-stresstest - a stresstest for codeworld-gameserver")
where
config :: Parser Config
config = Config
<$> option auto
( long "clients"
<> short 'c'
<> showDefault
<> metavar "N"
<> value 3
<> help "Number of clients (>=1)" )
<*> option auto
( long "events"
<> short 'e'
<> showDefault
<> metavar "M"
<> value 100
<> help "Number of events every client should send" )
<*> strOption
( long "hostname"
<> showDefault
<> value "0.0.0.0"
<> metavar "HOSTNAME"
<> help "Hostname" )
<*> option auto
( long "port"
<> showDefault
<> metavar "PORT"
<> value 9160
<> help "Port" )
<*> strOption
( long "path"
<> showDefault
<> metavar "PATH"
<> value "gameserver"
<> help "Path" )
main = do
config <- execParser opts
start <- getTime Monotonic
connect config $ \conn -> do
sendClientMessage (NewGame (clients config) sig) conn
JoinedAs 0 gid <- getServerMessage conn
results <- mapConcurrently id $
waitForStart config conn : replicate (clients config - 1) (joinGame config gid)
end <- getTime Monotonic
let consistent = all (== head results) (tail results)
if consistent then putStrLn "All clients got consistent data."
else putStrLn "The clients got different results!"
putStrLn $ "Events sent: " ++ show (nrequests config)
putStrLn $ "Running time was: " ++ show (timeSpecToS (end-start) * 1000) ++ "ms"
putStrLn $ "Requests per second: " ++ show (fromIntegral (nrequests config) / timeSpecToS (end-start))
sig :: BS.ByteString
sig = BS.pack "DemoGame"
nrequests config = clients config * events config
|
venkat24/codeworld
|
codeworld-game-server/src/Stresstest.hs
|
apache-2.0
| 4,674
| 26
| 18
| 1,214
| 1,259
| 604
| 655
| 112
| 2
|
{-# LANGUAGE Unsafe #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.ST.Imp
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (requires universal quantification for runST)
--
-- This library provides support for /strict/ state threads, as
-- described in the PLDI \'94 paper by John Launchbury and Simon Peyton
-- Jones /Lazy Functional State Threads/.
--
-----------------------------------------------------------------------------
module Control.Monad.ST.Imp (
-- * The 'ST' Monad
ST, -- abstract, instance of Functor, Monad, Typeable.
runST,
fixST,
-- * Converting 'ST' to 'IO'
RealWorld, -- abstract
stToIO,
-- * Unsafe operations
unsafeInterleaveST,
unsafeIOToST,
unsafeSTToIO
) where
import GHC.ST ( ST, runST, fixST, unsafeInterleaveST )
import GHC.Base ( RealWorld )
import GHC.IO ( stToIO, unsafeIOToST, unsafeSTToIO )
|
pparkkin/eta
|
libraries/base/Control/Monad/ST/Imp.hs
|
bsd-3-clause
| 1,252
| 0
| 5
| 309
| 101
| 73
| 28
| 14
| 0
|
{-# LANGUAGE OverloadedStrings, RebindableSyntax #-}
module FromString where
import FromString.FayText
import FromString.Dep (myString, depTest)
import Prelude
main :: Fay ()
main = do
print ("This is not a String" :: Text)
print "This is not a String"
putStrLn myString
print myString
depTest
|
beni55/fay
|
tests/FromString.hs
|
bsd-3-clause
| 306
| 0
| 8
| 54
| 74
| 38
| 36
| 12
| 1
|
{-# LANGUAGE CPP#-}
{-# LANGUAGE OverloadedStrings #-}
module SDL.Filesystem
( -- * Filesystem Paths
getBasePath
, getPrefPath
) where
import Control.Exception
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Text (Text)
import Foreign.Marshal.Alloc
import SDL.Exception
import qualified Data.ByteString as BS
import qualified Data.Text.Encoding as Text
import qualified SDL.Raw.Filesystem as Raw
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
-- | An absolute path to the application data directory.
--
-- The path is guaranteed to end with a path separator.
--
-- Throws 'SDLException' on failure, or if the platform does not implement this
-- functionality.
getBasePath :: MonadIO m => m Text
getBasePath = liftIO $ mask_ $ do
cpath <- throwIfNull "SDL.Filesystem.getBasePath" "SDL_GetBasePath"
Raw.getBasePath
finally (Text.decodeUtf8 <$> BS.packCString cpath) (free cpath)
-- | A path to a unique per user and per application directory for the given
-- organization and application name, intended for writing preferences and
-- other personal files.
--
-- The path is guaranteed to end with a path separator.
--
-- You should assume the path returned by this function is the only safe place
-- to write files to.
--
-- Throws 'SDLException' on failure.
getPrefPath :: MonadIO m => Text -> Text -> m Text
getPrefPath organization application = liftIO $ mask_ $ do
cpath <- throwIfNull "SDL.Filesystem.getPrefPath" "SDL_GetPrefPath" $
BS.useAsCString (Text.encodeUtf8 organization) $ \org ->
BS.useAsCString (Text.encodeUtf8 application) $ \app ->
Raw.getPrefPath org app
finally (Text.decodeUtf8 <$> BS.packCString cpath) (free cpath)
|
bj4rtmar/sdl2
|
src/SDL/Filesystem.hs
|
bsd-3-clause
| 1,709
| 0
| 15
| 277
| 315
| 178
| 137
| 27
| 1
|
-- | Tests mutually recursive closures inside a tail recursive function
module Tests.TailrecClosures where
import Data.Set (Set)
import qualified Data.Set as S
runTest :: IO [String]
runTest = return $ S.toList $ S.map S.toList $ cartProd xs ys
xs = S.fromList "abc"
ys = S.fromList "def"
cartProd xs ys = S.fold outerFold S.empty xs
where outerFold x zss = S.fold (innerFold x) S.empty ys `S.union` zss
innerFold x y zs = S.fromList [x,y] `S.insert` zs
|
jtojnar/haste-compiler
|
Tests/TailrecClosures.hs
|
bsd-3-clause
| 467
| 0
| 10
| 88
| 176
| 94
| 82
| 10
| 1
|
{-# LANGUAGE Safe #-}
-- | Import safe versions of unsafe modules from prelude
module Main where
import Control.Monad.ST.Safe
import Control.Monad.ST.Lazy.Safe
import Foreign.ForeignPtr.Safe
import Foreign.Safe
f :: Int
f = 2
main :: IO ()
main = putStrLn $ "X is: " ++ show f
|
frantisekfarka/ghc-dsi
|
testsuite/tests/safeHaskell/unsafeLibs/GoodImport02.hs
|
bsd-3-clause
| 281
| 0
| 6
| 49
| 68
| 42
| 26
| 10
| 1
|
-- In this example, make the imported items explicit in 'import D1'
module A1 where
import D1
import C1
import B1
main :: Tree Int ->Bool
main t = isSame (sumSquares (fringe t))
(sumSquares (B1.myFringe t)+sumSquares (C1.myFringe t))
|
SAdams601/HaRe
|
old/testing/rmFromExport/A1_TokOut.hs
|
bsd-3-clause
| 266
| 0
| 11
| 68
| 80
| 42
| 38
| 7
| 1
|
module Main where
import Control.Exception
import Control.Monad
import System.Mem
import Control.Monad.ST
import Data.Array
import Data.Array.ST
import qualified Data.Array.Unboxed as U
import GHC.Compact
assertFail :: String -> IO ()
assertFail msg = throwIO $ AssertionFailed msg
assertEquals :: (Eq a, Show a) => a -> a -> IO ()
assertEquals expected actual =
if expected == actual then return ()
else assertFail $ "expected " ++ (show expected)
++ ", got " ++ (show actual)
arrTest :: (Monad m, MArray a e m, Num e) => m (a Int e)
arrTest = do
arr <- newArray (1, 10) 0
forM_ [1..10] $ \j -> do
writeArray arr j (fromIntegral $ 2*j + 1)
return arr
-- test :: (Word -> a -> IO (Maybe (Compact a))) -> IO ()
test func = do
let fromList :: Array Int Int
fromList = listArray (1, 10) [1..]
frozen :: Array Int Int
frozen = runST $ do
arr <- arrTest :: ST s (STArray s Int Int)
freeze arr
stFrozen :: Array Int Int
stFrozen = runSTArray arrTest
unboxedFrozen :: U.UArray Int Int
unboxedFrozen = runSTUArray arrTest
let val = (fromList, frozen, stFrozen, unboxedFrozen)
str <- func val
-- check that val is still good
assertEquals (fromList, frozen, stFrozen, unboxedFrozen) val
-- check the value in the compact
assertEquals val (getCompact str)
performMajorGC
-- check again the value in the compact
assertEquals val (getCompact str)
main = do
test (compactSized 4096 True)
test (compactSized 4096 False)
|
ezyang/ghc
|
libraries/ghc-compact/tests/compact_simple_array.hs
|
bsd-3-clause
| 1,518
| 0
| 16
| 356
| 530
| 272
| 258
| 42
| 2
|
module Roles5 where
data T a
class C a
type S a = Int
type role T nominal
type role C representational
type role S phantom
|
urbanslug/ghc
|
testsuite/tests/roles/should_fail/Roles5.hs
|
bsd-3-clause
| 124
| 0
| 5
| 27
| 40
| 26
| 14
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module Shed.Images where
import Codec.Picture (DynamicImage (ImageRGB8), Image (..),
convertRGB8, decodeImage)
import Codec.Picture.Extra (scaleBilinear)
import Codec.Picture.Saving (imageToJpg)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BL
import Data.ByteString.Unsafe (unsafePackMallocCStringLen)
import Data.Monoid ((<>))
import Foreign.C.Types
import qualified Language.C.Inline as C
C.context (C.baseCtx <> C.bsCtx)
C.include "<stdlib.h>"
C.include "<string.h>"
C.include "<libexif/exif-loader.h>"
getExifThumbnail :: ByteString -> IO (Maybe ByteString)
getExifThumbnail jpg = (C.withPtr $ \str -> C.withPtr $ \size -> [C.block|
int {
ExifLoader *l = exif_loader_new();
ExifData *ed;
exif_loader_write(l, (unsigned char *)$bs-ptr:jpg, $bs-len:jpg);
ed = exif_loader_get_data(l);
exif_loader_unref(l);
if (ed) {
if (ed->data && ed->size) {
*$(char** str) = (char *)malloc(ed->size);
memcpy(*$(char** str), ed->data, ed->size);
*$(int* size) = ed->size;
exif_data_unref(ed);
return 0;
} else {
exif_data_unref(ed);
return -1;
}
} else {
return -1;
}
}
|]) >>= \(ptr, (len, rv)) ->
if rv == 0 then do
Just <$> unsafePackMallocCStringLen (ptr, fromIntegral len)
else
return Nothing
createThumbnail :: ByteString -> IO (Maybe BL.ByteString)
createThumbnail bs =
case decodeImage bs of
Left _ -> return Nothing
Right img' ->
do let img = convertRGB8 img'
let ht = imageHeight img
let wd = imageWidth img
let (wd', ht') = if ht >= wd then
((128 * wd) `div` ht, 128)
else
(128, (128 * ht) `div` wd)
return $ Just $ imageToJpg 75 $ ImageRGB8 $ scaleBilinear wd' ht' img
|
dbp/shed
|
src/Shed/Images.hs
|
isc
| 2,170
| 0
| 17
| 700
| 457
| 251
| 206
| 36
| 3
|
module Y2017.M03.D16.Exercise where
import Data.Set (Set)
-- below imports available from 1HaskellADay git respository
import Analytics.Theory.Number.Prime
import Y2017.M03.D15.Exercise
{--
So, yesterday, when we solved the Exercise imported above, we saw that we had
614 unique values with the max value being Just 126410606437752. That max value
is quite the spicy meatball, however. But a help here is that we are looking
for prime-square-free numbers, or, that is to say more precisely, numbers that
are not divisible by the squares of the primes. So, let's winnow down our list
a bit.
--}
squareFreed :: Prime -> Set Integer -> Set Integer
squareFreed prime uniqVals = undefined
{--
How many values in uniqueValuesUpTo 51 when that list is squareFreed of the
first Prime, 2? (remember to square 2 as the factor to check against)o
>>> length (squareFreed (head primes) (uniqueValuesUpTo 51))
286
>>> fst <$> Set.maxView (squareFreed (head primes) (uniqueValuesUpTo 51))
Just 18053528883775
Boom! A marked improvement! Let's do the same for the next prime, 3. First,
assign smr0 to the squareFreed 2 value:
>>> let smr0 = squareFreed (head primes) (uniqueValuesUpTo 51)
and repeat the above for the next prime (head (tail primes)). What is the new
length and new max value you get for your newly filtered set from smr0?
assign smr1 to that newer smaller subset.
>>> let smr1 = squareFreed (head (tail primes)) smr0
>>> length smr1
185
>>> fst <$> Set.maxView smr1
Just 18053528883775
No change to the max, let's go a bit further. Now how about for the next prime?
>>> let smr2 = squareFreed (head (drop 2 primes)) smr1
>>> length smr2
162
>>> fst <$> Set.maxView smr2
Just 9762479679106
>>> sqrt . fromIntegral <$> it
Just 3124496.708128527
This shows after filtering out only 3 prime-squares we've significantly reduced
the number of values we need to test against AND the maximum value prime we need
to compute to test.
So.
Today's Haskell problem. Using the above algorithm, filter the unique values
of the Pascal's Triangle up to row 51 down to only the square-free numbers,
then sum the resulting set. What is the value you get?
--}
sqFreeSieve :: Set Integer -> Set Integer
sqFreeSieve uniqs = undefined
{--
>>> length (sqFreeSieve (uniqueValuesUpTo 51))
158
Eheh! We found only four more beasties for all that work?!? ;)
>>> sum (sqFreeSieve (uniqueValuesUpTo 51))
... some value
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2017/M03/D16/Exercise.hs
|
mit
| 2,423
| 0
| 7
| 420
| 88
| 51
| 37
| 8
| 1
|
{-# LANGUAGE PatternSynonyms #-}
module Ornament where
import Test.Tasty
import Test.Tasty.HUnit
import Evidences.Tm
import Evidences.Ornament
-- pattern RET i = C (Ornament (Ret i))
-- pattern ARG a f = C (Ornament (Arg a f))
-- pattern REC i d = C (Ornament (Rec i d))
tests :: TestTree
tests = testGroup "Ornament"
[ testGroup "nat"
[
]
]
|
kwangkim/pigment
|
tests/Ornament.hs
|
mit
| 373
| 0
| 8
| 90
| 54
| 33
| 21
| 10
| 1
|
module Music where
import Control.Arrow
import qualified Data.EventList.Relative.TimeBody as EL
import Data.List
import qualified Sound.MIDI.File as F
import qualified Sound.MIDI.File.Event as FE
import qualified Sound.MIDI.File.Load as FL
import qualified Sound.MIDI.Message.Channel.Voice as MCV
import qualified Sound.MIDI.Message.Channel as MC
type Time = Double
data Beat
= F1
| F2
| F3
| F4
deriving (Show, Eq, Ord, Enum)
newtype Note = Note { note :: (Time, Beat) }
deriving (Show, Eq, Ord)
-- Code
midiLoadFile :: FilePath -> IO F.T
midiLoadFile
= FL.fromFile
fetchNoteEvents :: [(F.ElapsedTime, FE.T)] -> [(F.ElapsedTime, MCV.T)]
fetchNoteEvents fe
= map (second toMCV) (filter (isMCV . snd)
(map (second (MC.messageBody . eventToChannelT)) fe))
maxNotes :: [MCV.T] -> Int
maxNotes a =
maximum (map MC.fromPitch (pitches a))
minNotes :: [MCV.T] -> Int
minNotes a =
minimum (map MC.fromPitch (pitches a))
pitches :: [MCV.T] -> [MC.Pitch]
pitches = map pitches'
where
pitches' (MCV.NoteOn p _) = p
pitches' (MCV.NoteOff p _) = p
toMCV :: MC.Body -> MCV.T
toMCV (MC.Voice t) = t
isMCV :: MC.Body -> Bool
isMCV (MC.Voice _) = True
isMCV _ = False
eventToChannelT :: FE.T -> MC.T
eventToChannelT (FE.MIDIEvent t)
= t
eventToChannelT p
= error $ show p
getMidiEvents :: [(F.ElapsedTime, FE.T)] -> [(F.ElapsedTime, FE.T)]
getMidiEvents
= filter (isMIDIEvent . snd)
isMIDIEvent :: FE.T -> Bool
isMIDIEvent (FE.MIDIEvent _) = True
isMIDIEvent _ = False
midiGetEvents :: [F.Track] -> [(F.ElapsedTime, FE.T)]
midiGetEvents tr
= sort (concatMap EL.toPairList tr)
midiGetTracks :: F.T -> [F.Track]
midiGetTracks (F.Cons _ _ tracks)
= tracks
midiFilterNoteMessage :: [MCV.T] -> [MCV.T]
midiFilterNoteMessage
= filter noteChange
noteChange :: MCV.T -> Bool
noteChange (MCV.NoteOn _ _) = True
noteChange (MCV.NoteOff _ _) = True
noteChange _ = False
data Lol
= Lel Int
| Lul Int
deriving (Show)
|
davedissian/hackcambridge2016
|
Music.hs
|
mit
| 2,076
| 0
| 14
| 474
| 790
| 442
| 348
| 68
| 2
|
-- | This module provides functions for converting a full URL to just the
-- domain name or the TLD.
module YesWeScan.DomainName (domainName, topLevelDomain) where
import Data.Text (unpack)
import Network.URI (parseURI)
import Network.URI.TLD (parseTLDURI)
-- | Split an url into subdomain(s), domain, TLD.
splitTld :: String -> Maybe (String, String, String)
splitTld url =
do uri <- parseURI url
(sub,dom,tld) <- parseTLDURI uri
return (unpack sub,unpack dom,unpack tld)
-- | Return the domain name.
domainName :: String -> String
domainName url =
case splitTld url of
Just (_,dom,tld) -> dom ++ "." ++ tld
Nothing -> error "domainName: Invalid URI provided."
-- | Return just the TLD.
topLevelDomain :: String -> String
topLevelDomain url =
case splitTld url of
Just (_,_,tld) -> tld
Nothing -> error "Invalid URI provided."
|
kmein/yes-we-scan
|
YesWeScan/DomainName.hs
|
mit
| 882
| 0
| 9
| 183
| 242
| 130
| 112
| 19
| 2
|
-- This is OLD CODE. IT DOES NOT WORK!!!
-- General image stuff; mostly imported from C++
module Image( maskToImage -- Mask -> ImageInt
, imageToMask -- ImageInt -> Mask
, emptyImageInt -- ISize -> ImageInt
, iPlusImageInt -- Int -> ImageInt -> ImageInt
, iDivImageInt -- Int -> ImageInt -> ImageInt
, iTimesImageInt -- Int -> ImageInt -> ImageInt
, innerProductImageInt -- ImageInt -> ImageInt -> Double
, sumImageInt -- ImageInt -> Double
, subImageInt -- (Int,Int) -> (Int,Int) -> ImageInt ->
-- ImageInt
, scaleImageInt -- (Double,Double) -> ImageInt -> ImageInt
, reduceResolutionImageInt -- (Int,Int) -> ImageInt -> ImageInt
, magnifyImageInt -- (Int,Int) -> ImageInt -> ImageInt
, convolveImageInt -- Mask -> ImageInt -> ImageInt
, product
, gaussianMask -- (Int,Int) -> Double -> Mask
, dxImageInt -- ImageInt -> ImageInt
, dyImageInt -- ImageInt -> ImageInt
, smoothDxImageInt -- ImageInt -> ImageInt
, smoothDyImageInt -- ImageInt -> ImageInt
, compressxImageInt -- ImageInt -> ImageInt
, compressyImageInt -- ImageInt -> ImageInt
, compressxyImageInt -- ImageInt -> ImageInt
, colorToBWImage -- ImageRGB -> ImageInt
, bwToColorImage -- ImageInt -> ImageRGB
, avgColorImageRGB -- RGBtriple -> ImageRGB -> ImageInt
, mkImageInt -- ISize -> Int -> ImageInt
, threshBWImageInt -- Int -> Int -> ImageInt -> ImageInt
, centroidP2BWImageInt -- ImageInt -> (Point2,Double)
) where
-- operations on image types
import XVTypes
import XVision
import GeometryStatic
import FVUtils
---------------
-- ImageInt (as a matrix of Ints)
---------------
instance Eq ImageInt -- bogus; could be fixed!
instance Show ImageInt where
showsPrec p i = showSized "ImageInt" i
instance Num ImageInt where
(+) = plusImageInt
(-) = minusImageInt
(*) = multImageInt
abs = absImageInt
negate = iTimesImageInt (-1)
-- could also add VectorSpace except you need to round
instance Sized ImageInt where sizeOf = toSize . sizeImageInt
instance Sized ImageRGB where sizeOf = toSize . sizeImageRGB
instance Sized ImageFloat where sizeOf = toSize . sizeImageFloat
compressxyImageInt = compressxImageInt . compressyImageInt
centroidP2BWImageInt:: ImageInt -> (Point2, RealVal)
centroidP2BWImageInt im = (Point2XY x y,v)
where
((x,y),v) = centroidBWImageInt im
|
jatinshah/autonomous_systems
|
project/fvision.hugs/image.hs
|
mit
| 2,896
| 0
| 8
| 998
| 332
| 211
| 121
| 48
| 1
|
-- | Core functions relating to unification and predicates
module UProlog.State where
import Prelude hiding (and, or)
import Control.Monad
import Control.Monad.Logic
import Control.Monad.State
import qualified Data.Map as M
import UProlog.Val
-- | A 'scope' mapping Identifiers to values
type State' = M.Map Id Val
-- | The core type used in unification, representing a function from a given
-- state to a number of new states in a tree like form, which can be
-- traversed in a backtracking, breadth first fashion to find all possible
-- unifying states. We also provide a supply of bindable names in the form
-- of a 'State [Val]' where 'Val' in this case is simply numbered 'Var' 's.
-- It is assumed (but unproven) that these names can't clash across branches
-- of this tree.
type Pred = State' -> LogicT (State [Val]) State'
-- | Inject number of names into a binding function, giving back a new
-- predicate
withN :: Int -- ^ Number of names to bind
-> ([Val] -> Pred) -- ^ Binding function
-> Pred -- ^ The resulting predicate
withN n p s = state (splitAt n) >>= flip p s
-- | A special case of 'withN' for @n = 1@
with :: (Val -> Pred) -> Pred
with p = withN 1 (p . head)
-- | Walk the graph represented by the given state to obtain the terminal value
-- for a given identifier. In the case of a pair we walk both braches and return
-- a pair of the result. Any other value is simply returned unchanged ie.
--
-- >>> walk (I 42) s
-- 42
walk :: Val -> State' -> Val
walk (P (x,y)) s = P(walk x s, walk y s)
walk (Var x) s = maybe (Var x) (flip walk s) $ M.lookup x s
walk x _ = x
-- | Mark two values as equal in a state, giving us a new predicate. If we
-- interpret the search space as a graph this is equivalent to adding a new
-- edge constraint between two nodes.
unify :: Val -> Val -> Pred
unify v w m =
case (walk v m, walk w m) of
(a,b) | a == b -> return m
(Var a,b) -> return (M.insert a b m)
(a,Var b) -> return (M.insert b a m)
(P(x,y), P(x',y')) -> unify x x' m >>= unify y y'
_ -> mzero
-- | Infix version of 'unify'
(===) :: Val -> Val -> Pred
(===) = unify
-- | Given two predicates a and b, return a new predicate in which everything
-- specified by a and b is true. In the graph interpretation this is
-- equivalent to adding all the constraints of a to b.
and :: Pred -> Pred -> Pred
p `and` q = \s-> p s >>- q
-- | Given two predicates a and b, return a new predicate in which everything
-- in a is true or everything in b is true. Both a and b can potentially be
-- true. In the graph interpretatin this is equivalent to taking an initial
-- graph i and returning @/(i+a)/@ and @/(i+b)/@ (where @/(i+x)/@ represents
-- i with all the constraints of x) and looking at both conccurrently in
-- future computation.
or :: Pred -> Pred -> Pred
p `or` q = \s-> interleave (p s) (q s)
-- | Return a predicate specifying that all the input predicates must be true
all :: [Pred] -> Pred
all = foldr and return
-- | Return a predicate that holds if any of its input predicates are true
any :: [Pred] -> Pred
any = foldr or (const mzero)
-- | Negation as failure. Given a predicate return a predicate that prunes
-- any input states that match the input predicate. __NB:__ This cannot be
-- unified across to get all states that don't match. We only ever prune on
-- negation; never add:
--
-- >>> run $ \v -> naf (v === (quote 42))
-- []
naf :: Pred -- ^ A predicate
-> Pred -- ^ Negation of the given predicate
naf p s = do
lnot (p s)
return s
-- | Run a given logic program and return a list of formated solutions.
run :: (Val -> Pred) -- ^ A logic program
-> [String] -- ^ List of solutions formated with @show@
run = (map show) . runVals
-- | Run a given logic program and return the list of raw values that result
-- by walking the first value across the final graph.
runVals :: (Val -> Pred) -- ^ A logic program
-> [Val] -- ^ List of raw solutions
runVals p = map (walk $ Var 0)
$ evalState (observeAllT $ with p M.empty)
$ map Var [0..]
|
lukegrehan/uprolog
|
src/UProlog/State.hs
|
mit
| 4,111
| 0
| 11
| 955
| 820
| 456
| 364
| 50
| 5
|
{-# LANGUAGE OverloadedStrings #-}
module Commands where
import Text.LaTeX.Base
import Text.LaTeX.Base.Class
import Text.LaTeX.Base.Syntax
-- shortcut to remove navigation symbols without using the latex name...
nonavigationsymbols :: LaTeXC l => l
nonavigationsymbols = commS "beamertemplatenavigationsymbolsempty" -- lol latex code
usebeamercolor :: LaTeXC l => LaTeX -> l -> l
usebeamercolor x = liftL $ \y -> TeXComm "usebeamercolor" [OptArg x,FixArg y]
usebeamerfont :: LaTeXC l => l -> l
usebeamerfont = liftL $ \y -> TeXComm "usebeamerfont" [FixArg y]
useinnertheme :: LaTeXC l => [LaTeX] -> l -> l
useinnertheme os = liftL $ \x -> TeXComm "useinnertheme" [MOptArg os,FixArg x]
usecolortheme :: LaTeXC l => l -> l
usecolortheme = liftL $ \c -> TeXComm "usecolortheme" [FixArg c]
setbeamerfont :: LaTeXC l => l -> l -> l
setbeamerfont = liftL2 $ \c v -> TeXComm "setbeamerfont" [FixArg c,FixArg v]
setbeamercolor :: LaTeXC l => l -> l -> l
setbeamercolor = liftL2 $ \n v -> TeXComm "setbeamercolor" [FixArg n,FixArg v]
setbeamercolor_ :: LaTeXC l => l -> l -> l
setbeamercolor_ = liftL2 $ \n v -> TeXComm "setbeamercolor*" [FixArg n,FixArg v]
setbeamertemplate :: LaTeXC l => l -> l -> l
setbeamertemplate = liftL2 $ \s t -> TeXComm "setbeamertemplate" [FixArg s,FixArg t]
defbeamertemplate_ :: LaTeXC l => l -> l -> l -> l
defbeamertemplate_ = liftL3 $ \s tn c -> TeXComm "defbeamertemplate*" [FixArg s,FixArg tn,FixArg c]
setbeamersize :: LaTeXC l => [(LaTeX,Measure)] -> l
setbeamersize ls = fromLaTeX $ TeXComm "setbeamersize" [FixArg $ rendertex ls']
where ls' = intercalate "," $ fmap renderTuple ls
intercalate _ [] = ""
intercalate _ (x:[]) = x
intercalate c (x:xs) = x <> c <> intercalate c xs
renderTuple (k,v) = k <> "=" <> rendertex v
shortstack :: LaTeXC l => LaTeX -> l -> l
shortstack pos = liftL $ \vals -> TeXComm "shortstack" [OptArg pos,FixArg vals]
-- | Cell taking multiple rows.
multirow :: LaTeXC l => Int -> l -> l -> l
multirow n = liftL2 $ \l1 l2 -> TeXComm "multirow" [ FixArg $ rendertex n,FixArg l1,FixArg l2]
raggedright :: LaTeXC l => l
raggedright = commS "raggedright"
insertcaption :: LaTeXC l => l
insertcaption = commS "insertcaption"
mvRightarrow :: LaTeXC l => l
mvRightarrow = commS "MVRightarrow"
flatsteel :: LaTeXC l => l
flatsteel = commS "Flatsteel"
rightarrow :: LaTeXC l => l
rightarrow = commS "Rightarrow"
abovecaptionskip :: LaTeXC l => l
abovecaptionskip = commS "abovecaptionskip"
setlength :: LaTeXC l => LaTeX -> Measure -> l
setlength x y = fromLaTeX $ TeXComm "setlength" [FixArg x,FixArg $ texy y]
-- creates a hypersetup from a list of key-val pairs
-- TODO: should be a Map but LaTeX isn't an instance of Ord
hypersetup :: LaTeXC l => [(LaTeX,LaTeX)] -> l
hypersetup = hypersetup' . intercalate "," . fmap toKeyVal
where toKeyVal (k,v) = rendertex k <> raw "={" <> rendertex v <> raw "}"
hypersetup' = liftL $ \c -> TeXComm "hypersetup" [FixArg c]
intercalate _ [] = ""
intercalate _ (x:[]) = x
intercalate c (x:xs) = x <> c <> intercalate c xs
leavevmode :: LaTeXC l => l
leavevmode = comm0 "leavevmode"
beamercolorbox :: LaTeXC l => [LaTeX] -> l -> l -> l
beamercolorbox os = liftL2 $ \x -> TeXEnv "beamercolorbox" [MOptArg os,FixArg x]
insertshortauthor :: LaTeXC l => l
insertshortauthor = commS "insertshortauthor"
insertshortinstitute :: LaTeXC l => l
insertshortinstitute = commS "insertshortinstitute"
insertshorttitle :: LaTeXC l => l
insertshorttitle = commS "insertshorttitle"
insertframenumber :: LaTeXC l => l
insertframenumber = commS "insertframenumber"
insertshortdate :: LaTeXC l => l
insertshortdate = comm0 "insertshortdate"
expandafter :: LaTeXC l => l
expandafter = comm0 "expandafter"
vskip :: LaTeXC l => Measure -> l
vskip m = commS "vskip" <> rendertex m
hbox :: LaTeXC l => l -> l
hbox = liftL $ \x -> TeXComm "hbox" [FixArg x]
paperwidth :: LaTeXC l => l
paperwidth = comm0 "paperwidth"
totalheight :: LaTeXC l => l
totalheight = comm0 "totalheight"
mode :: LaTeXC l => l -> l
mode = liftL $ \x -> TeXComm "mode" [SymArg x]
rowspacing :: LaTeXC l => Measure -> l
rowspacing m = raw "\\\\[" <> rendertex m <> "]"
|
melrief/PhDPresentation
|
src/Commands.hs
|
mit
| 4,212
| 0
| 11
| 809
| 1,541
| 784
| 757
| 85
| 3
|
{-# LANGUAGE RankNTypes, ExistentialQuantification, ImpredicativeTypes #-}
module FP15.Evaluator.Standard where
import FP15.Disp
import Control.Applicative hiding (Const)
import Data.List(transpose, sort)
import Prelude hiding (div)
import Control.Monad(liftM, (>=>))
import qualified Data.Map.Strict as M
import Data.Maybe(isJust)
import FP15.Value
import FP15.Evaluator.FP (runIO)
import FP15.Evaluator.Types
import FP15.Evaluator.Error
import FP15.Evaluator.Contract
import FP15.Evaluator.Number as N
-- * Function Creation Helpers
-- ** Building Blocks & Contract Enforcement
-- | The 'ensure' function validates a value against a contract, and returns the
-- matched value, or else, raise a 'ContractViolation' error.
ensure :: Contract a -> FPValue -> FP a
-- | The 'ensureFunc' function attaches contracts on the input and output of the
-- 'FPFunc', and the return type will be converted to 'FP' the type the
-- output contract matches.
ensureFunc :: Contract a -> Contract b -> (a -> FPResult) -> FPValue -> FP b
-- | The 'ensureIn' function attaches a contract on the input of the 'FPFunc', and
-- if the contract validates, the matched value will be applied on the function
-- given.
ensureIn :: Contract a -> (a -> FPResult) -> FPValue -> FPResult
-- | The 'ensureOut' function attaches a contract on the output of the 'FPFunc',
-- and if the output validates the output contract, the matched value will be
-- returned.
ensureOut :: Contract b -> (FPValue -> FPResult) -> FPValue -> FP b
-- | The 'predOnly' function attaches a 'BoolC' contract on the output of the
-- 'FPFunc', making sure the function only returns booleans.
predOnly :: FPFunc -> FPValue -> FP Bool
ensure c v =
case validate c v of
Nothing -> raiseContractViolation c v
Just x -> return x
func' :: FPValueConvertible b => Contract a -> (a -> b) -> FPFunc
func :: (ContractConvertible a, FPValueConvertible b) => (a -> b) -> FPFunc
func2 :: (ContractConvertible a, ContractConvertible b,
FPValueConvertible c) => (a -> b -> c) -> FPFunc
func' c f x = liftM (toFPValue . f) (ensure c x)
func = func' asContract
func2 = func . uncurry
funcE :: (ContractConvertible a, FPValueConvertible b) => (a -> FP b) -> FPFunc
funcE f v = do
x <- ensure asContract v
y <- f x
return $ toFPValue y
ensureFunc a b f x = ensure a x >>= f >>= ensure b
ensureIn = (`ensureFunc` AnyC)
ensureOut = (AnyC `ensureFunc`)
predOnly = ensureOut BoolC
-- ** Math
numListF, numNEListF :: ([Number] -> Number) -> FPFunc
foldN :: (Number -> Number -> Number) -> Number -> FPFunc
foldN1 :: (Number -> Number -> Number) -> FPFunc
subLike :: (b -> a -> b) -> Cons b [a] -> b
numListF f x = liftM (toFPValue . f) (ensure (ListC NumberC) x)
numNEListF f x = (toFPValue . f . consToList) <$> ensure contract x where
consToList (Cons (x, xs)) = x : xs
contract = ConsC NumberC (ListC NumberC)
foldN f x0 = numListF (foldl f x0)
foldN1 f = numNEListF (foldl1 f)
subLike f (Cons (a, b)) = foldl f a b
-- ** Equality and Comparison
eq :: [Value] -> Bool
eq (a:b:xs) | a == b = eq (b:xs)
| otherwise = False
eq _ = True
-- | The 'checkFunc' function creates a 'FPFunc' that returns true if and only if
-- the input value passes the contract provided.
checkFunc :: Contract a -> FPFunc
-- | The 'eqFunc' function creates a 'FPFunc' that returns True if and only if the
-- input values equals the value provided.
eqFunc :: Value -> FPFunc
checkFunc c = return . Bool . isJust . validate c
eqFunc x v = do v' <- ensure ValueC v
return $ Bool $ (==) v' x
-- ** List Processing
cons :: (FPValue, [FPValue]) -> [FPValue]
decons :: Cons FPValue [FPValue] -> (FPValue, [FPValue])
distl :: (FPValue, [FPValue]) -> [(FPValue, FPValue)]
distr :: ([FPValue], FPValue) -> [(FPValue, FPValue)]
hd :: Cons FPValue [FPValue] -> FPValue
tl :: Cons FPValue [FPValue] -> [FPValue]
zipn :: [[a]] -> [[a]]
index :: ([FPValue], Integer) -> FPResult
cons (a, b) = a : b
decons (Cons (x, xs)) = (x, xs)
distl (a, xs) = map (\x -> (a, x)) xs
distr (xs, a) = map (\x -> (x, a)) xs
hd (Cons (a, b)) = a
tl (Cons (a, b)) = b
zipn xs = if all (not . null) xs
then map head xs : zipn (map tail xs)
else []
index (xs, i) = case res of
Nothing -> raiseErrorMessage "Index out of range."
Just x -> return x
where res :: Maybe FPValue
res = get $ until cond upd (xs, i)
cond (l, m) = null l || m == 0
upd (_:as, k) = (as, k - 1)
upd _ = error "index: upd: impossible"
get (a:_, 0) = Just a
get ([], _) = Nothing
get (a:_, _) = error "index: get: impossible"
-- ** I/O
ioFunc' :: FPValueConvertible r => Contract a -> (a -> IO r) -> FPFunc
ioFunc :: (ContractConvertible a, FPValueConvertible r) => (a -> IO r) -> FPFunc
ioFunc'0 :: ContractConvertible a => (a -> IO r) -> FPFunc
ioFunc'1 :: (ContractConvertible a, FPValueConvertible r) => (a -> IO r) -> FPFunc
ioFunc1'0 :: ContractConvertible a => (a -> IO r) -> FPFunc
ioFunc0'1 :: FPValueConvertible t => IO t -> FPFunc
ioFunc1'1 :: (ContractConvertible a, FPValueConvertible r) => (a -> IO r) -> FPFunc
ioFunc' c f x = do
z <- ensure c x
w <- runIO $ f z
return $ toFPValue w
--liftM (runIO . f) (ensure c x)
ioFunc = ioFunc' asContract
ioFunc'0 f = ioFunc (\args -> f args >> return RW)
ioFunc'1 f = ioFunc (f >=> (\y -> return (RW, y)))
ioFunc1'0 f = ioFunc'0 (\(RW, x) -> f x)
ioFunc0'1 f = ioFunc (\RW -> f >>= (\y -> return (RW, y)))
ioFunc1'1 f = ioFunc (\(RW, x) -> f x >>= (\y -> return (RW, y)))
-- cases for IOFunc
-- * () -> IO () -- RealWorld^ -> RealWorld^
-- * args -> IO () -- RealWorld^ & args -> RealWorld^
-- * () -> IO ret -- RealWorld^ -> {RealWorld^, arg}
-- * args -> IO ret -- RealWorld^ & args -> {RealWorld, arg}
-- * Standard Library
-- The 'standardEnv' is the standard environment that includes all standard
-- function definitions with names prefixed with @Std.@
standardEnv :: M.Map String FPFunc
-- 'standardEnv'' is like 'standardEnv' except there is no @Std.@ prefix in
-- front of all names
standardEnv' :: M.Map String FPFunc
standardEnv = M.mapKeys (\n -> "Std." ++ n) standardEnv'
standardEnv' = M.fromList [
("_", return)
-- Math
, ("min", foldN1 min)
, ("max", foldN1 max)
, ("range", func $ either (\(a, b) -> range a b (IntN 1)) (\(a, b, d) -> range a b d))
, ("xrange", func $ either (\(a, b) -> xrange a b (IntN 1)) (\(a, b, d) -> xrange a b d))
, ("succ", func (`add` IntN 1))
, ("pred", func (`sub` IntN 1))
, ("isEven", func (even :: Integer -> Bool))
, ("isOdd", func (odd :: Integer -> Bool))
, ("neg", func neg)
, ("add", foldN add (IntN 0))
, ("sub", func $ subLike sub)
, ("mul", foldN mul (IntN 1))
, ("div", func $ subLike div)
, ("mod", func $ subLike N.mod)
, ("sum", foldN add (IntN 0))
, ("prod", foldN mul (IntN 1))
, ("pow", func2 pow)
, ("sqrt", func N.sqrt)
, ("sin", func N.sin)
, ("cos", func N.cos)
, ("tan", func N.tan)
, ("sgn", func N.sgn)
, ("abs", func N.abs)
, ("gt", func2 greaterThan)
, ("lt", func2 lessThan)
, ("ge", func2 greaterEq)
, ("le", func2 lessEq)
, ("neq", func2 equals)
, ("nne", func2 notEquals)
, ("cons", func cons)
, ("decons", func decons)
, ("hd", func hd)
, ("tl", func tl)
, ("eq", func eq)
, ("ne", func (not . eq))
-- Logic
, ("and", func (and :: [Bool] -> Bool))
, ("or", func (or :: [Bool] -> Bool))
, ("not", func not)
-- Type Checking
, ("is0", func isZero)
, ("isT", eqFunc $ Bool True)
, ("isF", eqFunc $ Bool False)
, ("isBool", checkFunc BoolC)
, ("isChar", checkFunc CharC)
, ("isInt", checkFunc IntC)
, ("isReal", checkFunc RealC)
, ("isNum", checkFunc NumberC)
, ("isSymbol", checkFunc SymbolC)
, ("isString", checkFunc StringC)
, ("isList", checkFunc listAnyC)
, ("isEmpty", checkFunc EmptyC)
, ("isCons", checkFunc $ ConsC AnyC listAnyC)
-- List Processing
, ("s0", func (\x -> head (x :: [FPValue])))
, ("s1", func (\x -> (x :: [FPValue]) !! 1))
, ("sort", func (sort :: [Value] -> [Value]))
, ("distl", func distl)
, ("distr", func distr)
, ("rev", func (reverse :: [FPValue] -> [FPValue]))
, ("reverse", func (reverse :: [FPValue] -> [FPValue]))
, ("append", func (concat :: [[FPValue]] -> [FPValue]))
, ("cross", func (sequence :: [[FPValue]] -> [[FPValue]]))
, ("trans", func (transpose :: [[FPValue]] -> [[FPValue]]))
, ("zip", func (zipn :: [[FPValue]] -> [[FPValue]]))
, ("index", funcE index)
, ("len", func (length :: [FPValue] -> Int))
-- I/O
, ("put", ioFunc1'0 (\x -> putStr $ disp (x :: FPValue)))
, ("putL", ioFunc1'0 (\x -> putStrLn $ disp (x :: FPValue)))
, ("putS", ioFunc1'0 (\(Str s) -> putStr s))
, ("putSL", ioFunc1'0 (\(Str s) -> putStrLn s))
, ("putC", ioFunc1'0 putChar)
, ("getL", ioFunc0'1 (Str <$> getLine))
, ("getC", ioFunc0'1 getChar)
] :: M.Map String FPFunc
|
Ming-Tang/FP15
|
src/FP15/Evaluator/Standard.hs
|
mit
| 9,089
| 0
| 14
| 2,083
| 3,512
| 1,958
| 1,554
| 182
| 5
|
-- If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
--
-- Find the sum of all the multiples of 3 or 5 below 1000.
calc :: Int
calc = sum [x| x <- [1..999], x `mod` 3 == 0 || x `mod` 5 == 0]
main :: IO ()
main = print calc
|
daniel-beard/projecteulerhaskell
|
Problems/p1.hs
|
mit
| 306
| 4
| 11
| 78
| 75
| 43
| 32
| 4
| 1
|
{-|
Module : TTN.Controller.Core
Description : Diverse code for working in Spock which is not particularly
related to Articles or authentication.
Author : Sam van Herwaarden <samvherwaarden@protonmail.com>
-}
{-# LANGUAGE DataKinds #-}
module TTN.Controller.Core where
import TTN.Util
import TTN.Model.Article
import TTN.Model.Core
import TTN.Model.Translation
import TTN.Model.User
import TTN.View.Core
import TTN.View.Shared
import Control.Monad.Logger ( runNoLoggingT )
import Control.Monad.IO.Class ( liftIO )
import Data.HVect ( HVect(..) )
import Data.Text ( pack )
import qualified Database.Persist.Postgresql as Pg
import qualified Web.Spock as S
import qualified Web.Spock.Config as S
-- | Spock configuration
getCfg :: Pg.ConnectionString -> IO TTNCfg
getCfg connString = do
-- Set up connection for Persistent
pool <- runNoLoggingT $ Pg.createPostgresqlPool connString 5
runNoLoggingT . flip Pg.runSqlPool pool $ do
Pg.runMigration migrateUser
Pg.runMigration migrateArticle
Pg.runMigration migrateTranslation
-- Set up Spock config
cfg' <- S.defaultSpockCfg defSession (S.PCPool pool) defState
-- Enable CSRF protection
return cfg' { S.spc_csrfProtection = True }
initHook :: TTNAction () (HVect '[])
initHook = return HNil
welcomePage :: TTNAction ctx a
welcomePage = do
-- TODO: some systematic location and wrapper
welcome <- liftIO $ readFile "WELCOME.md"
renderSimpleHtml . hr . pack $ mdToHtml welcome
|
samvher/translatethenews
|
app/TTN/Controller/Core.hs
|
mit
| 1,582
| 0
| 11
| 348
| 327
| 181
| 146
| 31
| 1
|
module Unison.Util.Exception where
import Unison.Prelude
import Control.Concurrent.Async (withAsync, waitCatch)
-- These are adapted from: https://github.com/snoyberg/classy-prelude/blob/ccd19f2c62882c69d5dcdd3da5c0df1031334c5a/classy-prelude/ClassyPrelude.hs#L320
-- License is MIT: https://github.com/snoyberg/classy-prelude/blob/ccd19f2c62882c69d5dcdd3da5c0df1031334c5a/classy-prelude/LICENSE
-- Catch all exceptions except asynchronous exceptions.
tryAny :: MonadIO m => IO a -> m (Either SomeException a)
tryAny action = liftIO $ withAsync action waitCatch
-- Catch all exceptions except asynchronous exceptions.
catchAny :: IO a -> (SomeException -> IO a) -> IO a
catchAny action onE = tryAny action >>= either onE return
|
unisonweb/platform
|
parser-typechecker/src/Unison/Util/Exception.hs
|
mit
| 733
| 0
| 9
| 81
| 128
| 67
| 61
| 7
| 1
|
{- |
Module : $Header$
Description : Contains all relevant definitions for the initialization command.
Author : Nils 'bash0r' Jonsson
Copyright : (c) 2015 Nils 'bash0r' Jonsson
License : MIT
Maintainer : aka.bash0r@gmail.com
Stability : unstable
Portability : non-portable (Portability is untested.)
Contains all relevant definitions for the initialization command.
-}
module Headergen.Commands.Initialization
( command
, help
) where
import Control.Applicative
import Control.Monad
import Data.Aeson ()
import Data.Aeson.Encode.Pretty
import Data.Time.Calendar
import Data.Time.Clock
import qualified Data.ByteString.Lazy as BS
import System.Console.Haskeline
import System.Directory
import System.IO
import Headergen.Configuration
import Headergen.Messages
import Headergen.Utility
command :: [String] -> IO ()
command [] = initializeDefinition
command _ = help
help :: IO ()
help = do
putStrLn " headergen init"
putStrLn " --> initializes a new .headergen.def."
-- | Initialize a .headergen.def.
initializeDefinition = do
exists <- doesFileExist ".headergen.def"
if exists
then do
allowance <- requestForAllowance
if allowance
then do
hgd <- requestConfiguration
createHeadergenDef hgd
else
putStrLn noResourcesCreatedMessage
else do
hgd <- requestConfiguration
createHeadergenDef hgd
-- | Request the configuration from console.
requestConfiguration = do
(year, _, _) <- date
runInputT defaultSettings $ do
mod <- getInputLine moduleMessage
desc <- getInputLine descriptionMessage
auth <- getInputLine authorMessage
let copyRightText = "(c) " ++ show year ++ " " ++ def auth ""
copyRight = copyRightMessage copyRightText
copyr <- getInputLine copyRight
lic <- getInputLine licenseMessage
maint <- getInputLine maintainerMessage
stab <- getInputLine stabilityMessage
portab <- getInputLine portabilityMessage
return ( Configuration (def mod "$Header$" )
(def desc "" )
(def auth "" )
(def copyr copyRightText )
(def lic "MIT" )
(def maint "" )
(def stab "unstable" )
(def portab "non-portable (Portability is untested.)") )
-- | Create a .headergen.def in the current directory.
createHeadergenDef conf = do
file <- openFile ".headergen.def" WriteMode
BS.hPutStr file (encodePretty conf)
hFlush file
hClose file
-- | Current date.
date = liftM (toGregorian . utctDay) getCurrentTime
|
aka-bash0r/headergen
|
src/Headergen/Commands/Initialization.hs
|
mit
| 2,961
| 0
| 16
| 979
| 535
| 266
| 269
| 63
| 3
|
{-# LANGUAGE
TupleSections,
RecordWildCards,
ViewPatterns
#-}
module ConstraintWitness.Plugin.Witness (
witnessPlugin
) where
-- external
import GHC.TcPluginM.Extra (evByFiat, lookupModule, lookupName, newWanted)
import Data.Maybe (mapMaybe)
import Data.Either (partitionEithers)
import Data.Bifunctor (bimap, second)
import Data.IORef (writeIORef)
import Data.STRef (readSTRef, newSTRef, writeSTRef)
import Control.Monad.ST (runST)
import System.IO.Unsafe (unsafePerformIO)
-- GHC API
import GhcPlugins (Plugin(..), defaultPlugin)
import TcRnTypes (Ct(..), TcPlugin(..), TcPluginResult(..), ctEvidence, ctEvPred, CtEvidence(..), CtLoc, ctLoc)
import FastString (fsLit)
import OccName (mkTcOcc, mkOccName, dataName, occNameString)
import Name (nameOccName, nameUnique)
import Module (mkModuleName)
import TcPluginM (TcPluginM, tcLookupTyCon, tcLookupDataCon, tcPluginIO)
import TcEvidence (EvTerm)
import TyCon (TyCon, tyConDataCons, tyConRoles, mkPromotedDataCon)
import Type (EqRel(..), PredTree (..), classifyPredType, mkEqPred, typeKind)
import TypeRep (Type(..), PredType)
import Kind (constraintKind, liftedTypeKind)
import DataCon (dataConTyCon, dataConName, DataCon)
import StaticFlags (v_opt_C_ready) -- THIS IS A HORRIBLE HACK BECAUSE THE API SUCKS
import Outputable (showPpr)
import DynFlags (unsafeGlobalDynFlags)
witnessPlugin :: TcPlugin
witnessPlugin = TcPlugin {
tcPluginInit = findTyCons,
tcPluginSolve = solveWitness,
tcPluginStop = const (return ())
}
-- Holds all the type constructors, values etc. that are needed in this plugin.
-- Mostly used with wildcard syntax; that way, we can sort-of treat the fields as top-level constants.
data State = State { witness :: TyCon -- ^ constraint-witness:ConstraintWitness.Internal (Witness). The magical type family.
-- , iso :: TyCon -- ^ constraint-witness:ConstraintWitness.Internal (Isomorphism)
, eq :: TyCon -- ^ base:Data.Type.Equality ((:~:)), the witness datatype for equality constraints.
, hlist :: TyCon -- ^ HList:Data.HList.HList (HList), a strongly-typed heterogenous list. The witness for tupled constraints.
, list :: TyCon -- ^ ghc-prim:GHC.Types ([]), the standard list type.
, cons :: TyCon -- ^ ghc-prim:GHC.Types ((:)), lifted.
, nil :: Type -- ^ ghc-prim:GHC.Types ([]), the lifted constructor (NOT the type!)
, unit :: Type -- ^ ghc-prim:GHC.Tuple (()), the unit tuple
}
data WitnessEquality = WitnessEquality {
we_loc :: CtLoc,
we_precond :: (Type, Type),
we_ev :: EvTerm,
we_proven :: Ct }
-- | Find the type family constructors we need.
findTyCons :: TcPluginM State
findTyCons = do
-- This is an utterly horrible hack. I know. But there's no reinitializeGlobals equivalent for TcPluginM.
tcPluginIO $ writeIORef v_opt_C_ready True
witness <- summonTc "constraint-witness" "ConstraintWitness.Internal" "Witness"
iso <- summonTc "constraint-witness" "ConstraintWitness.Internal" "Isomorphism"
eq <- summonTc "base" "Data.Type.Equality" ":~:"
hlist <- summonTc "HList" "Data.HList.HList" "HList"
list <- summonTc "ghc-prim" "GHC.Types" "[]"
unit' <- summonTc "ghc-prim" "GHC.Tuple" "()"
let unit = TyConApp unit' []
let promote :: DataCon -> TyCon
promote con = let name = dataConName con
unique = nameUnique name
kind = TyConApp list [liftedTypeKind]
roles = tyConRoles (dataConTyCon con)
in mkPromotedDataCon con name unique kind roles
consts = tyConDataCons list
-- This type is wired-in, so it's fine to hardfail the pattern matches
let [flip TyConApp [] . promote ->
nil] = filter ((== "[]") . occNameString . nameOccName . dataConName) consts
[promote ->
cons] = filter ((== ":" ) . occNameString . nameOccName . dataConName) consts
return $ State {..}
where
summonTc :: String -> String -> String -> TcPluginM TyCon
summonTc pack mod name = tcLookupTyCon =<< flip lookupName (mkTcOcc name) =<< lookupModule (mkModuleName mod) (fsLit pack)
-- | The actual constraint solver. Well, it's mostly just an interface to toWitnessEquality
solveWitness :: State -> [Ct] -> [Ct] -> [Ct] -> TcPluginM TcPluginResult
solveWitness _ givens deriveds [] = return (TcPluginOk [] [])
solveWitness (State{..}) givens deriveds wanteds = TcPluginOk solved <$> reduced
where
touched :: [WitnessEquality]
touched = mapMaybe (toWitnessEquality State{..}) wanteds
solved :: [(EvTerm, Ct)]
solved = [(we_ev, we_proven) | WitnessEquality{..} <- touched]
wanted :: [(CtLoc, (Type, Type))]
wanted = [(we_loc, we_precond) | WitnessEquality{..} <- touched]
reduced :: TcPluginM [Ct]
reduced = sequence $ mapMaybe satisfyPrecond wanted
satisfyPrecond :: (CtLoc, (Type, Type)) -> Maybe (TcPluginM Ct)
satisfyPrecond (loc, (lhs, rhs)) =
if foldr (\given found -> case classifyPredType $ ctEvPred $ ctEvidence given of
EqPred NomEq l r -> found || (lhs == l && rhs == r) || (lhs == r && rhs == l)
_ -> found) False givens
then Nothing
else Just (CNonCanonical <$> newWanted loc (mkEqPred lhs rhs))
-- | Check if a constraint is an equality constraint with (Witness a) on one or both sides
-- @'toWitnessEquality' s ct@ is either:
-- - @'Right' (ct, (equ, fiat))@ when ct is an equality constraint where one or both sides are of the form @'Witness' cxt@.
-- In that case, @equ@ is the original equality constraint with values of the form @'Witness' cxt@ replaced by the witness for cxt.
-- @fiat@ is an evidence term that basically says "Magic!" and that's it.
-- - @'Left' ct@, when the above isn't the case.
toWitnessEquality :: State -- ^ The type constructors we need
-> Ct -- ^ The constraint to pattern-match on
-> Maybe WitnessEquality
toWitnessEquality (State{..}) ct =
case classifyPredType $ ctEvPred $ ctEvidence ct of
EqPred NomEq lhs rhs ->
runST $ do
pass <- newSTRef True
lhs' <- case lhs of
TyConApp con [arg] | con == witness -> writeSTRef pass False >> return (constructWitness State{..} arg)
_ -> return lhs
rhs' <- case rhs of
TyConApp con [arg] | con == witness -> writeSTRef pass False >> return (constructWitness State{..} arg)
_ -> return rhs
readSTRef pass >>= \f -> if f
then log__ "toWitnessEquality found no Witness constructors" $ return Nothing
else log__ "toWitnessEquality found Witness constructor(s)" $ return $ Just WitnessEquality {
we_proven = ct,
we_ev = evByFiat "magical type family: Witness" lhs rhs,
we_loc = ctLoc ct,
we_precond = (lhs', rhs')}
_ -> Nothing
constructWitness :: State -- ^ The type constructors we need
-> Type -- ^ The type to make a witness of. Must have kind Constraint.
-> Type
constructWitness (State{..}) arg
| typeKind arg == constraintKind =
case classifyPredType arg of
ClassPred clas args -> error "TODO: implement dictionary thingy"
EqPred NomEq l r -> log__ "transforming (a ~ b) to (a :~: b)" $ TyConApp eq [l, r]
TuplePred [] -> log__ "transforming an empty tuple constraint" $ unit
TuplePred tys -> log__ "transforming a non-empty tuple constraint" $ TyConApp hlist [promotedList $ map (constructWitness State{..}) tys]
| otherwise = error "argument is not a constraint"
where
promotedList :: [Type] -> Type
promotedList = foldr (\head spine -> TyConApp cons [head, spine]) nil
log__ :: String -> a -> a
log__ s v = unsafePerformIO (putStrLn s) `seq` v
|
Solonarv/constraint-witness
|
plugin/ConstraintWitness/Plugin/Witness.hs
|
mit
| 8,574
| 0
| 20
| 2,526
| 1,869
| 1,019
| 850
| 126
| 5
|
-- | This module defines 'Scope' monad and related helpers.
-- It can be used as underlying monad:
--
-- * Module scope;
--
-- * 'Block' scope, such as compound statements in C;
--
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Data.Scope (
-- * Scope monad
Scope, Index
-- * Manipulating scope context
, add, freshIndex
-- * Names
, mkVarName, initialIndex
-- * Unlifting scope context
, context
-- * Markers
, Begin, End, begin, end
) where
import Control.Monad.State (StateT, runStateT, modify, get)
import Control.Monad.Writer (Writer, runWriter, tell)
-- | Int is sufficient for variable indexes because it's impossible to compile so big program.
-- We don't have so much videomemory assigned for code.
type Index = Int
-- | 'Scope' monad is convenient monad transformer wrapper
newtype Scope r a = Scope { runScope :: StateT Index (Writer [r]) a }
deriving (Functor, Monad)
-- | The /initialIndex/ in index assigned for first entity in block.
initialIndex :: Index
initialIndex = 0
-- | 'freshIndex' should give unique index each time we call it within the /given/ scope.
freshIndex :: Scope r Index
freshIndex = Scope $ modify succ >> get
-- | Makes a name for a given 'Index'. Note that unique names are guarantted when prefix is fixed for all items in block.
mkVarName :: String -> Index -> String
mkVarName prefix index = prefix ++ show index
-- | 'add' pushes argument /to the end/ of the scope.
add :: r -> Scope r ()
add s = Scope $ tell [s]
-- | 'context' returns an accumulated context.
context :: Scope r a -> [r]
context = snd . runWriter . (`runStateT` initialIndex) . runScope
-- | 'Begin' datatype have one constructor which not supposed to be used somehow.
-- The constructor defined to escape use of EmptyDataDecls extension and 'undefined'.
data Begin = Begin
-- | The same as 'Begin'.
data End = End
-- | 'begin' is special marker which might sign /beginning/ of the scope.
begin :: Scope r Begin
begin = return Begin
-- | 'end' is special marker which might sign /ending/ of the scope.
end :: Scope r End
end = return End
|
pxqr/language-cl-c
|
Data/Scope.hs
|
mit
| 2,180
| 0
| 10
| 495
| 342
| 206
| 136
| 28
| 1
|
module Alpha where
import Math
import Clojure
import Data.List
import Data.Char
eul76 target coins
| target < 0 = 0
| target <= 1 = 1
| null coins = 0
| otherwise = (eul76 (target - (head coins)) coins) + (eul76 target (tail coins))
powerMe a n
| n == 0 = 1
| n == 1 = a
| otherwise = a * powerMe a (pred n)
|
skadinyo/conc
|
haskell/alpha.hs
|
epl-1.0
| 326
| 0
| 12
| 87
| 170
| 83
| 87
| 14
| 1
|
module Computability.Symbols.Macro where
import Types
import Macro.Math
import Macro.MetaMacro
-- * Symbols
-- ** Symbol equality
-- | Symbol equality sign
symEqSign :: Note
symEqSign = underset "s" "="
-- | Symbol equality operation
symEq :: Note -> Note -> Note
symEq = binop symEqSign
-- | Infix symbol equality operator
(=@=) :: Note -> Note -> Note
(=@=) = symEq
-- * Alphabets
-- | Concrete alphabet
alph_ :: Note
alph_ = comm0 "Sigma"
-- | Concrete alphabet and string
alphe_ :: Note
alphe_ = alph_ !: estr
-- * Strings
-- | Empty string
estr :: Note
estr = epsilon
-- | Concrete string
str_ :: Note
str_ = "s"
-- | Strings of alphabet
strsof :: Note -> Note
strsof alphabet = alphabet ^: "*"
-- | Strings of concrete alphabet
strsof_ :: Note
strsof_ = strsof alph_
-- ** Lists of symbols
strlst :: Note -> Note -> Note
strlst s1 sn = s1 <> dotsc <> sn
strlist :: Note -> Note -> Note -> Note
strlist s1 s2 sn = s1 <> s2 <> dotsc <> sn
strof :: [Note] -> Note
strof = mconcat
-- ** Concatenation
-- | String concatenation
strconcat :: [Note] -> Note
strconcat = mconcat
-- | String concatenation infix operator
(<@>) :: Note -> Note -> Note
(<@>) = (<>)
-- ** Reverse String
-- | Reverse of a given string
rstr :: Note -> Note
rstr s = s ^: "R"
|
NorfairKing/the-notes
|
src/Computability/Symbols/Macro.hs
|
gpl-2.0
| 1,307
| 0
| 7
| 299
| 329
| 194
| 135
| 34
| 1
|
module Compiler.While_Goto where
import qualified While as W
import qualified Goto as G
compile :: W.Program -> G.Program
compile p = let (e,q) = comp (0,p) in q ++ [ G.Stop ]
comp :: (Int, W.Program) -> (Int, G.Program)
comp (a,p) = case p of
W.Skip -> (a, [])
W.Inc r -> (a+1, [G.Inc r])
W.Dec r -> (a+1, [G.Dec r])
W.Seq p1 p2 ->
let (m,q1) = comp (a, p1); (e,q2) = comp (m, p2)
in (e,q1 ++ q2)
W.IfZ r p1 p2 ->
let (h,q2) = comp (a+1,p2) ; (e,q1) = comp (h+1,p1)
in (e, [G.GotoZ r (h+1)] ++ q2 ++ [G.Goto e] ++ q1)
W.While r p ->
let (e,q) = comp (a+1,p)
in (e+1, [ G.GotoZ r (e+1)] ++ q ++ [G.Goto a])
|
marcellussiegburg/autotool
|
collection/src/Compiler/While_Goto.hs
|
gpl-2.0
| 661
| 0
| 17
| 181
| 466
| 253
| 213
| 19
| 6
|
{-
Copyright (C) 2015 Leon Medvinsky
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-}
{-|
Module : Needles.Bot.Configuration
Description : The configuration of PS bots
Copyright : (c) Leon Medvinsky, 2015
License : GPL-3
Maintainer : lmedvinsky@hotmail.com
Stability : experimental
Portability : portable
-}
module Needles.Bot.Configuration (
Configuration(..)
, mainServer
, mainPort
, mainPath
) where
import Needles.Bot.Types
-- | Address of the main Pokemon Showdown server
mainServer :: String
mainServer = "sim.smogon.com"
-- | Port used by the main Pokemon Showdown server
mainPort :: Int
mainPort = 8000
-- | Path used by the main Pokemon Showdown server
mainPath :: String
mainPath = "/showdown/websocket"
|
raymoo/needles
|
src/Needles/Bot/Configuration.hs
|
gpl-3.0
| 1,550
| 0
| 5
| 414
| 66
| 44
| 22
| 12
| 1
|
module Language.Bitcoin.Parser
-- export {{{1
(
run_parser
) where
-- import {{{1
import Control.Monad (liftM, when)
import Data.Char (isSpace)
import Data.Int (Int32)
import Data.Maybe (catMaybes)
import Data.Word (Word8)
import Language.Bitcoin.Types
import Language.Bitcoin.Utils (b2i, bsLength)
import qualified Data.ByteString as B
import qualified Data.Char as C
import qualified Data.List as List
import Text.Parsec.Prim (parserFail)
import Text.ParserCombinators.Parsec (Parser, parse, sepEndBy, eof, many, (<|>), (<?>), alphaNum, char, hexDigit, newline, unexpected, satisfy)
-- run_parser :: String -> Code -> Either String Script {{{1
run_parser :: String -> Code -> Either String Script
run_parser source code =
case parse script source (removeComments code) of
Left parseError -> Left $ show parseError
Right x -> Right x
removeComments :: String -> String
removeComments [] = []
removeComments string =
let
(code, rest) = List.break (=='#') string
(_, string') = List.break (=='\n') rest
in code ++ removeComments string'
script :: Parser Script
script = do
ops <- spaces >> (liftM catMaybes $ sepEndBy operation separator)
eof
return ops
separator :: Parser ()
separator = (newline <|> char ';') >> spaces >> return ()
spaces :: Parser String
spaces = many (satisfy (\c -> isSpace c && not (c =='\n')))
operation :: Parser (Maybe Command)
operation = do
op <- do
command <- many (alphaNum <|> char '_' <?> "opcode")
if command == ""
then return Nothing
else liftM Just $ case command of
"DATA" -> spaces >> liftM DATA hexString
"KEY" -> keyOrSig KEY
"SIG" -> keyOrSig SIG
"OP_PUSHDATA" -> push
"OP_PUSHDATA1" -> push1
"OP_PUSHDATA2" -> push2
"OP_PUSHDATA4" -> push4
x -> opcode x
spaces >> return op
keyOrSig :: (Int32 -> Command) -> Parser Command
keyOrSig createCommand = do
number <- spaces >> hexString
case b2i number of
Left e -> parserFail e
Right value -> return $ createCommand value
opcode :: String -> Parser Command
opcode x = liftM CmdOpcode $ liftReadS reads x
push :: Parser Command
push = pushN checkLength checkValue Direct
where
checkLength len = when (len /= 1) $ parserFail "OP_PUSHDATA expects a one byte size parameter"
checkValue value = when (value > 75) $ parserFail "OP_PUSHDATA only support up to 75 bytes of data"
push1 :: Parser Command
push1 = pushN checkLength checkValue OneByte
where
checkLength len = when (len /= 1) $ parserFail "OP_PUSHDATA1 expects a one byte size parameter"
checkValue _ = return ()
push2 :: Parser Command
push2 = pushN checkLength checkValue TwoBytes
where
checkLength len = when (len /= 2) $ parserFail "OP_PUSHDATA2 expects a two bytes size parameter"
checkValue _ = return ()
push4 :: Parser Command
push4 = pushN checkLength checkValue FourBytes
where
checkLength len = when (len /= 4) $ parserFail "OP_PUSHDATA4 expects a four bytes size parameter"
checkValue _ = return ()
pushN :: (Int -> Parser ()) -> (Int32 -> Parser ()) -> PushDataType -> Parser Command
pushN checkLength checkValue pushType = do
sizeString <- spaces >> hexString
checkLength $ bsLength sizeString
sizeValue <- liftError $ b2i sizeString
when (sizeValue == 0) $
parserFail "data of zero length is not allowed"
checkValue sizeValue
dataString <- spaces >> hexString
let dataLength = fromIntegral $ bsLength dataString
when (dataLength /= sizeValue) $
parserFail $ "actual length of data does not match the announced length (" ++ show dataLength ++ " vs. " ++ show sizeValue ++ ")"
return $ CmdOpcode $ OP_PUSHDATA pushType dataString
hexString :: Parser B.ByteString
hexString = liftM B.pack $ many hexByte
hexByte :: Parser Word8
hexByte = do
upperNibble <- hexDigit
lowerNibble <- hexDigit
return $ fromIntegral $ (C.digitToInt upperNibble) * 16 + (C.digitToInt lowerNibble)
liftReadS :: ReadS a -> String -> Parser a
liftReadS f s =
let readings = f s in
if length readings /= 1 || snd (head readings) /= ""
then unexpected s
else return $ fst $ head readings
liftError :: Either String a -> Parser a
liftError (Left e) = parserFail e
liftError (Right v) = return v
|
copton/bitcoin-script-tools
|
src/Language/Bitcoin/Parser.hs
|
gpl-3.0
| 4,263
| 0
| 16
| 890
| 1,415
| 708
| 707
| 105
| 9
|
module Murex.Interpreter.Builtin where
import Import
import Data.Sequence ( Seq, (|>), (<|), (><)
, ViewL(..), ViewR(..), viewl, viewr)
import qualified Data.Sequence as S
import Murex.Interpreter.Values
------ Booleans ------
notBool (MurexBool a) = MurexBool $ not a
eqBool (MurexBool a) (MurexBool b) = MurexBool $ a == b
andBool (MurexBool a) (MurexBool b) = MurexBool $ a && b
orBool (MurexBool a) (MurexBool b) = MurexBool $ a || b
xorBool (MurexBool a) (MurexBool b) = MurexBool $ a /= b
------ Arithmetic ------
negNum (MurexNum a) = MurexNum (negate a)
-- turns out, floating point arithmetic is hard. error conditions have to be put in sticky flags, which means I need access to some stateful flags
addNum :: Value -> Value -> Value
addNum (MurexNum a) (MurexNum b) = MurexNum (a + b)
----TODO verify these choice against floating point standards
----computations involving NaN
--addNum MurexNaN _ = MurexNaN
--addNum _ MurexNaN = MurexNaN
----computations involving infinities
--addNum MurexInf MurexNegInf = MurexNaN
--addNum MurexNegInf MurexInf = MurexNaN
--addNum MurexInf _ = MurexInf
--addNum _ MurexInf = MurexInf
--addNum MurexNegInf _ = MurexNegInf
--addNum _ MurexNegInf = MurexNegInf
----computations involving negative zero
--addNum MurexNegZ MurexNegZ = MurexNegZ
--addNum MurexNegZ (MurexNum a) = MurexNum a
--addNum (MurexNum a) MurexNegZ = MurexNum a
subNum (MurexNum a) (MurexNum b) = MurexNum (a - b)
mulNum (MurexNum a) (MurexNum b) = MurexNum (a * b)
divNum (MurexNum a) (MurexNum b) = if numerator b == 0 then Nothing else Just (MurexNum (a / b))
------ Relations ------
eqNum (MurexNum a) (MurexNum b) = MurexBool (a == b)
neqNum (MurexNum a) (MurexNum b) = MurexBool (a /= b)
ltNum (MurexNum a) (MurexNum b) = MurexBool (a < b)
lteNum (MurexNum a) (MurexNum b) = MurexBool (a > b)
gtNum (MurexNum a) (MurexNum b) = MurexBool (a <= b)
gteNum (MurexNum a) (MurexNum b) = MurexBool (a >= b)
------ Characters ------
eqChr (MurexChar a) (MurexChar b) = MurexBool (a == b)
------ Conversion ------
--numFloor (MurexNum a) = MurexInt (numerator a `div` denominator a)
--numCeil (MurexNum a) = MurexInt $ if denominator a == 1 then numerator a else (numerator a `div` denominator a) + 1
--numNumer (MurexNum a) = MurexInt $ numerator a
--numDenom (MurexNum a) = MurexInt $ denominator a
numToChr :: Value -> Maybe Value
numToChr (MurexNum a) = if valid then Just (MurexChar $ chr int) else Nothing
where
valid = denominator a == 1 && 0 <= int && int <= 0x10FFFF
int = fromInteger $ numerator a
chrToNum :: Value -> Value
chrToNum (MurexChar c) = MurexNum (fromIntegral (ord c) % 1)
------ Sequences ------
lenSeq :: Value -> Value
lenSeq (MurexSeq xs) = MurexNum (fromIntegral (S.length xs) % 1)
ixSeq :: Value -> Int -> Maybe Value
ixSeq (MurexSeq xs) i = if inBounds i xs then Just (S.index xs i) else Nothing
setSeq :: Value -> Int -> Value -> Maybe Value
setSeq (MurexSeq xs) i x = if inBounds i xs then Just (MurexSeq $ S.update i x xs) else Nothing
inBounds i xs = 0 <= i && i < S.length xs
consSeq :: Value -> Value -> Value
consSeq x (MurexSeq xs) = MurexSeq $ x <| xs
snocSeq :: Value -> Value -> Value
snocSeq (MurexSeq xs) x = MurexSeq $ xs |> x
catSeq :: Value -> Value -> Value
catSeq (MurexSeq a) (MurexSeq b) = MurexSeq $ a >< b
--TODO split seq at index
headSeq (MurexSeq xs) = case viewl xs of { EmptyL -> Nothing; x :< _ -> Just x }
lastSeq (MurexSeq xs) = case viewr xs of { EmptyR -> Nothing; _ :> x -> Just x }
tailSeq (MurexSeq xs) = case viewl xs of { EmptyL -> Nothing; _ :< xs -> Just (MurexSeq xs) }
initSeq (MurexSeq xs) = case viewr xs of { EmptyR -> Nothing; xs :> _ -> Just (MurexSeq xs) }
------ Finite Types ------
project :: Label -> Value -> Maybe Value
project i (MurexRecord xs) = lookup i xs
project i (MurexVariant i0 x) = if i == i0 then Just x else Nothing
update :: Label -> Value -> Value -> Maybe Value
update i (MurexRecord xs) v = case break ((==i) . fst) xs of
(_, []) -> Nothing
(before, (_:after)) -> Just . MurexRecord $ before ++ ((i,v):after)
setField :: Label -> Value -> Value -> Value
setField i (MurexRecord xs) x = MurexRecord $ (i, x) : filter ((i /=) . fst) xs
|
Zankoku-Okuno/murex
|
Murex/Interpreter/Builtin.hs
|
gpl-3.0
| 4,205
| 0
| 12
| 807
| 1,529
| 804
| 725
| 56
| 2
|
module HEP.Automation.MadGraph.Dataset.Set20110421set2 where
import HEP.Storage.WebDAV
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.ZpHFull
import HEP.Automation.MadGraph.Dataset.Common
import HEP.Automation.MadGraph.Dataset.Processes
import qualified Data.ByteString as B
psetup_zphfull_TTBarSemiLep :: ProcessSetup ZpHFull
psetup_zphfull_TTBarSemiLep = PS {
mversion = MadGraph4
, model = ZpHFull
, process = preDefProcess TTBarSemiLep
, processBrief = "TTBarSemiLep"
, workname = "421ZpH_TTBarSemiLep"
}
zpHFullParamSet :: [ModelParam ZpHFull]
zpHFullParamSet = [ ZpHFullParam m g (0.28)
| m <-[135.0, 140.0 .. 170.0 ]
, g <- [0.70, 0.75 .. 1.40] ]
psetuplist :: [ProcessSetup ZpHFull]
psetuplist = [ psetup_zphfull_TTBarSemiLep ]
sets :: [Int]
sets = [1]
zptasklist :: ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull]
zptasklist ssetup csetup =
[ WS ssetup (psetup_zphfull_TTBarSemiLep)
(RS { param = p
, numevent = 10000
, machine = TeVatron
, rgrun = Fixed
, rgscale = 200.0
, match = NoMatch
, cut = DefCut
, pythia = NoPYTHIA
, usercut = NoUserCutDef
, pgs = NoPGS
, setnum = num
})
csetup
(WebDAVRemoteDir "mc/TeVatronFor3/ZpHFull0421ScanTTBarSemiLep")
| p <- zpHFullParamSet , num <- sets ]
totaltasklistEvery :: Int -> Int -> ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull]
totaltasklistEvery n r ssetup csetup =
let lst = zip [1..] (zptasklist ssetup csetup)
in map snd . filter (\(x,_)-> x `mod` n == r) $ lst
|
wavewave/madgraph-auto-dataset
|
src/HEP/Automation/MadGraph/Dataset/Set20110421set2.hs
|
gpl-3.0
| 1,859
| 0
| 13
| 476
| 472
| 280
| 192
| 46
| 1
|
module P08PizzaSpec (main,spec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import P08Pizza hiding (main)
main :: IO ()
main = hspec spec
spec = do
describe "formatSlices" $ do
it "shows right message for no slices" $ do
formatSlices 0 `shouldBe` " So nobody gets a slice of pizza at all. Boo! And there was"
it "shows right message for 1 slices" $ do
formatSlices 1 `shouldBe` " So each person gets a single slice of pizza, with"
it "shows right message for 2 slices" $ do
formatSlices 2 `shouldBe` " So each person gets 2 slices of pizza, with"
describe "formatPizzas" $ do
it "shows right message for no pizzas" $ do
formatPizzas 0 `shouldBe` "There was no pizza. Boo!"
it "shows right message for 1 pizzas" $ do
formatPizzas 1 `shouldBe` "There was 1 pizza."
it "shows right message for 2 pizzas" $ do
formatPizzas 2 `shouldBe` "There were 2 pizzas."
describe "formatLeftovers" $ do
it "shows right message for no slices" $ do
formatLeftovers 0 `shouldBe` " no slices left over."
it "shows right message for 1 slices" $ do
formatLeftovers 1 `shouldBe` " one slice left over."
it "shows right message for 2 slices" $ do
formatLeftovers 2 `shouldBe` " 2 slices left over."
|
ciderpunx/57-exercises-for-programmers
|
test/P08PizzaSpec.hs
|
gpl-3.0
| 1,284
| 0
| 14
| 306
| 283
| 135
| 148
| 28
| 1
|
module Bamboo.Type (
module Bamboo.Type.Config
, module Bamboo.Type.Class
, module Bamboo.Type.Common
, module Bamboo.Type.Extension
, module Bamboo.Type.Pager
)
where
import Bamboo.Type.Class
import Bamboo.Type.Common
import Bamboo.Type.Config
import Bamboo.Type.Extension
import Bamboo.Type.Pager hiding (per_page)
|
nfjinjing/bamboo
|
src/Bamboo/Type.hs
|
gpl-3.0
| 334
| 0
| 5
| 48
| 79
| 54
| 25
| 11
| 0
|
-- Copyright 2016, 2017 Robin Raymond
--
-- This file is part of Purple Muon
--
-- Purple Muon 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.
--
-- Purple Muon 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 Purple Muon. If not, see <http://www.gnu.org/licenses/>.
{-# LANGUAGE TemplateHaskell #-}
module Server.Types
( WaitingState(..)
, GameState(..), gObjs, pObjs, frameBegin, clients, logger, intStep
, WaitingServer, clientsConnected
, Server
, Resources(..), tbqueue, socket, uuid
, ClientConnection(..), addr, name, connType
, ClientConnectionType(..)
) where
import Protolude
import qualified Control.Concurrent.STM as CCS
import qualified Control.Lens as CLE
import qualified Data.IntMap.Strict as DIS
import qualified Data.Thyme.Clock as DTC
import qualified Network.Socket as NSO
import qualified System.Log.FastLogger as SLF
import qualified PurpleMuon.Game.Types as PGT
import qualified PurpleMuon.Input.Types as PIT
import qualified PurpleMuon.Network.Types as PNT
import qualified PurpleMuon.Physics.Types as PPT
-- | A client connection saves all the data the server knows about
-- a client
data ClientConnection
= ClientConnection
{ _addr :: NSO.SockAddr
, _name :: Text
, _connType :: ClientConnectionType
}
-- | The type of client connection
data ClientConnectionType
= ClientConnectionPlayer
{ playerObj :: PGT.GameObjKey
, inputControls :: PIT.Controls
}
| ClientConnectionViewer
-- | The state of a server waiting for connections
data WaitingState
= WaitingState
{ _clientsConnected :: [ClientConnection]
}
-- | The state of a server in game
data GameState
= GameState
{ _gObjs :: DIS.IntMap PGT.GameObject
, _pObjs :: PPT.PhysicalObjects
, _frameBegin :: DTC.UTCTime
, _clients :: [ClientConnection]
, _intStep :: Word32 -- ^ Count of integration steps
}
-- | Read only resources that the server has access to
data Resources
= Resources
{ _tbqueue :: CCS.TBQueue PNT.NakedMessage
, _socket :: NSO.Socket
, _logger :: SLF.LoggerSet
, _uuid :: PNT.ProtocolUUID
}
type WaitingServer a = ReaderT Resources (StateT WaitingState IO) a
type Server a = ReaderT Resources (StateT GameState IO) a
CLE.makeLenses ''ClientConnection
CLE.makeLenses ''WaitingState
CLE.makeLenses ''GameState
CLE.makeLenses ''Resources
|
r-raymond/purple-muon
|
src/Server/Types.hs
|
gpl-3.0
| 2,956
| 0
| 10
| 662
| 461
| 299
| 162
| 52
| 0
|
{-# LANGUAGE TypeFamilies #-}
module Lamdu.Data.Ops
( newHole, applyHoleTo, setToAppliedHole
, replace, replaceWithHole, setToHole, lambdaWrap, redexWrap
, redexWrapWithGivenParam
, genNewTag, assocTagName
, newPublicDefinitionWithPane
, newPublicDefinitionToIRef
, newPane
, newIdentityLambda
, setTagOrder
) where
import qualified Control.Lens as Lens
import qualified Data.ByteString.Extended as BS
import Data.Char (toLower)
import Data.Property (MkProperty', Property(..))
import qualified Data.Property as Property
import qualified Data.Set as Set
import qualified Data.UUID as UUID
import qualified GUI.Momentu.Direction as Dir
import Hyper (_HCompose)
import Hyper.Type.Prune (Prune(..))
import Lamdu.Calc.Identifier (Identifier(..))
import qualified Lamdu.Calc.Term as V
import qualified Lamdu.Calc.Type as T
import qualified Lamdu.CharClassification as Chars
import qualified Lamdu.Data.Anchors as Anchors
import Lamdu.Data.Definition (Definition(..))
import Lamdu.Data.Meta (SpecialArgs(..), PresentationMode)
import Lamdu.Data.Tag (Symbol(..), TextsInLang(..), tagOrder, tagTexts, tagSymbol, getTagName, name)
import Lamdu.Expr.IRef (DefI, HRef, ValI)
import qualified Lamdu.Expr.IRef as ExprIRef
import Lamdu.I18N.LangId (LangId)
import Revision.Deltum.Transaction (Transaction)
import qualified Revision.Deltum.Transaction as Transaction
import Lamdu.Prelude
type T = Transaction
setToAppliedHole :: Monad m => ValI m -> HRef m # V.Term -> T m (ValI m)
setToAppliedHole innerI destP =
do
newFuncI <- newHole
resI <- ExprIRef.newValI . V.BApp $ V.App newFuncI innerI
(destP ^. ExprIRef.setIref) resI
pure resI
applyHoleTo :: Monad m => HRef m # V.Term -> T m (ValI m)
applyHoleTo exprP = setToAppliedHole (exprP ^. ExprIRef.iref) exprP
newHole :: Monad m => T m (ValI m)
newHole = ExprIRef.newValI $ V.BLeaf V.LHole
replace :: Monad m => HRef m # V.Term -> ValI m -> T m (ValI m)
replace exprP newExprI = newExprI <$ (exprP ^. ExprIRef.setIref) newExprI
replaceWithHole :: Monad m => HRef m # V.Term -> T m (ValI m)
replaceWithHole exprP = replace exprP =<< newHole
setToHole :: Monad m => HRef m # V.Term -> T m (ValI m)
setToHole exprP =
exprI <$ ExprIRef.writeValI exprI hole
where
hole = V.BLeaf V.LHole
exprI = exprP ^. ExprIRef.iref
lambdaWrap :: Monad m => HRef m # V.Term -> T m (V.Var, HRef m # V.Term)
lambdaWrap exprP =
do
newParam <- ExprIRef.newVar
t <- _HCompose # Pruned & ExprIRef.newValI
newExprI <-
exprP ^. ExprIRef.iref & V.TypedLam newParam t & V.BLam
& ExprIRef.newValI
(newParam, exprP & ExprIRef.iref .~ newExprI) <$
(exprP ^. ExprIRef.setIref) newExprI
redexWrapWithGivenParam ::
Monad m =>
V.Var -> ValI m -> HRef m # V.Term -> T m (HRef m # V.Term)
redexWrapWithGivenParam param newValueI exprP =
do
newLambdaI <- exprP ^. ExprIRef.iref & mkLam >>= ExprIRef.newValI
newApplyI <- ExprIRef.newValI . V.BApp $ V.App newLambdaI newValueI
let newSet v = mkLam v >>= ExprIRef.writeValI newLambdaI
(exprP & ExprIRef.setIref .~ newSet) <$ (exprP ^. ExprIRef.setIref) newApplyI
where
mkLam b =
_HCompose # Pruned & ExprIRef.newValI
<&> (V.TypedLam param ?? b) <&> V.BLam
redexWrap :: Monad m => HRef m # V.Term -> T m (ValI m)
redexWrap exprP =
do
newValueI <- newHole
newParam <- ExprIRef.newVar
_ <- redexWrapWithGivenParam newParam newValueI exprP
pure newValueI
genNewTag :: Monad m => T m T.Tag
genNewTag = Transaction.newKey <&> T.Tag . Identifier . BS.strictify . UUID.toByteString
assocTagName ::
(Monad f, MonadReader env m, Has LangId env, Has Dir.Layout env) =>
m (T.Tag -> MkProperty' (T f) Text)
assocTagName =
Lens.view id <&>
\env tag ->
let lang = env ^. has
result info =
Property (getTagName env info ^. _2 . name)
(Transaction.writeIRef (ExprIRef.tagI tag) . setName)
where
setName x
| x == mempty =
info
& tagSymbol .~ NoSymbol
& tagTexts . Lens.at lang .~ Nothing
| isOperator x =
info
& tagSymbol .~ UniversalSymbol x
& tagTexts . Lens.at lang .~ Nothing
| otherwise =
info
& tagSymbol .~ NoSymbol
& tagTexts . Lens.at lang ?~
TextsInLang (x & Lens.ix 0 %~ toLower) Nothing Nothing
isOperator = Lens.allOf Lens.each (`elem` Chars.operator)
in ExprIRef.readTagData tag
<&> result
& Property.MkProperty
newPane :: Monad m => Anchors.CodeAnchors m -> Anchors.Pane m -> T m ()
newPane codeAnchors pane =
do
Property panes setPanes <-
Anchors.panes codeAnchors ^. Property.mkProperty
panes ++ [pane] & setPanes & when (pane `notElem` panes)
newDefinition :: Monad m => PresentationMode -> Definition (ValI m) () -> T m (DefI m)
newDefinition presentationMode def =
do
newDef <- Transaction.newIRef def
let defVar = ExprIRef.globalId newDef
Property.setP (Anchors.assocPresentationMode defVar) presentationMode
pure newDef
-- Used when writing a definition into an identifier which was a variable.
-- Used in float.
newPublicDefinitionToIRef ::
Monad m => Anchors.CodeAnchors m -> Definition (ValI m) () -> DefI m -> T m ()
newPublicDefinitionToIRef codeAnchors def defI =
do
Transaction.writeIRef defI def
Property.modP (Anchors.globals codeAnchors) (Set.insert defI)
newPane codeAnchors (Anchors.PaneDefinition defI)
newPublicDefinitionWithPane ::
Monad m =>
Anchors.CodeAnchors m -> Definition (ValI m) () -> T m (DefI m)
newPublicDefinitionWithPane codeAnchors def =
do
defI <- newDefinition Verbose def
Property.modP (Anchors.globals codeAnchors) (Set.insert defI)
newPane codeAnchors (Anchors.PaneDefinition defI)
pure defI
newIdentityLambda :: Monad m => T m (V.Var, ValI m)
newIdentityLambda =
do
paramId <- ExprIRef.newVar
getVar <- V.LVar paramId & V.BLeaf & ExprIRef.newValI
paramType <- _HCompose # Pruned & ExprIRef.newValI
lamI <- V.TypedLam paramId paramType getVar & V.BLam & ExprIRef.newValI
pure (paramId, lamI)
setTagOrder :: Monad m => T.Tag -> Int -> T m ()
setTagOrder tag order =
ExprIRef.readTagData tag
<&> tagOrder .~ order
>>= Transaction.writeIRef (ExprIRef.tagI tag)
|
lamdu/lamdu
|
src/Lamdu/Data/Ops.hs
|
gpl-3.0
| 6,884
| 0
| 20
| 1,885
| 2,206
| 1,124
| 1,082
| -1
| -1
|
module Vector(primListVector, primSize, primIndex, primElems, primUpdate, listVector) where {
-- This module provides 0-based 1-D arrays with fast read access.
primitive primListVector :: Int -> [a] -> Vector a;
primitive primSize :: Vector a -> Int;
primitive primIndex :: Vector a -> Int -> a;
primitive primElems :: Vector a -> [a];
primitive primUpdate :: Vector a -> Int -> a -> Vector a;
listVector :: [a] -> Vector a;
listVector xs = primListVector (length xs) xs;
instance Show Vector where {
shows v s = "vector " ++ shows (primSize v) ( ' ' : shows (primElems v) s);
show v = shows v ""
}
}
|
ckaestne/CIDE
|
CIDE_Language_Haskell/test/fromviral/Vector.hs
|
gpl-3.0
| 714
| 22
| 12
| 221
| 235
| 125
| 110
| -1
| -1
|
import Control.Monad(zipWithM)
import System.Environment(getArgs)
import Ast(Module)
import Link(link)
import Parse(parse)
import StdLib(stdlib)
main :: IO ()
main = getArgs >>= dgol
dgol :: [String] -> IO ()
dgol args = do
files <- mapM readFile args
either putStrLn run (zipWithM parse args files)
run :: [Module] -> IO ()
run modules = either putStrLn id (link modules stdlib)
|
qpliu/esolang
|
DGOL/hs/interp/dgol.hs
|
gpl-3.0
| 393
| 0
| 9
| 71
| 169
| 89
| 80
| 14
| 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.Environments.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates a GTM Environment.
--
-- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.environments.update@.
module Network.Google.Resource.TagManager.Accounts.Containers.Environments.Update
(
-- * REST Resource
AccountsContainersEnvironmentsUpdateResource
-- * Creating a Request
, accountsContainersEnvironmentsUpdate
, AccountsContainersEnvironmentsUpdate
-- * Request Lenses
, aceuXgafv
, aceuUploadProtocol
, aceuPath
, aceuFingerprint
, aceuAccessToken
, aceuUploadType
, aceuPayload
, aceuCallback
) where
import Network.Google.Prelude
import Network.Google.TagManager.Types
-- | A resource alias for @tagmanager.accounts.containers.environments.update@ method which the
-- 'AccountsContainersEnvironmentsUpdate' request conforms to.
type AccountsContainersEnvironmentsUpdateResource =
"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] Environment :>
Put '[JSON] Environment
-- | Updates a GTM Environment.
--
-- /See:/ 'accountsContainersEnvironmentsUpdate' smart constructor.
data AccountsContainersEnvironmentsUpdate =
AccountsContainersEnvironmentsUpdate'
{ _aceuXgafv :: !(Maybe Xgafv)
, _aceuUploadProtocol :: !(Maybe Text)
, _aceuPath :: !Text
, _aceuFingerprint :: !(Maybe Text)
, _aceuAccessToken :: !(Maybe Text)
, _aceuUploadType :: !(Maybe Text)
, _aceuPayload :: !Environment
, _aceuCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsContainersEnvironmentsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aceuXgafv'
--
-- * 'aceuUploadProtocol'
--
-- * 'aceuPath'
--
-- * 'aceuFingerprint'
--
-- * 'aceuAccessToken'
--
-- * 'aceuUploadType'
--
-- * 'aceuPayload'
--
-- * 'aceuCallback'
accountsContainersEnvironmentsUpdate
:: Text -- ^ 'aceuPath'
-> Environment -- ^ 'aceuPayload'
-> AccountsContainersEnvironmentsUpdate
accountsContainersEnvironmentsUpdate pAceuPath_ pAceuPayload_ =
AccountsContainersEnvironmentsUpdate'
{ _aceuXgafv = Nothing
, _aceuUploadProtocol = Nothing
, _aceuPath = pAceuPath_
, _aceuFingerprint = Nothing
, _aceuAccessToken = Nothing
, _aceuUploadType = Nothing
, _aceuPayload = pAceuPayload_
, _aceuCallback = Nothing
}
-- | V1 error format.
aceuXgafv :: Lens' AccountsContainersEnvironmentsUpdate (Maybe Xgafv)
aceuXgafv
= lens _aceuXgafv (\ s a -> s{_aceuXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
aceuUploadProtocol :: Lens' AccountsContainersEnvironmentsUpdate (Maybe Text)
aceuUploadProtocol
= lens _aceuUploadProtocol
(\ s a -> s{_aceuUploadProtocol = a})
-- | GTM Environment\'s API relative path. Example:
-- accounts\/{account_id}\/containers\/{container_id}\/environments\/{environment_id}
aceuPath :: Lens' AccountsContainersEnvironmentsUpdate Text
aceuPath = lens _aceuPath (\ s a -> s{_aceuPath = a})
-- | When provided, this fingerprint must match the fingerprint of the
-- environment in storage.
aceuFingerprint :: Lens' AccountsContainersEnvironmentsUpdate (Maybe Text)
aceuFingerprint
= lens _aceuFingerprint
(\ s a -> s{_aceuFingerprint = a})
-- | OAuth access token.
aceuAccessToken :: Lens' AccountsContainersEnvironmentsUpdate (Maybe Text)
aceuAccessToken
= lens _aceuAccessToken
(\ s a -> s{_aceuAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
aceuUploadType :: Lens' AccountsContainersEnvironmentsUpdate (Maybe Text)
aceuUploadType
= lens _aceuUploadType
(\ s a -> s{_aceuUploadType = a})
-- | Multipart request metadata.
aceuPayload :: Lens' AccountsContainersEnvironmentsUpdate Environment
aceuPayload
= lens _aceuPayload (\ s a -> s{_aceuPayload = a})
-- | JSONP
aceuCallback :: Lens' AccountsContainersEnvironmentsUpdate (Maybe Text)
aceuCallback
= lens _aceuCallback (\ s a -> s{_aceuCallback = a})
instance GoogleRequest
AccountsContainersEnvironmentsUpdate
where
type Rs AccountsContainersEnvironmentsUpdate =
Environment
type Scopes AccountsContainersEnvironmentsUpdate =
'["https://www.googleapis.com/auth/tagmanager.edit.containers"]
requestClient
AccountsContainersEnvironmentsUpdate'{..}
= go _aceuPath _aceuXgafv _aceuUploadProtocol
_aceuFingerprint
_aceuAccessToken
_aceuUploadType
_aceuCallback
(Just AltJSON)
_aceuPayload
tagManagerService
where go
= buildClient
(Proxy ::
Proxy AccountsContainersEnvironmentsUpdateResource)
mempty
|
brendanhay/gogol
|
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Environments/Update.hs
|
mpl-2.0
| 6,123
| 0
| 18
| 1,357
| 862
| 502
| 360
| 129
| 1
|
-- You are given the following information, but you may prefer to do some research for yourself.
-- 1 Jan 1900 was a Monday.
-- Thirty days has September,
-- April, June and November.
-- All the rest have thirty-one,
-- Saving February alone,
-- Which has twenty-eight, rain or shine.
-- And on leap years, twenty-nine.
-- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
-- How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
data MonthName = January | February | March | April | May | June | July | August | September | October | November | December
deriving (Eq, Ord, Enum, Show, Bounded)
data WeekDay = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday
deriving (Eq, Ord, Enum, Show, Bounded)
monthnames :: [MonthName]
monthnames = cycle [ January , February , March , April , May , June , July , August , September , October , November , December]
weekdays :: [WeekDay]
weekdays = cycle [ Monday , Tuesday , Wednesday , Thursday , Friday , Saturday , Sunday]
skipNweekDays :: WeekDay -> Int -> WeekDay
skipNweekDays cwd n = head $ drop n $ fromWeekDayN cwd
fromWeekDayN :: WeekDay -> [WeekDay]
fromWeekDayN cwd = dropWhile(< cwd) weekdays
data Month =
Month { name :: MonthName
, numberOfDays :: Int
, firstDay :: WeekDay
, year :: Year
}
deriving (Eq, Ord, Show)
type Year = Int
type Day = Int
numberOfDaysInMonth :: MonthName -> Year -> Int
numberOfDaysInMonth m y = case m of
September -> 30
April -> 30
June -> 30
November -> 30
February -> calFeb y
_ -> 31
where calFeb a = if isLeapyear a
then 29
else 28
isLeapyear :: Year -> Bool
isLeapyear y
| (y == 1900) = False -- fix me!!!
| (y `mod` 4 == 0 ) = True
| otherwise = False
getYear :: Year -> Year -> WeekDay -> [Month]
getYear sy ey fd = setDay fd $ setyear sy mlist
where mlist = take takeXyears $ map (\ m -> Month{ name=m , numberOfDays = 0,firstDay = Monday,year=0} ) monthnames
takeXyears = (ey - sy + 1) * 12
setDay _ [] = []
setDay cd (m:ms) = m{ firstDay= cd} : setDay dayhelper ms
where dayhelper = skipNweekDays cd $ numberOfDays m
setyear _ [] = []
setyear y m = (yhelper $ take 12 $ m) ++ (setyear (y + 1) $ drop 12 m)
where yhelper [] = []
yhelper (x:xs) = x{year=y,numberOfDays=numberOfDaysInMonth (name x) y } : yhelper xs
numberOfSundays :: Int
numberOfSundays = length $ filter isSunday $ drop 12 $ getYear 1900 2000 Monday
where isSunday m = (firstDay m == Sunday)
|
nmarshall23/Programming-Challenges
|
project-euler/019/19.hs
|
unlicense
| 2,671
| 26
| 13
| 672
| 845
| 470
| 375
| 50
| 7
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Reader
import Data.IORef
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as TL
import System.Environment (getArgs)
import Web.Scotty.Trans
data Config =
Config {
-- that's one, one click!
-- two...two clicks!
-- Three BEAUTIFUL clicks! ah ah ahhhh
counts :: IORef (M.Map Text Integer)
, prefix :: Text
}
-- Stuff inside ScottyT is, except for things that escape
-- via IO, effectively read-only so we can't use StateT.
-- It would overcomplicate things to attempt to do so and
-- you should be using a proper database for production
-- applications.
type Scotty = ScottyT Text (ReaderT Config IO)
type Handler = ActionT Text (ReaderT Config IO)
bumpBoomp :: Text
-> M.Map Text Integer
-> (M.Map Text Integer, Integer)
bumpBoomp k m = (M.insert k bump m, bump)
where bump = (fromMaybe 0 (M.lookup k m)) + 1
app :: Scotty ()
app =
get "/:key" $ do
unprefixed <- param "key"
config <- lift ask
let key' = mappend (prefix config) unprefixed
ref = counts config
map' = readIORef ref
(newMap, newInteger) <- liftIO (bumpBoomp key' <$> map')
liftIO $ writeIORef ref newMap
html $ mconcat [ "<h1>Success! Count was: "
, TL.pack $ show newInteger
, "</h1>"
]
main :: IO ()
main = do
[prefixArg] <- getArgs
counter <- newIORef M.empty
let config = Config counter (TL.pack prefixArg)
runR r = runReaderT r config
scottyT 3000 runR app
|
dmvianna/haskellbook
|
src/Ch26-HitCounter.hs
|
unlicense
| 1,712
| 0
| 13
| 421
| 478
| 256
| 222
| 43
| 1
|
splitOn :: Char -> String -> [String]
splitOn c s =
let e = takeWhile (/= c) s
r = dropWhile (/= c) s
in
if r == []
then [e]
else e:(splitOn c $ drop 1 r)
swap [] l = l
swap ([x,y]:xs) l
| x < y =
let b = take (x-1) l
m = drop x $ take (y-1) l
e = drop y l
in
swap xs (b ++ [(l!!(y-1))] ++ m ++ [(l!!(x-1))] ++ e)
| x == y = l
| x > y = swap ([y,x]:xs) l
ans w c = swap c [1..w]
main = do
w <- getLine
_ <- getLine
c <- getContents
let w' = read w :: Int
c' = map (map read) $ map (splitOn ',') $ lines c :: [[Int]]
o = ans w' c'
mapM_ print o
|
a143753/AOJ
|
0011.hs
|
apache-2.0
| 643
| 0
| 18
| 243
| 423
| 215
| 208
| 25
| 2
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UnicodeSyntax #-}
{-| This module contains examples of logic programs that generate solutions to the
n-queens problem, which is the problem of finding ways to put n queens on an
n x n chessboard in such a way that they do not conflict. Solutions of the
n-queens problem take the form of a list of n coordinates such that no
coordinates have overlapping rows, columns, or diagonals (as these are the
directions in which a queen can attack).
-}
module LogicGrowsOnTrees.Examples.Queens
(
-- * Correct solution counts
nqueens_correct_counts
, nqueens_maximum_size
, nqueensCorrectCount
-- * Basic examples
-- $basic
-- ** Using sets
-- $sets
, nqueensUsingSetsSolutions
, nqueensUsingSetsCount
-- ** Using bits
, nqueensUsingBitsSolutions
, nqueensUsingBitsCount
-- * Advanced example
-- $advanced
, nqueensGeneric
, nqueensSolutions
, nqueensCount
-- ** With a list at the bottom (instead of C)
,nqueensWithListAtBottomGeneric
,nqueensWithListAtBottomSolutions
,nqueensWithListAtBottomCount
-- ** With nothing at the bottom (instead of C or a List)
,nqueensWithNothingAtBottomGeneric
,nqueensWithNothingAtBottomSolutions
,nqueensWithNothingAtBottomCount
-- * Board size command argument
, board_size_parser
) where
import Control.Monad (MonadPlus,(>=>),guard,liftM)
import Data.Bits ((.|.),(.&.),bit,finiteBitSize,shiftL,shiftR)
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.IntSet as IntSet
import Data.Maybe (fromJust)
import Data.Word (Word,Word64)
import Options.Applicative (Parser,ReadM,argument,eitherReader,help,metavar)
import Text.Read (readMaybe)
import Text.Printf (printf)
import LogicGrowsOnTrees (Tree,allFrom) -- exploreTree added so that haddock will link to it
import qualified LogicGrowsOnTrees.Examples.Queens.Advanced as Advanced
import LogicGrowsOnTrees.Examples.Queens.Advanced
(NQueensSolution
,NQueensSolutions
,Updater(..)
,multiplySolution
,nqueensGeneric
,nqueensWithListAtBottomGeneric
,nqueensWithNothingAtBottomGeneric
)
import LogicGrowsOnTrees.Utils.WordSum
--------------------------------------------------------------------------------
---------------------------------- Board size ----------------------------------
--------------------------------------------------------------------------------
{-| The argument for specifying the board size. -}
board_size_parser ∷ Parser Word
board_size_parser =
argument argumentReader $ metavar "BOARD_SIZE" <> help "board size"
where
argumentReader ∷ ReadM Word
argumentReader = eitherReader $
maybe
(fail "board size was not a valid number")
pure
.
readMaybe
>=>
(\n → if n >= 1 && n <= fromIntegral nqueens_maximum_size
then pure n
else fail $ printf
"bad board size %i %i (must be between 1 and %i inclusive)"
(show n) (show n)
(show nqueens_maximum_size)
)
--------------------------------------------------------------------------------
-------------------------------- Correct counts --------------------------------
--------------------------------------------------------------------------------
{-| A table with the correct number of solutions for board sizes ranging from 1
to `nqueens_maximum_size`.
This data was pulled from <http://queens.inf.tu-dresden.de/?n=f&l=en>.
-}
nqueens_correct_counts :: IntMap Word
nqueens_correct_counts = IntMap.fromDistinctAscList $
[( 1,1)
,( 2,0)
,( 3,0)
,( 4,2)
,( 5,10)
,( 6,4)
,( 7,40)
,( 8,92)
,( 9,352)
,(10,724)
,(11,2680)
,(12,14200)
,(13,73712)
,(14,365596)
,(15,2279184)
,(16,14772512)
,(17,95815104)
,(18,666090624)
] ++ if finiteBitSize (undefined :: Int) < 64 then [] else
[(19,4968057848)
,(20,39029188884)
,(21,314666222712)
,(22,2691008701644)
,(23,24233937684440)
,(24,227514171973736)
,(25,2207893435808352)
,(26,22317699616364044)
]
{-| The maximum board size in 'nqueens_correct_counts'. In a 64-bit environment
this value is equal to the largest board size for which we know the number
of solutions, which is 26. In a 32-bit environment this value is equal to
the largest board size such that the number of solutions fits within a
32-bit (unsigned) integer (i.e., the range of 'Word'), which is 18.
-}
nqueens_maximum_size :: Int
nqueens_maximum_size = fst . IntMap.findMax $ nqueens_correct_counts
{-| A /partial function/ that returns the number of solutions for the given
input board size; this should only be used when you are sure that the input
is not greater than 'nqueens_maximum_size'.
-}
nqueensCorrectCount :: Word → Word
nqueensCorrectCount =
fromJust
.
($ nqueens_correct_counts)
.
IntMap.lookup
.
fromIntegral
--------------------------------------------------------------------------------
-------------------------------- Basic examples --------------------------------
--------------------------------------------------------------------------------
{- $basic
The two examples in this section are pretty basic in that they do not make use of
the many optimizations that are available (at the cost of code complexity). The first
example uses set operations, and the second uses bitwise operations.
-}
---------------------------------- Using sets ----------------------------------
{- $sets
The functions in this subsection use 'IntSet's to keep track of which columns
and diagonals are occupied by queens. (It is not necessarily to keep track of
occupied rows because the rows are filled consecutively.)
-}
{-| Generate solutions to the n-queens problem using 'IntSet's. -}
nqueensUsingSetsSolutions :: MonadPlus m ⇒ Word → m NQueensSolution
nqueensUsingSetsSolutions n =
go n
0
(IntSet.fromDistinctAscList [0..fromIntegral n-1])
IntSet.empty
IntSet.empty
[]
where
go 0 _ _ _ _ !value = return . reverse $ value
go !n
!row
!available_columns
!occupied_negative_diagonals
!occupied_positive_diagonals
!value
= do
column ← allFrom $ IntSet.toList available_columns
let negative_diagonal = row + column
guard $ IntSet.notMember negative_diagonal occupied_negative_diagonals
let positive_diagonal = row - column
guard $ IntSet.notMember positive_diagonal occupied_positive_diagonals
go (n-1)
(row+1)
(IntSet.delete column available_columns)
(IntSet.insert negative_diagonal occupied_negative_diagonals)
(IntSet.insert positive_diagonal occupied_positive_diagonals)
((fromIntegral row,fromIntegral column):value)
{-# SPECIALIZE nqueensUsingSetsSolutions :: Word → NQueensSolutions #-}
{-# SPECIALIZE nqueensUsingSetsSolutions :: Word → Tree NQueensSolution #-}
{-# INLINEABLE nqueensUsingSetsSolutions #-}
{-| Generates the solution count to the n-queens problem with the given board
size; you need to sum over all these counts to obtain the total, which is
done by the 'exploreTree' (and related) functions.
-}
nqueensUsingSetsCount :: MonadPlus m ⇒ Word → m WordSum
nqueensUsingSetsCount = liftM (const $ WordSum 1) . nqueensUsingSetsSolutions
{-# SPECIALIZE nqueensUsingSetsCount :: Word → [WordSum] #-}
{-# SPECIALIZE nqueensUsingSetsCount :: Word → Tree WordSum #-}
{-# INLINEABLE nqueensUsingSetsCount #-}
---------------------------------- Using bits ----------------------------------
{- $bits
A basic optimization that results in a signiciant performance improvements is to
use 'Word64's as set implemented using bitwise operations --- that is, a bit in
position 1 means that column 1 / negative diagonal 1 / positive diagnal 1 is
occupied. The total occupied positions can be obtained by taking the bitwise or
of the occupied columns, positive diagonals, and negative diagonals.
Note that when we go to the next row, we shift the negative diagonals right and
the positive diagonals left as every negative/positive diagonal that contains a
square at a given row and column also contains column (x+1)/(x-1) of the
succeeding row.
-}
{-| Generate solutions to the n-queens problem using bitwise-operations. -}
nqueensUsingBitsSolutions :: MonadPlus m ⇒ Word → m NQueensSolution
nqueensUsingBitsSolutions n =
go n 0 (0::Word64) (0::Word64) (0::Word64) []
where
go 0 _ _ _ _ !value = return . reverse $ value
go !n
!row
!occupied_columns
!occupied_negative_diagonals
!occupied_positive_diagonals
!value
= do
column ← allFrom . goGetOpenings 0 $
occupied_columns .|.
occupied_negative_diagonals .|.
occupied_positive_diagonals
let column_bit = bit (fromIntegral column)
go (n-1)
(row+1)
(occupied_columns .|. column_bit)
((occupied_negative_diagonals .|. column_bit) `shiftR` 1)
((occupied_positive_diagonals .|. column_bit) `shiftL` 1)
((row,column):value)
goGetOpenings column bits
| column >= n = []
| bits .&. 1 == 0 = column:next
| otherwise = next
where
next = goGetOpenings (column + 1) (bits `shiftR` 1)
{-# SPECIALIZE nqueensUsingBitsSolutions :: Word → NQueensSolutions #-}
{-# SPECIALIZE nqueensUsingBitsSolutions :: Word → Tree NQueensSolution #-}
{-# INLINEABLE nqueensUsingBitsSolutions #-}
{-| Generates the solution count to the n-queens problem with the given board
size; you need to sum over all these counts to obtain the total, which is
done by the 'exploreTree' (and related) functions.
-}
nqueensUsingBitsCount :: MonadPlus m ⇒ Word → m WordSum
nqueensUsingBitsCount = liftM (const $ WordSum 1) . nqueensUsingBitsSolutions
{-# SPECIALIZE nqueensUsingBitsCount :: Word → [WordSum] #-}
{-# SPECIALIZE nqueensUsingBitsCount :: Word → Tree WordSum #-}
{-# INLINEABLE nqueensUsingBitsCount #-}
--------------------------------------------------------------------------------
------------------------------- Advanced example -------------------------------
--------------------------------------------------------------------------------
{- $advanced
The advanced example use several techniques to try and squeeze out as much
performance as possible using the functionality of this package. The functions
listed here are just the interface to it; for the implementation driving these
functions, see the "LogicGrowsOnTrees.Examples.Queens.Advanced" module.
-}
{-| Generates the solutions to the n-queens problem with the given board size. -}
nqueensSolutions :: MonadPlus m ⇒ Word → m NQueensSolution
nqueensSolutions n = nqueensGeneric (StateUpdater (++)) multiplySolution [] n
{-# SPECIALIZE nqueensSolutions :: Word → NQueensSolutions #-}
{-# SPECIALIZE nqueensSolutions :: Word → Tree NQueensSolution #-}
{-| Generates the solution count to the n-queens problem with the given board
size; you need to sum over all these counts to obtain the total, which is
done by the 'exploreTree' (and related) functions.
-}
nqueensCount :: MonadPlus m ⇒ Word → m WordSum
nqueensCount = nqueensGeneric CountUpdater (\_ symmetry _ → return . WordSum . Advanced.multiplicityForSymmetry $ symmetry) ()
{-# SPECIALIZE nqueensCount :: Word → [WordSum] #-}
{-# SPECIALIZE nqueensCount :: Word → Tree WordSum #-}
{-| Like 'nqueensSolutions', but uses List at the bottom instead of C. -}
nqueensWithListAtBottomSolutions :: MonadPlus m ⇒ Word → m NQueensSolution
nqueensWithListAtBottomSolutions n = nqueensWithListAtBottomGeneric (StateUpdater (++)) multiplySolution [] n
{-# SPECIALIZE nqueensWithListAtBottomSolutions :: Word → NQueensSolutions #-}
{-# SPECIALIZE nqueensWithListAtBottomSolutions :: Word → Tree NQueensSolution #-}
{-| Like 'nqueensCount', but uses List at the bottom instead of C. -}
nqueensWithListAtBottomCount :: MonadPlus m ⇒ Word → m WordSum
nqueensWithListAtBottomCount = nqueensWithListAtBottomGeneric CountUpdater (\_ symmetry _ → return . WordSum . Advanced.multiplicityForSymmetry $ symmetry) ()
{-# SPECIALIZE nqueensWithListAtBottomCount :: Word → [WordSum] #-}
{-# SPECIALIZE nqueensWithListAtBottomCount :: Word → Tree WordSum #-}
{-| Like 'nqueensSolutions', but uses List at the bottom instead of C. -}
nqueensWithNothingAtBottomSolutions :: MonadPlus m ⇒ Word → m NQueensSolution
nqueensWithNothingAtBottomSolutions n = nqueensWithNothingAtBottomGeneric (StateUpdater (++)) multiplySolution [] n
{-# SPECIALIZE nqueensWithNothingAtBottomSolutions :: Word → NQueensSolutions #-}
{-# SPECIALIZE nqueensWithNothingAtBottomSolutions :: Word → Tree NQueensSolution #-}
{-| Like 'nqueensCount', but uses List at the bottom instead of C. -}
nqueensWithNothingAtBottomCount :: MonadPlus m ⇒ Word → m WordSum
nqueensWithNothingAtBottomCount = nqueensWithNothingAtBottomGeneric CountUpdater (\_ symmetry _ → return . WordSum . Advanced.multiplicityForSymmetry $ symmetry) ()
{-# SPECIALIZE nqueensWithNothingAtBottomCount :: Word → [WordSum] #-}
{-# SPECIALIZE nqueensWithNothingAtBottomCount :: Word → Tree WordSum #-}
|
gcross/LogicGrowsOnTrees
|
LogicGrowsOnTrees/sources/LogicGrowsOnTrees/Examples/Queens.hs
|
bsd-2-clause
| 13,513
| 0
| 14
| 2,528
| 1,786
| 1,011
| 775
| -1
| -1
|
module Main where
import System.FilePath.Glob (glob)
import Test.DocTest (doctest)
main :: IO ()
main = glob "src/**/*.hs" >>=
doctest . (["-optP-include",
"-optPdist/build/autogen/cabal_macros.h"] ++)
|
Ericson2314/clash-prelude
|
tests/doctests.hs
|
bsd-2-clause
| 230
| 0
| 7
| 51
| 61
| 36
| 25
| 7
| 1
|
module Language.JavaScript.AST
where
data IdentName =
IdentName String
deriving (Eq, Show)
data Ident =
Ident IdentName
deriving (Eq, Show)
data Literal
= LiteralNull NullLit
| LiteralBool BoolLit
| LiteralNum NumLit
| LiteralString StringLit
| LiteralRegExp RegExpLit
deriving (Eq, Show)
data NullLit
= NullLit
deriving (Eq, Show)
data BoolLit
= BoolLit Bool
deriving (Eq, Show)
data NumLit
= NumLit Double
deriving (Eq, Show)
data StringLit
= StringLit String
deriving (Eq, Show)
data RegExpLit
= RegExpLit (String, String)
deriving (Eq, Show)
data PrimExpr
= PrimExprThis
| PrimExprIdent Ident
| PrimExprLiteral Literal
| PrimExprArray ArrayLit
| PrimExprObject ObjectLit
| PrimExprParens Expr
deriving (Eq, Show)
data ArrayLit
= ArrayLitH (Maybe Elision)
| ArrayLit ElementList
| ArrayLitT ElementList (Maybe Elision)
deriving (Eq, Show)
data ElementList
= ElementList (Maybe Elision) AssignExpr
| ElementListCons ElementList (Maybe Elision) AssignExpr
deriving (Eq, Show)
data Elision
= ElisionComma
| ElisionCons Elision
deriving (Eq, Show)
data ObjectLit
= ObjectLitEmpty
| ObjectLit PropList
deriving (Eq, Show)
data PropList
= PropListAssign PropAssign
| PropListCons PropList PropAssign
deriving (Eq, Show)
data PropAssign
= PropAssignField PropName AssignExpr
| PropAssignGet PropName FuncBody
| PropAssignSet PropName PropSetParamList FuncBody
deriving (Eq, Show)
data PropSetParamList
= PropSetParamList Ident
deriving (Eq, Show)
data PropName
= PropNameId IdentName
| PropNameStr StringLit
| PropNameNum NumLit
deriving (Eq, Show)
data MemberExpr
= MemberExprPrim PrimExpr
| MemberExprFunc FuncExpr
| MemberExprArray MemberExpr Expr
| MemberExprDot MemberExpr IdentName
| MemberExprNew MemberExpr Arguments
deriving (Eq, Show)
data NewExpr
= NewExprMember MemberExpr
| NewExprNew NewExpr
deriving (Eq, Show)
data CallExpr
= CallExprMember MemberExpr Arguments
| CallExprCall CallExpr Arguments
| CallExprArray CallExpr Expr
| CallExprDot CallExpr IdentName
deriving (Eq, Show)
data Arguments
= ArgumentsEmpty
| Arguments ArgumentList
deriving (Eq, Show)
data ArgumentList
= ArgumentList AssignExpr
| ArgumentListCons ArgumentList AssignExpr
deriving (Eq, Show)
data LeftExpr
= LeftExprNewExpr NewExpr
| LeftExprCallExpr CallExpr
deriving (Eq, Show)
data PostFixExpr
= PostFixExprLeftExpr LeftExpr
| PostFixExprPostInc LeftExpr
| PostFixExprPostDec LeftExpr
deriving (Eq, Show)
data UExpr
= UExprPostFix PostFixExpr
| UExprDelete UExpr
| UExprVoid UExpr
| UExprTypeOf UExpr
| UExprDoublePlus UExpr
| UExprDoubleMinus UExpr
| UExprUnaryPlus UExpr
| UExprUnaryMinus UExpr
| UExprBitNot UExpr
| UExprNot UExpr
deriving (Eq, Show)
data MultExpr
= MultExpr UExpr
| MultExprMult MultExpr UExpr
| MultExprDiv MultExpr UExpr
| MultExprMod MultExpr UExpr
deriving (Eq, Show)
data AddExpr
= AddExpr MultExpr
| AddExprAdd AddExpr MultExpr
| AddExprSub AddExpr MultExpr
deriving (Eq, Show)
data ShiftExpr
= ShiftExpr AddExpr
| ShiftExprLeft ShiftExpr AddExpr
| ShiftExprRight ShiftExpr AddExpr
| ShiftExprRightZero ShiftExpr AddExpr
deriving (Eq, Show)
data RelExpr
= RelExpr ShiftExpr
| RelExprLess RelExpr ShiftExpr
| RelExprGreater RelExpr ShiftExpr
| RelExprLessEq RelExpr ShiftExpr
| RelExprGreaterEq RelExpr ShiftExpr
| RelExprInstanceOf RelExpr ShiftExpr
| RelExprIn RelExpr ShiftExpr
deriving (Eq, Show)
data RelExprNoIn
= RelExprNoIn ShiftExpr
| RelExprNoInLess RelExprNoIn ShiftExpr
| RelExprNoInGreater RelExprNoIn ShiftExpr
| RelExprNoInLessEq RelExprNoIn ShiftExpr
| RelExprNoInGreaterEq RelExprNoIn ShiftExpr
| RelExprNoInInstanceOf RelExprNoIn ShiftExpr
deriving (Eq, Show)
data EqExpr
= EqExpr RelExpr
| EqExprEq EqExpr RelExpr
| EqExprNotEq EqExpr RelExpr
| EqExprStrictEq EqExpr RelExpr
| EqExprStrictNotEq EqExpr RelExpr
deriving (Eq, Show)
data EqExprNoIn
= EqExprNoIn RelExprNoIn
| EqExprNoInEq EqExprNoIn RelExprNoIn
| EqExprNoInNotEq EqExprNoIn RelExprNoIn
| EqExprNoInStrictEq EqExprNoIn RelExprNoIn
| EqExprNoInStrictNotEq EqExprNoIn RelExprNoIn
deriving (Eq, Show)
data BitAndExpr
= BitAndExpr EqExpr
| BitAndExprAnd BitAndExpr EqExpr
deriving (Eq, Show)
data BitAndExprNoIn
= BitAndExprNoIn EqExprNoIn
| BitAndExprNoInAnd BitAndExprNoIn EqExprNoIn
deriving (Eq, Show)
data BitXorExpr
= BitXorExpr BitAndExpr
| BitXorExprXor BitXorExpr BitAndExpr
deriving (Eq, Show)
data BitXorExprNoIn
= BitXorExprNoIn BitAndExprNoIn
| BitXorExprNoInXor BitXorExprNoIn BitAndExprNoIn
deriving (Eq, Show)
data BitOrExpr
= BitOrExpr BitXorExpr
| BitOrExprOr BitOrExpr BitXorExpr
deriving (Eq, Show)
data BitOrExprNoIn
= BitOrExprNoIn BitXorExprNoIn
| BitOrExprNoInOr BitOrExprNoIn BitXorExprNoIn
deriving (Eq, Show)
data LogicalAndExpr
= LogicalAndExpr BitOrExpr
| LogicalAndExprAnd LogicalAndExpr BitOrExpr
deriving (Eq, Show)
data LogicalAndExprNoIn
= LogicalAndExprNoIn BitOrExprNoIn
| LogicalAndExprNoInAnd LogicalAndExprNoIn BitOrExprNoIn
deriving (Eq, Show)
data LogicalOrExpr
= LogicalOrExpr LogicalAndExpr
| LogicalOrExprOr LogicalOrExpr LogicalAndExpr
deriving (Eq, Show)
data LogicalOrExprNoIn
= LogicalOrExprNoIn LogicalAndExprNoIn
| LogicalOrExprNoInOr LogicalOrExprNoIn LogicalAndExprNoIn
deriving (Eq, Show)
data CondExpr
= CondExpr LogicalOrExpr
| CondExprIf LogicalOrExpr AssignExpr AssignExpr
deriving (Eq, Show)
data CondExprNoIn
= CondExprNoIn LogicalOrExprNoIn
| CondExprNoInIf LogicalOrExprNoIn AssignExpr AssignExpr
deriving (Eq, Show)
data AssignExpr
= AssignExprCondExpr CondExpr
| AssignExprAssign LeftExpr AssignOp AssignExpr
deriving (Eq, Show)
data AssignExprNoIn
= AssignExprNoInCondExpr CondExprNoIn
| AssignExprNoInAssign LeftExpr AssignOp AssignExprNoIn
deriving (Eq, Show)
data AssignOp
= AssignOpNormal
| AssignOpMult
| AssignOpDiv
| AssignOpMod
| AssignOpPlus
| AssignOpMinus
| AssignOpShiftLeft
| AssignOpShiftRight
| AssignOpShiftRightZero
| AssignOpBitAnd
| AssignOpBitXor
| AssignOpBitOr
deriving (Eq, Show)
data Expr
= Expr AssignExpr
| ExprCons Expr AssignExpr
deriving (Eq, Show)
data ExprNoIn
= ExprNoIn AssignExprNoIn
| ExprNoInCons ExprNoIn AssignExprNoIn
deriving (Eq, Show)
data Stmt
= StmtBlock Block
| StmtVar VarStmt
| StmtEmpty EmptyStmt
| StmtExpr ExprStmt
| StmtIf IfStmt
| StmtIt ItStmt
| StmtCont ContStmt
| StmtBreak BreakStmt
| StmtReturn ReturnStmt
| StmtWith WithStmt
| StmtLabelled LabelledStmt
| StmtSwitch SwitchStmt
| StmtThrow ThrowStmt
| StmtTry TryStmt
| StmtDbg DbgStmt
deriving (Eq, Show)
data Block
= Block (Maybe StmtList)
deriving (Eq, Show)
data StmtList
= StmtList Stmt
| StmtListCons StmtList Stmt
deriving (Eq, Show)
data VarStmt
= VarStmt VarDeclList
deriving (Eq, Show)
data VarDeclList
= VarDeclList VarDecl
| VarDeclListCons VarDeclList VarDecl
deriving (Eq, Show)
data VarDeclListNoIn
= VarDeclListNoIn VarDeclNoIn
| VarDeclListNoInCons VarDeclListNoIn VarDeclNoIn
deriving (Eq, Show)
data VarDecl
= VarDecl Ident (Maybe Initialiser)
deriving (Eq, Show)
data VarDeclNoIn
= VarDeclNoIn Ident (Maybe InitialiserNoIn)
deriving (Eq, Show)
data Initialiser
= Initialiser AssignExpr
deriving (Eq, Show)
data InitialiserNoIn
= InitialiserNoIn AssignExprNoIn
deriving (Eq, Show)
data EmptyStmt
= EmptyStmt
deriving (Eq, Show)
data ExprStmt
= ExprStmt Expr
deriving (Eq, Show)
data IfStmt
= IfStmtIfElse Expr Stmt Stmt
| IfStmtIf Expr Stmt
deriving (Eq, Show)
data ItStmt
= ItStmtDoWhile Stmt Expr
| ItStmtWhile Expr Stmt
| ItStmtFor (Maybe ExprNoIn) (Maybe Expr) (Maybe Expr) Stmt
| ItStmtForVar VarDeclListNoIn (Maybe Expr) (Maybe Expr) Stmt
| ItStmtForIn LeftExpr Expr Stmt
| ItStmtForVarIn VarDeclNoIn Expr Stmt
deriving (Eq, Show)
data ContStmt
= ContStmt
| ContStmtLabelled Ident
deriving (Eq, Show)
data BreakStmt
= BreakStmt
| BreakStmtLabelled Ident
deriving (Eq, Show)
data ReturnStmt
= ReturnStmt
| ReturnStmtExpr Expr
deriving (Eq, Show)
data WithStmt
= WithStmt Expr Stmt
deriving (Eq, Show)
data SwitchStmt
= SwitchStmt Expr CaseBlock
deriving (Eq, Show)
data CaseBlock
= CaseBlock (Maybe CaseClauses)
| CaseBlockDefault (Maybe CaseClauses) DefaultClause (Maybe CaseClauses)
deriving (Eq, Show)
data CaseClauses
= CaseClauses CaseClause
| CaseClausesCons CaseClauses CaseClause
deriving (Eq, Show)
data CaseClause
= CaseClause Expr (Maybe StmtList)
deriving (Eq, Show)
data DefaultClause
= DefaultClause (Maybe StmtList)
deriving (Eq, Show)
data LabelledStmt
= LabelledStmt Ident Stmt
deriving (Eq, Show)
data ThrowStmt
= ThrowStmt Expr
deriving (Eq, Show)
data TryStmt
= TryStmtBC Block Catch
| TryStmtBF Block Finally
| TryStmtBCF Block Catch Finally
deriving (Eq, Show)
data Catch
= Catch Ident Block
deriving (Eq, Show)
data Finally
= Finally Block
deriving (Eq, Show)
data DbgStmt
= DbgStmt
deriving (Eq, Show)
data FuncDecl
= FuncDecl Ident (Maybe FormalParamList) FuncBody
deriving (Eq, Show)
data FuncExpr
= FuncExpr (Maybe Ident) (Maybe FormalParamList) FuncBody
deriving (Eq, Show)
data FormalParamList
= FormalParamList Ident
| FormalParamListCons FormalParamList Ident
deriving (Eq, Show)
data FuncBody =
FuncBody (Maybe SourceElements)
deriving (Eq, Show)
data Program =
Program (Maybe SourceElements)
deriving (Eq, Show)
data SourceElements
= SourceElements SourceElement
| SourceElementsCons SourceElements SourceElement
deriving (Eq, Show)
data SourceElement
= SourceElementStmt Stmt
| SourceElementFuncDecl FuncDecl
deriving (Eq, Show)
|
fabianbergmark/ECMA-262
|
src/Language/JavaScript/AST.hs
|
bsd-2-clause
| 9,936
| 0
| 8
| 1,858
| 2,645
| 1,474
| 1,171
| 384
| 0
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Glazier.React.Main
( LogConfig(..)
, simpleWidgetMain
, AppCmd'
, execApp
, module Glazier.React.Exec
) where
import Control.Concurrent
import Control.Monad.IO.Unlift
import Control.Monad.Trans.Cont
import Data.Foldable
import Data.IORef
import Data.Tagged.Extras
import Data.Typeable
import GHCJS.Foreign.Export
import Glazier.React.Exec
import qualified JS.DOM as DOM
-----------------------------------------------
-- | Add a newtype wrapper to allow recursive definition
type instance AppCmds "Simple" c = [[c], IO c, LogLine JSString, Reactant c]
type AppCmd' = AppCmd "Simple"
execApp :: (
c ~ AppCmd "Simple"
, Cmd' [] c
, Cmd' IO c
, Cmd (LogLine JSString) c
, Cmd' Reactant c
, MonadUnliftIO m
, AskLogConfigRef m
, AskNextReactIdRef m
, AskDirtyPlans m
) => c -> m ()
execApp = fixVerifyExec (unAppCmd @"Simple") maybeExecApp
where
maybeExecApp executor =
maybeExec (traverse_ @[] executor) -- import Data.Foldable
`orExec` maybeExec ((>>= executor) . liftIO)
`orExec` maybeExec execLogLineJS
`orExec` maybeExec (execReactant executor)
-- | An example of starting an app using the glazier-react framework
-- A different @Obj o@ will be create everytime this function is used
simpleWidgetMain ::
( Typeable s
)
=> LogConfig
-> Int
-> DOM.Element
-> Widget s AppCmd' ()
-> LogName
-> s
-> IO (Maybe (Export (Obj s)))
simpleWidgetMain logCfg rerenderDelayMicroseconds root wid logname s = do
-- Create the Environ required by the executor
logConfigRef <- newIORef logCfg
nextReactIdRef <- Tagged @"NextReactId" <$> newIORef @Int 0
dirtyPlansRef <- Tagged @"DirtyPlans" <$> newIORef @DirtyPlans mempty
rb <- mkReactBatch
void $ forkIO $ forever $ do
threadDelay rerenderDelayMicroseconds
void . (`runReaderT` rb)
. (`runReaderT` dirtyPlansRef)
. (`evalMaybeT` ())
$ rerenderDirtyPlans
-- create an mvar to store the obj to be created
v <- newEmptyMVar
-- generate the commands that will create the obj
cs <- execProgramT' . evalContT $ mkObj wid logname s >>= void . liftIO . tryPutMVar v
-- run the commands to generate the obj
let u = ((`runReaderT` dirtyPlansRef)
. (`runReaderT` nextReactIdRef)
. (`runReaderT` logConfigRef))
u $ traverse_ execApp cs
-- try render the obj
runMaybeT $ do
obj <- MaybeT $ tryTakeMVar v
renderAndExportObj root obj
|
louispan/glazier-react
|
src/Glazier/React/Main.hs
|
bsd-3-clause
| 2,864
| 0
| 18
| 677
| 669
| 365
| 304
| 73
| 1
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
-- | This modules extends the 'Prim' from "Data.Primitive" class to cases
-- where we don't know the primitive information (like the size) at compile
-- time. Instead, we must pass in a 'PseudoPrimInfo' object that will get
-- evaluated on every function call and that contains the needed information.
--
-- For 'PseudoPrim' instances that are also 'Prim' instances, this involves
-- no run time overhead. For 'PseudoPrim' instances that cannot be made
-- 'Prim' instances, this involves a mild memory and speed bookkeeping
-- overhead.
module Data.Params.PseudoPrim
where
import GHC.Base (Int (..))
import GHC.Int
import GHC.Prim
import Data.Word
import Control.Monad.Primitive
import Data.Primitive
-------------------------------------------------------------------------------
-- PseudoPrim class
class PseudoPrim a where
data family PseudoPrimInfo a
pp_sizeOf# :: PseudoPrimInfo a -> Int#
pp_alignment# :: PseudoPrimInfo a -> Int#
pp_indexByteArray# :: PseudoPrimInfo a -> ByteArray# -> Int# -> a
pp_readByteArray# :: PseudoPrimInfo a -> MutableByteArray# s -> Int# -> State# s -> (# State# s, a #)
pp_writeByteArray# :: PseudoPrimInfo a -> MutableByteArray# s -> Int# -> a -> State# s -> State# s
-- | Do we need to evaluate the info in order to call these functions?
seqInfo :: a -> Bool
-- | If 'seqInfo' returns 'True', then this function is undefined.
-- Otherwise, it containes an empty 'PseudoPrimInfo' whose type is
-- sufficient to determine all the needed information.
emptyInfo :: PseudoPrimInfo a
#define mkPseudoPrim(t,ppi) \
instance PseudoPrim t where\
newtype PseudoPrimInfo t = ppi () ;\
pp_sizeOf# a = sizeOf# (undefined :: t) ;\
pp_alignment# a = alignment# (undefined :: t) ;\
pp_indexByteArray# a = indexByteArray# ;\
pp_readByteArray# _ = readByteArray# ;\
pp_writeByteArray# _ = writeByteArray# ;\
seqInfo _ = False ;\
emptyInfo = ppi ()
mkPseudoPrim(Double,PseudoPrimInfo_Double)
mkPseudoPrim(Float,PseudoPrimInfo_Float)
mkPseudoPrim(Int,PseudoPrimInfo_Int)
mkPseudoPrim(Char,PseudoPrimInfo_Char)
mkPseudoPrim(Word8,PseudoPrimInfo_Word8)
mkPseudoPrim(Word16,PseudoPrimInfo_Word16)
mkPseudoPrim(Word32,PseudoPrimInfo_Word32)
mkPseudoPrim(Word64,PseudoPrimInfo_Word64)
-------------------------------------------------------------------------------
-- helper functions
{-# INLINE pp_sizeOf #-}
pp_sizeOf :: PseudoPrim a => PseudoPrimInfo a -> Int
pp_sizeOf x = I# (pp_sizeOf# x)
{-# INLINE pp_alignment #-}
pp_alignment :: PseudoPrim a => PseudoPrimInfo a -> Int
pp_alignment x = I# (pp_alignment# x)
{-# INLINE pp_readByteArray #-}
pp_readByteArray
:: (PseudoPrim a, PrimMonad m) => PseudoPrimInfo a -> MutableByteArray (PrimState m) -> Int -> m a
pp_readByteArray ppi (MutableByteArray arr#) (I# i#) = primitive (pp_readByteArray# ppi arr# i#)
{-# INLINE pp_writeByteArray #-}
pp_writeByteArray
:: (PseudoPrim a, PrimMonad m) => PseudoPrimInfo a -> MutableByteArray (PrimState m) -> Int -> a -> m ()
pp_writeByteArray ppi (MutableByteArray arr#) (I# i#) x = primitive_ (pp_writeByteArray# ppi arr# i# x)
{-# INLINE pp_indexByteArray #-}
pp_indexByteArray :: PseudoPrim a => PseudoPrimInfo a -> ByteArray -> Int -> a
pp_indexByteArray ppi (ByteArray arr#) (I# i#) = pp_indexByteArray# ppi arr# i#
|
mikeizbicki/typeparams
|
src/Data/Params/PseudoPrim.hs
|
bsd-3-clause
| 3,528
| 0
| 12
| 666
| 627
| 327
| 300
| -1
| -1
|
{-# LANGUAGE BangPatterns #-}
module Certificate
( arbitraryX509
, arbitraryX509WithKey
, simpleCertificate
, simpleX509
) where
import Control.Applicative
import Test.Tasty.QuickCheck
import Data.X509
import Data.Hourglass
import qualified Data.ByteString as B
import PubKey
testExtensionEncode critical ext = ExtensionRaw (extOID ext) critical (extEncode ext)
arbitraryDN = return $ DistinguishedName []
instance Arbitrary Date where
arbitrary = do
y <- choose (1971, 2035)
m <- elements [ January .. December]
d <- choose (1, 30)
return $ normalizeDate $ Date y m d
normalizeDate :: Date -> Date
normalizeDate d = timeConvert (timeConvert d :: Elapsed)
instance Arbitrary TimeOfDay where
arbitrary = do
h <- choose (0, 23)
mi <- choose (0, 59)
se <- choose (0, 59)
nsec <- return 0
return $ TimeOfDay (Hours h) (Minutes mi) (Seconds se) nsec
instance Arbitrary DateTime where
arbitrary = DateTime <$> arbitrary <*> arbitrary
maxSerial = 16777216
arbitraryCertificate pubKey = do
serial <- choose (0,maxSerial)
issuerdn <- arbitraryDN
subjectdn <- arbitraryDN
validity <- (,) <$> arbitrary <*> arbitrary
let sigalg = SignatureALG HashSHA1 (pubkeyToAlg pubKey)
return $ Certificate
{ certVersion = 3
, certSerial = serial
, certSignatureAlg = sigalg
, certIssuerDN = issuerdn
, certSubjectDN = subjectdn
, certValidity = validity
, certPubKey = pubKey
, certExtensions = Extensions $ Just
[ testExtensionEncode True $ ExtKeyUsage [KeyUsage_digitalSignature,KeyUsage_keyEncipherment,KeyUsage_keyCertSign]
]
}
simpleCertificate pubKey =
Certificate
{ certVersion = 3
, certSerial = 0
, certSignatureAlg = SignatureALG HashSHA1 (pubkeyToAlg pubKey)
, certIssuerDN = simpleDN
, certSubjectDN = simpleDN
, certValidity = (time1, time2)
, certPubKey = pubKey
, certExtensions = Extensions $ Just
[ testExtensionEncode True $ ExtKeyUsage [KeyUsage_digitalSignature,KeyUsage_keyEncipherment]
]
}
where time1 = DateTime (Date 1999 January 1) (TimeOfDay 0 0 0 0)
time2 = DateTime (Date 2049 January 1) (TimeOfDay 0 0 0 0)
simpleDN = DistinguishedName []
simpleX509 pubKey = do
let cert = simpleCertificate pubKey
sig = replicate 40 1
sigalg = SignatureALG HashSHA1 (pubkeyToAlg pubKey)
(signedExact, ()) = objectToSignedExact (\_ -> (B.pack sig,sigalg,())) cert
in signedExact
arbitraryX509WithKey (pubKey, _) = do
cert <- arbitraryCertificate pubKey
sig <- resize 40 $ listOf1 arbitrary
let sigalg = SignatureALG HashSHA1 (pubkeyToAlg pubKey)
let (signedExact, ()) = objectToSignedExact (\(!(_)) -> (B.pack sig,sigalg,())) cert
return signedExact
arbitraryX509 = do
let (pubKey, privKey) = getGlobalRSAPair
arbitraryX509WithKey (PubKeyRSA pubKey, PrivKeyRSA privKey)
|
tolysz/hs-tls
|
core/Tests/Certificate.hs
|
bsd-3-clause
| 3,191
| 0
| 16
| 905
| 926
| 484
| 442
| 77
| 1
|
module RectIntegralSpec where
import Control.Exception (evaluate)
import Data.Bifunctor (first)
import qualified Data.Vector as Vec
import Function
import qualified Library as Lib
import qualified RectIntegral
import Test.Hspec
import TestLib
suite :: SpecWith ()
suite = describe "Definite integral. Rectangular rule." $ do
let compute = CReal . RectIntegral.compute . first Vec.fromList
it "2*x from 1 to 2" $
compute ([1, 2], simpleFunc "2*x" (Right . (2*))) `shouldBe` CReal 3
it "1/x from exp(-1) to exp(1)" $
compute ([exp(-1), exp 1], simpleFunc "1/x" (Right . (1/))) `shouldBe` CReal 2
|
hrsrashid/nummet
|
tests/RectIntegralSpec.hs
|
bsd-3-clause
| 682
| 0
| 15
| 175
| 210
| 117
| 93
| 16
| 1
|
{-# LANGUAGE MonadComprehensions #-}
module Database.DSH.Backend.Sql.Opt.Properties.Nullable
( inferNullableNullOp
, inferNullableUnOp
, inferNullableBinOp
) where
import qualified Data.Set.Monad as S
import Database.Algebra.Table.Lang
import Database.DSH.Backend.Sql.Opt.Properties.Types
import Database.DSH.Backend.Sql.Opt.Properties.Auxiliary
nullableExpr :: S.Set Attr -> Expr -> Bool
nullableExpr ns e =
case e of
BinAppE Coalesce e1 e2 -> (nullableExpr ns e1 && nullableExpr ns e2)
||
(not (nullableExpr ns e1) && nullableExpr ns e2)
BinAppE _ e1 e2 -> nullableExpr ns e1 || nullableExpr ns e2
UnAppE _ e1 -> nullableExpr ns e1
ColE c -> c `S.member` ns
TernaryAppE _ e1 e2 e3 -> any (nullableExpr ns) [e1, e2, e3]
ConstE _ -> False
nullableAggr :: S.Set Attr -> AggrType -> Bool
nullableAggr ns a =
case a of
CountStar -> False
Count _ -> False
CountDistinct _ -> False
Avg e -> nullableExpr ns e
Max e -> nullableExpr ns e
Min e -> nullableExpr ns e
Sum e -> nullableExpr ns e
All e -> nullableExpr ns e
Any e -> nullableExpr ns e
inferNullableNullOp :: NullOp -> S.Set Attr
inferNullableNullOp op =
case op of
LitTable _ -> S.empty
TableRef _ -> S.empty
inferNullableUnOp :: S.Set Attr -> UnOp -> S.Set Attr
inferNullableUnOp ns op =
case op of
Serialize _ -> ns
Select _ -> ns
Distinct _ -> ns
Project ps -> ls [ a | (a, e) <- ps, nullableExpr ns e ]
RowNum (c, _, _) -> S.delete c ns
RowRank (c, _) -> S.delete c ns
Rank (c, _) -> S.delete c ns
-- Non-grouped aggregate functions might return NULL if their
-- input is empty (except for COUNT)
Aggr (as, []) -> ns ∪ ls [ c | (a, c) <- as, nullableAggr ns a ]
-- For grouped aggregates:
-- 1. The grouping columns might be NULL if they were nullable in the input.
--
-- 2. Aggregate output (except for COUNT) is nullable if the
-- input expression is nullable
Aggr (as, gs) -> ls [ c | (c, e) <- gs, nullableExpr ns e ]
∪
ls [ c | (a, c) <- as, nullableAggr ns a ]
-- FIXME under what circumstances does the window aggregate
-- output get NULL? This is the safe variant that considers
-- the output always nullable.
WinFun a -> let ((c, _), _, _, _) = a in S.insert c ns
inferNullableBinOp :: BottomUpProps -> BottomUpProps -> BinOp -> S.Set Attr
inferNullableBinOp ps1 ps2 op =
case op of
Cross _ -> pNullable ps1 ∪ pNullable ps2
-- FIXME for joins we could be more precise: any column that
-- shows up in the join predicate can be considered non-null
-- in the join result (tuples in which the predicate evaluates
-- to NULL will not be in the result).
ThetaJoin _ -> pNullable ps1 ∪ pNullable ps2
LeftOuterJoin _ -> pNullable ps1 ∪ [ c | (c, _) <- pCols ps2 ]
SemiJoin _ -> pNullable ps1
AntiJoin _ -> pNullable ps1
DisjUnion _ -> pNullable ps1 ∪ pNullable ps2
Difference _ -> pNullable ps1
|
ulricha/dsh-sql
|
src/Database/DSH/Backend/Sql/Opt/Properties/Nullable.hs
|
bsd-3-clause
| 3,517
| 0
| 13
| 1,254
| 965
| 488
| 477
| 62
| 10
|
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1998
\section[TcForeign]{Typechecking \tr{foreign} declarations}
A foreign declaration is used to either give an externally
implemented function a Haskell type (and calling interface) or
give a Haskell function an external calling interface. Either way,
the range of argument and result types these functions can accommodate
is restricted to what the outside world understands (read C), and this
module checks to see if a foreign declaration has got a legal type.
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies #-}
module TcForeign
( tcForeignImports
, tcForeignExports
-- Low-level exports for hooks
, isForeignImport, isForeignExport
, tcFImport, tcFExport
, tcForeignImports'
, tcCheckFIType, checkCTarget, checkForeignArgs, checkForeignRes
, normaliseFfiType
, nonIOok, mustBeIO
, checkSafe, noCheckSafe
, tcForeignExports'
, tcCheckFEType
) where
#include "HsVersions.h"
import GhcPrelude
import GHC.Hs
import TcRnMonad
import TcHsType
import TcExpr
import TcEnv
import FamInst
import FamInstEnv
import Coercion
import Type
import ForeignCall
import ErrUtils
import Id
import Name
import RdrName
import DataCon
import TyCon
import TcType
import PrelNames
import DynFlags
import Outputable
import GHC.Platform
import SrcLoc
import Bag
import Hooks
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad
-- Defines a binding
isForeignImport :: LForeignDecl name -> Bool
isForeignImport (L _ (ForeignImport {})) = True
isForeignImport _ = False
-- Exports a binding
isForeignExport :: LForeignDecl name -> Bool
isForeignExport (L _ (ForeignExport {})) = True
isForeignExport _ = False
{-
Note [Don't recur in normaliseFfiType']
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
normaliseFfiType' is the workhorse for normalising a type used in a foreign
declaration. If we have
newtype Age = MkAge Int
we want to see that Age -> IO () is the same as Int -> IO (). But, we don't
need to recur on any type parameters, because no paramaterized types (with
interesting parameters) are marshalable! The full list of marshalable types
is in the body of boxedMarshalableTyCon in TcType. The only members of that
list not at kind * are Ptr, FunPtr, and StablePtr, all of which get marshaled
the same way regardless of type parameter. So, no need to recur into
parameters.
Similarly, we don't need to look in AppTy's, because nothing headed by
an AppTy will be marshalable.
Note [FFI type roles]
~~~~~~~~~~~~~~~~~~~~~
The 'go' helper function within normaliseFfiType' always produces
representational coercions. But, in the "children_only" case, we need to
use these coercions in a TyConAppCo. Accordingly, the roles on the coercions
must be twiddled to match the expectation of the enclosing TyCon. However,
we cannot easily go from an R coercion to an N one, so we forbid N roles
on FFI type constructors. Currently, only two such type constructors exist:
IO and FunPtr. Thus, this is not an onerous burden.
If we ever want to lift this restriction, we would need to make 'go' take
the target role as a parameter. This wouldn't be hard, but it's a complication
not yet necessary and so is not yet implemented.
-}
-- normaliseFfiType takes the type from an FFI declaration, and
-- evaluates any type synonyms, type functions, and newtypes. However,
-- we are only allowed to look through newtypes if the constructor is
-- in scope. We return a bag of all the newtype constructors thus found.
-- Always returns a Representational coercion
normaliseFfiType :: Type -> TcM (Coercion, Type, Bag GlobalRdrElt)
normaliseFfiType ty
= do fam_envs <- tcGetFamInstEnvs
normaliseFfiType' fam_envs ty
normaliseFfiType' :: FamInstEnvs -> Type -> TcM (Coercion, Type, Bag GlobalRdrElt)
normaliseFfiType' env ty0 = go initRecTc ty0
where
go :: RecTcChecker -> Type -> TcM (Coercion, Type, Bag GlobalRdrElt)
go rec_nts ty
| Just ty' <- tcView ty -- Expand synonyms
= go rec_nts ty'
| Just (tc, tys) <- splitTyConApp_maybe ty
= go_tc_app rec_nts tc tys
| (bndrs, inner_ty) <- splitForAllVarBndrs ty
, not (null bndrs)
= do (coi, nty1, gres1) <- go rec_nts inner_ty
return ( mkHomoForAllCos (binderVars bndrs) coi
, mkForAllTys bndrs nty1, gres1 )
| otherwise -- see Note [Don't recur in normaliseFfiType']
= return (mkRepReflCo ty, ty, emptyBag)
go_tc_app :: RecTcChecker -> TyCon -> [Type]
-> TcM (Coercion, Type, Bag GlobalRdrElt)
go_tc_app rec_nts tc tys
-- We don't want to look through the IO newtype, even if it is
-- in scope, so we have a special case for it:
| tc_key `elem` [ioTyConKey, funPtrTyConKey, funTyConKey]
-- These *must not* have nominal roles on their parameters!
-- See Note [FFI type roles]
= children_only
| isNewTyCon tc -- Expand newtypes
, Just rec_nts' <- checkRecTc rec_nts tc
-- See Note [Expanding newtypes] in TyCon.hs
-- We can't just use isRecursiveTyCon; sometimes recursion is ok:
-- newtype T = T (Ptr T)
-- Here, we don't reject the type for being recursive.
-- If this is a recursive newtype then it will normally
-- be rejected later as not being a valid FFI type.
= do { rdr_env <- getGlobalRdrEnv
; case checkNewtypeFFI rdr_env tc of
Nothing -> nothing
Just gre -> do { (co', ty', gres) <- go rec_nts' nt_rhs
; return (mkTransCo nt_co co', ty', gre `consBag` gres) } }
| isFamilyTyCon tc -- Expand open tycons
, (co, ty) <- normaliseTcApp env Representational tc tys
, not (isReflexiveCo co)
= do (co', ty', gres) <- go rec_nts ty
return (mkTransCo co co', ty', gres)
| otherwise
= nothing -- see Note [Don't recur in normaliseFfiType']
where
tc_key = getUnique tc
children_only
= do xs <- mapM (go rec_nts) tys
let (cos, tys', gres) = unzip3 xs
-- the (repeat Representational) is because 'go' always
-- returns R coercions
cos' = zipWith3 downgradeRole (tyConRoles tc)
(repeat Representational) cos
return ( mkTyConAppCo Representational tc cos'
, mkTyConApp tc tys', unionManyBags gres)
nt_co = mkUnbranchedAxInstCo Representational (newTyConCo tc) tys []
nt_rhs = newTyConInstRhs tc tys
ty = mkTyConApp tc tys
nothing = return (mkRepReflCo ty, ty, emptyBag)
checkNewtypeFFI :: GlobalRdrEnv -> TyCon -> Maybe GlobalRdrElt
checkNewtypeFFI rdr_env tc
| Just con <- tyConSingleDataCon_maybe tc
, Just gre <- lookupGRE_Name rdr_env (dataConName con)
= Just gre -- See Note [Newtype constructor usage in foreign declarations]
| otherwise
= Nothing
{-
Note [Newtype constructor usage in foreign declarations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC automatically "unwraps" newtype constructors in foreign import/export
declarations. In effect that means that a newtype data constructor is
used even though it is not mentioned expclitly in the source, so we don't
want to report it as "defined but not used" or "imported but not used".
eg newtype D = MkD Int
foreign import foo :: D -> IO ()
Here 'MkD' us used. See #7408.
GHC also expands type functions during this process, so it's not enough
just to look at the free variables of the declaration.
eg type instance F Bool = D
foreign import bar :: F Bool -> IO ()
Here again 'MkD' is used.
So we really have wait until the type checker to decide what is used.
That's why tcForeignImports and tecForeignExports return a (Bag GRE)
for the newtype constructors they see. Then TcRnDriver can add them
to the module's usages.
************************************************************************
* *
\subsection{Imports}
* *
************************************************************************
-}
tcForeignImports :: [LForeignDecl GhcRn]
-> TcM ([Id], [LForeignDecl GhcTc], Bag GlobalRdrElt)
tcForeignImports decls
= getHooked tcForeignImportsHook tcForeignImports' >>= ($ decls)
tcForeignImports' :: [LForeignDecl GhcRn]
-> TcM ([Id], [LForeignDecl GhcTc], Bag GlobalRdrElt)
-- For the (Bag GlobalRdrElt) result,
-- see Note [Newtype constructor usage in foreign declarations]
tcForeignImports' decls
= do { (ids, decls, gres) <- mapAndUnzip3M tcFImport $
filter isForeignImport decls
; return (ids, decls, unionManyBags gres) }
tcFImport :: LForeignDecl GhcRn
-> TcM (Id, LForeignDecl GhcTc, Bag GlobalRdrElt)
tcFImport (L dloc fo@(ForeignImport { fd_name = L nloc nm, fd_sig_ty = hs_ty
, fd_fi = imp_decl }))
= setSrcSpan dloc $ addErrCtxt (foreignDeclCtxt fo) $
do { sig_ty <- tcHsSigType (ForSigCtxt nm) hs_ty
; (norm_co, norm_sig_ty, gres) <- normaliseFfiType sig_ty
; let
-- Drop the foralls before inspecting the
-- structure of the foreign type.
(arg_tys, res_ty) = tcSplitFunTys (dropForAlls norm_sig_ty)
id = mkLocalId nm sig_ty
-- Use a LocalId to obey the invariant that locally-defined
-- things are LocalIds. However, it does not need zonking,
-- (so TcHsSyn.zonkForeignExports ignores it).
; imp_decl' <- tcCheckFIType arg_tys res_ty imp_decl
-- Can't use sig_ty here because sig_ty :: Type and
-- we need HsType Id hence the undefined
; let fi_decl = ForeignImport { fd_name = L nloc id
, fd_sig_ty = undefined
, fd_i_ext = mkSymCo norm_co
, fd_fi = imp_decl' }
; return (id, L dloc fi_decl, gres) }
tcFImport d = pprPanic "tcFImport" (ppr d)
-- ------------ Checking types for foreign import ----------------------
tcCheckFIType :: [Type] -> Type -> ForeignImport -> TcM ForeignImport
tcCheckFIType arg_tys res_ty (CImport (L lc cconv) safety mh l@(CLabel _) src)
-- Foreign import label
= do checkCg checkCOrAsmOrLlvmOrInterp
-- NB check res_ty not sig_ty!
-- In case sig_ty is (forall a. ForeignPtr a)
check (isFFILabelTy (mkVisFunTys arg_tys res_ty)) (illegalForeignTyErr Outputable.empty)
cconv' <- checkCConv cconv
return (CImport (L lc cconv') safety mh l src)
tcCheckFIType arg_tys res_ty (CImport (L lc cconv) safety mh CWrapper src) = do
-- Foreign wrapper (former f.e.d.)
-- The type must be of the form ft -> IO (FunPtr ft), where ft is a valid
-- foreign type. For legacy reasons ft -> IO (Ptr ft) is accepted, too.
-- The use of the latter form is DEPRECATED, though.
checkCg checkCOrAsmOrLlvmOrInterp
cconv' <- checkCConv cconv
case arg_tys of
[arg1_ty] -> do checkForeignArgs isFFIExternalTy arg1_tys
checkForeignRes nonIOok checkSafe isFFIExportResultTy res1_ty
checkForeignRes mustBeIO checkSafe (isFFIDynTy arg1_ty) res_ty
where
(arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
_ -> addErrTc (illegalForeignTyErr Outputable.empty (text "One argument expected"))
return (CImport (L lc cconv') safety mh CWrapper src)
tcCheckFIType arg_tys res_ty idecl@(CImport (L lc cconv) (L ls safety) mh
(CFunction target) src)
| isDynamicTarget target = do -- Foreign import dynamic
checkCg checkCOrAsmOrLlvmOrInterp
cconv' <- checkCConv cconv
case arg_tys of -- The first arg must be Ptr or FunPtr
[] ->
addErrTc (illegalForeignTyErr Outputable.empty (text "At least one argument expected"))
(arg1_ty:arg_tys) -> do
dflags <- getDynFlags
let curried_res_ty = mkVisFunTys arg_tys res_ty
check (isFFIDynTy curried_res_ty arg1_ty)
(illegalForeignTyErr argument)
checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys
checkForeignRes nonIOok checkSafe (isFFIImportResultTy dflags) res_ty
return $ CImport (L lc cconv') (L ls safety) mh (CFunction target) src
| cconv == PrimCallConv = do
dflags <- getDynFlags
checkTc (xopt LangExt.GHCForeignImportPrim dflags)
(text "Use GHCForeignImportPrim to allow `foreign import prim'.")
checkCg checkCOrAsmOrLlvmOrInterp
checkCTarget target
checkTc (playSafe safety)
(text "The safe/unsafe annotation should not be used with `foreign import prim'.")
checkForeignArgs (isFFIPrimArgumentTy dflags) arg_tys
-- prim import result is more liberal, allows (#,,#)
checkForeignRes nonIOok checkSafe (isFFIPrimResultTy dflags) res_ty
return idecl
| otherwise = do -- Normal foreign import
checkCg checkCOrAsmOrLlvmOrInterp
cconv' <- checkCConv cconv
checkCTarget target
dflags <- getDynFlags
checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys
checkForeignRes nonIOok checkSafe (isFFIImportResultTy dflags) res_ty
checkMissingAmpersand dflags arg_tys res_ty
case target of
StaticTarget _ _ _ False
| not (null arg_tys) ->
addErrTc (text "`value' imports cannot have function types")
_ -> return ()
return $ CImport (L lc cconv') (L ls safety) mh (CFunction target) src
-- This makes a convenient place to check
-- that the C identifier is valid for C
checkCTarget :: CCallTarget -> TcM ()
checkCTarget (StaticTarget _ str _ _) = do
checkCg checkCOrAsmOrLlvmOrInterp
checkTc (isCLabelString str) (badCName str)
checkCTarget DynamicTarget = panic "checkCTarget DynamicTarget"
checkMissingAmpersand :: DynFlags -> [Type] -> Type -> TcM ()
checkMissingAmpersand dflags arg_tys res_ty
| null arg_tys && isFunPtrTy res_ty &&
wopt Opt_WarnDodgyForeignImports dflags
= addWarn (Reason Opt_WarnDodgyForeignImports)
(text "possible missing & in foreign import of FunPtr")
| otherwise
= return ()
{-
************************************************************************
* *
\subsection{Exports}
* *
************************************************************************
-}
tcForeignExports :: [LForeignDecl GhcRn]
-> TcM (LHsBinds GhcTcId, [LForeignDecl GhcTcId], Bag GlobalRdrElt)
tcForeignExports decls =
getHooked tcForeignExportsHook tcForeignExports' >>= ($ decls)
tcForeignExports' :: [LForeignDecl GhcRn]
-> TcM (LHsBinds GhcTcId, [LForeignDecl GhcTcId], Bag GlobalRdrElt)
-- For the (Bag GlobalRdrElt) result,
-- see Note [Newtype constructor usage in foreign declarations]
tcForeignExports' decls
= foldlM combine (emptyLHsBinds, [], emptyBag) (filter isForeignExport decls)
where
combine (binds, fs, gres1) (L loc fe) = do
(b, f, gres2) <- setSrcSpan loc (tcFExport fe)
return (b `consBag` binds, L loc f : fs, gres1 `unionBags` gres2)
tcFExport :: ForeignDecl GhcRn
-> TcM (LHsBind GhcTc, ForeignDecl GhcTc, Bag GlobalRdrElt)
tcFExport fo@(ForeignExport { fd_name = L loc nm, fd_sig_ty = hs_ty, fd_fe = spec })
= addErrCtxt (foreignDeclCtxt fo) $ do
sig_ty <- tcHsSigType (ForSigCtxt nm) hs_ty
rhs <- tcPolyExpr (nlHsVar nm) sig_ty
(norm_co, norm_sig_ty, gres) <- normaliseFfiType sig_ty
spec' <- tcCheckFEType norm_sig_ty spec
-- we're exporting a function, but at a type possibly more
-- constrained than its declared/inferred type. Hence the need
-- to create a local binding which will call the exported function
-- at a particular type (and, maybe, overloading).
-- We need to give a name to the new top-level binding that
-- is *stable* (i.e. the compiler won't change it later),
-- because this name will be referred to by the C code stub.
id <- mkStableIdFromName nm sig_ty loc mkForeignExportOcc
return ( mkVarBind id rhs
, ForeignExport { fd_name = L loc id
, fd_sig_ty = undefined
, fd_e_ext = norm_co, fd_fe = spec' }
, gres)
tcFExport d = pprPanic "tcFExport" (ppr d)
-- ------------ Checking argument types for foreign export ----------------------
tcCheckFEType :: Type -> ForeignExport -> TcM ForeignExport
tcCheckFEType sig_ty (CExport (L l (CExportStatic esrc str cconv)) src) = do
checkCg checkCOrAsmOrLlvm
checkTc (isCLabelString str) (badCName str)
cconv' <- checkCConv cconv
checkForeignArgs isFFIExternalTy arg_tys
checkForeignRes nonIOok noCheckSafe isFFIExportResultTy res_ty
return (CExport (L l (CExportStatic esrc str cconv')) src)
where
-- Drop the foralls before inspecting
-- the structure of the foreign type.
(arg_tys, res_ty) = tcSplitFunTys (dropForAlls sig_ty)
{-
************************************************************************
* *
\subsection{Miscellaneous}
* *
************************************************************************
-}
------------ Checking argument types for foreign import ----------------------
checkForeignArgs :: (Type -> Validity) -> [Type] -> TcM ()
checkForeignArgs pred tys = mapM_ go tys
where
go ty = check (pred ty) (illegalForeignTyErr argument)
------------ Checking result types for foreign calls ----------------------
-- | Check that the type has the form
-- (IO t) or (t) , and that t satisfies the given predicate.
-- When calling this function, any newtype wrappers (should) have been
-- already dealt with by normaliseFfiType.
--
-- We also check that the Safe Haskell condition of FFI imports having
-- results in the IO monad holds.
--
checkForeignRes :: Bool -> Bool -> (Type -> Validity) -> Type -> TcM ()
checkForeignRes non_io_result_ok check_safe pred_res_ty ty
| Just (_, res_ty) <- tcSplitIOType_maybe ty
= -- Got an IO result type, that's always fine!
check (pred_res_ty res_ty) (illegalForeignTyErr result)
-- We disallow nested foralls in foreign types
-- (at least, for the time being). See #16702.
| tcIsForAllTy ty
= addErrTc $ illegalForeignTyErr result (text "Unexpected nested forall")
-- Case for non-IO result type with FFI Import
| not non_io_result_ok
= addErrTc $ illegalForeignTyErr result (text "IO result type expected")
| otherwise
= do { dflags <- getDynFlags
; case pred_res_ty ty of
-- Handle normal typecheck fail, we want to handle this first and
-- only report safe haskell errors if the normal type check is OK.
NotValid msg -> addErrTc $ illegalForeignTyErr result msg
-- handle safe infer fail
_ | check_safe && safeInferOn dflags
-> recordUnsafeInfer emptyBag
-- handle safe language typecheck fail
_ | check_safe && safeLanguageOn dflags
-> addErrTc (illegalForeignTyErr result safeHsErr)
-- success! non-IO return is fine
_ -> return () }
where
safeHsErr =
text "Safe Haskell is on, all FFI imports must be in the IO monad"
nonIOok, mustBeIO :: Bool
nonIOok = True
mustBeIO = False
checkSafe, noCheckSafe :: Bool
checkSafe = True
noCheckSafe = False
-- Checking a supported backend is in use
checkCOrAsmOrLlvm :: HscTarget -> Validity
checkCOrAsmOrLlvm HscC = IsValid
checkCOrAsmOrLlvm HscAsm = IsValid
checkCOrAsmOrLlvm HscLlvm = IsValid
checkCOrAsmOrLlvm _
= NotValid (text "requires unregisterised, llvm (-fllvm) or native code generation (-fasm)")
checkCOrAsmOrLlvmOrInterp :: HscTarget -> Validity
checkCOrAsmOrLlvmOrInterp HscC = IsValid
checkCOrAsmOrLlvmOrInterp HscAsm = IsValid
checkCOrAsmOrLlvmOrInterp HscLlvm = IsValid
checkCOrAsmOrLlvmOrInterp HscInterpreted = IsValid
checkCOrAsmOrLlvmOrInterp _
= NotValid (text "requires interpreted, unregisterised, llvm or native code generation")
checkCg :: (HscTarget -> Validity) -> TcM ()
checkCg check = do
dflags <- getDynFlags
let target = hscTarget dflags
case target of
HscNothing -> return ()
_ ->
case check target of
IsValid -> return ()
NotValid err -> addErrTc (text "Illegal foreign declaration:" <+> err)
-- Calling conventions
checkCConv :: CCallConv -> TcM CCallConv
checkCConv CCallConv = return CCallConv
checkCConv CApiConv = return CApiConv
checkCConv StdCallConv = do dflags <- getDynFlags
let platform = targetPlatform dflags
if platformArch platform == ArchX86
then return StdCallConv
else do -- This is a warning, not an error. see #3336
when (wopt Opt_WarnUnsupportedCallingConventions dflags) $
addWarnTc (Reason Opt_WarnUnsupportedCallingConventions)
(text "the 'stdcall' calling convention is unsupported on this platform," $$ text "treating as ccall")
return CCallConv
checkCConv PrimCallConv = do addErrTc (text "The `prim' calling convention can only be used with `foreign import'")
return PrimCallConv
checkCConv JavaScriptCallConv = do dflags <- getDynFlags
if platformArch (targetPlatform dflags) == ArchJavaScript
then return JavaScriptCallConv
else do addErrTc (text "The `javascript' calling convention is unsupported on this platform")
return JavaScriptCallConv
-- Warnings
check :: Validity -> (MsgDoc -> MsgDoc) -> TcM ()
check IsValid _ = return ()
check (NotValid doc) err_fn = addErrTc (err_fn doc)
illegalForeignTyErr :: SDoc -> SDoc -> SDoc
illegalForeignTyErr arg_or_res extra
= hang msg 2 extra
where
msg = hsep [ text "Unacceptable", arg_or_res
, text "type in foreign declaration:"]
-- Used for 'arg_or_res' argument to illegalForeignTyErr
argument, result :: SDoc
argument = text "argument"
result = text "result"
badCName :: CLabelString -> MsgDoc
badCName target
= sep [quotes (ppr target) <+> text "is not a valid C identifier"]
foreignDeclCtxt :: ForeignDecl GhcRn -> SDoc
foreignDeclCtxt fo
= hang (text "When checking declaration:")
2 (ppr fo)
|
sdiehl/ghc
|
compiler/typecheck/TcForeign.hs
|
bsd-3-clause
| 23,574
| 62
| 18
| 6,486
| 4,152
| 2,124
| 2,028
| 324
| 4
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Dependency
-- Copyright : (c) David Himmelstrup 2005,
-- Bjorn Bringert 2007
-- Duncan Coutts 2008
-- License : BSD-like
--
-- Maintainer : cabal-devel@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Top level interface to dependency resolution.
-----------------------------------------------------------------------------
module Distribution.Client.Dependency (
-- * The main package dependency resolver
chooseSolver,
resolveDependencies,
Progress(..),
foldProgress,
-- * Alternate, simple resolver that does not do dependencies recursively
resolveWithoutDependencies,
-- * Constructing resolver policies
PackageProperty(..),
PackageConstraint(..),
scopeToplevel,
PackagesPreferenceDefault(..),
PackagePreference(..),
-- ** Standard policy
basicInstallPolicy,
standardInstallPolicy,
PackageSpecifier(..),
-- ** Sandbox policy
applySandboxInstallPolicy,
-- ** Extra policy options
upgradeDependencies,
reinstallTargets,
-- ** Policy utils
addConstraints,
addPreferences,
setPreferenceDefault,
setReorderGoals,
setCountConflicts,
setIndependentGoals,
setAvoidReinstalls,
setShadowPkgs,
setStrongFlags,
setAllowBootLibInstalls,
setMaxBackjumps,
setEnableBackjumping,
setSolveExecutables,
setGoalOrder,
setSolverVerbosity,
removeLowerBounds,
removeUpperBounds,
addDefaultSetupDependencies,
addSetupCabalMinVersionConstraint,
) where
import Distribution.Solver.Modular
( modularResolver, SolverConfig(..) )
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex
import Distribution.Client.SolverInstallPlan (SolverInstallPlan)
import qualified Distribution.Client.SolverInstallPlan as SolverInstallPlan
import Distribution.Client.Types
( SourcePackageDb(SourcePackageDb)
, UnresolvedPkgLoc, UnresolvedSourcePackage
, AllowNewer(..), AllowOlder(..), RelaxDeps(..), RelaxedDep(..)
)
import Distribution.Client.Dependency.Types
( PreSolver(..), Solver(..)
, PackagesPreferenceDefault(..) )
import Distribution.Client.Sandbox.Types
( SandboxPackageInfo(..) )
import Distribution.Client.Targets
import Distribution.Package
( PackageName, mkPackageName, PackageIdentifier(PackageIdentifier), PackageId
, Package(..), packageName, packageVersion )
import Distribution.Types.Dependency
import qualified Distribution.PackageDescription as PD
import qualified Distribution.PackageDescription.Configuration as PD
import Distribution.PackageDescription.Configuration
( finalizePD )
import Distribution.Client.PackageUtils
( externalBuildDepends )
import Distribution.Version
( Version, mkVersion
, VersionRange, anyVersion, thisVersion, orLaterVersion, withinRange
, simplifyVersionRange, removeLowerBound, removeUpperBound )
import Distribution.Compiler
( CompilerInfo(..) )
import Distribution.System
( Platform )
import Distribution.Client.Utils
( duplicates, duplicatesBy, mergeBy, MergeResult(..) )
import Distribution.Simple.Utils
( comparing )
import Distribution.Simple.Setup
( asBool )
import Distribution.Text
( display )
import Distribution.Verbosity
( normal, Verbosity )
import qualified Distribution.Compat.Graph as Graph
import Distribution.Solver.Types.ComponentDeps (ComponentDeps)
import qualified Distribution.Solver.Types.ComponentDeps as CD
import Distribution.Solver.Types.ConstraintSource
import Distribution.Solver.Types.DependencyResolver
import Distribution.Solver.Types.InstalledPreference
import Distribution.Solver.Types.LabeledPackageConstraint
import Distribution.Solver.Types.OptionalStanza
import Distribution.Solver.Types.PackageConstraint
import Distribution.Solver.Types.PackagePath
import Distribution.Solver.Types.PackagePreferences
import qualified Distribution.Solver.Types.PackageIndex as PackageIndex
import Distribution.Solver.Types.PkgConfigDb (PkgConfigDb)
import Distribution.Solver.Types.Progress
import Distribution.Solver.Types.ResolverPackage
import Distribution.Solver.Types.Settings
import Distribution.Solver.Types.SolverId
import Distribution.Solver.Types.SolverPackage
import Distribution.Solver.Types.SourcePackage
import Distribution.Solver.Types.Variable
import Data.List
( foldl', sort, sortBy, nubBy, maximumBy, intercalate, nub )
import Data.Function (on)
import Data.Maybe (fromMaybe, mapMaybe)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Set (Set)
import Control.Exception
( assert )
-- ------------------------------------------------------------
-- * High level planner policy
-- ------------------------------------------------------------
-- | The set of parameters to the dependency resolver. These parameters are
-- relatively low level but many kinds of high level policies can be
-- implemented in terms of adjustments to the parameters.
--
data DepResolverParams = DepResolverParams {
depResolverTargets :: Set PackageName,
depResolverConstraints :: [LabeledPackageConstraint],
depResolverPreferences :: [PackagePreference],
depResolverPreferenceDefault :: PackagesPreferenceDefault,
depResolverInstalledPkgIndex :: InstalledPackageIndex,
depResolverSourcePkgIndex :: PackageIndex.PackageIndex UnresolvedSourcePackage,
depResolverReorderGoals :: ReorderGoals,
depResolverCountConflicts :: CountConflicts,
depResolverIndependentGoals :: IndependentGoals,
depResolverAvoidReinstalls :: AvoidReinstalls,
depResolverShadowPkgs :: ShadowPkgs,
depResolverStrongFlags :: StrongFlags,
-- | Whether to allow base and its dependencies to be installed.
depResolverAllowBootLibInstalls :: AllowBootLibInstalls,
depResolverMaxBackjumps :: Maybe Int,
depResolverEnableBackjumping :: EnableBackjumping,
-- | Whether or not to solve for dependencies on executables.
-- This should be true, except in the legacy code path where
-- we can't tell if an executable has been installed or not,
-- so we shouldn't solve for them. See #3875.
depResolverSolveExecutables :: SolveExecutables,
-- | Function to override the solver's goal-ordering heuristics.
depResolverGoalOrder :: Maybe (Variable QPN -> Variable QPN -> Ordering),
depResolverVerbosity :: Verbosity
}
showDepResolverParams :: DepResolverParams -> String
showDepResolverParams p =
"targets: " ++ intercalate ", " (map display $ Set.toList (depResolverTargets p))
++ "\nconstraints: "
++ concatMap (("\n " ++) . showLabeledConstraint)
(depResolverConstraints p)
++ "\npreferences: "
++ concatMap (("\n " ++) . showPackagePreference)
(depResolverPreferences p)
++ "\nstrategy: " ++ show (depResolverPreferenceDefault p)
++ "\nreorder goals: " ++ show (asBool (depResolverReorderGoals p))
++ "\ncount conflicts: " ++ show (asBool (depResolverCountConflicts p))
++ "\nindependent goals: " ++ show (asBool (depResolverIndependentGoals p))
++ "\navoid reinstalls: " ++ show (asBool (depResolverAvoidReinstalls p))
++ "\nshadow packages: " ++ show (asBool (depResolverShadowPkgs p))
++ "\nstrong flags: " ++ show (asBool (depResolverStrongFlags p))
++ "\nallow boot library installs: " ++ show (asBool (depResolverAllowBootLibInstalls p))
++ "\nmax backjumps: " ++ maybe "infinite" show
(depResolverMaxBackjumps p)
where
showLabeledConstraint :: LabeledPackageConstraint -> String
showLabeledConstraint (LabeledPackageConstraint pc src) =
showPackageConstraint pc ++ " (" ++ showConstraintSource src ++ ")"
-- | A package selection preference for a particular package.
--
-- Preferences are soft constraints that the dependency resolver should try to
-- respect where possible. It is not specified if preferences on some packages
-- are more important than others.
--
data PackagePreference =
-- | A suggested constraint on the version number.
PackageVersionPreference PackageName VersionRange
-- | If we prefer versions of packages that are already installed.
| PackageInstalledPreference PackageName InstalledPreference
-- | If we would prefer to enable these optional stanzas
-- (i.e. test suites and/or benchmarks)
| PackageStanzasPreference PackageName [OptionalStanza]
-- | Provide a textual representation of a package preference
-- for debugging purposes.
--
showPackagePreference :: PackagePreference -> String
showPackagePreference (PackageVersionPreference pn vr) =
display pn ++ " " ++ display (simplifyVersionRange vr)
showPackagePreference (PackageInstalledPreference pn ip) =
display pn ++ " " ++ show ip
showPackagePreference (PackageStanzasPreference pn st) =
display pn ++ " " ++ show st
basicDepResolverParams :: InstalledPackageIndex
-> PackageIndex.PackageIndex UnresolvedSourcePackage
-> DepResolverParams
basicDepResolverParams installedPkgIndex sourcePkgIndex =
DepResolverParams {
depResolverTargets = Set.empty,
depResolverConstraints = [],
depResolverPreferences = [],
depResolverPreferenceDefault = PreferLatestForSelected,
depResolverInstalledPkgIndex = installedPkgIndex,
depResolverSourcePkgIndex = sourcePkgIndex,
depResolverReorderGoals = ReorderGoals False,
depResolverCountConflicts = CountConflicts True,
depResolverIndependentGoals = IndependentGoals False,
depResolverAvoidReinstalls = AvoidReinstalls False,
depResolverShadowPkgs = ShadowPkgs False,
depResolverStrongFlags = StrongFlags False,
depResolverAllowBootLibInstalls = AllowBootLibInstalls False,
depResolverMaxBackjumps = Nothing,
depResolverEnableBackjumping = EnableBackjumping True,
depResolverSolveExecutables = SolveExecutables True,
depResolverGoalOrder = Nothing,
depResolverVerbosity = normal
}
addTargets :: [PackageName]
-> DepResolverParams -> DepResolverParams
addTargets extraTargets params =
params {
depResolverTargets = Set.fromList extraTargets `Set.union` depResolverTargets params
}
addConstraints :: [LabeledPackageConstraint]
-> DepResolverParams -> DepResolverParams
addConstraints extraConstraints params =
params {
depResolverConstraints = extraConstraints
++ depResolverConstraints params
}
addPreferences :: [PackagePreference]
-> DepResolverParams -> DepResolverParams
addPreferences extraPreferences params =
params {
depResolverPreferences = extraPreferences
++ depResolverPreferences params
}
setPreferenceDefault :: PackagesPreferenceDefault
-> DepResolverParams -> DepResolverParams
setPreferenceDefault preferenceDefault params =
params {
depResolverPreferenceDefault = preferenceDefault
}
setReorderGoals :: ReorderGoals -> DepResolverParams -> DepResolverParams
setReorderGoals reorder params =
params {
depResolverReorderGoals = reorder
}
setCountConflicts :: CountConflicts -> DepResolverParams -> DepResolverParams
setCountConflicts count params =
params {
depResolverCountConflicts = count
}
setIndependentGoals :: IndependentGoals -> DepResolverParams -> DepResolverParams
setIndependentGoals indep params =
params {
depResolverIndependentGoals = indep
}
setAvoidReinstalls :: AvoidReinstalls -> DepResolverParams -> DepResolverParams
setAvoidReinstalls avoid params =
params {
depResolverAvoidReinstalls = avoid
}
setShadowPkgs :: ShadowPkgs -> DepResolverParams -> DepResolverParams
setShadowPkgs shadow params =
params {
depResolverShadowPkgs = shadow
}
setStrongFlags :: StrongFlags -> DepResolverParams -> DepResolverParams
setStrongFlags sf params =
params {
depResolverStrongFlags = sf
}
setAllowBootLibInstalls :: AllowBootLibInstalls -> DepResolverParams -> DepResolverParams
setAllowBootLibInstalls i params =
params {
depResolverAllowBootLibInstalls = i
}
setMaxBackjumps :: Maybe Int -> DepResolverParams -> DepResolverParams
setMaxBackjumps n params =
params {
depResolverMaxBackjumps = n
}
setEnableBackjumping :: EnableBackjumping -> DepResolverParams -> DepResolverParams
setEnableBackjumping b params =
params {
depResolverEnableBackjumping = b
}
setSolveExecutables :: SolveExecutables -> DepResolverParams -> DepResolverParams
setSolveExecutables b params =
params {
depResolverSolveExecutables = b
}
setGoalOrder :: Maybe (Variable QPN -> Variable QPN -> Ordering)
-> DepResolverParams
-> DepResolverParams
setGoalOrder order params =
params {
depResolverGoalOrder = order
}
setSolverVerbosity :: Verbosity -> DepResolverParams -> DepResolverParams
setSolverVerbosity verbosity params =
params {
depResolverVerbosity = verbosity
}
-- | Some packages are specific to a given compiler version and should never be
-- upgraded.
dontUpgradeNonUpgradeablePackages :: DepResolverParams -> DepResolverParams
dontUpgradeNonUpgradeablePackages params =
addConstraints extraConstraints params
where
extraConstraints =
[ LabeledPackageConstraint
(PackageConstraint (ScopeAnyQualifier pkgname) PackagePropertyInstalled)
ConstraintSourceNonUpgradeablePackage
| Set.notMember (mkPackageName "base") (depResolverTargets params)
-- If you change this enumeration, make sure to update the list in
-- "Distribution.Solver.Modular.Solver" as well
, pkgname <- [ mkPackageName "base"
, mkPackageName "ghc-prim"
, mkPackageName "integer-gmp"
, mkPackageName "integer-simple"
, mkPackageName "template-haskell"
]
, isInstalled pkgname ]
isInstalled = not . null
. InstalledPackageIndex.lookupPackageName
(depResolverInstalledPkgIndex params)
addSourcePackages :: [UnresolvedSourcePackage]
-> DepResolverParams -> DepResolverParams
addSourcePackages pkgs params =
params {
depResolverSourcePkgIndex =
foldl (flip PackageIndex.insert)
(depResolverSourcePkgIndex params) pkgs
}
hideInstalledPackagesSpecificBySourcePackageId :: [PackageId]
-> DepResolverParams
-> DepResolverParams
hideInstalledPackagesSpecificBySourcePackageId pkgids params =
--TODO: this should work using exclude constraints instead
params {
depResolverInstalledPkgIndex =
foldl' (flip InstalledPackageIndex.deleteSourcePackageId)
(depResolverInstalledPkgIndex params) pkgids
}
hideInstalledPackagesAllVersions :: [PackageName]
-> DepResolverParams -> DepResolverParams
hideInstalledPackagesAllVersions pkgnames params =
--TODO: this should work using exclude constraints instead
params {
depResolverInstalledPkgIndex =
foldl' (flip InstalledPackageIndex.deletePackageName)
(depResolverInstalledPkgIndex params) pkgnames
}
-- | Remove upper bounds in dependencies using the policy specified by the
-- 'AllowNewer' argument (all/some/none).
--
-- Note: It's important to apply 'removeUpperBounds' after
-- 'addSourcePackages'. Otherwise, the packages inserted by
-- 'addSourcePackages' won't have upper bounds in dependencies relaxed.
--
removeUpperBounds :: AllowNewer -> DepResolverParams -> DepResolverParams
removeUpperBounds (AllowNewer RelaxDepsNone) params = params
removeUpperBounds (AllowNewer allowNewer) params =
params {
depResolverSourcePkgIndex = sourcePkgIndex'
}
where
sourcePkgIndex' = fmap relaxDeps $ depResolverSourcePkgIndex params
relaxDeps :: UnresolvedSourcePackage -> UnresolvedSourcePackage
relaxDeps srcPkg = srcPkg {
packageDescription = relaxPackageDeps removeUpperBound allowNewer
(packageDescription srcPkg)
}
-- | Dual of 'removeUpperBounds'
removeLowerBounds :: AllowOlder -> DepResolverParams -> DepResolverParams
removeLowerBounds (AllowOlder RelaxDepsNone) params = params
removeLowerBounds (AllowOlder allowNewer) params =
params {
depResolverSourcePkgIndex = sourcePkgIndex'
}
where
sourcePkgIndex' = fmap relaxDeps $ depResolverSourcePkgIndex params
relaxDeps :: UnresolvedSourcePackage -> UnresolvedSourcePackage
relaxDeps srcPkg = srcPkg {
packageDescription = relaxPackageDeps removeLowerBound allowNewer
(packageDescription srcPkg)
}
-- | Relax the dependencies of this package if needed.
--
-- Helper function used by 'removeLowerBound' and 'removeUpperBounds'
relaxPackageDeps :: (VersionRange -> VersionRange)
-> RelaxDeps
-> PD.GenericPackageDescription -> PD.GenericPackageDescription
relaxPackageDeps _ RelaxDepsNone gpd = gpd
relaxPackageDeps vrtrans RelaxDepsAll gpd = PD.transformAllBuildDepends relaxAll gpd
where
relaxAll = \(Dependency pkgName verRange) ->
Dependency pkgName (vrtrans verRange)
relaxPackageDeps vrtrans (RelaxDepsSome allowNewerDeps') gpd =
PD.transformAllBuildDepends relaxSome gpd
where
thisPkgName = packageName gpd
allowNewerDeps = mapMaybe f allowNewerDeps'
f (RelaxedDep p) = Just p
f (RelaxedDepScoped scope p) | scope == thisPkgName = Just p
| otherwise = Nothing
relaxSome = \d@(Dependency depName verRange) ->
if depName `elem` allowNewerDeps
then Dependency depName (vrtrans verRange)
else d
-- | Supply defaults for packages without explicit Setup dependencies
--
-- Note: It's important to apply 'addDefaultSetupDepends' after
-- 'addSourcePackages'. Otherwise, the packages inserted by
-- 'addSourcePackages' won't have upper bounds in dependencies relaxed.
--
addDefaultSetupDependencies :: (UnresolvedSourcePackage -> Maybe [Dependency])
-> DepResolverParams -> DepResolverParams
addDefaultSetupDependencies defaultSetupDeps params =
params {
depResolverSourcePkgIndex =
fmap applyDefaultSetupDeps (depResolverSourcePkgIndex params)
}
where
applyDefaultSetupDeps :: UnresolvedSourcePackage -> UnresolvedSourcePackage
applyDefaultSetupDeps srcpkg =
srcpkg {
packageDescription = gpkgdesc {
PD.packageDescription = pkgdesc {
PD.setupBuildInfo =
case PD.setupBuildInfo pkgdesc of
Just sbi -> Just sbi
Nothing -> case defaultSetupDeps srcpkg of
Nothing -> Nothing
Just deps -> Just PD.SetupBuildInfo {
PD.defaultSetupDepends = True,
PD.setupDepends = deps
}
}
}
}
where
gpkgdesc = packageDescription srcpkg
pkgdesc = PD.packageDescription gpkgdesc
-- | If a package has a custom setup then we need to add a setup-depends
-- on Cabal.
--
addSetupCabalMinVersionConstraint :: Version
-> DepResolverParams -> DepResolverParams
addSetupCabalMinVersionConstraint minVersion =
addConstraints
[ LabeledPackageConstraint
(PackageConstraint (ScopeAnySetupQualifier cabalPkgname)
(PackagePropertyVersion $ orLaterVersion minVersion))
ConstraintSetupCabalMinVersion
]
where
cabalPkgname = mkPackageName "Cabal"
upgradeDependencies :: DepResolverParams -> DepResolverParams
upgradeDependencies = setPreferenceDefault PreferAllLatest
reinstallTargets :: DepResolverParams -> DepResolverParams
reinstallTargets params =
hideInstalledPackagesAllVersions (Set.toList $ depResolverTargets params) params
-- | A basic solver policy on which all others are built.
--
basicInstallPolicy :: InstalledPackageIndex
-> SourcePackageDb
-> [PackageSpecifier UnresolvedSourcePackage]
-> DepResolverParams
basicInstallPolicy
installedPkgIndex (SourcePackageDb sourcePkgIndex sourcePkgPrefs)
pkgSpecifiers
= addPreferences
[ PackageVersionPreference name ver
| (name, ver) <- Map.toList sourcePkgPrefs ]
. addConstraints
(concatMap pkgSpecifierConstraints pkgSpecifiers)
. addTargets
(map pkgSpecifierTarget pkgSpecifiers)
. hideInstalledPackagesSpecificBySourcePackageId
[ packageId pkg | SpecificSourcePackage pkg <- pkgSpecifiers ]
. addSourcePackages
[ pkg | SpecificSourcePackage pkg <- pkgSpecifiers ]
$ basicDepResolverParams
installedPkgIndex sourcePkgIndex
-- | The policy used by all the standard commands, install, fetch, freeze etc
-- (but not the new-build and related commands).
--
-- It extends the 'basicInstallPolicy' with a policy on setup deps.
--
standardInstallPolicy :: InstalledPackageIndex
-> SourcePackageDb
-> [PackageSpecifier UnresolvedSourcePackage]
-> DepResolverParams
standardInstallPolicy installedPkgIndex sourcePkgDb pkgSpecifiers
= addDefaultSetupDependencies mkDefaultSetupDeps
$ basicInstallPolicy
installedPkgIndex sourcePkgDb pkgSpecifiers
where
-- Force Cabal >= 1.24 dep when the package is affected by #3199.
mkDefaultSetupDeps :: UnresolvedSourcePackage -> Maybe [Dependency]
mkDefaultSetupDeps srcpkg | affected =
Just [Dependency (mkPackageName "Cabal")
(orLaterVersion $ mkVersion [1,24])]
| otherwise = Nothing
where
gpkgdesc = packageDescription srcpkg
pkgdesc = PD.packageDescription gpkgdesc
bt = fromMaybe PD.Custom (PD.buildType pkgdesc)
affected = bt == PD.Custom && hasBuildableFalse gpkgdesc
-- Does this package contain any components with non-empty 'build-depends'
-- and a 'buildable' field that could potentially be set to 'False'? False
-- positives are possible.
hasBuildableFalse :: PD.GenericPackageDescription -> Bool
hasBuildableFalse gpkg =
not (all alwaysTrue (zipWith PD.cOr buildableConditions noDepConditions))
where
buildableConditions = PD.extractConditions PD.buildable gpkg
noDepConditions = PD.extractConditions
(null . PD.targetBuildDepends) gpkg
alwaysTrue (PD.Lit True) = True
alwaysTrue _ = False
applySandboxInstallPolicy :: SandboxPackageInfo
-> DepResolverParams
-> DepResolverParams
applySandboxInstallPolicy
(SandboxPackageInfo modifiedDeps otherDeps allSandboxPkgs _allDeps)
params
= addPreferences [ PackageInstalledPreference n PreferInstalled
| n <- installedNotModified ]
. addTargets installedNotModified
. addPreferences
[ PackageVersionPreference (packageName pkg)
(thisVersion (packageVersion pkg)) | pkg <- otherDeps ]
. addConstraints
[ let pc = PackageConstraint
(scopeToplevel $ packageName pkg)
(PackagePropertyVersion $ thisVersion (packageVersion pkg))
in LabeledPackageConstraint pc ConstraintSourceModifiedAddSourceDep
| pkg <- modifiedDeps ]
. addTargets [ packageName pkg | pkg <- modifiedDeps ]
. hideInstalledPackagesSpecificBySourcePackageId
[ packageId pkg | pkg <- modifiedDeps ]
-- We don't need to add source packages for add-source deps to the
-- 'installedPkgIndex' since 'getSourcePackages' did that for us.
$ params
where
installedPkgIds =
map fst . InstalledPackageIndex.allPackagesBySourcePackageId
$ allSandboxPkgs
modifiedPkgIds = map packageId modifiedDeps
installedNotModified = [ packageName pkg | pkg <- installedPkgIds,
pkg `notElem` modifiedPkgIds ]
-- ------------------------------------------------------------
-- * Interface to the standard resolver
-- ------------------------------------------------------------
chooseSolver :: Verbosity -> PreSolver -> CompilerInfo -> IO Solver
chooseSolver _verbosity preSolver _cinfo =
case preSolver of
AlwaysModular -> do
return Modular
runSolver :: Solver -> SolverConfig -> DependencyResolver UnresolvedPkgLoc
runSolver Modular = modularResolver
-- | Run the dependency solver.
--
-- Since this is potentially an expensive operation, the result is wrapped in a
-- a 'Progress' structure that can be unfolded to provide progress information,
-- logging messages and the final result or an error.
--
resolveDependencies :: Platform
-> CompilerInfo
-> PkgConfigDb
-> Solver
-> DepResolverParams
-> Progress String String SolverInstallPlan
--TODO: is this needed here? see dontUpgradeNonUpgradeablePackages
resolveDependencies platform comp _pkgConfigDB _solver params
| Set.null (depResolverTargets params)
= return (validateSolverResult platform comp indGoals [])
where
indGoals = depResolverIndependentGoals params
resolveDependencies platform comp pkgConfigDB solver params =
Step (showDepResolverParams finalparams)
$ fmap (validateSolverResult platform comp indGoals)
$ runSolver solver (SolverConfig reordGoals cntConflicts
indGoals noReinstalls
shadowing strFlags allowBootLibs maxBkjumps enableBj
solveExes order verbosity)
platform comp installedPkgIndex sourcePkgIndex
pkgConfigDB preferences constraints targets
where
finalparams @ (DepResolverParams
targets constraints
prefs defpref
installedPkgIndex
sourcePkgIndex
reordGoals
cntConflicts
indGoals
noReinstalls
shadowing
strFlags
allowBootLibs
maxBkjumps
enableBj
solveExes
order
verbosity) =
if asBool (depResolverAllowBootLibInstalls params)
then params
else dontUpgradeNonUpgradeablePackages params
preferences = interpretPackagesPreference targets defpref prefs
-- | Give an interpretation to the global 'PackagesPreference' as
-- specific per-package 'PackageVersionPreference'.
--
interpretPackagesPreference :: Set PackageName
-> PackagesPreferenceDefault
-> [PackagePreference]
-> (PackageName -> PackagePreferences)
interpretPackagesPreference selected defaultPref prefs =
\pkgname -> PackagePreferences (versionPref pkgname)
(installPref pkgname)
(stanzasPref pkgname)
where
versionPref pkgname =
fromMaybe [anyVersion] (Map.lookup pkgname versionPrefs)
versionPrefs = Map.fromListWith (++)
[(pkgname, [pref])
| PackageVersionPreference pkgname pref <- prefs]
installPref pkgname =
fromMaybe (installPrefDefault pkgname) (Map.lookup pkgname installPrefs)
installPrefs = Map.fromList
[ (pkgname, pref)
| PackageInstalledPreference pkgname pref <- prefs ]
installPrefDefault = case defaultPref of
PreferAllLatest -> const PreferLatest
PreferAllInstalled -> const PreferInstalled
PreferLatestForSelected -> \pkgname ->
-- When you say cabal install foo, what you really mean is, prefer the
-- latest version of foo, but the installed version of everything else
if pkgname `Set.member` selected then PreferLatest
else PreferInstalled
stanzasPref pkgname =
fromMaybe [] (Map.lookup pkgname stanzasPrefs)
stanzasPrefs = Map.fromListWith (\a b -> nub (a ++ b))
[ (pkgname, pref)
| PackageStanzasPreference pkgname pref <- prefs ]
-- ------------------------------------------------------------
-- * Checking the result of the solver
-- ------------------------------------------------------------
-- | Make an install plan from the output of the dep resolver.
-- It checks that the plan is valid, or it's an error in the dep resolver.
--
validateSolverResult :: Platform
-> CompilerInfo
-> IndependentGoals
-> [ResolverPackage UnresolvedPkgLoc]
-> SolverInstallPlan
validateSolverResult platform comp indepGoals pkgs =
case planPackagesProblems platform comp pkgs of
[] -> case SolverInstallPlan.new indepGoals graph of
Right plan -> plan
Left problems -> error (formatPlanProblems problems)
problems -> error (formatPkgProblems problems)
where
graph = Graph.fromDistinctList pkgs
formatPkgProblems = formatProblemMessage . map showPlanPackageProblem
formatPlanProblems = formatProblemMessage . map SolverInstallPlan.showPlanProblem
formatProblemMessage problems =
unlines $
"internal error: could not construct a valid install plan."
: "The proposed (invalid) plan contained the following problems:"
: problems
++ "Proposed plan:"
: [SolverInstallPlan.showPlanIndex pkgs]
data PlanPackageProblem =
InvalidConfiguredPackage (SolverPackage UnresolvedPkgLoc)
[PackageProblem]
| DuplicatePackageSolverId SolverId [ResolverPackage UnresolvedPkgLoc]
showPlanPackageProblem :: PlanPackageProblem -> String
showPlanPackageProblem (InvalidConfiguredPackage pkg packageProblems) =
"Package " ++ display (packageId pkg)
++ " has an invalid configuration, in particular:\n"
++ unlines [ " " ++ showPackageProblem problem
| problem <- packageProblems ]
showPlanPackageProblem (DuplicatePackageSolverId pid dups) =
"Package " ++ display (packageId pid) ++ " has "
++ show (length dups) ++ " duplicate instances."
planPackagesProblems :: Platform -> CompilerInfo
-> [ResolverPackage UnresolvedPkgLoc]
-> [PlanPackageProblem]
planPackagesProblems platform cinfo pkgs =
[ InvalidConfiguredPackage pkg packageProblems
| Configured pkg <- pkgs
, let packageProblems = configuredPackageProblems platform cinfo pkg
, not (null packageProblems) ]
++ [ DuplicatePackageSolverId (Graph.nodeKey (head dups)) dups
| dups <- duplicatesBy (comparing Graph.nodeKey) pkgs ]
data PackageProblem = DuplicateFlag PD.FlagName
| MissingFlag PD.FlagName
| ExtraFlag PD.FlagName
| DuplicateDeps [PackageId]
| MissingDep Dependency
| ExtraDep PackageId
| InvalidDep Dependency PackageId
showPackageProblem :: PackageProblem -> String
showPackageProblem (DuplicateFlag flag) =
"duplicate flag in the flag assignment: " ++ PD.unFlagName flag
showPackageProblem (MissingFlag flag) =
"missing an assignment for the flag: " ++ PD.unFlagName flag
showPackageProblem (ExtraFlag flag) =
"extra flag given that is not used by the package: " ++ PD.unFlagName flag
showPackageProblem (DuplicateDeps pkgids) =
"duplicate packages specified as selected dependencies: "
++ intercalate ", " (map display pkgids)
showPackageProblem (MissingDep dep) =
"the package has a dependency " ++ display dep
++ " but no package has been selected to satisfy it."
showPackageProblem (ExtraDep pkgid) =
"the package configuration specifies " ++ display pkgid
++ " but (with the given flag assignment) the package does not actually"
++ " depend on any version of that package."
showPackageProblem (InvalidDep dep pkgid) =
"the package depends on " ++ display dep
++ " but the configuration specifies " ++ display pkgid
++ " which does not satisfy the dependency."
-- | A 'ConfiguredPackage' is valid if the flag assignment is total and if
-- in the configuration given by the flag assignment, all the package
-- dependencies are satisfied by the specified packages.
--
configuredPackageProblems :: Platform -> CompilerInfo
-> SolverPackage UnresolvedPkgLoc -> [PackageProblem]
configuredPackageProblems platform cinfo
(SolverPackage pkg specifiedFlags stanzas specifiedDeps' _specifiedExeDeps') =
[ DuplicateFlag flag | ((flag,_):_) <- duplicates specifiedFlags ]
++ [ MissingFlag flag | OnlyInLeft flag <- mergedFlags ]
++ [ ExtraFlag flag | OnlyInRight flag <- mergedFlags ]
++ [ DuplicateDeps pkgs
| pkgs <- CD.nonSetupDeps (fmap (duplicatesBy (comparing packageName))
specifiedDeps) ]
++ [ MissingDep dep | OnlyInLeft dep <- mergedDeps ]
++ [ ExtraDep pkgid | OnlyInRight pkgid <- mergedDeps ]
++ [ InvalidDep dep pkgid | InBoth dep pkgid <- mergedDeps
, not (packageSatisfiesDependency pkgid dep) ]
-- TODO: sanity tests on executable deps
where
specifiedDeps :: ComponentDeps [PackageId]
specifiedDeps = fmap (map solverSrcId) specifiedDeps'
mergedFlags = mergeBy compare
(sort $ map PD.flagName (PD.genPackageFlags (packageDescription pkg)))
(sort $ map fst specifiedFlags)
packageSatisfiesDependency
(PackageIdentifier name version)
(Dependency name' versionRange) = assert (name == name') $
version `withinRange` versionRange
dependencyName (Dependency name _) = name
mergedDeps :: [MergeResult Dependency PackageId]
mergedDeps = mergeDeps requiredDeps (CD.flatDeps specifiedDeps)
mergeDeps :: [Dependency] -> [PackageId]
-> [MergeResult Dependency PackageId]
mergeDeps required specified =
let sortNubOn f = nubBy ((==) `on` f) . sortBy (compare `on` f) in
mergeBy
(\dep pkgid -> dependencyName dep `compare` packageName pkgid)
(sortNubOn dependencyName required)
(sortNubOn packageName specified)
-- TODO: It would be nicer to use ComponentDeps here so we can be more
-- precise in our checks. That's a bit tricky though, as this currently
-- relies on the 'buildDepends' field of 'PackageDescription'. (OTOH, that
-- field is deprecated and should be removed anyway.) As long as we _do_
-- use a flat list here, we have to allow for duplicates when we fold
-- specifiedDeps; once we have proper ComponentDeps here we should get rid
-- of the `nubOn` in `mergeDeps`.
requiredDeps :: [Dependency]
requiredDeps =
--TODO: use something lower level than finalizePD
case finalizePD specifiedFlags
(enableStanzas stanzas)
(const True)
platform cinfo
[]
(packageDescription pkg) of
Right (resolvedPkg, _) ->
externalBuildDepends resolvedPkg
++ maybe [] PD.setupDepends (PD.setupBuildInfo resolvedPkg)
Left _ ->
error "configuredPackageInvalidDeps internal error"
-- ------------------------------------------------------------
-- * Simple resolver that ignores dependencies
-- ------------------------------------------------------------
-- | A simplistic method of resolving a list of target package names to
-- available packages.
--
-- Specifically, it does not consider package dependencies at all. Unlike
-- 'resolveDependencies', no attempt is made to ensure that the selected
-- packages have dependencies that are satisfiable or consistent with
-- each other.
--
-- It is suitable for tasks such as selecting packages to download for user
-- inspection. It is not suitable for selecting packages to install.
--
-- Note: if no installed package index is available, it is OK to pass 'mempty'.
-- It simply means preferences for installed packages will be ignored.
--
resolveWithoutDependencies :: DepResolverParams
-> Either [ResolveNoDepsError] [UnresolvedSourcePackage]
resolveWithoutDependencies (DepResolverParams targets constraints
prefs defpref installedPkgIndex sourcePkgIndex
_reorderGoals _countConflicts _indGoals _avoidReinstalls
_shadowing _strFlags _maxBjumps _enableBj
_solveExes _allowBootLibInstalls _order _verbosity) =
collectEithers $ map selectPackage (Set.toList targets)
where
selectPackage :: PackageName -> Either ResolveNoDepsError UnresolvedSourcePackage
selectPackage pkgname
| null choices = Left $! ResolveUnsatisfiable pkgname requiredVersions
| otherwise = Right $! maximumBy bestByPrefs choices
where
-- Constraints
requiredVersions = packageConstraints pkgname
pkgDependency = Dependency pkgname requiredVersions
choices = PackageIndex.lookupDependency sourcePkgIndex
pkgDependency
-- Preferences
PackagePreferences preferredVersions preferInstalled _
= packagePreferences pkgname
bestByPrefs = comparing $ \pkg ->
(installPref pkg, versionPref pkg, packageVersion pkg)
installPref = case preferInstalled of
PreferLatest -> const False
PreferInstalled -> not . null
. InstalledPackageIndex.lookupSourcePackageId
installedPkgIndex
. packageId
versionPref pkg = length . filter (packageVersion pkg `withinRange`) $
preferredVersions
packageConstraints :: PackageName -> VersionRange
packageConstraints pkgname =
Map.findWithDefault anyVersion pkgname packageVersionConstraintMap
packageVersionConstraintMap =
let pcs = map unlabelPackageConstraint constraints
in Map.fromList [ (scopeToPackageName scope, range)
| PackageConstraint
scope (PackagePropertyVersion range) <- pcs ]
packagePreferences :: PackageName -> PackagePreferences
packagePreferences = interpretPackagesPreference targets defpref prefs
collectEithers :: [Either a b] -> Either [a] [b]
collectEithers = collect . partitionEithers
where
collect ([], xs) = Right xs
collect (errs,_) = Left errs
partitionEithers :: [Either a b] -> ([a],[b])
partitionEithers = foldr (either left right) ([],[])
where
left a (l, r) = (a:l, r)
right a (l, r) = (l, a:r)
-- | Errors for 'resolveWithoutDependencies'.
--
data ResolveNoDepsError =
-- | A package name which cannot be resolved to a specific package.
-- Also gives the constraint on the version and whether there was
-- a constraint on the package being installed.
ResolveUnsatisfiable PackageName VersionRange
instance Show ResolveNoDepsError where
show (ResolveUnsatisfiable name ver) =
"There is no available version of " ++ display name
++ " that satisfies " ++ display (simplifyVersionRange ver)
|
mydaum/cabal
|
cabal-install/Distribution/Client/Dependency.hs
|
bsd-3-clause
| 40,415
| 1
| 33
| 9,930
| 6,740
| 3,647
| 3,093
| 688
| 4
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
-- | PlotBase provide the basic functions to build Plots
module EFA.Signal.Plot (
run,
signal,
signalFrameAttr,
heatmap, xyzrange3d, cbrange, xyzlabel, xyzlabelnode, depthorder,
paletteGH, paletteGray, paletteHSV, missing, contour,
Signal,
Value,
Labeled, label,
xy,
xyBasic,
xyStyle,
xyFrameAttr,
XY,
surface,
Surface,
record,
recordFrameAttr,
recordList,
sequence,
stack,
stackFrameAttr,
stacks,
stacksFrameAttr,
getData,
genAxLabel
) where
import qualified EFA.Signal.Sequence as Sequ
import qualified EFA.Signal.Signal as S
import qualified EFA.Signal.Data as D
import qualified EFA.Signal.Vector as SV
import qualified EFA.Signal.Record as Record
import qualified EFA.Signal.Colour as Colour
import EFA.Signal.Record (Record(Record))
import EFA.Signal.Signal (TC, toSigList, getDisplayType)
import EFA.Signal.Data (Data, (:>), Nil, NestedList)
import qualified EFA.Equation.Arithmetic as Arith
import EFA.Equation.Arithmetic (Sum, (~*), Constant)
import qualified EFA.Graph.Topology.Node as Node
import EFA.Report.Typ
(TDisp, DisplayType(Typ_T), getDisplayUnit, getDisplayTypName)
import EFA.Report.Base (UnitScale(UnitScale), getUnitScale)
import qualified EFA.Report.Format as Format
import EFA.Report.FormatValue (FormatValue, formatValue)
import EFA.Utility.Show (showNode)
import qualified Graphics.Gnuplot.Advanced as Plot
import qualified Graphics.Gnuplot.Terminal as Terminal
import qualified Graphics.Gnuplot.Plot as Plt
import qualified Graphics.Gnuplot.Plot.TwoDimensional as Plot2D
import qualified Graphics.Gnuplot.Plot.ThreeDimensional as Plot3D
import qualified Graphics.Gnuplot.Graph.TwoDimensional as Graph2D
import qualified Graphics.Gnuplot.Graph.ThreeDimensional as Graph3D
import qualified Graphics.Gnuplot.Graph as Graph
import qualified Graphics.Gnuplot.Value.Atom as Atom
import qualified Graphics.Gnuplot.Value.Tuple as Tuple
import qualified Graphics.Gnuplot.LineSpecification as LineSpec
import qualified Graphics.Gnuplot.ColorSpecification as ColourSpec
import qualified Graphics.Gnuplot.Frame as Frame
import qualified Graphics.Gnuplot.Frame.Option as Opt
import qualified Graphics.Gnuplot.Frame.OptionSet as Opts
import qualified Graphics.Gnuplot.Frame.OptionSet.Style as OptsStyle
import qualified Graphics.Gnuplot.Frame.OptionSet.Histogram as Histogram
import qualified Data.Map as Map
import qualified Data.List as List
import qualified Data.Foldable as Fold
import qualified Data.List.Key as Key
import Data.Map (Map)
import Control.Functor.HT (void)
import Data.Foldable (foldMap)
import Data.Monoid (mconcat)
import Prelude hiding (sequence)
-- | Generic IO Commands ---------------------------------------------------------------
run ::
(Terminal.C term, Graph.C graph) =>
term -> Opts.T graph -> Plt.T graph -> IO ()
run terminal frameAttr plt =
void $ Plot.plotSync terminal $ Frame.cons frameAttr plt
{-
-- | Example how to generate frame attributes
frameAttr ::
(AxisLabel tc, Graph.C graph) =>
String -> tc -> Opts.T graph
framAttr ti x =
Opts.title ti $
Opts.xLabel "Signal Index []" $
Opts.yLabel (genAxLabel x) $
Opts.grid True $
Opts.deflt
-}
-- | Class to generate Axis Labels
class Atom.C (Value tc) => AxisLabel tc where
type Value tc :: *
genAxLabel :: tc -> String
instance (TDisp t, Atom.C (D.Value c)) => AxisLabel (TC s t c) where
type Value (TC s t c) = D.Value c
genAxLabel x =
let dispType = getDisplayType x
in getDisplayTypName dispType ++
" [" ++ (show $ getDisplayUnit dispType) ++ "]"
instance (AxisLabel tc) => AxisLabel [tc] where
type Value [tc] = Value tc
genAxLabel x = genAxLabel $ head x
-- | Get Signal Plot Data (Unit Conversion) ---------------------------------------------------------------
getData ::
(TDisp typ, D.FromList c, D.Map c, D.Storage c a, Constant a) =>
TC s typ (Data c a) -> NestedList c a
getData x = S.toList $ S.map (~* Arith.fromRational s) x
where (UnitScale s) = getUnitScale $ getDisplayUnit $ getDisplayType x
-- | Function to simplify linecolor setting
lineColour :: Colour.Name -> LineSpec.T -> LineSpec.T
lineColour = LineSpec.lineColor . ColourSpec.name . Colour.unpackName
-- | Simple Signal Plotting -- plot signal values against signal index --------------------------------------------------------------
-- | All styles can be overloaded by opts
signalFrameAttr ::
(AxisLabel tc, Graph.C graph) =>
String -> tc -> Opts.T graph
signalFrameAttr ti x =
Opts.title ti $
Opts.xLabel "Signal Index []" $
Opts.yLabel (genAxLabel x) $
Opts.grid True $
Opts.deflt
signalStyle :: (LineSpec.T -> LineSpec.T) -> Graph2D.T x y -> Graph2D.T x y
signalStyle opts =
Graph2D.lineSpec $
{- not supported by "lines" style
LineSpec.pointSize 2 $
-}
opts $ -- default settings can be overloaded here
LineSpec.lineWidth 1 $
LineSpec.deflt
class AxisLabel tc => Signal tc where
signal :: (LineSpec.T -> LineSpec.T) -> tc -> Plot2D.T Int (Value tc)
instance
(TDisp t, SV.Walker v1, SV.FromList v1, SV.Storage v1 y,
Atom.C y, Tuple.C y, Constant y) =>
Signal (TC s t (Data (v1 :> Nil) y)) where
signal opts x =
fmap (signalStyle opts) $ Plot2D.list Graph2D.listLines $ getData x
-- | Plotting Signals against each other, can be also used for time plots and curves over power -----------------------------
xyFrameAttr ::
(AxisLabel tcX, AxisLabel tcY, Graph.C graph) =>
String -> tcX -> tcY -> Opts.T graph
xyFrameAttr ti x y =
Opts.title ti $
Opts.add (Opt.custom "hidden3d" "") ["back offset 1 trianglepattern 3 undefined 1 altdiagonal bentover"] $
Opts.xLabel (genAxLabel x) $
Opts.yLabel (genAxLabel y) $
Opts.grid True $
Opts.deflt
xyLineSpec :: LineSpec.T
xyLineSpec =
LineSpec.pointSize 0.1 $
LineSpec.pointType 7 $
LineSpec.lineWidth 1 $
LineSpec.deflt
heatmap :: (Graph.C graph) => Opts.T graph -> Opts.T graph
heatmap =
Opts.add (Opt.custom "view" "") ["map"] .
Opts.add (Opt.custom "pm3d" "") ["at b"]
contour :: (Graph.C graph) => Opts.T graph -> Opts.T graph
contour =
Opts.add (Opt.custom "contour" "") ["base"]
. Opts.add (Opt.custom "cntrparam" "") ["bspline"]
. Opts.add (Opt.custom "cntrparam" "") ["levels auto 10"]
missing ::
String -> Opts.T graph -> Opts.T graph
missing str =
Opts.add (Opt.custom "datafile" "") ["missing " ++ show str]
xyzrange3d ::
(Tuple.C x, Atom.C x,
Tuple.C y, Atom.C y,
Tuple.C z, Atom.C z) =>
(x, x) -> (y, y) -> (z, z) ->
Opts.T (Graph3D.T x y z) -> Opts.T (Graph3D.T x y z)
xyzrange3d xr yr zr =
Opts.xRange3d xr .
Opts.yRange3d yr .
Opts.zRange3d zr
cbrange ::
(Tuple.C x, Atom.C x,
Tuple.C y, Atom.C y,
Tuple.C z, Atom.C z,
Show a) =>
(a, a) ->
Opts.T (Graph3D.T x y z) -> Opts.T (Graph3D.T x y z)
cbrange (l, h) =
Opts.add (Opt.custom "cbrange" "") ["[" ++ show l ++ ":" ++ show h ++ "]"]
xyzlabel ::
(Atom.C x, Atom.C y, Atom.C z) =>
String -> String -> String ->
Opts.T (Graph3D.T x y z) -> Opts.T (Graph3D.T x y z)
xyzlabel xstr ystr zstr =
Opts.xLabel xstr .
Opts.yLabel ystr .
Opts.zLabel zstr
xyzlabelnode ::
(Atom.C x, Atom.C y, Atom.C z, Node.C node) =>
(Maybe node) -> (Maybe node) -> (Maybe node) ->
Opts.T (Graph3D.T x y z) -> Opts.T (Graph3D.T x y z)
xyzlabelnode xnode ynode znode =
Opts.xLabel (f xnode) .
Opts.yLabel (f ynode) .
Opts.zLabel (f znode)
where f = maybe "" showNode
paletteGH ::
(Graph.C graph) => Opts.T graph -> Opts.T graph
paletteGH = Opts.add (Opt.custom "palette" "")
["defined (0 \"#000044\", 1 \"#336dbf\", 2 \"#3dafe2\", 3 \"#21bced\", 4 \"#87d6f9\", 5 \"#f9af60\", 6 \"#f9af60\", 7 \"#ffaa00\")"]
paletteGray ::
(Graph.C graph) => Opts.T graph -> Opts.T graph
paletteGray =
Opts.add (Opt.custom "palette" "") ["defined ( 0 0 0 0, 1 1 1 1 )"]
paletteHSV ::
(Graph.C graph) => Opts.T graph -> Opts.T graph
paletteHSV =
Opts.add (Opt.custom "palette" "") ["model HSV defined ( 0 0 1 1, 1 1 1 1 )"]
depthorder ::
(Graph.C graph) => Opts.T graph -> Opts.T graph
depthorder =
Opts.add (Opt.custom "pm3d" "") ["depthorder"]
data Labeled tc = Labeled String tc
label :: String -> tc -> Labeled tc
label = Labeled
instance (AxisLabel tc) => AxisLabel (Labeled tc) where
type Value (Labeled tc) = Value tc
genAxLabel (Labeled _lab x) = genAxLabel x
xyStyle ::
(LineSpec.T -> LineSpec.T) -> Plot2D.T x y -> Plot2D.T x y
xyStyle opts =
fmap $ Graph2D.lineSpec $
opts $
LineSpec.pointSize 0.1 $
LineSpec.pointType 7 $
LineSpec.lineWidth 1 $
LineSpec.deflt
class (AxisLabel tcX, AxisLabel tcY) => XY tcX tcY where
xy ::
(LineSpec.T -> LineSpec.T) ->
tcX -> tcY -> Plot2D.T (Value tcX) (Value tcY)
xyBasic ::
(TDisp t1, SV.Walker v1, SV.FromList v1, SV.Storage v1 x,
TDisp t2, SV.Walker v2, SV.FromList v2, SV.Storage v2 y,
Atom.C x, Tuple.C x, Constant x,
Atom.C y, Tuple.C y, Constant y) =>
(LineSpec.T -> LineSpec.T) ->
TC s t1 (Data (v1 :> Nil) x) ->
TC s t2 (Data (v2 :> Nil) y) ->
Plot2D.T x y
xyBasic opts x y =
fmap (Graph2D.lineSpec $ opts xyLineSpec) $
Plot2D.list Graph2D.lines $ zip (getData x) (getData y)
xyLabeled ::
(TDisp t1, SV.Walker v1, SV.FromList v1, SV.Storage v1 x,
TDisp t2, SV.Walker v2, SV.FromList v2, SV.Storage v2 y,
Atom.C x, Tuple.C x, Constant x,
Atom.C y, Tuple.C y, Constant y) =>
(LineSpec.T -> LineSpec.T) ->
TC s t1 (Data (v1 :> Nil) x) ->
Labeled (TC s t2 (Data (v2 :> Nil) y)) ->
Plot2D.T x y
xyLabeled opts x (Labeled lab y) =
xyBasic (LineSpec.title lab . opts) x y
instance
(TDisp t1, SV.Walker v1, SV.FromList v1, SV.Storage v1 x,
TDisp t2, SV.Walker v2, SV.FromList v2, SV.Storage v2 y,
Atom.C x, Tuple.C x, Constant x,
Atom.C y, Tuple.C y, Constant y) =>
XY (TC s t1 (Data (v1 :> Nil) x))
(Labeled (TC s t2 (Data (v2 :> Nil) y))) where
xy = xyLabeled
instance
( TDisp t1, SV.Walker v1, SV.FromList v1, SV.Storage v1 x,
TDisp t2, SV.Walker v2, SV.FromList v2, SV.Storage v2 y,
Atom.C x, Tuple.C x, Constant x,
Atom.C y, Tuple.C y, Constant y ) =>
XY (TC s t1 (Data (v1 :> Nil) x))
[Labeled (TC s t2 (Data (v2 :> Nil) y))] where
xy opts x = foldMap (xyLabeled opts x)
instance
(TDisp t1, SV.Walker v1, SV.FromList v1, SV.Storage v1 x,
TDisp t2, SV.Walker v2, SV.FromList v2, SV.Storage v2 y,
Atom.C x, Tuple.C x, Constant x,
Atom.C y, Tuple.C y, Constant y) =>
XY [TC s t1 (Data (v1 :> Nil) x)]
[Labeled (TC s t2 (Data (v2 :> Nil) y))] where
xy opts xs ys =
mconcat $ zipWith (xyLabeled opts) xs ys
instance
(TDisp t1, SV.Walker v1,
TDisp t2, SV.Walker v3,
SV.FromList v1, SV.Storage v1 x,
SV.FromList v3, SV.Storage v3 y,
SV.FromList v2, SV.Storage v2 (v1 x),
SV.FromList v4, SV.Storage v4 (v3 y),
Atom.C x, Tuple.C x, Constant x,
Atom.C y, Tuple.C y, Constant y) =>
XY
(TC s t1 (Data (v2 :> v1 :> Nil) x))
(Labeled (TC s t2 (Data (v4 :> v3 :> Nil) y))) where
xy opts xs (Labeled lab ys) =
mconcat $
zipWith
(\x y -> xyLabeled opts x (Labeled lab y))
(toSigList xs) (toSigList ys)
-- | Plotting Records ---------------------------------------------------------------
recordFrameAttr ::
(Graph.C graph) =>
String -> Opts.T graph
recordFrameAttr ti =
Opts.title (ti) $
Opts.grid True $
Opts.xLabel ("Time [" ++ (show $ getDisplayUnit Typ_T) ++ "]") $
Opts.yLabel ("")
Opts.deflt
recordLineSpec :: LineSpec.T
recordLineSpec =
LineSpec.pointSize 0.3$
LineSpec.pointType 1 $
LineSpec.lineWidth 1.6 $
LineSpec.deflt
record ::
(Ord id, TDisp typ1, TDisp typ2,
SV.Walker v, SV.FromList v,
SV.Storage v d1, Constant d1, Atom.C d1, Tuple.C d1,
SV.Storage v d2, Constant d2, Atom.C d2, Tuple.C d2) =>
(id -> String) ->
(LineSpec.T -> LineSpec.T) ->
Record s1 s2 typ1 typ2 id v d1 d2 -> Plot2D.T d1 d2
record showKey opts (Record time pMap) =
Fold.fold $
Map.mapWithKey
(\key (col, sig) ->
fmap
(Graph2D.lineSpec
(opts $ LineSpec.title (showKey key) $
lineColour col $ recordLineSpec)) $
Plot2D.list Graph2D.linesPoints $
zip (getData time) (getData sig)) $
Colour.adorn pMap
recordList ::
(Ord id, TDisp typ1, TDisp typ2,
SV.Walker v, SV.FromList v,
SV.Storage v d1, Constant d1, Atom.C d1, Tuple.C d1,
SV.Storage v d2, Constant d2, Atom.C d2, Tuple.C d2) =>
(id -> String) ->
(LineSpec.T -> LineSpec.T) ->
(Int -> LineSpec.T -> LineSpec.T) ->
[(Record.Name, Record s1 s2 typ1 typ2 id v d1 d2)] -> Plot2D.T d1 d2
recordList showKey opts varOpts xs =
Fold.fold $ zipWith (\(Record.Name name,x) k -> record (\ key -> name ++ "-" ++ showKey key) ((varOpts k). opts) x) xs [0..]
-- | Plotting Sequences ---------------------------------------------------------------
sequence :: (Constant d2, Constant d1, Ord id,
SV.Walker v, SV.Storage v d2,
SV.Storage v d1, SV.FromList v, TDisp typ1,
TDisp typ2, Atom.C d2, Atom.C d1, Tuple.C d2,
Tuple.C d1) =>
(id -> String) ->
(LineSpec.T -> LineSpec.T) ->
(Int -> LineSpec.T -> LineSpec.T) ->
Sequ.List (Record s1 s2 typ1 typ2 id v d1 d2) ->
Plot2D.T d1 d2
sequence showKey opts varOpts (Sequ.List xs) =
Fold.fold $ zipWith (\(Sequ.Section s _ x) k -> record (\key -> show "Sec " ++ show s ++ "-" ++ showKey key) ((varOpts k). opts) x) xs [0..]
-- | Plotting Stacks ---------------------------------------------------------------
stackFrameAttr ::
String -> Format.ASCII -> Opts.T (Graph2D.T Int Double)
stackFrameAttr title var =
Opts.title title $
Histogram.rowstacked $
OptsStyle.fillBorderLineType (-1) $
OptsStyle.fillSolid $
Opts.keyOutside $
Opts.xTicks2d [(Format.unASCII var, 0)] $
Opts.deflt
stackLineSpec ::
(FormatValue term) =>
term -> Colour.Name -> Plot2D.T x y -> Plot2D.T x y
stackLineSpec term colour =
fmap (Graph2D.lineSpec (LineSpec.title (Format.unASCII $ formatValue term)
(lineColour colour $ LineSpec.deflt)))
stack ::
(FormatValue term, Ord term,
Sum d, Ord d, Atom.C d, Tuple.C d) =>
Map term d -> Plot2D.T Int d
stack =
foldMap
(\(col, (term, val)) ->
stackLineSpec term col $
Plot2D.list Graph2D.histograms [val]) .
Colour.adorn .
Key.sort (Arith.negate . Arith.abs . snd) .
Map.toList
stacksFrameAttr ::
String -> [Format.ASCII] -> Opts.T (Graph2D.T Int Double)
stacksFrameAttr title vars =
Opts.title title $
Histogram.rowstacked $
OptsStyle.fillBorderLineType (-1) $
OptsStyle.fillSolid $
Opts.keyOutside $
Opts.boxwidthAbsolute 0.9 $
Opts.xTicks2d (zip (map Format.unASCII vars) [0..]) $
Opts.deflt
stacks ::
(FormatValue term, Ord term,
Sum d, Ord d, Atom.C d, Tuple.C d) =>
Map term [d] -> Plot2D.T Int d
stacks =
foldMap
(\(col, (term, vals)) ->
stackLineSpec term col $
Plot2D.list Graph2D.histograms vals) .
Colour.adorn .
Key.sort (Arith.negate . maximum . map Arith.abs . snd) .
Map.toList
-- | Plotting Surfaces -------------------------------------------------------------------------
surfaceLineSpec :: LineSpec.T
surfaceLineSpec =
LineSpec.pointSize 0.1 $
LineSpec.pointType 7 $
LineSpec.lineWidth 1 $
LineSpec.deflt
surfaceBasic ::
(Constant a2, Constant a1, Constant a, D.FromList c2,
D.FromList c1, D.FromList c, D.Map c2, D.Map c1, D.Map c,
D.Storage c2 a2, D.Storage c1 a1, D.Storage c a, TDisp typ2,
TDisp typ1, TDisp typ, Atom.C z, Atom.C y, Atom.C x, Tuple.C z,
Tuple.C y, Tuple.C x, NestedList c2 a2 ~ [[z]],
NestedList c1 a1 ~ [[y]], NestedList c a ~ [[x]]) =>
(LineSpec.T -> LineSpec.T) ->
TC s typ (Data c a) ->
TC s1 typ1 (Data c1 a1) ->
TC s2 typ2 (Data c2 a2) ->
Plot3D.T x y z
surfaceBasic opts x y z =
fmap (Graph3D.lineSpec (opts surfaceLineSpec)) $
Plot3D.mesh $ List.zipWith3 zip3 (getData x) (getData y) (getData z)
class
(AxisLabel tcX, AxisLabel tcY, AxisLabel tcZ) =>
Surface tcX tcY tcZ where
surface ::
(LineSpec.T -> LineSpec.T) ->
tcX -> tcY -> tcZ -> Plot3D.T (Value tcX) (Value tcY) (Value tcZ)
instance
( Constant x, Constant y, Constant z,
SV.Walker v2, SV.Walker v1, SV.Walker v4, SV.Walker v3,
SV.Walker v6, SV.Walker v5, SV.FromList v1,
SV.Storage v1 x, SV.FromList v2, SV.Storage v2 (v1 x), TDisp t1,
SV.FromList v3, SV.Storage v3 y, SV.FromList v4, SV.Storage v4 (v3 y), TDisp t2,
SV.FromList v5, SV.Storage v5 z, SV.FromList v6, SV.Storage v6 (v5 z), TDisp t3,
Atom.C x, Tuple.C x,
Atom.C y, Tuple.C y,
Atom.C z, Tuple.C z) =>
Surface
(TC s1 t1 (Data (v2 :> v1 :> Nil) x))
(TC s2 t2 (Data (v4 :> v3 :> Nil) y))
(TC s3 t3 (Data (v6 :> v5 :> Nil) z)) where
surface = surfaceBasic
instance
( Constant x, Constant y, Constant z,
SV.Walker v2, SV.Walker v1, SV.Walker v4, SV.Walker v3,
SV.Walker v6, SV.Walker v5, SV.FromList v1,
SV.Storage v1 x, SV.FromList v2, SV.Storage v2 (v1 x), TDisp t1,
SV.FromList v3, SV.Storage v3 y, SV.FromList v4, SV.Storage v4 (v3 y), TDisp t2,
SV.FromList v5, SV.Storage v5 z, SV.FromList v6, SV.Storage v6 (v5 z), TDisp t3,
Atom.C x, Tuple.C x,
Atom.C y, Tuple.C y,
Atom.C z, Tuple.C z) =>
Surface
(TC s1 t1 (Data (v2 :> v1 :> Nil) x))
(TC s2 t2 (Data (v4 :> v3 :> Nil) y))
(Labeled (TC s3 t3 (Data (v6 :> v5 :> Nil) z))) where
surface opts x y (Labeled lab z) =
surfaceBasic (LineSpec.title lab . opts) x y z
instance
( Constant x, Constant y, Constant z,
SV.Walker v2, SV.Walker v1, SV.Walker v4,
SV.Walker v3, SV.Walker v6, SV.Walker v5,
SV.FromList v1, SV.Storage v1 x, SV.FromList v2, SV.Storage v2 (v1 x), TDisp t1,
SV.FromList v3, SV.Storage v3 y, SV.FromList v4, SV.Storage v4 (v3 y), TDisp t2,
SV.FromList v5, SV.Storage v5 z, SV.FromList v6, SV.Storage v6 (v5 z), TDisp t3,
Atom.C x, Tuple.C x,
Atom.C y, Tuple.C y,
Atom.C z, Tuple.C z) =>
Surface
(TC s1 t1 (Data (v2 :> v1 :> Nil) x))
(TC s2 t2 (Data (v4 :> v3 :> Nil) y))
[TC s3 t3 (Data (v6 :> v5 :> Nil) z)] where
surface opts x y =
foldMap (surfaceBasic opts x y)
instance
( Constant x, Constant y, Constant z,
SV.Walker v2, SV.Walker v1, SV.Walker v4,
SV.Walker v3, SV.Walker v6, SV.Walker v5,
SV.FromList v1, SV.Storage v1 x, SV.FromList v2, SV.Storage v2 (v1 x), TDisp t1,
SV.FromList v3, SV.Storage v3 y, SV.FromList v4, SV.Storage v4 (v3 y), TDisp t2,
SV.FromList v5, SV.Storage v5 z, SV.FromList v6, SV.Storage v6 (v5 z), TDisp t3,
Atom.C x, Tuple.C x,
Atom.C y, Tuple.C y,
Atom.C z, Tuple.C z) =>
Surface
(TC s1 t1 (Data (v2 :> v1 :> Nil) x))
(TC s2 t2 (Data (v4 :> v3 :> Nil) y))
[Labeled (TC s3 t3 (Data (v6 :> v5 :> Nil) z))] where
surface opts x y =
foldMap
(\ (Labeled lab z) ->
surfaceBasic (LineSpec.title lab . opts) x y z)
|
energyflowanalysis/efa-2.1
|
src/EFA/Signal/Plot.hs
|
bsd-3-clause
| 19,574
| 0
| 21
| 4,462
| 7,986
| 4,151
| 3,835
| 487
| 1
|
module ResultsParsing where
import Text.HTML.TagSoup
import Text.HTML.TagSoup.Tree
import Text.HTML.TagSoup.Tree.Selection
import Data.List.Split
import Data.List
import Text.CSS3.Selectors.Parser
import Text.HTML.TagSoup.Tree.Zipper
import Text.CSS3.Selectors.Syntax
import Data.Maybe
import Text.Read
import PriceParsing (parsePrice)
data PropertyDetails = PropertyDetails { bedroomsAsString :: Maybe String
, bathroomsAsString :: Maybe String
, carsAsString :: Maybe String
, bedrooms :: Int
, bathrooms :: Int
, cars :: Int
} deriving (Show)
data ParsedProperty = ParsedProperty
{ details :: PropertyDetails
, location :: String
, link :: String
, price :: Maybe Int
, priceAsText :: Maybe String
} deriving (Show)
parsePage :: String -> [ParsedProperty]
parsePage content =
fromMaybe [] maybeProperties
where
tagTree = parseTree content
maybeBodyTree = find hasListings tagTree
maybeListingTrees = fmap listings maybeBodyTree
maybeProperties = fmap (concatMap parseListing) maybeListingTrees
parseListing :: TagTreePos String -> [ParsedProperty]
parseListing listingTree =
fmap (`combineData` address) details
where
address :: String
address = addressFromListingTree listingTree
details :: [(PropertyDetails, Maybe String, String)]
details = detailsFromListingTree listingTree
combineData :: (PropertyDetails, Maybe String, String) -> String -> ParsedProperty
combineData (propertyDetails, maybePriceAsText, link) address =
ParsedProperty
{ details = propertyDetails
, priceAsText = maybePriceAsText
, price = maybePrice
, link = link
, location = address
}
where
maybePrice :: Maybe Int
maybePrice = maybePriceAsText >>= parsePrice
addressFromListingTree :: TagTreePos String -> String
addressFromListingTree listingTree =
head streetAddresses
where
addressTrees :: [TagTreePos String]
addressTrees = select (sel "a[rel=listingName]") (content listingTree)
streetAddresses :: [String]
streetAddresses = fmap streetFromAddressTree addressTrees
detailsFromListingTree :: TagTreePos String -> [(PropertyDetails, Maybe String, String)]
detailsFromListingTree listingTree =
extractedDetails
where
projectChildTrees :: [TagTreePos String]
projectChildTrees = select (sel "div.project-child-listings") (content listingTree)
extractedDetails :: [(PropertyDetails, Maybe String, String)]
extractedDetails = if not (null projectChildTrees) then
processProjectChildren $ head projectChildTrees
else
[processSingleProperty listingTree]
processSingleProperty :: TagTreePos String -> (PropertyDetails, Maybe String, String)
processSingleProperty propertyTree =
(propertyDetails, propertyPrice, propertyLink)
where
propertyDetails :: PropertyDetails
propertyDetails = extractPropertyDetails propertyTree
propertyPrice :: Maybe String
propertyPrice = extractSinglePropertyPrice propertyTree
propertyLink :: String
propertyLink = extractSinglePropertyLink propertyTree
processProjectChildren :: TagTreePos String -> [(PropertyDetails, Maybe String, String)]
processProjectChildren projectChildTree =
processedProjectChildren
where
childrenTrees :: [TagTreePos String]
childrenTrees = select (sel "div.child") (content projectChildTree)
processedProjectChildren :: [(PropertyDetails, Maybe String, String)]
processedProjectChildren = fmap processProjectChild childrenTrees
processProjectChild :: TagTreePos String -> (PropertyDetails, Maybe String, String)
processProjectChild projectChild =
(propertyDetails, propertyPrice, propertyLink)
where
propertyDetails :: PropertyDetails
propertyDetails = extractPropertyDetails projectChild
propertyPrice :: Maybe String
propertyPrice = extractProjectChildPrice projectChild
propertyLink :: String
propertyLink = extractProjectChildLink projectChild
extractPrice :: String -> TagTreePos String -> Maybe String
extractPrice selector tree =
if not (null priceTree) then
Just $ innerText $ flattenTree [content $ head priceTree]
else
Nothing
where
priceTree :: [TagTreePos String]
priceTree = select (sel selector) (content tree)
extractProjectChildPrice :: TagTreePos String -> Maybe String
extractProjectChildPrice = extractPrice ".price"
extractSinglePropertyPrice :: TagTreePos String -> Maybe String
extractSinglePropertyPrice = extractPrice ".priceText"
extractProjectChildLink :: TagTreePos String -> String
extractProjectChildLink projectChildTree =
fromAttrib "href" tagOpenA
where
parentTree :: TagTreePos String
parentTree = fromJust $ parent projectChildTree
tagOpenA :: Tag String
tagOpenA = head $ flattenTree [content parentTree]
extractSinglePropertyLink :: TagTreePos String -> String
extractSinglePropertyLink tree =
fromAttrib "href" tagOpenA
where
linkTree :: [TagTreePos String]
linkTree = select (sel ".photoviewer a") (content tree)
tagOpenA :: Tag String
tagOpenA = head $ flattenTree [content $ head linkTree]
extractHref :: Tag String -> String
extractHref tagOpen = ""
iconToValue :: [TagTreePos String] -> Maybe String
iconToValue [] = Nothing
iconToValue (x:xs) =
Just $ innerText $ flattenTree [Text.HTML.TagSoup.Tree.Zipper.after x !! 1]
extractPropertyDetails :: TagTreePos String -> PropertyDetails
extractPropertyDetails propertyTree =
PropertyDetails
{ bedroomsAsString = bedroomsAsString
, bathroomsAsString = bathroomsAsString
, carsAsString = carsAsString
, bedrooms = detailToInt bedroomsAsString
, bathrooms = detailToInt bathroomsAsString
, cars = detailToInt carsAsString
}
where
bedroomsAsString = iconToValue $ select (sel ".rui-icon-bed") (content propertyTree)
bathroomsAsString = iconToValue $ select (sel ".rui-icon-bath") (content propertyTree)
carsAsString = iconToValue $ select (sel ".rui-icon-car") (content propertyTree)
detailToInt :: Maybe String -> Int
detailToInt maybeDetail =
maybeToInt maybeIntDetail
where
detailToMaybeInt :: String -> Maybe Int
detailToMaybeInt = readMaybe
maybeIntDetail = maybeDetail >>= detailToMaybeInt
maybeToInt :: Maybe Int -> Int
maybeToInt (Just detail) = detail
maybeToInt Nothing = 0
streetFromAddressTree :: TagTreePos String -> String
streetFromAddressTree addressTree =
innerText tagList
where
tagList :: [Tag String]
tagList = flattenTree [content addressTree]
listings :: TagTree String -> [TagTreePos String]
listings = select (sel "article.resultBody")
propertyFeaturesSelector :: Selector
propertyFeaturesSelector = sel "dl.rui-property-features"
propertyFeaturesTree :: TagTreePos String -> [TagTreePos String]
propertyFeaturesTree listingTree = select propertyFeaturesSelector (content listingTree)
hasListings :: TagTree String -> Bool
hasListings tree = not (null (select (sel "article.resultBody") tree))
|
Leonti/haskell-memory-so
|
src/ResultsParsing.hs
|
bsd-3-clause
| 7,824
| 0
| 11
| 2,019
| 1,713
| 916
| 797
| 156
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.