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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Control.Proof.Simple where
import Control.Applicative
import Control.Arrow
import Control.Eff
import Control.Eff.Choose
import Control.Eff.Lift
import Control.Eff.State.Lazy
import Control.Lens
import Control.Monad
import Data.Function
import Data.List
import Data.Typeable
import Numeric.Natural
import qualified Data.Map as M
import System.IO (hFlush, stdout)
import Data.Name
import Data.Prop
import Data.Proof
import Control.Proof.Common
type Hypotheses = M.Map Name PropS
type Target = PropS
data Prove' = Prove
{ _hypotheses :: Hypotheses
, _target :: Target
} deriving (Typeable)
makeLenses ''Prove'
instance Show Prove' where
show x = hypos x ++ fence ++ trg x where
hypos = concatMap (\ (n,p) -> show n ++ "\t" ++ show p ++ "\n") . M.toList . (^. hypotheses)
fence = replicate 40 '-' ++ "\n"
trg = show . (^. target)
type Prove = State Prove'
getProve :: (Member Prove r) => Eff r Prove'
getProve = get
putProve :: (Member Prove r) => Prove' -> Eff r ()
putProve = put
modifyProve :: (Member Prove r) => (Prove' -> Prove') -> Eff r ()
modifyProve = modify
getHypotheses :: (Member Prove r) => Eff r Hypotheses
getHypotheses = (^. hypotheses) <$> getProve
putHypotheses :: (Member Prove r) => Hypotheses -> Eff r ()
putHypotheses = modifyProve . (hypotheses .~)
modifyHypotheses :: (Member Prove r) => (Hypotheses -> Hypotheses) -> Eff r ()
modifyHypotheses = modifyProve . (hypotheses %~)
getTarget :: (Member Prove r) => Eff r Target
getTarget = (^. target) <$> getProve
putTarget :: (Member Prove r) => Target -> Eff r ()
putTarget = modifyProve . (target .~)
modifyTarget :: (Member Prove r) => (Target -> Target) -> Eff r ()
modifyTarget = modifyProve . (target %~)
intro :: (Member Prove r, Member Choose r) => Eff r ProofS -> Eff r ProofS
intro cont = do
a <- getTarget
case a of
Prop _ -> mzero'
Imply p q -> do
name <- newName . M.keys <$> getHypotheses
modifyHypotheses (M.insert name p)
putTarget q
Lambda name <$> cont
intros :: (Member Prove r, Member Choose r) => Eff r ProofS -> Eff r ProofS
intros cont = intro cont >> (cont `mplus'` intros cont)
chooseHypothesis :: (Member Prove r, Member Choose r) => Eff r (Name, PropS)
chooseHypothesis = choose . M.toList =<< getHypotheses where
chooseImplyHypothesis :: (Member Prove r, Member Choose r) => Eff r (Name, (PropS, PropS))
chooseImplyHypothesis = do
(n, p) <- chooseHypothesis
case p of
a `Imply` b -> return (n, (a, b))
_ -> mzero'
exact :: (Member Prove r, Member Choose r) => Eff r ProofS
exact = do
(n, p) <- chooseHypothesis
q <- getTarget
if p == q
then return $ Proof n
else mzero'
apply :: (Member Prove r, Member Choose r) => Eff r ProofS -> Eff r ProofS
apply cont = do
(n, (p, q)) <- chooseImplyHypothesis
(ps, q') <- choose $ split (p ~> q)
r <- getTarget
if q' == r
then do
rs <- forM ps $ \ p' -> do
putTarget p'
cont
return . foldr1 Apply $ Proof n : rs
else mzero'
auto :: (Member Prove r, Member Choose r) => Eff r ProofS -> Eff r ProofS
auto cont = join $ choose
[ intro cont
, apply cont
, exact
]
hand :: (SetMember Lift (Lift IO) r, Member Prove r, Member Choose r) => Eff r ProofS -> Eff r ProofS
hand cont = do
lift . print =<< getProve
s <- lift $ do
putStr "tactic> "
hFlush stdout
getLine
case s of
"print" -> getProve >>= (lift . print) >> cont
"intro" -> intro cont
"intros" -> intros cont
"apply" -> apply cont
"exact" -> exact
"auto" -> auto cont
_ -> lift (putStrLn $ "no such command: " ++ s) >> cont
runTactic :: Hypotheses -> Target -> (Eff (Prove :> Choose :> r) ProofS -> Eff (Prove :> Choose :> r) ProofS) -> Eff r [ProofS]
runTactic x y = ((nubBy alphaEqual . map reduceS) <$>) . runChoice . evalState (Prove x y) . fix
autoSolve :: Hypotheses -> Target -> [ProofS]
autoSolve x y = run $ runTactic x y auto
handSolve :: Hypotheses -> Target -> IO [ProofS]
handSolve x y = putStrLn "* handSolve is wroking in progress *" >> runLift (runTactic x y hand)
-- | >>> autoSolve' [] "(a -> b) -> (b -> c) -> a -> c"
-- [\ x0 x1 . x1 x0]
-- >>> autoSolve' [] "b -> (a -> b) -> a -> b"
-- [\ x0 x1 . x1,\ x0 x1 x2 . x0]
-- >>> autoSolve' [("maybe_case", "maybe_a -> b -> (a -> b) -> b1")] "b -> (a -> b) -> maybe_a -> b1"
-- [\ x0 x1 x2 . maybe_case (x2 (x0 x1)),\ x0 x1 x2 . maybe_case (x2 (x0 (\ x3 . x0)))]
autoSolve' :: [(String, String)] -> String -> [ProofS]
autoSolve' xs y = autoSolve (M.fromList $ map (toName *** readPropS) xs) (readPropS y)
| solorab/proof-haskell | Control/Proof/Simple.hs | mit | 5,049 | 0 | 16 | 1,233 | 1,755 | 924 | 831 | 126 | 7 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.S3.GetObjectAcl
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns the access control list (ACL) of an object.
--
-- <http://docs.aws.amazon.com/AmazonS3/latest/API/GetObjectAcl.html>
module Network.AWS.S3.GetObjectAcl
(
-- * Request
GetObjectAcl
-- ** Request constructor
, getObjectAcl
-- ** Request lenses
, goaBucket
, goaKey
, goaRequestPayer
, goaVersionId
-- * Response
, GetObjectAclResponse
-- ** Response constructor
, getObjectAclResponse
-- ** Response lenses
, goarGrants
, goarOwner
, goarRequestCharged
) where
import Network.AWS.Prelude
import Network.AWS.Request.S3
import Network.AWS.S3.Types
import qualified GHC.Exts
data GetObjectAcl = GetObjectAcl
{ _goaBucket :: Text
, _goaKey :: Text
, _goaRequestPayer :: Maybe RequestPayer
, _goaVersionId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'GetObjectAcl' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'goaBucket' @::@ 'Text'
--
-- * 'goaKey' @::@ 'Text'
--
-- * 'goaRequestPayer' @::@ 'Maybe' 'RequestPayer'
--
-- * 'goaVersionId' @::@ 'Maybe' 'Text'
--
getObjectAcl :: Text -- ^ 'goaBucket'
-> Text -- ^ 'goaKey'
-> GetObjectAcl
getObjectAcl p1 p2 = GetObjectAcl
{ _goaBucket = p1
, _goaKey = p2
, _goaVersionId = Nothing
, _goaRequestPayer = Nothing
}
goaBucket :: Lens' GetObjectAcl Text
goaBucket = lens _goaBucket (\s a -> s { _goaBucket = a })
goaKey :: Lens' GetObjectAcl Text
goaKey = lens _goaKey (\s a -> s { _goaKey = a })
goaRequestPayer :: Lens' GetObjectAcl (Maybe RequestPayer)
goaRequestPayer = lens _goaRequestPayer (\s a -> s { _goaRequestPayer = a })
-- | VersionId used to reference a specific version of the object.
goaVersionId :: Lens' GetObjectAcl (Maybe Text)
goaVersionId = lens _goaVersionId (\s a -> s { _goaVersionId = a })
data GetObjectAclResponse = GetObjectAclResponse
{ _goarGrants :: List "Grant" Grant
, _goarOwner :: Maybe Owner
, _goarRequestCharged :: Maybe RequestCharged
} deriving (Eq, Read, Show)
-- | 'GetObjectAclResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'goarGrants' @::@ ['Grant']
--
-- * 'goarOwner' @::@ 'Maybe' 'Owner'
--
-- * 'goarRequestCharged' @::@ 'Maybe' 'RequestCharged'
--
getObjectAclResponse :: GetObjectAclResponse
getObjectAclResponse = GetObjectAclResponse
{ _goarOwner = Nothing
, _goarGrants = mempty
, _goarRequestCharged = Nothing
}
-- | A list of grants.
goarGrants :: Lens' GetObjectAclResponse [Grant]
goarGrants = lens _goarGrants (\s a -> s { _goarGrants = a }) . _List
goarOwner :: Lens' GetObjectAclResponse (Maybe Owner)
goarOwner = lens _goarOwner (\s a -> s { _goarOwner = a })
goarRequestCharged :: Lens' GetObjectAclResponse (Maybe RequestCharged)
goarRequestCharged =
lens _goarRequestCharged (\s a -> s { _goarRequestCharged = a })
instance ToPath GetObjectAcl where
toPath GetObjectAcl{..} = mconcat
[ "/"
, toText _goaBucket
, "/"
, toText _goaKey
]
instance ToQuery GetObjectAcl where
toQuery GetObjectAcl{..} = mconcat
[ "acl"
, "versionId" =? _goaVersionId
]
instance ToHeaders GetObjectAcl where
toHeaders GetObjectAcl{..} = mconcat
[ "x-amz-request-payer" =: _goaRequestPayer
]
instance ToXMLRoot GetObjectAcl where
toXMLRoot = const (namespaced ns "GetObjectAcl" [])
instance ToXML GetObjectAcl
instance AWSRequest GetObjectAcl where
type Sv GetObjectAcl = S3
type Rs GetObjectAcl = GetObjectAclResponse
request = get
response = xmlHeaderResponse $ \h x -> GetObjectAclResponse
<$> x .@? "AccessControlList" .!@ mempty
<*> x .@? "Owner"
<*> h ~:? "x-amz-request-charged"
| romanb/amazonka | amazonka-s3/gen/Network/AWS/S3/GetObjectAcl.hs | mpl-2.0 | 4,902 | 0 | 14 | 1,194 | 828 | 487 | 341 | 90 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : RoverTests
-- Copyright : (c) 2017 Pascal Poizat
-- License : Apache-2.0 (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : unknown
--
-- Test file for the Veca module.
-----------------------------------------------------------------------------
module RoverTests (roverTests)
where
import Test.Tasty
import Test.Tasty.HUnit
-- import Test.Tasty.QuickCheck as QC
-- import Test.Tasty.SmallCheck as SC
import Data.Map as M (Map, fromList)
import Data.Monoid ((<>))
import qualified Data.Set as S (fromList)
import Examples.Rover.Model
import Models.Events
import Models.LabelledTransitionSystem as LTS (LabelledTransitionSystem (..),
Path (..), paths')
import Models.Name (Name (..))
import Models.Named (Named (..))
import Models.TimedAutomaton as TA (Bounds (..),
ClockConstraint (..),
ClockOperator (..),
ClockReset (..),
Edge (..),
Expression (..),
Location (..),
TimedAutomaton (..),
VariableAssignment (..),
VariableType (..),
VariableTyping (..),
relabel)
import Veca.Model
import Veca.Operations
listDone :: Int -> Map (Name String) VariableTyping
listDone n = M.fromList
[ ( Name ["done"]
, VariableTyping (Name ["done"]) (IntType bounds) (Just $ Expression "0")
)
]
where bounds = Bounds 0 n
setDone :: Int -> VariableAssignment
setDone n = VariableAssignment (Name ["done"]) (Expression (show n))
roverTests :: TestTree
roverTests = testGroup "Tests" [unittests]
unittests :: TestTree
unittests = testGroup
"Unit tests for the Rover Case Study"
[uController, uStoreUnit, uPictureUnit, uVideoUnit, uAcquisitionUnit, uRover]
uController :: TestTree
uController = testGroup
"Unit tests for Controller"
[ testCase "basic component definition is valid"
$ isValidComponent (componentType controllerUnit)
@?= True
, testCase "TA generation" $ cToTA controllerUnit @?= controllerTA
]
uStoreUnit :: TestTree
uStoreUnit = testGroup
"Unit tests for Store Unit"
[ testCase "basic component definition is valid"
$ isValidComponent (componentType storeUnit)
@?= True
, testCase "TA generation" $ cToTA storeUnit @?= storeUnitTA
]
uPictureUnit :: TestTree
uPictureUnit = testGroup
"Unit tests for Picture Unit"
[ testCase "basic component definition is valid"
$ isValidComponent (componentType pictureUnit)
@?= True
, testCase "TA generation" $ cToTA pictureUnit @?= pictureUnitTA
]
uVideoUnit :: TestTree
uVideoUnit = testGroup
"Unit tests for Video Unit"
[ testCase "basic component definition is valid"
$ isValidComponent (componentType videoUnit)
@?= True
, testCase "paths" $ S.fromList computedVUPaths @?= S.fromList expectedVUPaths
, testCase "isCPaths k1" $ (isCPath vuk1 <$> expectedVUPaths) @?= resk1
, testCase "isCPaths k2" $ (isCPath vuk2 <$> expectedVUPaths) @?= resk2
, testCase "isCPaths k3" $ (isCPath vuk3 <$> expectedVUPaths) @?= resk3
, testCase "TA generation" $ cToTA videoUnit @?= videoUnitTA
]
where computedVUPaths = paths' (behavior (componentType videoUnit))
uAcquisitionUnit :: TestTree
uAcquisitionUnit = testGroup
"Unit tests for Acquisition Unit"
[ testCase "composite component definition is valid"
$ isValidComponent (componentType acquisitionUnit)
@?= True
]
uRover :: TestTree
uRover = testGroup
"Unit tests for Rover"
[ testCase "composite component definition is valid"
$ isValidComponent (componentType rover)
@?= True
, testCase "TA generation for the Rover (standalone)"
$ (cTreeToTAList . cToCTree) rover
@?= roverTAs
]
--
-- Results
--
expectedVUPaths :: [VPath]
expectedVUPaths =
Path
<$> [ []
, [vut1]
, [vut2]
, [vut3]
, [vut4]
, [vut5]
, [vut6]
, [vut7]
, [vut1, vut2]
, [vut2, vut3]
, [vut3, vut4]
, [vut3, vut5]
, [vut4, vut6]
, [vut5, vut7]
, [vut6, vut7]
, [vut1, vut2, vut3]
, [vut2, vut3, vut4]
, [vut2, vut3, vut5]
, [vut3, vut4, vut6]
, [vut3, vut5, vut7]
, [vut4, vut6, vut7]
, [vut1, vut2, vut3, vut4]
, [vut1, vut2, vut3, vut5]
, [vut2, vut3, vut4, vut6]
, [vut2, vut3, vut5, vut7]
, [vut3, vut4, vut6, vut7]
, [vut1, vut2, vut3, vut4, vut6]
, [vut1, vut2, vut3, vut5, vut7]
, [vut2, vut3, vut4, vut6, vut7]
, [vut1, vut2, vut3, vut4, vut6, vut7]
]
resk1 :: [Bool]
resk1 =
[ False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, True
, False
, True
]
resk2 :: [Bool]
resk2 =
[ False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, True
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
]
resk3 :: [Bool]
resk3 =
[ False
, False
, False
, False
, False
, False
, False
, False
, False
, True
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
]
--
-- test results
--
videoUnitTA :: VTA
videoUnitTA = TimedAutomaton
v
(Location <$> ["0", "1", "2", "3", "4", "5", "6"])
(Location "0")
[]
[]
clocksVU
(listDone 6)
(alphabet . behavior . componentType $ videoUnit)
[ Edge (Location "0") (receive askVid) [] [ClockReset c1] [setDone 1] (Location "1")
, Edge (Location "1") (invoke getVid) [] [ClockReset c3] [setDone 3] (Location "2")
, Edge (Location "2")
(result getVid)
[ClockConstraint c3 GE 0]
[ClockReset c2]
[setDone 4]
(Location "3")
, Edge (Location "3") tau [] [] [setDone 6] (Location "4")
, Edge (Location "3") tau [] [] [setDone 6] (Location "5")
, Edge (Location "4")
(invoke storeVid)
[ClockConstraint c2 GE 0]
[]
[setDone 5]
(Location "5")
, Edge (Location "5")
(reply askVid)
[ClockConstraint c1 GE 44]
[]
[setDone 2]
(Location "6")
, Edge (Location "6") tau [] [] [setDone 6] (Location "6")
]
[ (Location "1", [ClockConstraint c1 LE 46])
, (Location "2", [ClockConstraint c1 LE 46, ClockConstraint c3 LE 6])
, (Location "3", [ClockConstraint c1 LE 46, ClockConstraint c2 LE 12])
, (Location "4", [ClockConstraint c1 LE 46, ClockConstraint c2 LE 12])
, (Location "5", [ClockConstraint c1 LE 46])
]
where
clocksVU = genClock <$> timeconstraints (componentType videoUnit)
c1 = head clocksVU
c2 = clocksVU !! 1
c3 = clocksVU !! 2
pictureUnitTA :: VTA
pictureUnitTA = TimedAutomaton
p
(Location <$> ["0", "1", "2", "3", "4", "5", "6"])
(Location "0")
[]
[]
clocksPU
(listDone 6)
(alphabet . behavior . componentType $ pictureUnit)
[ Edge (Location "0") (receive askPic) [] [ClockReset c1] [setDone 1] (Location "1")
, Edge (Location "1") (invoke getPic) [] [ClockReset c3] [setDone 3] (Location "2")
, Edge (Location "2")
(result getPic)
[ClockConstraint c3 GE 0]
[ClockReset c2]
[setDone 4]
(Location "3")
, Edge (Location "3") tau [] [] [setDone 6] (Location "4")
, Edge (Location "3") tau [] [] [setDone 6] (Location "5")
, Edge (Location "4")
(invoke storePic)
[ClockConstraint c2 GE 0]
[]
[setDone 5]
(Location "5")
, Edge (Location "5")
(reply askPic)
[ClockConstraint c1 GE 44]
[]
[setDone 2]
(Location "6")
, Edge (Location "6") tau [] [] [setDone 6] (Location "6")
]
[ (Location "1", [ClockConstraint c1 LE 46])
, (Location "2", [ClockConstraint c1 LE 46, ClockConstraint c3 LE 6])
, (Location "3", [ClockConstraint c1 LE 46, ClockConstraint c2 LE 12])
, (Location "4", [ClockConstraint c1 LE 46, ClockConstraint c2 LE 12])
, (Location "5", [ClockConstraint c1 LE 46])
]
where
clocksPU = genClock <$> timeconstraints (componentType pictureUnit)
c1 = head clocksPU
c2 = clocksPU !! 1
c3 = clocksPU !! 2
storeUnitTA :: VTA
storeUnitTA = TimedAutomaton
s
(Location <$> ["0", "1"])
(Location "0")
[]
[]
[]
(listDone 3)
(alphabet . behavior . componentType $ storeUnit)
[ Edge (Location "0") (receive storePic) [] [] [setDone 2] (Location "1")
, Edge (Location "0") (receive storeVid) [] [] [setDone 3] (Location "1")
, Edge (Location "1") tau [] [] [setDone 1] (Location "0")
, Edge (Location "0") tau [] [] [setDone 1] (Location "0")
]
[]
controllerTA :: VTA
controllerTA = TimedAutomaton
c
(Location <$> ["0", "1", "2", "3", "4", "5", "6"])
(Location "0")
[]
[]
clocksC
(listDone 7)
((alphabet . behavior . componentType $ controllerUnit) ++ [tau])
[ Edge (Location "0")
(receive run)
[]
[ClockReset c1]
[setDone 1]
(Location "1")
, Edge (Location "1") (invoke askVid) [] [] [setDone 3] (Location "2")
, Edge (Location "2") (result askVid) [] [] [setDone 4] (Location "3")
, Edge (Location "3") (invoke askPic) [] [] [setDone 5] (Location "4")
, Edge (Location "4") (result askPic) [] [] [setDone 6] (Location "5")
, Edge (Location "5")
(reply run)
[ClockConstraint c1 GE 55]
[]
[setDone 2]
(Location "6")
, Edge (Location "6") tau [] [] [setDone 7] (Location "6")
]
[ (Location "1", [ClockConstraint c1 LE 60])
, (Location "2", [ClockConstraint c1 LE 60])
, (Location "3", [ClockConstraint c1 LE 60])
, (Location "4", [ClockConstraint c1 LE 60])
, (Location "5", [ClockConstraint c1 LE 60])
]
where
clocksC = genClock <$> timeconstraints (componentType controllerUnit)
c1 = head clocksC
roverTAs :: [VTA]
roverTAs =
[ prefixBy r $ relabel sub1 controllerTA
, prefixBy (r <> a) $ relabel sub2 pictureUnitTA
, prefixBy (r <> a) $ relabel sub3 videoUnitTA
, prefixBy r $ relabel sub4 storeUnitTA
]
where
sub1 =
lift [mksub (r <> n5) run, mksub (r <> n1) askPic, mksub (r <> n2) askVid]
sub2 = lift
[mksub (r <> n1) askPic, mksub (r <> n6) getPic, mksub (r <> n3) storePic]
sub3 = lift
[mksub (r <> n2) askVid, mksub (r <> n7) getVid, mksub (r <> n4) storeVid]
sub4 = lift [mksub (r <> n3) storePic, mksub (r <> n4) storeVid]
lift = foldMap (fLift [CReceive, CReply, CInvoke, CResult])
mksub i o = (o, indexBy i o)
| pascalpoizat/veca-haskell | test/RoverTests.hs | apache-2.0 | 11,809 | 0 | 11 | 3,731 | 3,946 | 2,176 | 1,770 | 364 | 1 |
{-# LANGUAGE Rank2Types #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.IntSet.Lens
-- Copyright : (C) 2012-16 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : provisional
-- Portability : portable
--
----------------------------------------------------------------------------
module Data.IntSet.Lens
( members
, setmapped
, setOf
) where
import Control.Lens
import Data.IntSet as IntSet
-- $setup
-- >>> :set -XNoOverloadedStrings
-- >>> import Control.Lens
-- | IntSet isn't Foldable, but this 'Fold' can be used to access the members of an 'IntSet'.
--
-- >>> sumOf members $ setOf folded [1,2,3,4]
-- 10
members :: Fold IntSet Int
members = folding IntSet.toAscList
{-# INLINE members #-}
-- | This 'Setter' can be used to change the contents of an 'IntSet' by mapping
-- the elements to new values.
--
-- Sadly, you can't create a valid 'Traversal' for a 'Set', because the number of
-- elements might change but you can manipulate it by reading using 'folded' and
-- reindexing it via 'setmapped'.
--
-- >>> over setmapped (+1) (fromList [1,2,3,4])
-- fromList [2,3,4,5]
setmapped :: IndexPreservingSetter' IntSet Int
setmapped = setting IntSet.map
{-# INLINE setmapped #-}
-- | Construct an 'IntSet' from a 'Getter', 'Fold', 'Traversal', 'Lens' or 'Iso'.
--
-- >>> setOf folded [1,2,3,4]
-- fromList [1,2,3,4]
--
-- >>> setOf (folded._2) [("hello",1),("world",2),("!!!",3)]
-- fromList [1,2,3]
--
-- @
-- 'setOf' :: 'Getter' s 'Int' -> s -> 'IntSet'
-- 'setOf' :: 'Fold' s 'Int' -> s -> 'IntSet'
-- 'setOf' :: 'Iso'' s 'Int' -> s -> 'IntSet'
-- 'setOf' :: 'Lens'' s 'Int' -> s -> 'IntSet'
-- 'setOf' :: 'Traversal'' s 'Int' -> s -> 'IntSet'
-- @
setOf :: Getting IntSet s Int -> s -> IntSet
setOf l = views l IntSet.singleton
{-# INLINE setOf #-}
| ddssff/lens | src/Data/IntSet/Lens.hs | bsd-3-clause | 1,938 | 0 | 6 | 351 | 150 | 102 | 48 | 16 | 1 |
{-# LANGUAGE PatternGuards, ExistentialQuantification, CPP #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Core.Execute (execute) where
import Idris.AbsSyntax
import Idris.AbsSyntaxTree
import IRTS.Lang(FDesc(..), FType(..))
import Idris.Primitives(Prim(..), primitives)
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.CaseTree
import Idris.Error
import Debug.Trace
import Util.DynamicLinker
import Util.System
import Control.Applicative hiding (Const)
import Control.Exception
import Control.Monad.Trans
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)
import Control.Monad hiding (forM)
import Data.Maybe
import Data.Bits
import Data.Traversable (forM)
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Data.Map as M
#ifdef IDRIS_FFI
import Foreign.LibFFI
import Foreign.C.String
import Foreign.Marshal.Alloc (free)
import Foreign.Ptr
#endif
import System.IO
#ifndef IDRIS_FFI
execute :: Term -> Idris Term
execute tm = fail "libffi not supported, rebuild Idris with -f FFI"
#else
-- else is rest of file
readMay :: (Read a) => String -> Maybe a
readMay s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
data Lazy = Delayed ExecEnv Context Term | Forced ExecVal deriving Show
data ExecState = ExecState { exec_dynamic_libs :: [DynamicLib] -- ^ Dynamic libs from idris monad
, binderNames :: [Name] -- ^ Used to uniquify binders when converting to TT
}
data ExecVal = EP NameType Name ExecVal
| EV Int
| EBind Name (Binder ExecVal) (ExecVal -> Exec ExecVal)
| EApp ExecVal ExecVal
| EType UExp
| EUType Universe
| EErased
| EConstant Const
| forall a. EPtr (Ptr a)
| EThunk Context ExecEnv Term
| EHandle Handle
instance Show ExecVal where
show (EP _ n _) = show n
show (EV i) = "!!V" ++ show i ++ "!!"
show (EBind n b body) = "EBind " ++ show b ++ " <<fn>>"
show (EApp e1 e2) = show e1 ++ " (" ++ show e2 ++ ")"
show (EType _) = "Type"
show (EUType _) = "UType"
show EErased = "[__]"
show (EConstant c) = show c
show (EPtr p) = "<<ptr " ++ show p ++ ">>"
show (EThunk _ env tm) = "<<thunk " ++ show env ++ "||||" ++ show tm ++ ">>"
show (EHandle h) = "<<handle " ++ show h ++ ">>"
toTT :: ExecVal -> Exec Term
toTT (EP nt n ty) = (P nt n) <$> (toTT ty)
toTT (EV i) = return $ V i
toTT (EBind n b body) = do n' <- newN n
body' <- body $ EP Bound n' EErased
b' <- fixBinder b
Bind n' b' <$> toTT body'
where fixBinder (Lam t) = Lam <$> toTT t
fixBinder (Pi i t k) = Pi i <$> toTT t <*> toTT k
fixBinder (Let t1 t2) = Let <$> toTT t1 <*> toTT t2
fixBinder (NLet t1 t2) = NLet <$> toTT t1 <*> toTT t2
fixBinder (Hole t) = Hole <$> toTT t
fixBinder (GHole i t) = GHole i <$> toTT t
fixBinder (Guess t1 t2) = Guess <$> toTT t1 <*> toTT t2
fixBinder (PVar t) = PVar <$> toTT t
fixBinder (PVTy t) = PVTy <$> toTT t
newN n = do (ExecState hs ns) <- lift get
let n' = uniqueName n ns
lift (put (ExecState hs (n':ns)))
return n'
toTT (EApp e1 e2) = do e1' <- toTT e1
e2' <- toTT e2
return $ App Complete e1' e2'
toTT (EType u) = return $ TType u
toTT (EUType u) = return $ UType u
toTT EErased = return Erased
toTT (EConstant c) = return (Constant c)
toTT (EThunk ctxt env tm) = do env' <- mapM toBinder env
return $ normalise ctxt env' tm
where toBinder (n, v) = do v' <- toTT v
return (n, Let Erased v')
toTT (EHandle _) = execFail $ Msg "Can't convert handles back to TT after execution."
toTT (EPtr ptr) = execFail $ Msg "Can't convert pointers back to TT after execution."
unApplyV :: ExecVal -> (ExecVal, [ExecVal])
unApplyV tm = ua [] tm
where ua args (EApp f a) = ua (a:args) f
ua args t = (t, args)
mkEApp :: ExecVal -> [ExecVal] -> ExecVal
mkEApp f [] = f
mkEApp f (a:args) = mkEApp (EApp f a) args
initState :: Idris ExecState
initState = do ist <- getIState
return $ ExecState (idris_dynamic_libs ist) []
type Exec = ExceptT Err (StateT ExecState IO)
runExec :: Exec a -> ExecState -> IO (Either Err a)
runExec ex st = fst <$> runStateT (runExceptT ex) st
getExecState :: Exec ExecState
getExecState = lift get
putExecState :: ExecState -> Exec ()
putExecState = lift . put
execFail :: Err -> Exec a
execFail = throwE
execIO :: IO a -> Exec a
execIO = lift . lift
execute :: Term -> Idris Term
execute tm = do est <- initState
ctxt <- getContext
res <- lift . lift . flip runExec est $
do res <- doExec [] ctxt tm
toTT res
case res of
Left err -> ierror err
Right tm' -> return tm'
ioWrap :: ExecVal -> ExecVal
ioWrap tm = mkEApp (EP (DCon 0 2 False) (sUN "prim__IO") EErased) [EErased, tm]
ioUnit :: ExecVal
ioUnit = ioWrap (EP Ref unitCon EErased)
type ExecEnv = [(Name, ExecVal)]
doExec :: ExecEnv -> Context -> Term -> Exec ExecVal
doExec env ctxt p@(P Ref n ty) | Just v <- lookup n env = return v
doExec env ctxt p@(P Ref n ty) =
do let val = lookupDef n ctxt
case val of
[Function _ tm] -> doExec env ctxt tm
[TyDecl _ _] -> return (EP Ref n EErased) -- abstract def
[Operator tp arity op] -> return (EP Ref n EErased) -- will be special-cased later
[CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun
doExec env ctxt tm
[CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] -> return (EP Ref n EErased)
[] -> execFail . Msg $ "Could not find " ++ show n ++ " in definitions."
other | length other > 1 -> execFail . Msg $ "Multiple definitions found for " ++ show n
| otherwise -> execFail . Msg . take 500 $ "got to " ++ show other ++ " lookup up " ++ show n
doExec env ctxt p@(P Bound n ty) =
case lookup n env of
Nothing -> execFail . Msg $ "not found"
Just tm -> return tm
doExec env ctxt (P (DCon a b u) n _) = return (EP (DCon a b u) n EErased)
doExec env ctxt (P (TCon a b) n _) = return (EP (TCon a b) n EErased)
doExec env ctxt v@(V i) | i < length env = return (snd (env !! i))
| otherwise = execFail . Msg $ "env too small"
doExec env ctxt (Bind n (Let t v) body) = do v' <- doExec env ctxt v
doExec ((n, v'):env) ctxt body
doExec env ctxt (Bind n (NLet t v) body) = trace "NLet" $ undefined
doExec env ctxt tm@(Bind n b body) = do b' <- forM b (doExec env ctxt)
return $
EBind n b' (\arg -> doExec ((n, arg):env) ctxt body)
doExec env ctxt a@(App _ _ _) =
do let (f, args) = unApply a
f' <- doExec env ctxt f
args' <- case f' of
(EP _ d _) | d == delay ->
case args of
[t,a,tm] -> do t' <- doExec env ctxt t
a' <- doExec env ctxt a
return [t', a', EThunk ctxt env tm]
_ -> mapM (doExec env ctxt) args -- partial applications are fine to evaluate
fun' -> do mapM (doExec env ctxt) args
execApp env ctxt f' args'
doExec env ctxt (Constant c) = return (EConstant c)
doExec env ctxt (Proj tm i) = let (x, xs) = unApply tm in
doExec env ctxt ((x:xs) !! i)
doExec env ctxt Erased = return EErased
doExec env ctxt Impossible = fail "Tried to execute an impossible case"
doExec env ctxt (TType u) = return (EType u)
doExec env ctxt (UType u) = return (EUType u)
execApp :: ExecEnv -> Context -> ExecVal -> [ExecVal] -> Exec ExecVal
execApp env ctxt v [] = return v -- no args is just a constant! can result from function calls
execApp env ctxt (EP _ f _) (t:a:delayed:rest)
| f == force
, (_, [_, _, EThunk tmCtxt tmEnv tm]) <- unApplyV delayed =
do tm' <- doExec tmEnv tmCtxt tm
execApp env ctxt tm' rest
execApp env ctxt (EP _ fp _) (ty:action:rest)
| fp == upio,
(prim__IO, [_, v]) <- unApplyV action
= execApp env ctxt v rest
execApp env ctxt (EP _ fp _) args@(_:_:v:k:rest)
| fp == piobind,
(prim__IO, [_, v']) <- unApplyV v =
do res <- execApp env ctxt k [v']
execApp env ctxt res rest
execApp env ctxt con@(EP _ fp _) args@(tp:v:rest)
| fp == pioret = execApp env ctxt (mkEApp con [tp, v]) rest
-- Special cases arising from not having access to the C RTS in the interpreter
execApp env ctxt f@(EP _ fp _) args@(xs:_:_:_:args')
| fp == mkfprim,
(ty : fn : w : rest) <- reverse args' =
execForeign env ctxt getArity ty fn rest (mkEApp f args)
where getArity = case unEList xs of
Just as -> length as
_ -> 0
execApp env ctxt c@(EP (DCon _ arity _) n _) args =
do let args' = take arity args
let restArgs = drop arity args
execApp env ctxt (mkEApp c args') restArgs
execApp env ctxt c@(EP (TCon _ arity) n _) args =
do let args' = take arity args
let restArgs = drop arity args
execApp env ctxt (mkEApp c args') restArgs
execApp env ctxt f@(EP _ n _) args
| Just (res, rest) <- getOp n args = do r <- res
execApp env ctxt r rest
execApp env ctxt f@(EP _ n _) args =
do let val = lookupDef n ctxt
case val of
[Function _ tm] -> fail "should already have been eval'd"
[TyDecl nt ty] -> return $ mkEApp f args
[Operator tp arity op] ->
if length args >= arity
then let args' = take arity args in
case getOp n args' of
Just (res, []) -> do r <- res
execApp env ctxt r (drop arity args)
_ -> return (mkEApp f args)
else return (mkEApp f args)
[CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun
do rhs <- doExec env ctxt tm
execApp env ctxt rhs args
[CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] ->
do res <- execCase env ctxt ns sc args
return $ fromMaybe (mkEApp f args) res
thing -> return $ mkEApp f args
execApp env ctxt bnd@(EBind n b body) (arg:args) = do ret <- body arg
let (f', as) = unApplyV ret
execApp env ctxt f' (as ++ args)
execApp env ctxt app@(EApp _ _) args2 | (f, args1) <- unApplyV app = execApp env ctxt f (args1 ++ args2)
execApp env ctxt f args = return (mkEApp f args)
execForeign env ctxt arity ty fn xs onfail
| Just (FFun "putStr" [(_, str)] _) <- foreignFromTT arity ty fn xs
= case str of
EConstant (Str arg) -> do execIO (putStr arg)
execApp env ctxt ioUnit (drop arity xs)
_ -> execFail . Msg $
"The argument to putStr should be a constant string, but it was " ++
show str ++
". Are all cases covered?"
| Just (FFun "putchar" [(_, ch)] _) <- foreignFromTT arity ty fn xs
= case ch of
EConstant (Ch c) -> do execIO (putChar c)
execApp env ctxt ioUnit (drop arity xs)
EConstant (I i) -> do execIO (putChar (toEnum i))
execApp env ctxt ioUnit (drop arity xs)
_ -> execFail . Msg $
"The argument to putchar should be a constant character, but it was " ++
show str ++
". Are all cases covered?"
| Just (FFun "idris_readStr" [_, (_, handle)] _) <- foreignFromTT arity ty fn xs
= case handle of
EHandle h -> do contents <- execIO $ hGetLine h
execApp env ctxt (EConstant (Str (contents ++ "\n"))) (drop arity xs)
_ -> execFail . Msg $
"The argument to idris_readStr should be a handle, but it was " ++
show handle ++
". Are all cases covered?"
| Just (FFun "getchar" _ _) <- foreignFromTT arity ty fn xs
= do -- The C API returns an Int which Idris library code
-- converts; thus, we must make an int here.
ch <- execIO $ fmap (ioWrap . EConstant . I . fromEnum) getChar
execApp env ctxt ch xs
| Just (FFun "idris_time" _ _) <- foreignFromTT arity ty fn xs
= do execIO $ fmap (ioWrap . EConstant . I . round) getPOSIXTime
| Just (FFun "fileOpen" [(_,fileStr), (_,modeStr)] _) <- foreignFromTT arity ty fn xs
= case (fileStr, modeStr) of
(EConstant (Str f), EConstant (Str mode)) ->
do f <- execIO $
catch (do let m = case mode of
"r" -> Right ReadMode
"w" -> Right WriteMode
"a" -> Right AppendMode
"rw" -> Right ReadWriteMode
"wr" -> Right ReadWriteMode
"r+" -> Right ReadWriteMode
_ -> Left ("Invalid mode for " ++ f ++ ": " ++ mode)
case fmap (openFile f) m of
Right h -> do h' <- h
hSetBinaryMode h' True
return $ Right (ioWrap (EHandle h'), drop arity xs)
Left err -> return $ Left err)
(\e -> let _ = ( e::SomeException)
in return $ Right (ioWrap (EPtr nullPtr), drop arity xs))
case f of
Left err -> execFail . Msg $ err
Right (res, rest) -> execApp env ctxt res rest
_ -> execFail . Msg $
"The arguments to fileOpen should be constant strings, but they were " ++
show fileStr ++ " and " ++ show modeStr ++
". Are all cases covered?"
| Just (FFun "fileEOF" [(_,handle)] _) <- foreignFromTT arity ty fn xs
= case handle of
EHandle h -> do eofp <- execIO $ hIsEOF h
let res = ioWrap (EConstant (I $ if eofp then 1 else 0))
execApp env ctxt res (drop arity xs)
_ -> execFail . Msg $
"The argument to fileEOF should be a file handle, but it was " ++
show handle ++
". Are all cases covered?"
| Just (FFun "fileClose" [(_,handle)] _) <- foreignFromTT arity ty fn xs
= case handle of
EHandle h -> do execIO $ hClose h
execApp env ctxt ioUnit (drop arity xs)
_ -> execFail . Msg $
"The argument to fileClose should be a file handle, but it was " ++
show handle ++
". Are all cases covered?"
| Just (FFun "isNull" [(_, ptr)] _) <- foreignFromTT arity ty fn xs
= case ptr of
EPtr p -> let res = ioWrap . EConstant . I $
if p == nullPtr then 1 else 0
in execApp env ctxt res (drop arity xs)
-- Handles will be checked as null pointers sometimes - but if we got a
-- real Handle, then it's valid, so just return 1.
EHandle h -> let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (drop arity xs)
-- A foreign-returned char* has to be tested for NULL sometimes
EConstant (Str s) -> let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (drop arity xs)
_ -> execFail . Msg $
"The argument to isNull should be a pointer or file handle or string, but it was " ++
show ptr ++
". Are all cases covered?"
-- Right now, there's no way to send command-line arguments to the executor,
-- so just return 0.
execForeign env ctxt arity ty fn xs onfail
| Just (FFun "idris_numArgs" _ _) <- foreignFromTT arity ty fn xs
= let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (drop arity xs)
execForeign env ctxt arity ty fn xs onfail
= case foreignFromTT arity ty fn xs of
Just ffun@(FFun f argTs retT) | length xs >= arity ->
do let (args', xs') = (take arity xs, -- foreign args
drop arity xs) -- rest
res <- call ffun (map snd argTs)
case res of
Nothing -> fail $ "Could not call foreign function \"" ++ f ++
"\" with args " ++ show (map snd argTs)
Just r -> return (mkEApp r xs')
_ -> return onfail
splitArg tm | (_, [_,_,l,r]) <- unApplyV tm -- pair, two implicits
= Just (toFDesc l, r)
splitArg _ = Nothing
toFDesc tm
| (EP _ n _, []) <- unApplyV tm = FCon (deNS n)
| (EP _ n _, as) <- unApplyV tm = FApp (deNS n) (map toFDesc as)
toFDesc _ = FUnknown
deNS (NS n _) = n
deNS n = n
prf = sUN "prim__readFile"
pwf = sUN "prim__writeFile"
prs = sUN "prim__readString"
pws = sUN "prim__writeString"
pbm = sUN "prim__believe_me"
pstdin = sUN "prim__stdin"
pstdout = sUN "prim__stdout"
mkfprim = sUN "mkForeignPrim"
pioret = sUN "prim_io_return"
piobind = sUN "prim_io_bind"
upio = sUN "unsafePerformPrimIO"
delay = sUN "Delay"
force = sUN "Force"
-- | Look up primitive operations in the global table and transform
-- them into ExecVal functions
getOp :: Name -> [ExecVal] -> Maybe (Exec ExecVal, [ExecVal])
getOp fn (_ : _ : x : xs) | fn == pbm = Just (return x, xs)
getOp fn (_ : EConstant (Str n) : xs)
| fn == pws =
Just (do execIO $ putStr n
return (EConstant (I 0)), xs)
getOp fn (_:xs)
| fn == prs =
Just (do line <- execIO getLine
return (EConstant (Str line)), xs)
getOp fn (_ : EP _ fn' _ : EConstant (Str n) : xs)
| fn == pwf && fn' == pstdout =
Just (do execIO $ putStr n
return (EConstant (I 0)), xs)
getOp fn (_ : EP _ fn' _ : xs)
| fn == prf && fn' == pstdin =
Just (do line <- execIO getLine
return (EConstant (Str line)), xs)
getOp fn (_ : EHandle h : EConstant (Str n) : xs)
| fn == pwf =
Just (do execIO $ hPutStr h n
return (EConstant (I 0)), xs)
getOp fn (_ : EHandle h : xs)
| fn == prf =
Just (do contents <- execIO $ hGetLine h
return (EConstant (Str (contents ++ "\n"))), xs)
getOp fn (_ : arg : xs)
| fn == prf =
Just $ (execFail (Msg "Can't use prim__readFile on a raw pointer in the executor."), xs)
getOp n args = do (arity, prim) <- getPrim n primitives
if (length args >= arity)
then do res <- applyPrim prim (take arity args)
Just (res, drop arity args)
else Nothing
where getPrim :: Name -> [Prim] -> Maybe (Int, [ExecVal] -> Maybe ExecVal)
getPrim n [] = Nothing
getPrim n ((Prim pn _ arity def _ _) : prims)
| n == pn = Just (arity, execPrim def)
| otherwise = getPrim n prims
execPrim :: ([Const] -> Maybe Const) -> [ExecVal] -> Maybe ExecVal
execPrim f args = EConstant <$> (mapM getConst args >>= f)
getConst (EConstant c) = Just c
getConst _ = Nothing
applyPrim :: ([ExecVal] -> Maybe ExecVal) -> [ExecVal] -> Maybe (Exec ExecVal)
applyPrim fn args = return <$> fn args
-- | Overall wrapper for case tree execution. If there are enough arguments, it takes them,
-- evaluates them, then begins the checks for matching cases.
execCase :: ExecEnv -> Context -> [Name] -> SC -> [ExecVal] -> Exec (Maybe ExecVal)
execCase env ctxt ns sc args =
let arity = length ns in
if arity <= length args
then do let amap = zip ns args
-- trace ("Case " ++ show sc ++ "\n in " ++ show amap ++"\n in env " ++ show env ++ "\n\n" ) $ return ()
caseRes <- execCase' env ctxt amap sc
case caseRes of
Just res -> Just <$> execApp (map (\(n, tm) -> (n, tm)) amap ++ env) ctxt res (drop arity args)
Nothing -> return Nothing
else return Nothing
-- | Take bindings and a case tree and examines them, executing the matching case if possible.
execCase' :: ExecEnv -> Context -> [(Name, ExecVal)] -> SC -> Exec (Maybe ExecVal)
execCase' env ctxt amap (UnmatchedCase _) = return Nothing
execCase' env ctxt amap (STerm tm) =
Just <$> doExec (map (\(n, v) -> (n, v)) amap ++ env) ctxt tm
execCase' env ctxt amap (Case sh n alts) | Just tm <- lookup n amap =
case chooseAlt tm alts of
Just (newCase, newBindings) ->
let amap' = newBindings ++ (filter (\(x,_) -> not (elem x (map fst newBindings))) amap) in
execCase' env ctxt amap' newCase
Nothing -> return Nothing
execCase' _ _ _ cse = fail $ "The impossible happened: tried to exec " ++ show cse
chooseAlt :: ExecVal -> [CaseAlt] -> Maybe (SC, [(Name, ExecVal)])
chooseAlt tm (DefaultCase sc : alts) | ok tm = Just (sc, [])
| otherwise = Nothing
where -- Default cases should only work on applications of constructors or on constants
ok (EApp f x) = ok f
ok (EP Bound _ _) = False
ok (EP Ref _ _) = False
ok _ = True
chooseAlt (EConstant c) (ConstCase c' sc : alts) | c == c' = Just (sc, [])
chooseAlt tm (ConCase n i ns sc : alts) | ((EP _ cn _), args) <- unApplyV tm
, cn == n = Just (sc, zip ns args)
| otherwise = chooseAlt tm alts
chooseAlt tm (_:alts) = chooseAlt tm alts
chooseAlt _ [] = Nothing
data Foreign = FFun String [(FDesc, ExecVal)] FDesc deriving Show
toFType :: FDesc -> FType
toFType (FCon c)
| c == sUN "C_Str" = FString
| c == sUN "C_Float" = FArith ATFloat
| c == sUN "C_Ptr" = FPtr
| c == sUN "C_MPtr" = FManagedPtr
| c == sUN "C_Unit" = FUnit
toFType (FApp c [_,ity])
| c == sUN "C_IntT" = FArith (toAType ity)
where toAType (FCon i)
| i == sUN "C_IntChar" = ATInt ITChar
| i == sUN "C_IntNative" = ATInt ITNative
| i == sUN "C_IntBits8" = ATInt (ITFixed IT8)
| i == sUN "C_IntBits16" = ATInt (ITFixed IT16)
| i == sUN "C_IntBits32" = ATInt (ITFixed IT32)
| i == sUN "C_IntBits64" = ATInt (ITFixed IT64)
toAType t = error (show t ++ " not defined in toAType")
toFType (FApp c [_])
| c == sUN "C_Any" = FAny
toFType t = error (show t ++ " not defined in toFType")
call :: Foreign -> [ExecVal] -> Exec (Maybe ExecVal)
call (FFun name argTypes retType) args =
do fn <- findForeign name
maybe (return Nothing)
(\f -> Just . ioWrap <$> call' f args (toFType retType)) fn
where call' :: ForeignFun -> [ExecVal] -> FType -> Exec ExecVal
call' (Fun _ h) args (FArith (ATInt ITNative)) = do
res <- execIO $ callFFI h retCInt (prepArgs args)
return (EConstant (I (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT8))) = do
res <- execIO $ callFFI h retCChar (prepArgs args)
return (EConstant (B8 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT16))) = do
res <- execIO $ callFFI h retCWchar (prepArgs args)
return (EConstant (B16 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT32))) = do
res <- execIO $ callFFI h retCInt (prepArgs args)
return (EConstant (B32 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT64))) = do
res <- execIO $ callFFI h retCLong (prepArgs args)
return (EConstant (B64 (fromIntegral res)))
call' (Fun _ h) args (FArith ATFloat) = do
res <- execIO $ callFFI h retCDouble (prepArgs args)
return (EConstant (Fl (realToFrac res)))
call' (Fun _ h) args (FArith (ATInt ITChar)) = do
res <- execIO $ callFFI h retCChar (prepArgs args)
return (EConstant (Ch (castCCharToChar res)))
call' (Fun _ h) args FString = do res <- execIO $ callFFI h retCString (prepArgs args)
if res == nullPtr
then return (EPtr res)
else do hStr <- execIO $ peekCString res
return (EConstant (Str hStr))
call' (Fun _ h) args FPtr = EPtr <$> (execIO $ callFFI h (retPtr retVoid) (prepArgs args))
call' (Fun _ h) args FUnit = do _ <- execIO $ callFFI h retVoid (prepArgs args)
return $ EP Ref unitCon EErased
call' _ _ _ = fail "the impossible happened in call' in Execute.hs"
prepArgs = map prepArg
prepArg (EConstant (I i)) = argCInt (fromIntegral i)
prepArg (EConstant (B8 i)) = argCChar (fromIntegral i)
prepArg (EConstant (B16 i)) = argCWchar (fromIntegral i)
prepArg (EConstant (B32 i)) = argCInt (fromIntegral i)
prepArg (EConstant (B64 i)) = argCLong (fromIntegral i)
prepArg (EConstant (Fl f)) = argCDouble (realToFrac f)
prepArg (EConstant (Ch c)) = argCChar (castCharToCChar c) -- FIXME - castCharToCChar only safe for first 256 chars
-- Issue #1720 on the issue tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1720
prepArg (EConstant (Str s)) = argString s
prepArg (EPtr p) = argPtr p
prepArg other = trace ("Could not use " ++ take 100 (show other) ++ " as FFI arg.") undefined
foreignFromTT :: Int -> ExecVal -> ExecVal -> [ExecVal] -> Maybe Foreign
foreignFromTT arity ty (EConstant (Str name)) args
= do argFTyVals <- mapM splitArg (take arity args)
return $ FFun name argFTyVals (toFDesc ty)
foreignFromTT arity ty fn args = trace ("failed to construct ffun from " ++ show (ty,fn,args)) Nothing
getFTy :: ExecVal -> Maybe FType
getFTy (EApp (EP _ (UN fi) _) (EP _ (UN intTy) _))
| fi == txt "FIntT" =
case str intTy of
"ITNative" -> Just (FArith (ATInt ITNative))
"ITChar" -> Just (FArith (ATInt ITChar))
"IT8" -> Just (FArith (ATInt (ITFixed IT8)))
"IT16" -> Just (FArith (ATInt (ITFixed IT16)))
"IT32" -> Just (FArith (ATInt (ITFixed IT32)))
"IT64" -> Just (FArith (ATInt (ITFixed IT64)))
_ -> Nothing
getFTy (EP _ (UN t) _) =
case str t of
"FFloat" -> Just (FArith ATFloat)
"FString" -> Just FString
"FPtr" -> Just FPtr
"FUnit" -> Just FUnit
_ -> Nothing
getFTy _ = Nothing
unEList :: ExecVal -> Maybe [ExecVal]
unEList tm = case unApplyV tm of
(nil, [_]) -> Just []
(cons, ([_, x, xs])) ->
do rest <- unEList xs
return $ x:rest
(f, args) -> Nothing
toConst :: Term -> Maybe Const
toConst (Constant c) = Just c
toConst _ = Nothing
mapMaybeM :: (Functor m, Monad m) => (a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM f [] = return []
mapMaybeM f (x:xs) = do rest <- mapMaybeM f xs
maybe rest (:rest) <$> f x
findForeign :: String -> Exec (Maybe ForeignFun)
findForeign fn = do est <- getExecState
let libs = exec_dynamic_libs est
fns <- mapMaybeM getFn libs
case fns of
[f] -> return (Just f)
[] -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" not found"
return Nothing
fs -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" is ambiguous. Found " ++
show (length fs) ++ " occurrences."
return Nothing
where getFn lib = execIO $ catchIO (tryLoadFn fn lib) (\_ -> return Nothing)
#endif
| athanclark/Idris-dev | src/Idris/Core/Execute.hs | bsd-3-clause | 29,467 | 0 | 6 | 10,849 | 259 | 166 | 93 | 28 | 1 |
-- A wrapper script for Cabal Setup.hs scripts. Allows compiling the real Setup
-- conditionally depending on the Cabal version.
module SetupWrapper (setupWrapper) where
import Distribution.Package
import Distribution.Compiler
import Distribution.Simple.Utils
import Distribution.Simple.Program
import Distribution.Simple.Compiler
import Distribution.Simple.BuildPaths (exeExtension)
import Distribution.Simple.Configure (configCompilerEx)
import Distribution.Simple.GHC (getInstalledPackages)
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Version
import Distribution.Verbosity
import Distribution.Text
import System.Environment
import System.Process
import System.Exit (ExitCode(..), exitWith)
import System.FilePath
import System.Directory (doesFileExist, getModificationTime)
import qualified Control.Exception as Exception
import System.IO.Error (isDoesNotExistError)
import Data.List
import Data.Char
import Control.Monad
-- moreRecentFile is implemented in Distribution.Simple.Utils, but only in
-- Cabal >= 1.18. For backwards-compatibility, we implement a copy with a new
-- name here. Some desirable alternate strategies don't work:
-- * We can't use CPP to check which version of Cabal we're up against because
-- this is the file that's generating the macros for doing that.
-- * We can't use the name moreRecentFiles and use
-- import D.S.U hiding (moreRecentFiles)
-- because on old GHC's (and according to the Report) hiding a name that
-- doesn't exist is an error.
moreRecentFile' :: FilePath -> FilePath -> IO Bool
moreRecentFile' a b = do
exists <- doesFileExist b
if not exists
then return True
else do tb <- getModificationTime b
ta <- getModificationTime a
return (ta > tb)
setupWrapper :: FilePath -> IO ()
setupWrapper setupHsFile = do
args <- getArgs
createDirectoryIfMissingVerbose verbosity True setupDir
compileSetupExecutable
invokeSetupScript args
where
setupDir = "dist/setup-wrapper"
setupVersionFile = setupDir </> "setup" <.> "version"
setupProgFile = setupDir </> "setup" <.> exeExtension
setupMacroFile = setupDir </> "wrapper-macros.h"
useCabalVersion = Version [1,8] []
usePackageDB = [GlobalPackageDB, UserPackageDB]
verbosity = normal
cabalLibVersionToUse comp conf = do
savedVersion <- savedCabalVersion
case savedVersion of
Just version
-> return version
_ -> do version <- installedCabalVersion comp conf
writeFile setupVersionFile (show version ++ "\n")
return version
savedCabalVersion = do
versionString <- readFile setupVersionFile
`Exception.catch` \e -> if isDoesNotExistError e
then return ""
else Exception.throwIO e
case reads versionString of
[(version,s)] | all isSpace s -> return (Just version)
_ -> return Nothing
installedCabalVersion comp conf = do
index <- getInstalledPackages verbosity usePackageDB conf
let cabalDep = Dependency (PackageName "Cabal")
(orLaterVersion useCabalVersion)
case PackageIndex.lookupDependency index cabalDep of
[] -> die $ "The package requires Cabal library version "
++ display useCabalVersion
++ " but no suitable version is installed."
pkgs -> return $ bestVersion (map fst pkgs)
where
bestVersion = maximumBy (comparing preference)
preference version = (sameVersion, sameMajorVersion
,stableVersion, latestVersion)
where
sameVersion = version == cabalVersion
sameMajorVersion = majorVersion version == majorVersion cabalVersion
majorVersion = take 2 . versionBranch
stableVersion = case versionBranch version of
(_:x:_) -> even x
_ -> False
latestVersion = version
-- | If the Setup.hs is out of date wrt the executable then recompile it.
-- Currently this is GHC only. It should really be generalised.
--
compileSetupExecutable = do
setupHsNewer <- setupHsFile `moreRecentFile'` setupProgFile
cabalVersionNewer <- setupVersionFile `moreRecentFile'` setupProgFile
let outOfDate = setupHsNewer || cabalVersionNewer
when outOfDate $ do
debug verbosity "Setup script is out of date, compiling..."
(comp, _, conf) <- configCompilerEx (Just GHC) Nothing Nothing
defaultProgramConfiguration verbosity
cabalLibVersion <- cabalLibVersionToUse comp conf
let cabalPkgid = PackageIdentifier (PackageName "Cabal") cabalLibVersion
debug verbosity $ "Using Cabal library version " ++ display cabalLibVersion
writeFile setupMacroFile (generateVersionMacro cabalLibVersion)
rawSystemProgramConf verbosity ghcProgram conf $
["--make", setupHsFile, "-o", setupProgFile]
++ ghcPackageDbOptions usePackageDB
++ ["-package", display cabalPkgid
,"-cpp", "-optP-include", "-optP" ++ setupMacroFile
,"-odir", setupDir, "-hidir", setupDir]
where
ghcPackageDbOptions dbstack = case dbstack of
(GlobalPackageDB:UserPackageDB:dbs) -> concatMap specific dbs
(GlobalPackageDB:dbs) -> "-no-user-package-conf"
: concatMap specific dbs
_ -> ierror
where
specific (SpecificPackageDB db) = [ "-package-conf", db ]
specific _ = ierror
ierror = error "internal error: unexpected package db stack"
generateVersionMacro :: Version -> String
generateVersionMacro version =
concat
["/* DO NOT EDIT: This file is automatically generated by Cabal */\n\n"
,"#define CABAL_VERSION_CHECK(major1,major2,minor) (\\\n"
," (major1) < ",major1," || \\\n"
," (major1) == ",major1," && (major2) < ",major2," || \\\n"
," (major1) == ",major1," && (major2) == ",major2," && (minor) <= ",minor,")"
,"\n\n"
]
where
(major1:major2:minor:_) = map show (versionBranch version ++ repeat 0)
invokeSetupScript :: [String] -> IO ()
invokeSetupScript args = do
info verbosity $ unwords (setupProgFile : args)
process <- runProcess (currentDir </> setupProgFile) args
Nothing Nothing
Nothing Nothing Nothing
exitCode <- waitForProcess process
unless (exitCode == ExitSuccess) $ exitWith exitCode
| fit-ivs/calc | deps/pango-0.13.1.1/SetupWrapper.hs | gpl-3.0 | 6,967 | 0 | 17 | 2,012 | 1,351 | 703 | 648 | 123 | 9 |
{-# LANGUAGE Rank2Types #-}
module Opaleye.Internal.PackMap where
import qualified Opaleye.Internal.Tag as T
import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ
import Control.Applicative (Applicative, pure, (<*>), liftA2)
import qualified Control.Monad.Trans.State as State
import Data.Profunctor (Profunctor, dimap)
import Data.Profunctor.Product (ProductProfunctor, empty, (***!))
import qualified Data.Profunctor.Product as PP
import qualified Data.Functor.Identity as I
-- This is rather like a Control.Lens.Traversal with the type
-- parameters switched but I'm not sure if it should be required to
-- obey the same laws.
--
-- TODO: We could attempt to generalise this to
--
-- data LensLike f a b s t = LensLike ((a -> f b) -> s -> f t)
--
-- i.e. a wrapped, argument-flipped Control.Lens.LensLike
--
-- This would allow us to do the Profunctor and ProductProfunctor
-- instances (requiring just Functor f and Applicative f respectively)
-- and share them between many different restrictions of f. For
-- example, TableColumnMaker is like a Setter so we would restrict f
-- to the Distributive case.
-- | A 'PackMap' @a@ @b@ @s@ @t@ encodes how an @s@ contains an
-- updatable sequence of @a@ inside it. Each @a@ in the sequence can
-- be updated to a @b@ (and the @s@ changes to a @t@ to reflect this
-- change of type).
--
-- 'PackMap' is just like a @Traversal@ from the lens package.
-- 'PackMap' has a different order of arguments to @Traversal@ because
-- it typically needs to be made a 'Profunctor' (and indeed
-- 'ProductProfunctor') in @s@ and @t@. It is unclear at this point
-- whether we want the same @Traversal@ laws to hold or not. Our use
-- cases may be much more general.
data PackMap a b s t = PackMap (Applicative f =>
(a -> f b) -> s -> f t)
-- | Replaces the targeted occurences of @a@ in @s@ with @b@ (changing
-- the @s@ to a @t@ in the process). This can be done via an
-- 'Applicative' action.
--
-- 'traversePM' is just like @traverse@ from the @lens@ package.
-- 'traversePM' used to be called @packmap@.
traversePM :: Applicative f => PackMap a b s t -> (a -> f b) -> s -> f t
traversePM (PackMap f) = f
-- | Modify the targeted occurrences of @a@ in @s@ with @b@ (changing
-- the @s@ to a @t@ in the process).
--
-- 'overPM' is just like @over@ from the @lens@ pacakge.
overPM :: PackMap a b s t -> (a -> b) -> s -> t
overPM p f = I.runIdentity . traversePM p (I.Identity . f)
-- {
-- | A helpful monad for writing columns in the AST
type PM a = State.State (a, Int)
new :: PM a String
new = do
(a, i) <- State.get
State.put (a, i + 1)
return (show i)
write :: a -> PM [a] ()
write a = do
(as, i) <- State.get
State.put (as ++ [a], i)
run :: PM [a] r -> (r, [a])
run m = (r, as)
where (r, (as, _)) = State.runState m ([], 0)
-- }
-- { General functions for writing columns in the AST
-- | Make a fresh name for an input value (the variable @primExpr@
-- type is typically actually a 'HPQ.PrimExpr') based on the supplied
-- function and the unique 'T.Tag' that is used as part of our
-- @QueryArr@.
--
-- Add the fresh name and the input value it refers to to the list in
-- the state parameter.
extractAttrPE :: (primExpr -> String -> String) -> T.Tag -> primExpr
-> PM [(HPQ.Symbol, primExpr)] HPQ.PrimExpr
extractAttrPE mkName t pe = do
i <- new
let s = HPQ.Symbol (mkName pe i) t
write (s, pe)
return (HPQ.AttrExpr s)
-- | As 'extractAttrPE' but ignores the 'primExpr' when making the
-- fresh column name and just uses the supplied 'String' and 'T.Tag'.
extractAttr :: String -> T.Tag -> primExpr
-> PM [(HPQ.Symbol, primExpr)] HPQ.PrimExpr
extractAttr s = extractAttrPE (const (s ++))
-- }
eitherFunction :: Functor f
=> (a -> f b)
-> (a' -> f b')
-> Either a a'
-> f (Either b b')
eitherFunction f g = fmap (either (fmap Left) (fmap Right)) (f PP.+++! g)
-- {
-- Boilerplate instance definitions. There's no choice here apart
-- from the order in which the applicative is applied.
instance Functor (PackMap a b s) where
fmap f (PackMap g) = PackMap ((fmap . fmap . fmap) f g)
instance Applicative (PackMap a b s) where
pure x = PackMap (pure (pure (pure x)))
PackMap f <*> PackMap x = PackMap (liftA2 (liftA2 (<*>)) f x)
instance Profunctor (PackMap a b) where
dimap f g (PackMap q) = PackMap (fmap (dimap f (fmap g)) q)
instance ProductProfunctor (PackMap a b) where
empty = PP.defaultEmpty
(***!) = PP.defaultProfunctorProduct
instance PP.SumProfunctor (PackMap a b) where
f +++! g = (PackMap (\x -> eitherFunction (f' x) (g' x)))
where PackMap f' = f
PackMap g' = g
-- }
| alanz/haskell-opaleye | src/Opaleye/Internal/PackMap.hs | bsd-3-clause | 4,764 | 0 | 12 | 1,065 | 1,136 | 629 | 507 | 59 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Stack.FileWatch
( fileWatch
, fileWatchPoll
, printExceptionStderr
) where
import Blaze.ByteString.Builder (toLazyByteString, copyByteString)
import Blaze.ByteString.Builder.Char.Utf8 (fromShow)
import Control.Concurrent.Async (race_)
import Control.Concurrent.STM
import Control.Exception (Exception)
import Control.Exception.Enclosed (tryAny)
import Control.Monad (forever, unless, when)
import qualified Data.ByteString.Lazy as L
import qualified Data.Map.Strict as Map
import Data.Monoid ((<>))
import Data.Set (Set)
import qualified Data.Set as Set
import Data.String (fromString)
import Data.Traversable (forM)
import Ignore
import Path
import System.FSNotify
import System.IO (stderr)
-- | Print an exception to stderr
printExceptionStderr :: Exception e => e -> IO ()
printExceptionStderr e =
L.hPut stderr $ toLazyByteString $ fromShow e <> copyByteString "\n"
fileWatch :: IO (Path Abs Dir)
-> ((Set (Path Abs File) -> IO ()) -> IO ())
-> IO ()
fileWatch = fileWatchConf defaultConfig
fileWatchPoll :: IO (Path Abs Dir)
-> ((Set (Path Abs File) -> IO ()) -> IO ())
-> IO ()
fileWatchPoll = fileWatchConf $ defaultConfig { confUsePolling = True }
-- | Run an action, watching for file changes
--
-- The action provided takes a callback that is used to set the files to be
-- watched. When any of those files are changed, we rerun the action again.
fileWatchConf :: WatchConfig
-> IO (Path Abs Dir)
-> ((Set (Path Abs File) -> IO ()) -> IO ())
-> IO ()
fileWatchConf cfg getProjectRoot inner = withManagerConf cfg $ \manager -> do
allFiles <- newTVarIO Set.empty
dirtyVar <- newTVarIO True
watchVar <- newTVarIO Map.empty
projRoot <- getProjectRoot
mChecker <- findIgnoreFiles [VCSGit, VCSMercurial, VCSDarcs] projRoot >>= buildChecker
(FileIgnoredChecker isFileIgnored) <-
case mChecker of
Left err ->
do putStrLn $ "Failed to parse VCS's ignore file: " ++ err
return $ FileIgnoredChecker (const False)
Right chk -> return chk
let onChange event = atomically $ do
files <- readTVar allFiles
when (eventPath event `Set.member` files) (writeTVar dirtyVar True)
setWatched :: Set (Path Abs File) -> IO ()
setWatched files = do
atomically $ writeTVar allFiles $ Set.map toFilePath files
watch0 <- readTVarIO watchVar
let actions = Map.mergeWithKey
keepListening
stopListening
startListening
watch0
newDirs
watch1 <- forM (Map.toList actions) $ \(k, mmv) -> do
mv <- mmv
return $
case mv of
Nothing -> Map.empty
Just v -> Map.singleton k v
atomically $ writeTVar watchVar $ Map.unions watch1
where
newDirs = Map.fromList $ map (, ())
$ Set.toList
$ Set.map parent files
keepListening _dir listen () = Just $ return $ Just listen
stopListening = Map.map $ \f -> do
() <- f
return Nothing
startListening = Map.mapWithKey $ \dir () -> do
let dir' = fromString $ toFilePath dir
listen <- watchDir manager dir' (not . isFileIgnored . eventPath) onChange
return $ Just listen
let watchInput = do
line <- getLine
unless (line == "quit") $ do
case line of
"help" -> do
putStrLn ""
putStrLn "help: display this help"
putStrLn "quit: exit"
putStrLn "build: force a rebuild"
putStrLn "watched: display watched directories"
"build" -> atomically $ writeTVar dirtyVar True
"watched" -> do
watch <- readTVarIO watchVar
mapM_ (putStrLn . toFilePath) (Map.keys watch)
_ -> putStrLn $ concat
[ "Unknown command: "
, show line
, ". Try 'help'"
]
watchInput
race_ watchInput $ forever $ do
atomically $ do
dirty <- readTVar dirtyVar
check dirty
eres <- tryAny $ inner setWatched
-- Clear dirtiness flag after the build to avoid an infinite
-- loop caused by the build itself triggering dirtiness. This
-- could be viewed as a bug, since files changed during the
-- build will not trigger an extra rebuild, but overall seems
-- like better behavior. See
-- https://github.com/commercialhaskell/stack/issues/822
atomically $ writeTVar dirtyVar False
case eres of
Left e -> printExceptionStderr e
Right () -> putStrLn "Success! Waiting for next file change."
putStrLn "Type help for available commands"
| robstewart57/stack | src/Stack/FileWatch.hs | bsd-3-clause | 5,294 | 0 | 25 | 1,856 | 1,292 | 642 | 650 | 111 | 7 |
import Sudoku
import Control.Exception
import System.Environment
import Data.Maybe
main :: IO ()
main = do
[f] <- getArgs
grids <- fmap lines $ readFile f
print (length (filter isJust (map solve grids)))
| lywaterman/parconc-examples | sudoku-par1.hs | bsd-3-clause | 217 | 0 | 13 | 45 | 89 | 44 | 45 | 9 | 1 |
{-# LANGUAGE ImplicitParams, TypeFamilies #-}
module T3540 where
thing :: (a~Int)
thing = undefined
thing1 :: Int -> (a~Int)
thing1 = undefined
thing2 :: (a~Int) -> Int
thing2 = undefined
thing3 :: (?dude :: Int) -> Int
thing3 = undefined
thing4:: (Eq a) -> Int
thing4 = undefined | forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/typecheck/should_fail/T3540.hs | bsd-3-clause | 288 | 0 | 7 | 55 | 104 | 61 | 43 | -1 | -1 |
module Main where
import Data.Functor ((<$>))
import Data.Maybe (isJust, fromJust)
import System.Cmd (rawSystem)
import System.Exit (ExitCode(..))
import System.IO (hFlush, stdout)
import System.Posix.Process (forkProcess, getProcessStatus)
import Hackonad.LineParser
typePrompt :: IO ()
typePrompt = putStr "> " >> hFlush stdout
readCommand :: IO (String, [String])
readCommand = parseInputLine <$> getLine
while :: (Monad m) => (a -> m (Bool, a)) -> a -> m ()
while action initialValue = action initialValue >>= \ (res, iterVal) -> if res then while action iterVal else return ()
proccessExitCode :: ExitCode -> String -> Int -> IO ()
proccessExitCode ExitSuccess _ _ = return ()
proccessExitCode (ExitFailure code) command sessionLine = case code of
127 -> putStrLn $ "Hackonad: " ++ show sessionLine ++ ": " ++ command ++ ": not found"
otherwise -> putStrLn $ "Hackonad: " ++ show code ++ ": " ++ command
mainLoop :: Int -> IO (Bool, Int)
mainLoop sessionLine = do
typePrompt
(command, parameters) <- readCommand
if command == "exit"
then return (False, sessionLine)
else do
pid <- forkProcess $ do
exitCode <- rawSystem command parameters
proccessExitCode exitCode command sessionLine
status <- getProcessStatus True False pid
if isJust status
then do
putStrLn $ "Base +" ++ show ( fromJust status )
return (True, sessionLine + 1)
else do
putStrLn "Base +"
return (True, sessionLine + 1)
main :: IO ()
main = while mainLoop 0
| triplepointfive/Hackonad | src/Main.hs | mit | 1,671 | 0 | 16 | 466 | 545 | 283 | 262 | 39 | 3 |
module Main where
import Data.Monoid
import Test.Framework
import qualified Test.Parser as Parser
import qualified Test.Eval as Eval
main :: IO ()
main = defaultMainWithOpts tests mempty
tests = concat
[ Parser.tests
, Eval.tests
]
| forestbelton/anima | Test/Main.hs | mit | 250 | 0 | 7 | 52 | 68 | 41 | 27 | 10 | 1 |
module Main where
import Reddit.TheButton.Connection
import Reddit.TheButton.Types
import Reddit.TheButton.AnyBar
import Reddit.TheButton.Utility
import Control.Monad (forever)
import Control.Concurrent (forkIO)
import Control.Concurrent.Chan (readChan, dupChan)
import System.IO (hSetBuffering, BufferMode(..), stdout)
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
chan1 <- getTicks
chan2 <- mapChan btnColor chan1
forkIO $ abUpdateFromChan "1738" chan2
forever $ do
tick <- readChan chan1
putStrLn (btnColor tick)
where
btnColor = show . secToColor . bSecondsLeft
| romac/thebutton.hs | src/Main.hs | mit | 624 | 0 | 12 | 112 | 180 | 97 | 83 | 19 | 1 |
-- | This file defines 'FormulaTree', the type used for modeling the calculation trees.
--
-- Author: Thorsten Rangwich. See file <../LICENSE> for details.
module Tree.FormulaTree
(
FormulaTree(..),
TreeError(..),
NamedFunction(..) -- FIXME: Export creater and exporters, not type
)
where
import qualified Data.Plain as P
import qualified Data.SheetLayout as L
-- | Type to mark error in tree
data TreeError = NamedError String -- ^ Named error - this should be used
| CircularReference -- ^ Circular reference in tree.
| UnspecifiedError -- ^ Unspecified error - not useful, better add more specific errors
deriving Show
-- | Wrapper to be used in the trees.
data NamedFunction = NamedFunction { funcName :: String, funcCall :: P.PlainFunction }
-- | Compiled representation of a formula
data FormulaTree = Raw P.Plain -- ^ Node is plain result value
| Reference L.Address
| Funcall NamedFunction [FormulaTree] -- ^ Node is a formula
| TreeError TreeError -- ^ Node is evaluated to an error
-- This makes sense for errors affecting the tree like circular references
-- in contrast to plain value errors like div/0.
| tnrangwi/grill | src/Tree/FormulaTree.hs | mit | 1,303 | 0 | 9 | 368 | 134 | 91 | 43 | 16 | 0 |
{-# LANGUAGE Rank2Types #-}
module Statistics
where
import Data.Foldable
import Control.Monad.State
import System.Random
import Data.List
type Rnd a = (RandomGen g) => State g a
randomRM :: (Random a) => (a, a) -> Rnd a
randomRM v = do
g <- get
(x, g') <- return $ randomR v g
put g'
return x
choose :: [a] -> Rnd a
choose l = do
let n = length l
i <- randomRM (0, n - 1)
return (l !! i)
chooseIO :: (Foldable f) => f a -> IO a
chooseIO l = do
let l' = toList l
n = length l'
i <- randomRIO (0, n - 1)
return (l' !! i)
stdNormal :: (Random a, Ord a, Floating a) => Rnd a
stdNormal = do
u1 <- randomRM (-1, 1)
u2 <- randomRM (-1, 1)
let m = stdNormalMarsaglia u1 u2
case m of
Nothing -> stdNormal
Just (z1, _) -> return z1
stdNormalMarsaglia :: (Ord a, Floating a) => a -> a -> Maybe (a, a)
stdNormalMarsaglia y1 y2 =
if q > 1 then Nothing else Just (z1, z2)
where z1 = y1 * p
z2 = y2 * p
q = y1 * y1 + y2 * y2
p = sqrt ((-2) * log q / q)
normal :: (Random a, Ord a, Floating a) => a -> a -> Rnd a
normal mu sigma = do
n <- stdNormal
return $ mu + n * sigma
normalR :: (Random a, Ord a, Floating a) => (a, a) -> a -> a -> Rnd a
normalR (mn, mx) mu sigma = do
n <- normal mu sigma
if n < mn
then return mn
else if n > mx
then return mx else return n
normalIO :: (Random a, Ord a, Floating a) => a -> a -> IO a
normalIO mu sigma = newStdGen >>= return . evalState (normal mu sigma)
normalRIO :: (Random a, Ord a, Floating a) => (a, a) -> a -> a -> IO a
normalRIO limits mu sigma = newStdGen >>= return . evalState (normalR limits mu sigma)
average :: (Fractional a) => [a] -> a
average l = go 0 0 l
where go acc len [] = acc / len
go acc len (x:xs) = go (acc + x) (len + 1) xs
averageInt :: [Int] -> Int
averageInt l = go 0 0 l
where go acc len [] = acc `div` len
go acc len (x:xs) = go (acc + x) (len + 1) xs
median :: (Ord a, Num a) => [a] -> a
median [] = error "Median on empty list"
median l = (sort l) !! (length l `div` 2)
-- chance of a to b
chance :: Int -> Int -> Rnd Bool
chance a b = do
v <- randomRM (1, b)
if a <= v - 1
then return True
else return False
-- shuffle :: [a] -> Rnd [a]
shuffle l = shuffle' l [] -- >>= reverse >>= flip shuffle' []
where shuffle' [] bs = return bs
shuffle' as bs = do
el <- choose as
shuffle' (delete el as) (el : bs)
| anttisalonen/starrover2 | src/Statistics.hs | mit | 2,451 | 0 | 12 | 719 | 1,251 | 639 | 612 | 76 | 3 |
{-# LANGUAGE FlexibleInstances #-}
module TermSpec where
import Data.Text as T
import Test.QuickCheck
import Faun.Term
import TextGen
instance Arbitrary Term where
arbitrary = oneof [genVar, genConst, genFun]
genTerms :: Gen [Term]
genTerms = sized $ \n -> do
size <- choose (0, n `mod` 6) -- Huge lists of arguments make the test result hard to read / interpret.
vectorOf size arbitrary
genVar :: Gen Term
genVar = do
name <- genCamelString
return $ Variable $ T.pack name
genConst :: Gen Term
genConst = do
name <- genPascalString
return $ Constant $ T.pack name
genFun :: Gen Term
genFun = do
name <- genPascalString
args <- genTerms
return $ Function (T.pack name) args
| PhDP/Sphinx-AI | tests/TermSpec.hs | mit | 701 | 0 | 12 | 140 | 225 | 117 | 108 | 25 | 1 |
-- |
-- Module: BigE.Attribute.Vert_P_N
-- Copyright: (c) 2017 Patrik Sandahl
-- Licence: MIT
-- Maintainer: Patrik Sandahl <[email protected]>
-- Stability: experimental
-- Portability: portable
-- Language: Haskell2010
module BigE.Attribute.Vert_P_N
( Vertex (..)
) where
import BigE.Attribute (Attribute (..), allocBoundBuffers,
fillBoundVBO, pointerOffset)
import Control.Monad (unless)
import qualified Data.Vector.Storable as Vector
import Foreign (Storable (..), castPtr, plusPtr)
import Graphics.GL (GLfloat)
import qualified Graphics.GL as GL
import Linear (V3)
-- | A convenience definition of a vertex containing two attributes.
-- The vertex position and the vertex normal.
data Vertex = Vertex
{ position :: !(V3 GLfloat)
, normal :: !(V3 GLfloat)
} deriving (Eq, Show)
-- | Storable instance.
instance Storable Vertex where
sizeOf v = sizeOf (position v) + sizeOf (normal v)
alignment v = alignment $ position v
peek ptr = do
p <- peek $ castPtr ptr
let nPtr = castPtr (ptr `plusPtr` sizeOf p)
n <- peek nPtr
return Vertex { position = p, normal = n }
poke ptr v = do
let pPtr = castPtr ptr
nPtr = castPtr (pPtr `plusPtr` sizeOf (position v))
poke pPtr $ position v
poke nPtr $ normal v
-- | Attribute instance.
instance Attribute Vertex where
initAttributes bufferUsage vertices = do
buffers <- allocBoundBuffers
unless (Vector.null vertices) $ do
item <- fillBoundVBO vertices bufferUsage
let itemSize = fromIntegral $ sizeOf item
-- Position.
GL.glEnableVertexAttribArray 0
GL.glVertexAttribPointer 0 3 GL.GL_FLOAT GL.GL_FALSE
itemSize
(pointerOffset 0)
-- Normal.
GL.glEnableVertexAttribArray 1
GL.glVertexAttribPointer 1 3 GL.GL_FLOAT GL.GL_FALSE
itemSize
(pointerOffset $ sizeOf (position item))
return buffers
| psandahl/big-engine | src/BigE/Attribute/Vert_P_N.hs | mit | 2,273 | 0 | 16 | 786 | 524 | 274 | 250 | 46 | 0 |
{-# LANGUAGE CPP, OverloadedStrings #-}
module NewAccount (newAccountSpecs) where
import Data.Monoid
import Yesod.Auth
import Yesod.Test
import Foundation
import Text.XML.Cursor (attribute)
import qualified Data.Text as T
redirectCode :: Int
#if MIN_VERSION_yesod_test(1,4,0)
redirectCode = 303
#else
redirectCode = 302
#endif
-- In 9f379bc219bd1fdf008e2c179b03e98a05b36401 (which went into yesod-form-1.3.9)
-- the numbering of fields was changed. We normally wouldn't care because fields
-- can be set via 'byLabel', but hidden fields have no label so we must use the id
-- directly. We temporarily support both versions of yesod form with the following.
f1, f2 :: T.Text
#if MIN_VERSION_yesod_form(1,3,9)
f1 = "f1"
f2 = "f2"
#else
f1 = "f2"
f2 = "f3"
#endif
newAccountSpecs :: YesodSpec MyApp
newAccountSpecs =
ydescribe "New account tests" $ do
yit "new account with mismatched passwords" $ do
get' "/auth/page/account/newaccount"
statusIs 200
bodyContains "Register"
post'"/auth/page/account/newaccount" $ do
addNonce
byLabel "Username" "abc"
byLabel "Email" "[email protected]"
byLabel "Password" "xxx"
byLabel "Confirm" "yyy"
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "Passwords did not match"
yit "creates a new account" $ do
get' "/auth/page/account/newaccount"
statusIs 200
post'"/auth/page/account/newaccount" $ do
addNonce
byLabel "Username" "abc"
byLabel "Email" "[email protected]"
byLabel "Password" "xxx"
byLabel "Confirm" "xxx"
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "A confirmation e-mail has been sent to [email protected]"
(username, email, verify) <- lastVerifyEmail
assertEqual "username" username "abc"
assertEqual "email" email "[email protected]"
get' "/auth/page/account/verify/abc/zzzzzz"
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "invalid verification key"
-- try login
get' "/auth/login"
statusIs 200
post'"/auth/page/account/login" $ do
byLabel "Username" "abc"
byLabel "Password" "yyy"
statusIs redirectCode
get' "/auth/login"
statusIs 200
bodyContains "Invalid username/password combination"
-- valid login
post'"/auth/page/account/login" $ do
byLabel "Username" "abc"
byLabel "Password" "xxx"
statusIs 200
bodyContains "Your email has not yet been verified"
-- valid login with email
get' "/auth/login"
statusIs 200
post'"/auth/page/account/login" $ do
byLabel "Username" "[email protected]"
byLabel "Password" "xxx"
statusIs 200
bodyContains "Your email has not yet been verified"
-- resend verify email
post'"/auth/page/account/resendverifyemail" $ do
addNonce
addPostParam f1 "abc" -- username is also a hidden field
statusIs redirectCode
get' "/"
bodyContains "A confirmation e-mail has been sent to [email protected]"
(username', email', verify') <- lastVerifyEmail
assertEqual "username" username' "abc"
assertEqual "email" email' "[email protected]"
assertEqual "verify" True (verify /= verify')
-- verify email
get' verify'
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "You are logged in as abc"
post $ AuthR LogoutR
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "Please visit the <a href=\"/auth/login\">Login page"
-- valid login
get' "/auth/login"
post'"/auth/page/account/login" $ do
byLabel "Username" "abc"
byLabel "Password" "xxx"
statusIs redirectCode
get' "/"
bodyContains "You are logged in as abc"
-- logout
post $ AuthR LogoutR
-- valid login with email
get' "/auth/login"
post'"/auth/page/account/login" $ do
byLabel "Username" "[email protected]"
byLabel "Password" "xxx"
statusIs 302
get' "/"
bodyContains "You are logged in as abc"
-- logout
post $ AuthR LogoutR
-- reset password
get' "/auth/page/account/resetpassword"
statusIs 200
bodyContains "Send password reset email"
post'"/auth/page/account/resetpassword" $ do
byLabel "Username" "abc"
addNonce
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "A password reset email has been sent to your email address"
(username'', email'', newpwd) <- lastNewPwdEmail
assertEqual "User" username'' "abc"
assertEqual "Email" email'' "[email protected]"
-- bad key
get' newpwd
statusIs 200
post'"/auth/page/account/setpassword" $ do
addNonce
byLabel "New password" "www"
byLabel "Confirm" "www"
addPostParam f1 "abc"
addPostParam f2 "qqqqqqqqqqqqqq"
statusIs 403
bodyContains "Invalid key"
-- good key
get' newpwd
statusIs 200
matches <- htmlQuery $ "input[name=" <> f2 <> "][type=hidden][value]"
post'"/auth/page/account/setpassword" $ do
addNonce
byLabel "New password" "www"
byLabel "Confirm" "www"
addPostParam f1 "abc"
key <- case matches of
[] -> error "Unable to find set password key"
element:_ -> return $ head $ attribute "value" $ parseHTML element
addPostParam f2 key
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "Password updated"
bodyContains "You are logged in as abc"
post $ AuthR LogoutR
-- check new password
get' "/auth/login"
post'"/auth/page/account/login" $ do
byLabel "Username" "abc"
byLabel "Password" "www"
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "You are logged in as abc"
yit "errors with a username with a period" $ do
get' "/auth/page/account/newaccount"
statusIs 200
post' "/auth/page/account/newaccount" $ do
addNonce
byLabel "Username" "x.y"
byLabel "Email" "[email protected]"
byLabel "Password" "hunter2"
byLabel "Confirm" "hunter2"
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "Invalid username" -- Issue #2: a valid username was not checked on creation
| jasonzoladz/yesod-auth-account-fork | tests/NewAccount.hs | mit | 7,624 | 0 | 20 | 2,916 | 1,282 | 522 | 760 | 170 | 2 |
module Hamming (distance) where
distance :: String -> String -> Maybe Int
distance xs ys = error "You need to implement this function."
| exercism/xhaskell | exercises/practice/hamming/src/Hamming.hs | mit | 137 | 0 | 7 | 24 | 38 | 20 | 18 | 3 | 1 |
import Data.Digits
lend = length . digits 10
bases = [1..9] -- lend (10^x) > 10 for all x
exponents = [1..30] -- lend (9^x) > x for x>30
pairs = [(base,exponent) | base <- bases, exponent <- exponents]
isValid (base,exponent) = (lend (base^exponent) == exponent)
valid = filter isValid pairs
answer = length valid | gumgl/project-euler | 63/63.hs | mit | 319 | 0 | 9 | 60 | 119 | 66 | 53 | 8 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
-- | The basic typeclass for a Yesod application.
module Yesod.Internal.Core
( -- * Type classes
Yesod (..)
, YesodDispatch (..)
, RenderRoute (..)
-- ** Breadcrumbs
, YesodBreadcrumbs (..)
, breadcrumbs
-- * Utitlities
, maybeAuthorized
, widgetToPageContent
-- * Defaults
, defaultErrorHandler
-- * Data types
, AuthResult (..)
-- * Sessions
, SessionBackend (..)
, defaultClientSessionBackend
, clientSessionBackend
, loadClientSession
, BackendSession
-- * jsLoader
, ScriptLoadPosition (..)
, BottomOfHeadAsync
, loadJsYepnope
-- * Misc
, yesodVersion
, yesodRender
, resolveApproot
, Approot (..)
, FileUpload (..)
, runFakeHandler
) where
import Yesod.Content
import Yesod.Handler hiding (lift, getExpires)
import Yesod.Routes.Class
import Data.Word (Word64)
import Control.Arrow ((***))
import Control.Monad (forM)
import Yesod.Widget
import Yesod.Request
import qualified Network.Wai as W
import Yesod.Internal
import Yesod.Internal.Session
import Yesod.Internal.Request
import qualified Web.ClientSession as CS
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as L
import qualified Data.IORef as I
import Data.Monoid
import Text.Hamlet
import Text.Julius
import Text.Blaze ((!), customAttribute, textTag, toValue, unsafeLazyByteString)
import qualified Text.Blaze.Html5 as TBH
import Data.Text.Lazy.Builder (toLazyText)
import Data.Text.Lazy.Encoding (encodeUtf8)
import Data.Maybe (fromMaybe, isJust)
import Control.Monad.IO.Class (MonadIO (liftIO))
import Control.Monad.Trans.Resource (runResourceT)
import Web.Cookie (parseCookies)
import qualified Data.Map as Map
import Data.Time
import Network.HTTP.Types (encodePath)
import qualified Data.Text as T
import Data.Text (Text)
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Encoding.Error as TEE
import Blaze.ByteString.Builder (Builder, toByteString)
import Blaze.ByteString.Builder.Char.Utf8 (fromText)
import Data.List (foldl')
import qualified Network.HTTP.Types as H
import Web.Cookie (SetCookie (..))
import Language.Haskell.TH.Syntax (Loc (..))
import Text.Blaze (preEscapedToMarkup)
import Data.Aeson (Value (Array, String))
import Data.Aeson.Encode (encode)
import qualified Data.Vector as Vector
import Network.Wai.Middleware.Gzip (GzipSettings, def)
import Network.Wai.Parse (tempFileBackEnd, lbsBackEnd)
import qualified Paths_yesod_core
import Data.Version (showVersion)
import System.Log.FastLogger (Logger, mkLogger, loggerDate, LogStr (..), loggerPutStr)
import Control.Monad.Logger (LogLevel (LevelInfo, LevelOther), LogSource)
import System.Log.FastLogger.Date (ZonedDate)
import System.IO (stdout)
yesodVersion :: String
yesodVersion = showVersion Paths_yesod_core.version
-- | This class is automatically instantiated when you use the template haskell
-- mkYesod function. You should never need to deal with it directly.
class YesodDispatch sub master where
yesodDispatch
:: Yesod master
=> Logger
-> master
-> sub
-> (Route sub -> Route master)
-> (Maybe (SessionBackend master) -> W.Application) -- ^ 404 handler
-> (Route sub -> Maybe (SessionBackend master) -> W.Application) -- ^ 405 handler
-> Text -- ^ request method
-> [Text] -- ^ pieces
-> Maybe (SessionBackend master)
-> W.Application
yesodRunner :: Yesod master
=> Logger
-> GHandler sub master ChooseRep
-> master
-> sub
-> Maybe (Route sub)
-> (Route sub -> Route master)
-> Maybe (SessionBackend master)
-> W.Application
yesodRunner = defaultYesodRunner
-- | How to determine the root of the application for constructing URLs.
--
-- Note that future versions of Yesod may add new constructors without bumping
-- the major version number. As a result, you should /not/ pattern match on
-- @Approot@ values.
data Approot master = ApprootRelative -- ^ No application root.
| ApprootStatic Text
| ApprootMaster (master -> Text)
| ApprootRequest (master -> W.Request -> Text)
type ResolvedApproot = Text
-- | Define settings for a Yesod applications. All methods have intelligent
-- defaults, and therefore no implementation is required.
class RenderRoute a => Yesod a where
-- | An absolute URL to the root of the application. Do not include
-- trailing slash.
--
-- Default value: 'ApprootRelative'. This is valid under the following
-- conditions:
--
-- * Your application is served from the root of the domain.
--
-- * You do not use any features that require absolute URLs, such as Atom
-- feeds and XML sitemaps.
--
-- If this is not true, you should override with a different
-- implementation.
approot :: Approot a
approot = ApprootRelative
-- | Output error response pages.
errorHandler :: ErrorResponse -> GHandler sub a ChooseRep
errorHandler = defaultErrorHandler
-- | Applies some form of layout to the contents of a page.
defaultLayout :: GWidget sub a () -> GHandler sub a RepHtml
defaultLayout w = do
p <- widgetToPageContent w
mmsg <- getMessage
hamletToRepHtml [hamlet|
$newline never
$doctype 5
<html>
<head>
<title>#{pageTitle p}
^{pageHead p}
<body>
$maybe msg <- mmsg
<p .message>#{msg}
^{pageBody p}
|]
-- | Override the rendering function for a particular URL. One use case for
-- this is to offload static hosting to a different domain name to avoid
-- sending cookies.
urlRenderOverride :: a -> Route a -> Maybe Builder
urlRenderOverride _ _ = Nothing
-- | Determine if a request is authorized or not.
--
-- Return 'Authorized' if the request is authorized,
-- 'Unauthorized' a message if unauthorized.
-- If authentication is required, return 'AuthenticationRequired'.
isAuthorized :: Route a
-> Bool -- ^ is this a write request?
-> GHandler s a AuthResult
isAuthorized _ _ = return Authorized
-- | Determines whether the current request is a write request. By default,
-- this assumes you are following RESTful principles, and determines this
-- from request method. In particular, all except the following request
-- methods are considered write: GET HEAD OPTIONS TRACE.
--
-- This function is used to determine if a request is authorized; see
-- 'isAuthorized'.
isWriteRequest :: Route a -> GHandler s a Bool
isWriteRequest _ = do
wai <- waiRequest
return $ W.requestMethod wai `notElem`
["GET", "HEAD", "OPTIONS", "TRACE"]
-- | The default route for authentication.
--
-- Used in particular by 'isAuthorized', but library users can do whatever
-- they want with it.
authRoute :: a -> Maybe (Route a)
authRoute _ = Nothing
-- | A function used to clean up path segments. It returns 'Right' with a
-- clean path or 'Left' with a new set of pieces the user should be
-- redirected to. The default implementation enforces:
--
-- * No double slashes
--
-- * There is no trailing slash.
--
-- Note that versions of Yesod prior to 0.7 used a different set of rules
-- involing trailing slashes.
cleanPath :: a -> [Text] -> Either [Text] [Text]
cleanPath _ s =
if corrected == s
then Right $ map dropDash s
else Left corrected
where
corrected = filter (not . T.null) s
dropDash t
| T.all (== '-') t = T.drop 1 t
| otherwise = t
-- | Builds an absolute URL by concatenating the application root with the
-- pieces of a path and a query string, if any.
-- Note that the pieces of the path have been previously cleaned up by 'cleanPath'.
joinPath :: a
-> T.Text -- ^ application root
-> [T.Text] -- ^ path pieces
-> [(T.Text, T.Text)] -- ^ query string
-> Builder
joinPath _ ar pieces' qs' =
fromText ar `mappend` encodePath pieces qs
where
pieces = if null pieces' then [""] else map addDash pieces'
qs = map (TE.encodeUtf8 *** go) qs'
go "" = Nothing
go x = Just $ TE.encodeUtf8 x
addDash t
| T.all (== '-') t = T.cons '-' t
| otherwise = t
-- | This function is used to store some static content to be served as an
-- external file. The most common case of this is stashing CSS and
-- JavaScript content in an external file; the "Yesod.Widget" module uses
-- this feature.
--
-- The return value is 'Nothing' if no storing was performed; this is the
-- default implementation. A 'Just' 'Left' gives the absolute URL of the
-- file, whereas a 'Just' 'Right' gives the type-safe URL. The former is
-- necessary when you are serving the content outside the context of a
-- Yesod application, such as via memcached.
addStaticContent :: Text -- ^ filename extension
-> Text -- ^ mime-type
-> L.ByteString -- ^ content
-> GHandler sub a (Maybe (Either Text (Route a, [(Text, Text)])))
addStaticContent _ _ _ = return Nothing
{- Temporarily disabled until we have a better interface.
-- | Whether or not to tie a session to a specific IP address. Defaults to
-- 'False'.
--
-- Note: This setting has two known problems: it does not work correctly
-- when behind a reverse proxy (including load balancers), and it may not
-- function correctly if the user is behind a proxy.
sessionIpAddress :: a -> Bool
sessionIpAddress _ = False
-}
-- | The path value to set for cookies. By default, uses \"\/\", meaning
-- cookies will be sent to every page on the current domain.
cookiePath :: a -> S8.ByteString
cookiePath _ = "/"
-- | The domain value to set for cookies. By default, the
-- domain is not set, meaning cookies will be sent only to
-- the current domain.
cookieDomain :: a -> Maybe S8.ByteString
cookieDomain _ = Nothing
-- | Maximum allowed length of the request body, in bytes.
--
-- Default: 2 megabytes.
maximumContentLength :: a -> Maybe (Route a) -> Word64
maximumContentLength _ _ = 2 * 1024 * 1024 -- 2 megabytes
-- | Returns a @Logger@ to use for log messages.
--
-- Default: Sends to stdout and automatically flushes on each write.
getLogger :: a -> IO Logger
getLogger _ = mkLogger True stdout
-- | Send a message to the @Logger@ provided by @getLogger@.
--
-- Note: This method is no longer used. Instead, you should override
-- 'messageLoggerSource'.
messageLogger :: a
-> Logger
-> Loc -- ^ position in source code
-> LogLevel
-> LogStr -- ^ message
-> IO ()
messageLogger a logger loc = messageLoggerSource a logger loc ""
-- | Send a message to the @Logger@ provided by @getLogger@.
messageLoggerSource :: a
-> Logger
-> Loc -- ^ position in source code
-> LogSource
-> LogLevel
-> LogStr -- ^ message
-> IO ()
messageLoggerSource a logger loc source level msg =
if shouldLog a source level
then formatLogMessage (loggerDate logger) loc source level msg >>= loggerPutStr logger
else return ()
-- | The logging level in place for this application. Any messages below
-- this level will simply be ignored.
logLevel :: a -> LogLevel
logLevel _ = LevelInfo
-- | GZIP settings.
gzipSettings :: a -> GzipSettings
gzipSettings _ = def
-- | Where to Load sripts from. We recommend the default value,
-- 'BottomOfBody'. Alternatively use the built in async yepnope loader:
--
-- > BottomOfHeadAsync $ loadJsYepnope $ Right $ StaticR js_modernizr_js
--
-- Or write your own async js loader: see 'loadJsYepnope'
jsLoader :: a -> ScriptLoadPosition a
jsLoader _ = BottomOfBody
-- | Create a session backend. Returning `Nothing' disables sessions.
--
-- Default: Uses clientsession with a 2 hour timeout.
makeSessionBackend :: a -> IO (Maybe (SessionBackend a))
makeSessionBackend _ = do
key <- CS.getKey CS.defaultKeyFile
return $ Just $ clientSessionBackend key 120
-- | How to store uploaded files.
--
-- Default: Whe nthe request body is greater than 50kb, store in a temp
-- file. Otherwise, store in memory.
fileUpload :: a
-> Word64 -- ^ request body size
-> FileUpload
fileUpload _ size
| size > 50000 = FileUploadDisk tempFileBackEnd
| otherwise = FileUploadMemory lbsBackEnd
-- | Should we log the given log source/level combination.
--
-- Default: Logs everything at or above 'logLevel'
shouldLog :: a -> LogSource -> LogLevel -> Bool
shouldLog a _ level = level >= logLevel a
{-# DEPRECATED messageLogger "Please use messageLoggerSource (since yesod-core 1.1.2)" #-}
formatLogMessage :: IO ZonedDate
-> Loc
-> LogSource
-> LogLevel
-> LogStr -- ^ message
-> IO [LogStr]
formatLogMessage getdate loc src level msg = do
now <- getdate
return
[ LB now
, LB " ["
, LS $
case level of
LevelOther t -> T.unpack t
_ -> drop 5 $ show level
, LS $
if T.null src
then ""
else "#" ++ T.unpack src
, LB "] "
, msg
, LB " @("
, LS $ fileLocationToString loc
, LB ")\n"
]
-- taken from file-location package
-- turn the TH Loc loaction information into a human readable string
-- leaving out the loc_end parameter
fileLocationToString :: Loc -> String
fileLocationToString loc = (loc_package loc) ++ ':' : (loc_module loc) ++
' ' : (loc_filename loc) ++ ':' : (line loc) ++ ':' : (char loc)
where
line = show . fst . loc_start
char = show . snd . loc_start
defaultYesodRunner :: Yesod master
=> Logger
-> GHandler sub master ChooseRep
-> master
-> sub
-> Maybe (Route sub)
-> (Route sub -> Route master)
-> Maybe (SessionBackend master)
-> W.Application
defaultYesodRunner logger handler master sub murl toMasterRoute msb req
| maximumContentLength master (fmap toMasterRoute murl) < len =
return $ W.responseLBS
(H.Status 413 "Too Large")
[("Content-Type", "text/plain")]
"Request body too large to be processed."
| otherwise = do
now <- liftIO getCurrentTime
let dontSaveSession _ _ = return []
(session, saveSession) <- liftIO $
maybe (return ([], dontSaveSession)) (\sb -> sbLoadSession sb master req now) msb
rr <- liftIO $ parseWaiRequest req session (isJust msb) len
let h = {-# SCC "h" #-} do
case murl of
Nothing -> handler
Just url -> do
isWrite <- isWriteRequest $ toMasterRoute url
ar <- isAuthorized (toMasterRoute url) isWrite
case ar of
Authorized -> return ()
AuthenticationRequired ->
case authRoute master of
Nothing ->
permissionDenied "Authentication required"
Just url' -> do
setUltDestCurrent
redirect url'
Unauthorized s' -> permissionDenied s'
handler
let sessionMap = Map.fromList . filter ((/=) tokenKey . fst) $ session
let ra = resolveApproot master req
let log' = messageLoggerSource master logger
yar <- handlerToYAR master sub (fileUpload master) log' toMasterRoute
(yesodRender master ra) errorHandler rr murl sessionMap h
extraHeaders <- case yar of
(YARPlain _ _ ct _ newSess) -> do
let nsToken = Map.toList $ maybe
newSess
(\n -> Map.insert tokenKey (TE.encodeUtf8 n) newSess)
(reqToken rr)
sessionHeaders <- liftIO (saveSession nsToken now)
return $ ("Content-Type", ct) : map headerToPair sessionHeaders
_ -> return []
return $ yarToResponse yar extraHeaders
where
len = fromMaybe 0 $ lookup "content-length" (W.requestHeaders req) >>= readMay
readMay s =
case reads $ S8.unpack s of
[] -> Nothing
(x, _):_ -> Just x
data AuthResult = Authorized | AuthenticationRequired | Unauthorized Text
deriving (Eq, Show, Read)
-- | A type-safe, concise method of creating breadcrumbs for pages. For each
-- resource, you declare the title of the page and the parent resource (if
-- present).
class YesodBreadcrumbs y where
-- | Returns the title and the parent resource, if available. If you return
-- a 'Nothing', then this is considered a top-level page.
breadcrumb :: Route y -> GHandler sub y (Text , Maybe (Route y))
-- | Gets the title of the current page and the hierarchy of parent pages,
-- along with their respective titles.
breadcrumbs :: YesodBreadcrumbs y => GHandler sub y (Text, [(Route y, Text)])
breadcrumbs = do
x' <- getCurrentRoute
tm <- getRouteToMaster
let x = fmap tm x'
case x of
Nothing -> return ("Not found", [])
Just y -> do
(title, next) <- breadcrumb y
z <- go [] next
return (title, z)
where
go back Nothing = return back
go back (Just this) = do
(title, next) <- breadcrumb this
go ((this, title) : back) next
applyLayout' :: Yesod master
=> Html -- ^ title
-> HtmlUrl (Route master) -- ^ body
-> GHandler sub master ChooseRep
applyLayout' title body = fmap chooseRep $ defaultLayout $ do
setTitle title
toWidget body
-- | The default error handler for 'errorHandler'.
defaultErrorHandler :: Yesod y => ErrorResponse -> GHandler sub y ChooseRep
defaultErrorHandler NotFound = do
r <- waiRequest
let path' = TE.decodeUtf8With TEE.lenientDecode $ W.rawPathInfo r
applyLayout' "Not Found"
[hamlet|
$newline never
<h1>Not Found
<p>#{path'}
|]
defaultErrorHandler (PermissionDenied msg) =
applyLayout' "Permission Denied"
[hamlet|
$newline never
<h1>Permission denied
<p>#{msg}
|]
defaultErrorHandler (InvalidArgs ia) =
applyLayout' "Invalid Arguments"
[hamlet|
$newline never
<h1>Invalid Arguments
<ul>
$forall msg <- ia
<li>#{msg}
|]
defaultErrorHandler (InternalError e) =
applyLayout' "Internal Server Error"
[hamlet|
$newline never
<h1>Internal Server Error
<p>#{e}
|]
defaultErrorHandler (BadMethod m) =
applyLayout' "Bad Method"
[hamlet|
$newline never
<h1>Method Not Supported
<p>Method "#{S8.unpack m}" not supported
|]
-- | Return the same URL if the user is authorized to see it.
--
-- Built on top of 'isAuthorized'. This is useful for building page that only
-- contain links to pages the user is allowed to see.
maybeAuthorized :: Yesod a
=> Route a
-> Bool -- ^ is this a write request?
-> GHandler s a (Maybe (Route a))
maybeAuthorized r isWrite = do
x <- isAuthorized r isWrite
return $ if x == Authorized then Just r else Nothing
jsToHtml :: Javascript -> Html
jsToHtml (Javascript b) = preEscapedToMarkup $ toLazyText b
jelper :: JavascriptUrl url -> HtmlUrl url
jelper = fmap jsToHtml
-- | Convert a widget to a 'PageContent'.
widgetToPageContent :: (Eq (Route master), Yesod master)
=> GWidget sub master ()
-> GHandler sub master (PageContent (Route master))
widgetToPageContent w = do
master <- getYesod
((), GWData (Body body) (Last mTitle) scripts' stylesheets' style jscript (Head head')) <- unGWidget w
let title = maybe mempty unTitle mTitle
scripts = runUniqueList scripts'
stylesheets = runUniqueList stylesheets'
render <- getUrlRenderParams
let renderLoc x =
case x of
Nothing -> Nothing
Just (Left s) -> Just s
Just (Right (u, p)) -> Just $ render u p
css <- forM (Map.toList style) $ \(mmedia, content) -> do
let rendered = toLazyText $ content render
x <- addStaticContent "css" "text/css; charset=utf-8"
$ encodeUtf8 rendered
return (mmedia,
case x of
Nothing -> Left $ preEscapedToMarkup rendered
Just y -> Right $ either id (uncurry render) y)
jsLoc <-
case jscript of
Nothing -> return Nothing
Just s -> do
x <- addStaticContent "js" "text/javascript; charset=utf-8"
$ encodeUtf8 $ renderJavascriptUrl render s
return $ renderLoc x
-- modernizr should be at the end of the <head> http://www.modernizr.com/docs/#installing
-- the asynchronous loader means your page doesn't have to wait for all the js to load
let (mcomplete, asyncScripts) = asyncHelper render scripts jscript jsLoc
regularScriptLoad = [hamlet|
$newline never
$forall s <- scripts
^{mkScriptTag s}
$maybe j <- jscript
$maybe s <- jsLoc
<script src="#{s}">
$nothing
<script>^{jelper j}
|]
headAll = [hamlet|
$newline never
\^{head'}
$forall s <- stylesheets
^{mkLinkTag s}
$forall s <- css
$maybe t <- right $ snd s
$maybe media <- fst s
<link rel=stylesheet media=#{media} href=#{t}>
$nothing
<link rel=stylesheet href=#{t}>
$maybe content <- left $ snd s
$maybe media <- fst s
<style media=#{media}>#{content}
$nothing
<style>#{content}
$case jsLoader master
$of BottomOfBody
$of BottomOfHeadAsync asyncJsLoader
^{asyncJsLoader asyncScripts mcomplete}
$of BottomOfHeadBlocking
^{regularScriptLoad}
|]
let bodyScript = [hamlet|
$newline never
^{body}
^{regularScriptLoad}
|]
return $ PageContent title headAll (case jsLoader master of
BottomOfBody -> bodyScript
_ -> body)
where
renderLoc' render' (Local url) = render' url []
renderLoc' _ (Remote s) = s
addAttr x (y, z) = x ! customAttribute (textTag y) (toValue z)
mkScriptTag (Script loc attrs) render' =
foldl' addAttr TBH.script (("src", renderLoc' render' loc) : attrs) $ return ()
mkLinkTag (Stylesheet loc attrs) render' =
foldl' addAttr TBH.link
( ("rel", "stylesheet")
: ("href", renderLoc' render' loc)
: attrs
)
data ScriptLoadPosition master
= BottomOfBody
| BottomOfHeadBlocking
| BottomOfHeadAsync (BottomOfHeadAsync master)
type BottomOfHeadAsync master
= [Text] -- ^ urls to load asynchronously
-> Maybe (HtmlUrl (Route master)) -- ^ widget of js to run on async completion
-> (HtmlUrl (Route master)) -- ^ widget to insert at the bottom of <head>
left :: Either a b -> Maybe a
left (Left x) = Just x
left _ = Nothing
right :: Either a b -> Maybe b
right (Right x) = Just x
right _ = Nothing
jsonArray :: [Text] -> Html
jsonArray = unsafeLazyByteString . encode . Array . Vector.fromList . map String
-- | For use with setting 'jsLoader' to 'BottomOfHeadAsync'
loadJsYepnope :: Yesod master => Either Text (Route master) -> [Text] -> Maybe (HtmlUrl (Route master)) -> (HtmlUrl (Route master))
loadJsYepnope eyn scripts mcomplete =
[hamlet|
$newline never
$maybe yn <- left eyn
<script src=#{yn}>
$maybe yn <- right eyn
<script src=@{yn}>
$maybe complete <- mcomplete
<script>yepnope({load:#{jsonArray scripts},complete:function(){^{complete}}});
$nothing
<script>yepnope({load:#{jsonArray scripts}});
|]
asyncHelper :: (url -> [x] -> Text)
-> [Script (url)]
-> Maybe (JavascriptUrl (url))
-> Maybe Text
-> (Maybe (HtmlUrl url), [Text])
asyncHelper render scripts jscript jsLoc =
(mcomplete, scripts'')
where
scripts' = map goScript scripts
scripts'' =
case jsLoc of
Just s -> scripts' ++ [s]
Nothing -> scripts'
goScript (Script (Local url) _) = render url []
goScript (Script (Remote s) _) = s
mcomplete =
case jsLoc of
Just{} -> Nothing
Nothing ->
case jscript of
Nothing -> Nothing
Just j -> Just $ jelper j
yesodRender :: Yesod y
=> y
-> ResolvedApproot
-> Route y
-> [(Text, Text)] -- ^ url query string
-> Text
yesodRender y ar url params =
TE.decodeUtf8 $ toByteString $
fromMaybe
(joinPath y ar ps
$ params ++ params')
(urlRenderOverride y url)
where
(ps, params') = renderRoute url
resolveApproot :: Yesod master => master -> W.Request -> ResolvedApproot
resolveApproot master req =
case approot of
ApprootRelative -> ""
ApprootStatic t -> t
ApprootMaster f -> f master
ApprootRequest f -> f master req
defaultClientSessionBackend :: Yesod master => IO (SessionBackend master)
defaultClientSessionBackend = do
key <- CS.getKey CS.defaultKeyFile
let timeout = 120 -- 120 minutes
return $ clientSessionBackend key timeout
clientSessionBackend :: Yesod master
=> CS.Key -- ^ The encryption key
-> Int -- ^ Inactive session valitity in minutes
-> SessionBackend master
clientSessionBackend key timeout = SessionBackend
{ sbLoadSession = loadClientSession key timeout "_SESSION"
}
loadClientSession :: Yesod master
=> CS.Key
-> Int -- ^ timeout
-> S8.ByteString -- ^ session name
-> master
-> W.Request
-> UTCTime
-> IO (BackendSession, SaveSession)
loadClientSession key timeout sessionName master req now = return (sess, save)
where
sess = fromMaybe [] $ do
raw <- lookup "Cookie" $ W.requestHeaders req
val <- lookup sessionName $ parseCookies raw
let host = "" -- fixme, properly lock sessions to client address
decodeClientSession key now host val
save sess' now' = do
-- We should never cache the IV! Be careful!
iv <- liftIO CS.randomIV
return [AddCookie def
{ setCookieName = sessionName
, setCookieValue = sessionVal iv
, setCookiePath = Just (cookiePath master)
, setCookieExpires = Just expires
, setCookieDomain = cookieDomain master
, setCookieHttpOnly = True
}]
where
host = "" -- fixme, properly lock sessions to client address
expires = fromIntegral (timeout * 60) `addUTCTime` now'
sessionVal iv = encodeClientSession key iv expires host sess'
-- | Run a 'GHandler' completely outside of Yesod. This
-- function comes with many caveats and you shouldn't use it
-- unless you fully understand what it's doing and how it works.
--
-- As of now, there's only one reason to use this function at
-- all: in order to run unit tests of functions inside 'GHandler'
-- but that aren't easily testable with a full HTTP request.
-- Even so, it's better to use @wai-test@ or @yesod-test@ instead
-- of using this function.
--
-- This function will create a fake HTTP request (both @wai@'s
-- 'W.Request' and @yesod@'s 'Request') and feed it to the
-- @GHandler@. The only useful information the @GHandler@ may
-- get from the request is the session map, which you must supply
-- as argument to @runFakeHandler@. All other fields contain
-- fake information, which means that they can be accessed but
-- won't have any useful information. The response of the
-- @GHandler@ is completely ignored, including changes to the
-- session, cookies or headers. We only return you the
-- @GHandler@'s return value.
runFakeHandler :: (Yesod master, MonadIO m) =>
SessionMap
-> (master -> Logger)
-> master
-> GHandler master master a
-> m (Either ErrorResponse a)
runFakeHandler fakeSessionMap logger master handler = liftIO $ do
ret <- I.newIORef (Left $ InternalError "runFakeHandler: no result")
let handler' = do liftIO . I.writeIORef ret . Right =<< handler
return ()
let YesodApp yapp =
runHandler
handler'
(yesodRender master "")
Nothing
id
master
master
(fileUpload master)
(messageLoggerSource master $ logger master)
errHandler err =
YesodApp $ \_ _ _ session -> do
liftIO $ I.writeIORef ret (Left err)
return $ YARPlain
H.status500
[]
typePlain
(toContent ("runFakeHandler: errHandler" :: S8.ByteString))
session
fakeWaiRequest =
W.Request
{ W.requestMethod = "POST"
, W.httpVersion = H.http11
, W.rawPathInfo = "/runFakeHandler/pathInfo"
, W.rawQueryString = ""
, W.serverName = "runFakeHandler-serverName"
, W.serverPort = 80
, W.requestHeaders = []
, W.isSecure = False
, W.remoteHost = error "runFakeHandler-remoteHost"
, W.pathInfo = ["runFakeHandler", "pathInfo"]
, W.queryString = []
, W.requestBody = mempty
, W.vault = mempty
}
fakeRequest =
Request
{ reqGetParams = []
, reqCookies = []
, reqWaiRequest = fakeWaiRequest
, reqLangs = []
, reqToken = Just "NaN" -- not a nonce =)
, reqBodySize = 0
}
fakeContentType = []
_ <- runResourceT $ yapp errHandler fakeRequest fakeContentType fakeSessionMap
I.readIORef ret
{-# WARNING runFakeHandler "Usually you should *not* use runFakeHandler unless you really understand how it works and why you need it." #-}
| piyush-kurur/yesod | yesod-core/Yesod/Internal/Core.hs | mit | 31,135 | 0 | 26 | 9,240 | 6,199 | 3,298 | 2,901 | 551 | 7 |
module MiniSequel.Adapter.PostgreSQL.Log
where
import qualified MiniSequel.Adapter.PostgreSQL as Adapter
--
-- exec con query = do
-- print query
-- Adapter.exec con query
--
-- takeModel con model = do
-- print model
-- Adapter.takeModel con model
| TachoMex/MiniSequel | src/MiniSequel/Adapter/Log.hs | mit | 276 | 0 | 4 | 63 | 25 | 21 | 4 | 2 | 0 |
import System.Exit
mul [x, y] = xInt * yInt
where xInt = read x :: Integer
yInt = read y :: Integer
mainLoop 0 = exitWith ExitSuccess
mainLoop x = do
values <- getLine
print $ mul (words values)
mainLoop (x - 1)
main = do
loops <- getLine
mainLoop (read loops :: Integer)
| ranisalt/spoj | mul.hs | mit | 288 | 0 | 10 | 70 | 130 | 64 | 66 | 12 | 1 |
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
module Main where
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Map.Strict(Map)
import qualified Data.Map.Strict as M
import Data.Maybe(fromJust)
import Data.Tree(Tree(..), flatten, unfoldTree)
import Diagrams.Backend.SVG.CmdLine(defaultMain)
import Diagrams.Prelude
import GHC.Generics
import Control.Applicative
import Data.Attoparsec.Char8
-- import Data.Attoparsec.Text
-- import qualified Data.HashMap.Strict as HM
-- import Data.Scientific (toRealFloat)
-- import Data.Text (Text)
-- import qualified Data.Text as T
-- import qualified Data.Vector as V
main = defaultMain $ pad 1.1 $ renderTree buildTree
renderTree = mconcat . flatten . fmap drawBranch
buildTree = unfoldTree (growTree fs) seed
seed = (origin, unitY)
drawBranch (p, v) = position [(p, fromOffsets [v])]
growTree fs n = if stop n then branchTip n else branches fs n
branchTip n = (n, [])
branches fs n = (n, zipWith ($) fs (repeat n))
fs = buildXfm symMap rule
-- The rule has been transformed from "b r [ < B ] [ > B ]"
--rule = [["b", "r", "<"], ["b", "r", ">"]]
rule = getRule userRule
getRule = elimVars stringToGrammarDef . distribute . parseRule
userRule = "b r [ < B ] [ > B ]"
symbols = (map toSymbolMap . filter isTerminal) grammar
isTerminal (Follow _) = True
isTerminal (Scale _ _) = True
isTerminal (Turn _ _) = True
isTerminal _ = False
toSymbolMap (Follow s) = (s, followBranch)
toSymbolMap (Scale s r) = (s, scaleBranch r)
toSymbolMap (Turn s t) = (s, rotateBranch t)
toSymbolMap t = error $ "Bad terminal in toSymbolMap:" ++ show t
type SeedVal = ((Double, Double), (Double, Double))
type RuleVal = (String, String)
type Grammar = [GrammarDef]
data GrammarDef = Var String
| Turn String Double
| Scale String Double
| Follow String
| Seed String SeedVal
| Rule String RuleVal
deriving (Show, Generic)
instance FromJSON GrammarDef
instance ToJSON GrammarDef
-- What I would like:
-- jsonInputWanted =
-- "[\
-- \{\"b\": {\"follow\":null}},\
-- \{\"r\": {\"scale\": 0.6}},\
-- \{\"<\": {\"turn\": 0.45}},\
-- \{\">\": {\"turn\": -0.45}},\
-- \{\"B\": {\"var\": null}},\
-- \{\"s\": {\"seed\": {\"p\": {\"x\":0, \"y\":0}, \"v\":{\"x\":0, \"y\":1}}}},\
-- \{\"R1\": {\"rule\": {\"B\": \"b r [ < B ] [ > B ]\"}}}\
-- \]"
-- What I have to use with generically derived instance
jsonInput =
"[\
\{\"contents\":\"b\",\"tag\":\"Follow\"},\
\{\"contents\":\"B\",\"tag\":\"Var\"},\
\{\"contents\":[\"r\",0.6],\"tag\":\"Scale\"},\
\{\"contents\":[\"\\u003c\",0.14285714285714],\"tag\":\"Turn\"},\
\{\"contents\":[\"\\u003e\",-0.14285714285714],\"tag\":\"Turn\"},\
\{\"contents\":[\"s\",[[0,0],[0,1]]],\"tag\":\"Seed\"},\
\{\"contents\":[\"R1\",[\"B\" ,\"b r [ < B ] [ > B ]\"]],\"tag\":\"Rule\"}\
\]"
parseGrammar j = case decode (BS.pack j) of
(Just g) -> g
Nothing -> error $ "Bad grammar in JSON: " ++ j
grammar = parseGrammar jsonInput
toGrammarMap g@(Var s) = (s, g)
toGrammarMap g@(Follow s) = (s, g)
toGrammarMap g@(Scale s _) = (s, g)
toGrammarMap g@(Turn s _) = (s, g)
toGrammarMap g@(Seed s _) = (s, g)
toGrammarMap g@(Rule s _) = (s, g)
stringToGrammarDef = initMap (map toGrammarMap grammar)
-- Assumes string has been converted to a list of lists of
-- terminal symbols corresponding to transformations.
buildXfm :: Map String ((P2, R2) -> (P2, R2))
-> [[String]]
-> [(P2, R2) -> (P2, R2)]
buildXfm _ [] = []
buildXfm m (xs:xss) = (buildXfm' m id xs) : buildXfm m xss
buildXfm' _ f [] = f
buildXfm' m f (x:xs) = buildXfm' m (g . f) xs
where g = fromJust (M.lookup x m)
--parseRule :: Text -> Tree [String]
parseRule r = case parseOnly tree r of
Left e -> error $ "Could not parse rule: " ++ show r ++ " (" ++ e ++ ")"
Right t -> t
tree :: Parser (Tree [String])
tree = (do ts <- many1 subTree
return $ Node [] ts)
<|> (do xs <- flatList
ts <- many1 subTree
return $ Node xs ts)
<|> (do xs <- flatList
return $ Node xs [])
-- One level of recursion only
subTree :: Parser (Tree [String])
subTree = do skipSpace
char '['
xs <- flatList
skipSpace
char ']'
return $ Node xs []
flatList :: Parser [String]
flatList = many1 idToken
idToken :: Parser String
idToken = skipSpace >> many1 (satisfy (notInClass "[] \t\n"))
-- One level of recursion.
distribute (Node p []) = [p]
distribute (Node p ts) = map (p ++) (map rootLabel ts)
elimVars m = map (filter (not . isVar m))
isVar m s = case M.lookup s m of
Just (Var _) -> True
otherwise -> False
symMap = initMap symbols
initMap = foldr updateMap M.empty
updateMap (k,f) = M.insert k f
stop (_, v) = magnitude v < 0.05
followBranch (p, v) = (p .+^ v, v)
scaleBranch s (p, v) = (p, v ^* s)
rotateBranch t (p, v) = (p, rotateBy t v)
| bobgru/tree-derivations | src/LSystem5.hs | mit | 5,140 | 0 | 12 | 1,247 | 1,561 | 840 | 721 | 102 | 2 |
import Test.Hspec
import StringCalculator
import Control.Exception (evaluate)
main :: IO ()
main = hspec $ do
describe "StringCalculator" $ do
it "should return 0 for an empty string" $ do
calculate "" `shouldBe` 0
it "should return 1 for a string '1'" $ do
calculate "1" `shouldBe` 1
it "should return 2 for a string '2'" $ do
calculate "2" `shouldBe` 2
it "should return 3 for a string '1,2'" $ do
calculate "1,2" `shouldBe` 3
it "should return 6 for a string '1\n2,3'" $ do
calculate "1\n2,3" `shouldBe` 6
it "should return 3 for a string of '//;\n1;2'" $ do
calculate "//;\n1;2" `shouldBe` 3
it "should throw an exception if a negative number is given" $ do
evaluate (calculate "1,-2") `shouldThrow` errorCall "negatives not allowed"
| theUniC/string-calculator.hs | tests/Spec.hs | mit | 890 | 0 | 17 | 278 | 211 | 99 | 112 | 20 | 1 |
module Main where
import qualified Network as Net
import System.IO (Handle, hClose)
import System.Environment (getArgs)
import Data.ByteString (ByteString)
import Control.Monad (forever, unless)
import Control.Concurrent.STM (STM, atomically)
import Control.Concurrent (ThreadId, forkIO, threadDelay)
import Control.Exception (SomeException, catch, finally)
import Network.Neks.Disk (saveTo, loadFrom)
import Network.Neks.NetPack (netRead, netWrite)
import Network.Neks.Message (parseRequests, formatResponses)
import Network.Neks.DataStore (DataStore, createStore, insert, get, delete)
import Network.Neks.Actions (Request(Set, Get, Delete, Atomic), Reply(Found, NotFound))
type Store = DataStore ByteString ByteString
main = do
args <- getArgs
case args of
[] -> serveWithPersistence
["--no-persistence"] -> serveWithoutPersistence
["--help"] -> putStrLn instructions -- To be explicit
_ -> putStrLn instructions
serveWithPersistence = do
loaded <- loadFrom "store.kvs"
globalStore <- case loaded of
Just store -> return store
Nothing -> atomically createStore
let periodically action = forever (threadDelay (30*10^6) >> action)
forkIO $ periodically (saveTo "store.kvs" globalStore)
putStrLn "Serving on port 9999 \nSaving DB to store.kvs"
serve globalStore (Net.PortNumber 9999)
serveWithoutPersistence = do
globalStore <- atomically createStore
putStrLn "Serving on port 9999\nNot persisting to disk"
serve globalStore (Net.PortNumber 9999)
serve :: Store -> Net.PortID -> IO ()
serve store port = Net.withSocketsDo $ do
sock <- Net.listenOn port
forever (wait sock store)
wait :: Net.Socket -> Store -> IO ThreadId
wait sock store = do
(client, _, _) <- Net.accept sock
forkIO (run client)
where
run client = (handle client store `finally` hClose client) `catch` exceptionHandler
exceptionHandler :: SomeException -> IO ()
exceptionHandler exception = return () -- Optional exception reporting
handle :: Handle -> Store -> IO ()
handle client store = do
result <- processRequests client store
case result of
Right success -> handle client store
Left failure -> return () -- Optional soft error reporting
processRequests :: Handle -> Store -> IO (Either String ())
processRequests client store = do
requestData <- netRead client
case requestData >>= parseRequests of
Left err -> return (Left err)
Right requests -> do
results <- mapM (atomically . processWith store) requests
netWrite client . formatResponses . concat $ results
return (Right ())
processWith :: Store -> Request -> STM [Reply]
processWith store (Set k v) = do
insert k v store
return []
processWith store (Get k) = do
result <- get k store
return $ case result of
Nothing -> [NotFound]
Just v -> [Found v]
processWith store (Delete k) = do
delete k store
return []
processWith store (Atomic requests) = do
results <- mapM (processWith store) requests
return (concat results)
instructions = "Usage: NeksServer <opt-args>\n" ++
"<opt-args> can be empty or can be \"--no-persistence\" to disable storing keys and values on disk"
| wyager/Neks | Network/Neks/NeksServer.hs | mit | 3,546 | 0 | 16 | 967 | 1,029 | 521 | 508 | 78 | 4 |
--------------------------------------------------------------------------
-- Copyright (c) 2007-2010, ETH Zurich.
-- All rights reserved.
--
-- This file is distributed under the terms in the attached LICENSE file.
-- If you do not find this file, copies can be found by writing to:
-- ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
--
-- Default architecture-specific definitions for Barrelfish
--
--------------------------------------------------------------------------
module ArchDefaults where
import Data.List
import HakeTypes
import Path
import qualified Config
commonFlags = [ Str s | s <- [ "-fno-builtin",
"-nostdinc",
"-U__linux__",
"-Ulinux",
"-Wall",
"-Wshadow",
"-Wmissing-declarations",
"-Wmissing-field-initializers",
"-Wredundant-decls",
"-Werror",
"-imacros" ] ]
++ [ NoDep SrcTree "src" "/include/deputy/nodeputy.h" ]
commonCFlags = [ Str s | s <- [ "-std=c99",
"-U__STRICT_ANSI__", -- for newlib headers
"-Wstrict-prototypes",
"-Wold-style-definition",
"-Wmissing-prototypes" ] ]
++ [ ContStr Config.use_fp "-fno-omit-frame-pointer" ""]
commonCxxFlags = [ Str s | s <- [ "-nostdinc++",
"-std=c++0x",
"-fno-exceptions",
"-I" ] ]
++ [ NoDep SrcTree "src" "/include/cxx" ]
++ [ ContStr Config.use_fp "-fno-omit-frame-pointer" ""]
cFlags = [ Str s | s <- [ "-Wno-packed-bitfield-compat" ] ]
++ commonCFlags
cxxFlags = [ Str s | s <- [ "-Wno-packed-bitfield-compat" ] ]
++ commonCxxFlags
cDefines options = [ Str ("-D"++s) | s <- [ "BARRELFISH" ]]
++ Config.defines
++ Config.arch_defines options
cStdIncs arch archFamily =
[ NoDep SrcTree "src" "/include",
NoDep SrcTree "src" ("/include/arch" ./. archFamily),
NoDep SrcTree "src" Config.libcInc,
NoDep SrcTree "src" "/include/c",
NoDep SrcTree "src" ("/include/target" ./. archFamily),
NoDep SrcTree "src" Config.lwipxxxInc, -- XXX
NoDep SrcTree "src" Config.lwipInc,
NoDep InstallTree arch "/include",
NoDep InstallTree arch "/include/dev",
NoDep SrcTree "src" ".",
NoDep BuildTree arch "." ]
ldFlags arch =
[ Str Config.cOptFlags,
In InstallTree arch "/lib/crt0.o",
In InstallTree arch "/lib/crtbegin.o",
Str "-fno-builtin",
Str "-nostdlib" ]
ldCxxFlags arch =
[ Str Config.cOptFlags,
In InstallTree arch "/lib/crt0.o",
In InstallTree arch "/lib/crtbegin.o",
Str "-fno-builtin",
Str "-nostdlib" ]
-- Libraries that are linked to all applications.
stdLibs arch =
[ In InstallTree arch "/lib/libbarrelfish.a",
In InstallTree arch "/lib/libterm_client.a",
In InstallTree arch "/lib/liboctopus_parser.a", -- XXX: For NS client in libbarrelfish
In InstallTree arch "/errors/errno.o",
In InstallTree arch ("/lib/lib" ++ Config.libc ++ ".a"),
--In InstallTree arch "/lib/libposixcompat.a",
--In InstallTree arch "/lib/libvfs.a",
--In InstallTree arch "/lib/libnfs.a",
--In InstallTree arch "/lib/liblwip.a",
--In InstallTree arch "/lib/libbarrelfish.a",
--In InstallTree arch "/lib/libcontmng.a",
--In InstallTree arch "/lib/libprocon.a",
In InstallTree arch "/lib/crtend.o" ,
In InstallTree arch "/lib/libcollections.a" ]
stdCxxLibs arch =
[ In InstallTree arch "/lib/libcxx.a",
Str "./libsupc++.a" ]
++ stdLibs arch
options arch archFamily = Options {
optArch = arch,
optArchFamily = archFamily,
optFlags = cFlags,
optCxxFlags = cxxFlags,
optDefines = [ Str "-DBARRELFISH" ] ++ Config.defines,
optIncludes = cStdIncs arch archFamily,
optDependencies =
[ PreDep InstallTree arch "/include/errors/errno.h",
PreDep InstallTree arch "/include/barrelfish_kpi/capbits.h",
PreDep InstallTree arch "/include/asmoffsets.h",
PreDep InstallTree arch "/include/trace_definitions/trace_defs.h" ],
optLdFlags = ldFlags arch,
optLdCxxFlags = ldCxxFlags arch,
optLibs = stdLibs arch,
optCxxLibs = stdCxxLibs arch,
optInterconnectDrivers = ["lmp", "ump", "multihop"],
optFlounderBackends = ["lmp", "ump", "multihop"],
extraFlags = [],
extraDefines = [],
extraIncludes = [],
extraDependencies = [],
extraLdFlags = [],
optSuffix = []
}
------------------------------------------------------------------------
--
-- Now, commands to actually do something
--
------------------------------------------------------------------------
--
-- C compiler
--
cCompiler arch compiler opts phase src obj =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
deps = (optDependencies opts) ++ (extraDependencies opts)
in
[ Str compiler ] ++ flags ++ [ Str Config.cOptFlags ]
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ [ Str "-o", Out arch obj,
Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src ]
++ deps
--
-- the C preprocessor, like C compiler but with -E
--
cPreprocessor arch compiler opts phase src obj =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
deps = (optDependencies opts) ++ (extraDependencies opts)
cOptFlags = unwords ((words Config.cOptFlags) \\ ["-g"])
in
[ Str compiler ] ++ flags ++ [ Str cOptFlags ]
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ [ Str "-o", Out arch obj,
Str "-E", In (if phase == "src" then SrcTree else BuildTree) phase src ]
++ deps
--
-- C++ compiler
--
cxxCompiler arch cxxcompiler opts phase src obj =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optCxxFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
deps = (optDependencies opts) ++ (extraDependencies opts)
in
[ Str cxxcompiler ] ++ flags ++ [ Str Config.cOptFlags ]
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ [ Str "-o", Out arch obj,
Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src ]
++ deps
--
-- Create C file dependencies
--
makeDepend arch compiler opts phase src obj depfile =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
in
[ Str ('@':compiler) ] ++ flags
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ (optDependencies opts) ++ (extraDependencies opts)
++ [ Str "-M -MF",
Out arch depfile,
Str "-MQ", NoDep BuildTree arch obj,
Str "-MQ", NoDep BuildTree arch depfile,
Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src
]
--
-- Create C++ file dependencies
--
makeCxxDepend arch cxxcompiler opts phase src obj depfile =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optCxxFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
in
[ Str ('@':cxxcompiler) ] ++ flags
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ (optDependencies opts) ++ (extraDependencies opts)
++ [ Str "-M -MF",
Out arch depfile,
Str "-MQ", NoDep BuildTree arch obj,
Str "-MQ", NoDep BuildTree arch depfile,
Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src
]
--
-- Compile a C program to assembler
--
cToAssembler :: String -> String -> Options -> String -> String -> String -> String -> [ RuleToken ]
cToAssembler arch compiler opts phase src afile objdepfile =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
deps = [ Dep BuildTree arch objdepfile ] ++ (optDependencies opts) ++ (extraDependencies opts)
in
[ Str compiler ] ++ flags ++ [ Str Config.cOptFlags ]
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ [ Str "-o ", Out arch afile,
Str "-S ", In (if phase == "src" then SrcTree else BuildTree) phase src ]
++ deps
--
-- Assemble an assembly language file
--
assembler :: String -> String -> Options -> String -> String -> [ RuleToken ]
assembler arch compiler opts src obj =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
deps = (optDependencies opts) ++ (extraDependencies opts)
in
[ Str compiler ] ++ flags ++ [ Str Config.cOptFlags ]
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ [ Str "-o ", Out arch obj, Str "-c ", In SrcTree "src" src ]
++ deps
--
-- Create a library from a set of object files
--
archive :: String -> Options -> [String] -> [String] -> String -> String -> [ RuleToken ]
archive arch opts objs libs name libname =
[ Str "rm -f ", Out arch libname ]
++
[ NL, Str "ar cr ", Out arch libname ]
++
[ In BuildTree arch o | o <- objs ]
++
if libs == [] then []
else (
[ NL, Str ("rm -fr tmp-" ++ arch ++ name ++ "; mkdir tmp-" ++ arch ++ name) ]
++
[ NL, Str ("cd tmp-" ++ arch ++ name ++ "; for i in ") ]
++
[ In BuildTree arch a | a <- libs ]
++
[ Str "; do ar x ../$$i; done" ]
++
[ NL, Str "ar q ", Out arch libname, Str (" tmp-" ++ arch ++ name ++ "/*.o") ]
++
[ NL, Str ("rm -fr tmp-" ++ arch ++ name) ]
)
++
[ NL, Str "ranlib ", Out arch libname ]
--
-- Link an executable
--
linker :: String -> String -> Options -> [String] -> [String] -> String -> [RuleToken]
linker arch compiler opts objs libs bin =
[ Str compiler ]
++ (optLdFlags opts)
++
(extraLdFlags opts)
++
[ Str "-o", Out arch bin ]
++
[ In BuildTree arch o | o <- objs ]
++
[ In BuildTree arch l | l <- libs ]
++
(optLibs opts)
--
-- Link an executable
--
cxxlinker :: String -> String -> Options -> [String] -> [String] -> String -> [RuleToken]
cxxlinker arch cxxcompiler opts objs libs bin =
[ Str cxxcompiler ]
++ (optLdCxxFlags opts)
++
(extraLdFlags opts)
++
[ Str "-o", Out arch bin ]
++
[ In BuildTree arch o | o <- objs ]
++
[ In BuildTree arch l | l <- libs ]
++
(optCxxLibs opts)
| UWNetworksLab/arrakis | hake/ArchDefaults.hs | mit | 11,931 | 0 | 21 | 3,947 | 3,310 | 1,746 | 1,564 | 237 | 2 |
{-# LANGUAGE QuasiQuotes, ScopedTypeVariables #-}
module Handler.EntryPics where
import Import
import Utils.Database
import qualified Hasql as H
import qualified Data.Text as T
getEntryPicsR :: Int -> Handler Html
getEntryPicsR entryId = do
dbres <- liftIO $ do
conn <- getDbConn
H.session conn $ H.tx Nothing $ do
(images :: [(Int,T.Text)]) <- H.listEx $ [H.stmt|
SELECT id
, ext
FROM images
WHERE entry_id = ? AND img_type = 'entry'
ORDER BY id ASC
|] entryId
return images
case dbres of
Left err -> error $ show err
Right images ->
defaultLayout $ do
setTitle $ "Entry Images | Brandreth Guestbook"
$(widgetFile "entrypics")
| dgonyeo/brandskell | Handler/EntryPics.hs | mit | 860 | 0 | 19 | 333 | 187 | 96 | 91 | 20 | 2 |
{-# LANGUAGE PackageImports #-}
{-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-}
-- | Reexports "Numeric.Natural.Compat"
-- from a globally unique namespace.
module Numeric.Natural.Compat.Repl (
module Numeric.Natural.Compat
) where
import "this" Numeric.Natural.Compat
| haskell-compat/base-compat | base-compat/src/Numeric/Natural/Compat/Repl.hs | mit | 292 | 0 | 5 | 31 | 28 | 21 | 7 | 5 | 0 |
{-# LANGUAGE BangPatterns #-}
{- |
- Module : Memo
- Description : Infinite memorization tree structure
- Copyright : (c) Maciej Bendkowski
-
- Maintainer : [email protected]
- Stability : experimental
-}
module Memo (
Tree(..), idx, nats, toList
) where
-- | An infinite binary tree data structure
-- with additional functor capabilities
data Tree a = Tree (Tree a) a (Tree a)
instance Functor Tree where
fmap f (Tree l x r) = Tree (fmap f l) (f x) (fmap f r)
-- | Tree indexer
idx :: Tree a -> Int -> a
idx (Tree _ x _) 0 = x
idx (Tree l _ r) k = case (k-1) `divMod` 2 of
(k', 0) -> idx l k'
(k', _) -> idx r k'
-- | Natural numbers represented in an
-- infinite binary tree
nats :: Tree Int
nats = f 0 1 where
f :: Int -> Int -> Tree Int
f !k !s = Tree (f l s') k (f r s') where
l = k + s
r = l + s
s' = s * 2
-- | Tree to list converter
toList :: Tree a -> [a]
toList ts = map (idx ts) [0..]
| maciej-bendkowski/blaz | src/Memo.hs | mit | 1,080 | 0 | 9 | 379 | 357 | 190 | 167 | 20 | 2 |
module YesNo (
YesNo
) where
import Tree
import TrafficLight
class YesNo a where
yesno :: a -> Bool
instance YesNo Int where
yesno 0 = False
yesno _ = True
instance YesNo [ a ] where
yesno [] = False
yesno _ = True
instance YesNo Bool where
yesno = id
-- Function 'id' means identity, get argument and return the same thing.
instance YesNo (Maybe a) where
yesno (Just _) = True
yesno Nothing = False
instance YesNo (Tree a) where
yesno EmptyTree = False
yesno _ = True
instance YesNo TrafficLight where
yesno Red = False
yesno _ = True
yesnoIf :: (YesNo y) => y -> a -> a -> a
yesnoIf yesnoVal yesResult noResult = if yesno yesnoVal then yesResult else noResult
| afronski/playground-fp | books/learn-you-a-haskell-for-great-good/making-our-own-types-and-typeclasses/YesNo.hs | mit | 713 | 0 | 8 | 178 | 239 | 125 | 114 | 25 | 2 |
{-# OPTIONS_GHC -O0 #-}
{-# LANGUAGE CPP,
DeriveGeneric,
DeriveDataTypeable,
LambdaCase,
MagicHash,
StandaloneDeriving
#-}
#ifndef __GHCJS__
{-# LANGUAGE PackageImports #-}
#endif
{- |
Communication between the compiler (GHCJS) and runtime (on node.js) for
Template Haskell
-}
module GHCJS.Prim.TH.Types ( Message(..)
, THResultType(..)
) where
import Prelude
import Data.Binary
import Data.ByteString (ByteString)
import Data.Data
import GHC.Generics
import GHCi.TH.Binary ()
#if defined(__GHCJS__) || !defined(MIN_VERSION_template_haskell_ghcjs)
import qualified Language.Haskell.TH as TH
import qualified Language.Haskell.TH.Syntax as TH
#else
import qualified "template-haskell-ghcjs" Language.Haskell.TH as TH
import qualified "template-haskell-ghcjs" Language.Haskell.TH.Syntax as TH
#endif
data THResultType = THExp | THPat | THType | THDec | THAnnWrapper
deriving (Enum, Show, Data, Generic)
data Message
-- | compiler to node requests
= RunTH THResultType ByteString (Maybe TH.Loc)
| FinishTH Bool -- ^ also stop runner (False to just clean up at end of module)
-- | node to compiler responses
| RunTH' ByteString -- ^ serialized result
| FinishTH' Int -- ^ memory consumption
-- | node to compiler requests
| NewName String
| Report Bool String
| LookupName Bool String
| Reify TH.Name
| ReifyInstances TH.Name [TH.Type]
| ReifyRoles TH.Name
| ReifyAnnotations TH.AnnLookup
| ReifyModule TH.Module
| ReifyFixity TH.Name
| ReifyConStrictness TH.Name
| AddForeignFilePath TH.ForeignSrcLang String
| AddDependentFile FilePath
| AddTempFile String
| AddTopDecls [TH.Dec]
| AddCorePlugin String
| IsExtEnabled TH.Extension
| ExtsEnabled
-- | compiler to node responses
| NewName' TH.Name
| Report'
| LookupName' (Maybe TH.Name)
| Reify' TH.Info
| ReifyInstances' [TH.Dec]
| ReifyRoles' [TH.Role]
| ReifyAnnotations' [ByteString]
| ReifyModule' TH.ModuleInfo
| ReifyFixity' (Maybe TH.Fixity)
| ReifyConStrictness' [TH.DecidedStrictness]
| AddForeignFilePath'
| AddDependentFile'
| AddTempFile' FilePath
| AddTopDecls'
| AddCorePlugin'
| IsExtEnabled' Bool
| ExtsEnabled' [TH.Extension]
| QFail'
| QCompilerException' Int String -- ^ exception id and result of showing the exception
-- | error recovery
| StartRecover
| EndRecover Bool -- ^ true for recovery action taken
| StartRecover'
| EndRecover'
-- | exit with error status
| QFail String -- ^ monadic fail called
| QUserException String -- ^ exception in user code
| QCompilerException Int -- ^ exception originated on compiler side
deriving (Generic)
-- deriving instance Generic TH.ForeignSrcLang
instance Binary TH.Extension
instance Binary TH.ForeignSrcLang
instance Binary THResultType
instance Binary Message
| ghcjs/ghcjs | lib/ghcjs-th/GHCJS/Prim/TH/Types.hs | mit | 3,274 | 0 | 9 | 954 | 495 | 303 | 192 | 73 | 0 |
--
--
-- (C) 2011-14 Nicola Bonelli <[email protected]>
--
-- 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.
--
-- The full GNU General Public License is included in this distribution in
-- the file called "COPYING".
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import qualified Network.PFq as Q
import Foreign
import System.Environment
import Control.Concurrent
import Control.Monad
-- import Foreign.C.Types
import qualified Data.ByteString as C
ping = C.pack [
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xbf, -- L`..UF..
0x97, 0xe2, 0xff, 0xae, 0x08, 0x00, 0x45, 0x00, -- ......E.
0x00, 0x54, 0xb3, 0xf9, 0x40, 0x00, 0x40, 0x01, -- .T..@.@.
0xf5, 0x32, 0xc0, 0xa8, 0x00, 0x02, 0xad, 0xc2, -- .2......
0x23, 0x10, 0x08, 0x00, 0xf2, 0xea, 0x42, 0x04, -- #.....B.
0x00, 0x01, 0xfe, 0xeb, 0xfc, 0x52, 0x00, 0x00, -- .....R..
0x00, 0x00, 0x06, 0xfe, 0x02, 0x00, 0x00, 0x00, -- ........
0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, -- ........
0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, -- ........
0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, -- .. !"#$%
0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, -- &'()*+,-
0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, -- ./012345
0x36, 0x37 -- 67
]
sendSync :: Ptr Q.PFqTag -> Int -> IO Int
sendSync q n =
Q.send q ping >>= (\b -> if b then return (n+1)
else return n)
sendAsync :: Ptr Q.PFqTag -> Int -> IO Int
sendAsync q n =
Q.sendAsync q ping 128 >>= (\b -> if b then return (n+1)
else return n)
while :: (a -> Bool) -> (a -> IO a) -> a -> IO a
while pred fun x
| pred x = do
y <- fun x
while pred fun y
| otherwise = return x
sender :: [String] -> IO ()
sender xs = do
let dev = head xs
let queue = read (xs !! 1) :: Int
let core = read (xs !! 2) :: Int
let num = read (xs !! 3) :: Int
fp <- Q.open' 64 1024 1024
withForeignPtr fp $ \q -> do
Q.enable q
Q.bindTxOnCpu q dev queue core
if core /= -1
then do
putStrLn $ "sending " ++ show num ++ " packets to dev " ++ dev ++ " (async)..."
Q.txAsync q True
while (< num) (sendAsync q) 0
else do
putStrLn $ "sending " ++ show num ++ " packets to dev " ++ dev ++ "..."
while (< num) (sendSync q) 0
threadDelay 2000000
stat <- Q.getStats q
print stat
Q.close q
main :: IO ()
main = do
args <- getArgs
case () of
_ | length args < 4 -> error "usage: test-send dev queue node num"
| otherwise -> sender args
| Mr-Click/PFQ | user/Haskell/test/test-send.hs | gpl-2.0 | 3,536 | 0 | 18 | 1,125 | 983 | 548 | 435 | 64 | 2 |
doubleMe x = x + x
tripleMe x = doubleMe x + x
doubleSmallNumbers x = if x < 100
then doubleMe x
else x
boomBang xs = [if x < 10 then "Boom" else "Bang" | x <- xs, odd x]
tmp :: Int->Int
tmp x = x * 4
lucky :: (Integral a) => a -> String
lucky 7 = "LUCKY NUMBER SEVEN!"
lucky x = "Sorry, you're out of luck, pal!"
factorial :: (Integral a) => a -> a
factorial 0 = 1
factorial n = n * factorial(n - 1)
pie "pi" = "Pie is delicious"
pie "ab" = "This is not right"
addVector :: (Num a) => (a,a) -> (a,a) -> (a,a)
addVector (a1, b1)(a2, b2) = (a1 + a2, b1 + b2)
headAlt :: [a] -> a
headAlt [] = error "Cannot call head on empty list"
headAlt (x:_) = x
lengthAlt :: (Num b) => [a] -> b
lengthAlt [] = 0
lengthAlt (_:xs) = 1 + lengthAlt xs
bmiTell bmi
| bmi <= 18.5 = "God damn emo!"
| bmi <= 25.0 = "Normal? Boring"
| bmi <= 30.0 = "OVERWEIGHT!"
| otherwise = "WHALE"
divideByTen :: (Floating a) => a -> a
divideByTen = (/10)
isUpperAlphanum :: Char -> Bool
isUpperAlphanum = (`elem` ['A'..'Z'])
quick :: (Ord a) => [a] -> [a]
quick [] = []
quick (x:xs) =
let smallBound = quick [a | a <- xs, a <= x]
bigBound = quick [a | a <- xs, a > x]
in smallBound ++ [x] ++ bigBound
| benetis/programming_theory_exercises | Benetis_Zygimantas/3/tmp.hs | gpl-2.0 | 1,252 | 0 | 12 | 342 | 604 | 321 | 283 | 39 | 2 |
{-# OPTIONS -Wall #-}
{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
module Editor.MonadF(MonadF) where
class (Monad m, Functor m) => MonadF m
instance (Monad m, Functor m) => MonadF m
| nimia/bottle | codeedit/Editor/MonadF.hs | gpl-3.0 | 196 | 0 | 6 | 29 | 57 | 31 | 26 | -1 | -1 |
module Export2 where
import ExportBasic
import ExportBasic2
f :: Int
f = 4
(/**) :: a -> Int -> Int
_ /** z = 2 * g * z -- 12 * z
where
g = 3 * k -- 6
where
k = 3
infixr 6 /**
data Listt a = a :> a | Empt
data Listt2 a = a :>< a | Empty
data Listt3 a = a :>>< a | Emptyy
type Hello = Int
main :: Int
main = 0 | Helium4Haskell/helium | test/exports/Export2.hs | gpl-3.0 | 337 | 0 | 8 | 113 | 140 | 83 | 57 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.MonteCarlo.Plain
-- Copyright : (c) 2011, 2013 Ian-Woo Kim
--
-- License : GPL-3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-- Plain non-adaptive monte carlo integration algorithm
--
-----------------------------------------------------------------------------
module Numeric.MonteCarlo.Plain where
import System.Random.Mersenne
-- | 1D integration
plain1DMC :: (Double -> IO Double)
-> Int
-> IO Double
plain1DMC integrand num = do
g <- getStdGen
let go :: Double -> Int -> IO Double
go !accr !accn
| accn <= 0 =
return accr
| otherwise = do
x1 <- random g :: IO Double
itr <- integrand x1
if isNaN itr
then putStrLn $ show (x1,itr)
else return ()
go (accr + itr) (accn-1)
r <- go 0.0 num
return $ r/fromIntegral num
-- | 2D integration
plain2DMC :: ((Double,Double) -> IO Double)
-> Int
-> IO Double
plain2DMC integrand num = do
g <- getStdGen
let go :: Double -> Int -> IO Double
go !accr !accn
| accn <= 0 =
return accr
| otherwise = do
x1 <- random g :: IO Double
x2 <- random g :: IO Double
itr <- integrand (x1,x2)
if isNaN itr
then putStrLn $ show (x1,x2,itr)
else return ()
go (accr + itr) (accn-1)
r <- go 0.0 num
return $ r/fromIntegral num
-- | 3D integration
plain3DMC :: ((Double,Double,Double) -> IO Double)
-> Int
-> IO Double
plain3DMC integrand num = do
g <- getStdGen
let go :: Double -> Int -> IO Double
go !accr !accn
| accn <= 0 =
return accr
| otherwise = do
x1 <- random g :: IO Double
x2 <- random g :: IO Double
x3 <- random g :: IO Double
itr <- integrand (x1,x2,x3)
if isNaN itr
then putStrLn $ show (x1,x2,x3,itr)
else return ()
go (accr + itr) (accn-1)
r <- go 0.0 num
return $ r/fromIntegral num
| wavewave/hMC | src/Numeric/MonteCarlo/Plain.hs | gpl-3.0 | 2,345 | 0 | 16 | 846 | 726 | 352 | 374 | 60 | 2 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies, TypeFamilies, TemplateHaskell, FlexibleContexts, ViewPatterns, NoMonomorphismRestriction #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS -Wall -fno-warn-orphans #-}
module QuickCheckUtil where
import Test.QuickCheck
import Control.Monad
import qualified Data.Set as S
import Data.Graph.Inductive.Tree
import Data.Graph.Inductive.Graph
import qualified Data.Vector as V
import Element
import qualified Data.Vector.Generic as VG
import Data.SumType
import Control.Applicative
import Data.Maybe
-- import Math.NumberTheory.Primes.Factorisation
cart :: Monad m => m a1 -> m a2 -> m (a1, a2)
cart = liftM2 (,)
data ShowWithVarName a = ShowWithVarName String a
instance Show a => Show (ShowWithVarName a) where
showsPrec _ (ShowWithVarName vn a) = showString vn . showString " = " . shows a
unShowWithVarName :: ShowWithVarName t -> t
unShowWithVarName (ShowWithVarName _ a) = a
forAllShrinkN
:: (Show b, Testable prop) =>
Gen b
-> (ShowWithVarName b -> [ShowWithVarName b])
-> String
-> (b -> prop)
-> Property
forAllShrinkN gen shr name p =
forAllShrink (ShowWithVarName name <$> gen) shr (p . unShowWithVarName)
forAllN
:: (Show b, Testable prop) =>
Gen b -> String -> (b -> prop) -> Property
forAllN gen name p =
forAll (ShowWithVarName name <$> gen) (p . unShowWithVarName)
forAllElements
:: (Show (Element xs), AsList xs, Testable prop) =>
xs -> (Element xs -> prop) -> Property
forAllElements (asList -> xs) p =
if null xs
then label "Vacuously true (empty domain)" True
else forAll (elements xs) p
forAllElementsN
:: (Show (Element xs), AsList xs, Testable prop) =>
xs -> String -> (Element xs -> prop) -> Property
forAllElementsN elts name p =
forAllElements
(ShowWithVarName name <$> asList elts)
(p . unShowWithVarName)
-- | Shrinks the index in the given list
forAllElementsShrink
:: (Show (Element xs), AsList xs, Testable prop) =>
xs -> (Element xs -> prop) -> Property
forAllElementsShrink (asList -> xs) p =
case length xs of
0 -> label "Vacuously true (empty domain)" True
n -> forAllShrink (choose (0,n-1)) shrink (\i -> let x = xs !! i in
printTestCase (show x) (p x))
forAllElements2
:: (Show (Element xs),
Show (Element xs1),
AsList xs,
AsList xs1,
Testable prop) =>
xs -> xs1 -> ((Element xs, Element xs1) -> prop) -> Property
forAllElements2 xs ys p = forAllElements (asList xs `cart` asList ys) p
forAll2 :: (Testable prop, Show a1, Show a) =>Gen a -> Gen a1 -> (a -> a1 -> prop) -> Property
forAll2 gen1 gen2 p = forAll gen1 (\x1 -> forAll gen2 (p x1))
forAll3 :: (Testable prop, Show a1, Show a2, Show a) =>Gen a -> Gen a1 -> Gen a2 -> (a -> a1 -> a2 -> prop) -> Property
forAll3 gen1 gen2 gen3 p = forAll gen1 (\x1 -> forAll gen2 (\x2 -> forAll gen3 (p x1 x2)))
changeSize :: (Int -> Int) -> Gen a -> Gen a
changeSize f gen = sized (\n -> resize (f n) gen)
-- | Exhaustively checks a property for all elements of a list (in contrast to 'forAll', which samples randomly)
conjoinMap :: Testable prop => [t] -> (t -> prop) -> Property
conjoinMap [] _ = label "Vacuously true (empty domain)" True
conjoinMap xs p = conjoin (fmap p xs)
conjoinMap2 :: Testable prop => [a1] -> [a2] -> ((a1, a2) -> prop) -> Property
conjoinMap2 xs ys p = conjoinMap (xs `cart` ys) p
(.=.) :: (Show a, Eq a) => a -> a -> Property
x .=. y =
printTestCase (unlines ["Checking equality","=== LHS of equation ===",show x,"=== RHS of equation ===",show y])
(x==y)
infix 4 .=.
setEq
:: (Ord (Element xs),
Show (Element xs),
AsList xs,
AsList xs1,
Element xs1 ~ Element xs) =>
xs -> xs1 -> Property
setEq (asList -> xs) (asList -> ys) =
printTestCase (unlines ["setEq:","=== FIRST SET ===",show xs,"=== SECOND SET ===",show ys]) $
(S.fromList xs == S.fromList ys)
isSubset :: (Show a, Ord a) => [a] -> [a] -> Property
isSubset x y =
printTestCase (unlines ["isSubset:","=== FIRST SET ===",show x,"=== SECOND SET ===",show y])
(S.fromList x `S.isSubsetOf` S.fromList y)
instance (Arbitrary a, Arbitrary b) => Arbitrary (Gr a b) where
arbitrary = do
ns <- (S.toList . S.fromList) `fmap` arbitrary :: Gen [Node]
let nNodes = length ns
lns <- zip ns `fmap` vector nNodes
nEdges <- choose (0,nNodes^(2::Int))
les <- let g = vectorOf nEdges (elements ns)
in liftM3 zip3 g g (vector nEdges)
return (mkGraph lns les)
conjoin' :: Testable a => [a] -> Gen Prop
conjoin' [] = label "conjoin' []" True
conjoin' ((V.fromList . fmap property) -> ps) =
(ps V.!) =<< choose (0,V.length ps-1)
noDupes
:: (Ord (Element xs), Show (Element xs), AsList xs) =>
xs -> Property
noDupes (asList -> xs) =
printTestCase ("Checking duplicate-freeness of "++ show xs) $
S.size (S.fromList xs) .=. length xs
elementsV :: (Ord b, VG.Vector v b) => v b -> Gen b
elementsV v | VG.null v = error "elementsV: empty vector"
elementsV v = do
i <- choose (0,VG.maxIndex v)
return (v VG.! i)
generateUntilRight
:: (Show (L a), SubSumTy a) => Gen a -> Gen (R a)
generateUntilRight g = fromRight <$> (g `suchThat` isRight)
generateUntilJust :: Gen (Maybe b) -> Gen b
generateUntilJust g = fromJust <$> (g `suchThat` isJust)
-- arbitraryDivisor :: Integer -> Gen Integer
-- arbitraryDivisor i =
-- let
-- factorisation = factorise i
-- in
-- do
-- powers <- mapM (\n -> choose (0,n)) (map snd factorisation)
-- return (product [ p ^ k | (p,k) <- zip (map fst factorisation) powers ])
-- arbitraryConvexCombination v
-- | VG.null v = assert False undefined
-- | otherwise = do
--
-- (coeffs,sum) <- (do
-- coeffs <- vectorOf (VG.length v) (choose (0,1))
-- return (coeffs, sum coeffs))
--
-- `suchThat` (
--
--
--
| DanielSchuessler/hstri | QuickCheckUtil.hs | gpl-3.0 | 6,113 | 0 | 15 | 1,508 | 2,176 | 1,132 | 1,044 | 125 | 2 |
module SocialForce.Run (
runSocialForce
) where
import Control.Monad.Random
import FRP.FrABS
import FRP.Yampa
import SocialForce.Init
import SocialForce.Renderer
import SocialForce.Model
winSize :: (Int, Int)
winSize = (1000, 600)
winTitle :: String
winTitle = "SocialForce"
frequency :: Int
frequency = 0
rngSeed :: Int
rngSeed = 42
dt :: DTime
dt = unitTime -- 0.1
-- TODO: unfinished implementation
runSocialForce :: IO ()
runSocialForce = do
params <- initSimulation Sequential Nothing Nothing True (Just rngSeed)
(initAdefs, initEnv) <- evalRandIO $ initSocialForce params
simulateAndRender
initAdefs
initEnv
params
dt
frequency
winTitle
winSize
renderSocialForceFrame
Nothing --(Just (\_ asenv -> printAgentDynamics asenv)) | thalerjonathan/phd | coding/libraries/chimera/examples/ABS/SocialForce/Run.hs | gpl-3.0 | 795 | 0 | 10 | 160 | 188 | 106 | 82 | 32 | 1 |
main :: IO()
main = do
args <- getContents
mapM_ putStrLn $ map compress $ lines args
compress :: String -> String
compress str = compress' str "" 0
compress' :: String -> String -> Int -> String
compress' [] prev count = prev ++ if count > 1 then show count else ""
compress' str _ 0 = (compress' (tail str) [(head str)] 1)
compress' str prev count = if prev /= [head str] then
prev ++
(if count > 1 then show count else "") ++ compress' (tail str) [(head str)] 1
else compress' (tail str) [(head str)] (count + 1)
| woodsjc/hackerrank-challenges | string-compression.hs | gpl-3.0 | 576 | 6 | 10 | 163 | 267 | 135 | 132 | 13 | 4 |
module Wordify.Rules.FormedWord (FormedWords,
FormedWord,
PlacedSquares,
allWords,
mainWord,
adjacentWords,
playerPlaced,
playerPlacedMap,
scoreWord,
overallScore,
bingoBonusApplied,
prettyPrintIntersections,
makeString,
wordStrings,
wordsWithScores,
wordsFormedMidGame,
wordFormedFirstMove) where
import Wordify.Rules.Pos
import Wordify.Rules.Square
import Wordify.Rules.Tile
import Wordify.Rules.Board
import Wordify.Rules.ScrabbleError
import Data.Sequence as Seq
import Data.Map as Map
import Control.Applicative
import Control.Monad
import Data.Foldable as Foldable
import qualified Data.Maybe as M
import qualified Data.List.Split as S
import Data.Char
import Data.Functor
data FormedWords = FirstWord FormedWord | FormedWords {
main :: FormedWord
, otherWords :: [FormedWord]
, placed :: PlacedSquares
} deriving (Show, Eq)
type FormedWord = Seq (Pos, Square)
type PlacedSquares = Map Pos Square
{- |
Pretty prints the places a given formed word intersects with letters that were already on the board
using brackets. E.g. T(HI)S would denote that the player placed a 'T' and an 'S' on to the board, using
the already placed word 'HI' to form the new word 'THIS'.
-}
prettyPrintIntersections :: PlacedSquares -> FormedWord -> String
prettyPrintIntersections placed formedWord = denotePassThroughs placed $ Foldable.toList formedWord
where
denotePassThroughs :: PlacedSquares -> [(Pos, Square)] -> String
denotePassThroughs placed formed =
let breaks = brokenSquaresToChars $ S.split (splitter placed) formed
in case breaks of
(part:parts) -> part ++ (Prelude.concat $ Prelude.zipWith (++) (cycle ["(",")"]) parts)
[] -> ""
squareToChar :: Square -> Char
squareToChar sq = maybe '_' id $ tileIfOccupied sq >>= printLetter
-- Splits whenever we encounter a series of squares that the player's word passes through
-- on the board
splitter :: PlacedSquares -> S.Splitter (Pos, Square)
splitter placed = S.condense $ S.whenElt (flip (Map.notMember . fst) placed)
brokenSquaresToChars :: [[(Pos, Square)]] -> [[Char]]
brokenSquaresToChars brokenSquares = (Prelude.map . Prelude.map) (squareToChar . snd) brokenSquares
{- |
Scores an individual word.
Note: overallscore should be used to obtain the overall score as it takes into account any bingo bonuses.
-}
scoreWord :: PlacedSquares -> FormedWord -> Int
scoreWord played formed =
let (notAlreadyPlaced, onBoardAlready) = partitionPlaced played formed
in scoreSquares onBoardAlready notAlreadyPlaced
where
partitionPlaced placed formed = (mapTuple . fmap) snd $ Seq.partition (\(pos, _) -> Map.member pos placed) formed
mapTuple :: (a -> b) -> (a, a) -> (b, b)
mapTuple f (a1, a2) = (f a1, f a2)
{- |
Calculates the overall score of the play.
If a player managed to place all 7 of their letters, then they receive a bingo bonus of 50 points.
-}
overallScore :: FormedWords -> Int
overallScore formedWords =
let wordsScore = Prelude.sum $ Prelude.map (scoreWord placed) $ allWords formedWords
in case (Prelude.length $ keys $ placed) of
7 -> wordsScore + 50
_ -> wordsScore
where
placed = playerPlacedMap formedWords
{-|
All the words formed by a play.
-}
allWords :: FormedWords -> [FormedWord]
allWords (FormedWords main adjacentWords _) = main : adjacentWords
allWords (FirstWord firstWord) = [firstWord]
{- |
Returns the word formed by the first move on the board. The word must cover
the star tile, and be linear. Any blank tiles must be labeled.
-}
wordFormedFirstMove :: Board -> Map Pos Tile -> Either ScrabbleError FormedWords
wordFormedFirstMove board tiles
| starPos `Map.notMember` tiles = Left DoesNotCoverTheStarTile
| otherwise = placedSquares board tiles >>= fmap (FirstWord . main) . wordsFormed board
{- |
Returns the words formed by the tiles played on the board. A played word
must be connected to a tile already on the board (or intersect tiles on the board),
and be formed linearly. Any blank tiles must be labeled.
-}
wordsFormedMidGame :: Board -> Map Pos Tile -> Either ScrabbleError FormedWords
wordsFormedMidGame board tiles = placedSquares board tiles >>=
\squares -> wordsFormed board squares >>= \formed ->
let FormedWords x xs _ = formed
-- Check it connects to at least one other word on the board
in if Seq.length x > Map.size squares || not (Prelude.null xs)
then Right $ FormedWords x xs squares
else Left DoesNotConnectWithWord
{- |
Returns the main word formed by the played tiles. The main word is
the linear stretch of tiles formed by the tiles placed.
-}
mainWord :: FormedWords -> FormedWord
mainWord (FirstWord word) = word
mainWord formed = main formed
{- |
Returns the list of words which were adjacent to the main word formed.
-}
adjacentWords :: FormedWords -> [FormedWord]
adjacentWords (FirstWord _) = []
adjacentWords formed = otherWords formed
{- |
Returns the list of positions mapped to the squares that the player placed their tiles on.
-}
playerPlaced :: FormedWords -> [(Pos, Square)]
playerPlaced (FirstWord word) = Foldable.toList word
playerPlaced formed = Map.toList $ placed formed
playerPlacedMap :: FormedWords -> Map Pos Square
playerPlacedMap (FirstWord word) = Map.fromList $ Foldable.toList word
playerPlacedMap formed = placed formed
{- |
Scores the words formed by the tiles placed. The first item in the tuple is the overall
score, while the second item is the list of scores for all the words formed.
-}
wordsWithScores :: FormedWords -> (Int, [(String, Int)])
wordsWithScores formedWords = (overallScore formedWords, fmap wordAndScore allFormedWords)
where
allFormedWords = allWords formedWords
wordAndScore formedWord = (makeString formedWord, scoreWord (playerPlacedMap formedWords) formedWord)
{- |
Returns true if the player placed all 7 of their letters while forming these words, incurring a + 50 score bonus.
-}
bingoBonusApplied :: FormedWords -> Bool
bingoBonusApplied formed = Prelude.length (playerPlaced formed) == 7
{- |
Returns the words formed by the play as strings.
-}
wordStrings :: FormedWords -> [String]
wordStrings (FirstWord word) = [makeString word]
wordStrings formed = Prelude.map makeString $ main formed : otherWords formed
makeString :: FormedWord -> String
makeString word = M.mapMaybe (\(_, sq) -> tileIfOccupied sq >>= tileLetter) $ Foldable.toList word
{-
Checks that the tiles can be placed, and if so returns a map of the squares at the placed positions.
A tile may be placed if the square is not already occupied, and if it is not an unlabeled blank tile.
-}
placedSquares :: Board -> Map Pos Tile -> Either ScrabbleError (Map Pos Square)
placedSquares board tiles = squares
where
squares = Map.fromList <$> sequence ((\ (pos, tile) ->
posTileIfNotBlank (pos, tile) >>= squareIfUnoccupied) <$> mapAsList)
posTileIfNotBlank (pos,tile) =
if tile == Blank Nothing then Left (CannotPlaceBlankWithoutLetter pos) else Right (pos, tile)
squareIfUnoccupied (pos,tile) = maybe (Left (PlacedTileOnOccupiedSquare pos tile)) (\sq ->
Right (pos, putTileOn sq tile)) $ unoccupiedSquareAt board pos
mapAsList = Map.toList tiles
wordsFormed :: Board -> Map Pos Square -> Either ScrabbleError FormedWords
wordsFormed board tiles
| Map.null tiles = Left NoTilesPlaced
| otherwise = formedWords >>= \formed ->
case formed of
x : xs -> Right $ FormedWords x xs tiles
[] -> Left NoTilesPlaced
where
formedWords = maybe (Left $ MisplacedLetter maxPos) (\direction ->
middleFirstWord direction >>= (\middle ->
let (midWord, _) = middle
in let mainLine = preceding direction minPos >< midWord >< after direction maxPos
in Right $ mainLine : adjacentToMain (swapDirection direction) ) ) getDirection
preceding direction pos = case direction of
Horizontal -> lettersLeft board pos
Vertical -> lettersBelow board pos
after direction pos = case direction of
Horizontal -> lettersRight board pos
Vertical -> lettersAbove board pos
(minPos, _) = Map.findMin tiles
(maxPos, _) = Map.findMax tiles
adjacentToMain direction = Prelude.filter (\word -> Seq.length word > 1) $ Prelude.map (\(pos, square) ->
(preceding direction pos |> (pos, square)) >< after direction pos) placedList
middleFirstWord direction =
case placedList of
[x] -> Right (Seq.singleton x, minPos)
(x:xs) ->
foldM (\(word, lastPos) (pos, square) ->
if not $ stillOnPath lastPos pos direction
then Left $ MisplacedLetter pos
else
if isDirectlyAfter lastPos pos direction then Right (word |> (pos, square), pos) else
let between = after direction lastPos in
if expectedLettersInbetween direction lastPos pos between
then Right ( word >< ( between |> (pos,square) ), pos)
else Left $ MisplacedLetter pos
) (Seq.singleton x, minPos ) xs
[] -> Left NoTilesPlaced
placedList = Map.toAscList tiles
stillOnPath lastPos thisPos direction = staticDirectionGetter direction thisPos == staticDirectionGetter direction lastPos
expectedLettersInbetween direction lastPos currentPos between =
Seq.length between + 1 == movingDirectionGetter direction currentPos - movingDirectionGetter direction lastPos
swapDirection direction = if direction == Horizontal then Vertical else Horizontal
getDirection
-- If only one tile is placed, we look for the first tile it connects with if any. If it connects with none, we return 'Nothing'
| (minPos == maxPos) && (not (Seq.null (lettersLeft board minPos)) || not (Seq.null (lettersRight board minPos))) = Just Horizontal
| (minPos == maxPos) && (not (Seq.null (lettersBelow board minPos)) || not (Seq.null (lettersAbove board minPos))) = Just Vertical
| xPos minPos == xPos maxPos = Just Vertical
| yPos minPos == yPos maxPos = Just Horizontal
| otherwise = Nothing
staticDirectionGetter direction pos = if direction == Horizontal then yPos pos else xPos pos
movingDirectionGetter direction pos = if direction == Horizontal then xPos pos else yPos pos
isDirectlyAfter pos nextPos direction = movingDirectionGetter direction nextPos == movingDirectionGetter direction pos + 1
| Happy0/haskellscrabble | src/Wordify/Rules/FormedWord.hs | gpl-3.0 | 11,930 | 0 | 23 | 3,582 | 2,684 | 1,394 | 1,290 | 162 | 12 |
{-# 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.ServiceConsumerManagement.Services.TenancyUnits.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Delete a tenancy unit. Before you delete the tenancy unit, there should
-- be no tenant resources in it that aren\'t in a DELETED state. Operation.
--
-- /See:/ <https://cloud.google.com/service-consumer-management/docs/overview Service Consumer Management API Reference> for @serviceconsumermanagement.services.tenancyUnits.delete@.
module Network.Google.Resource.ServiceConsumerManagement.Services.TenancyUnits.Delete
(
-- * REST Resource
ServicesTenancyUnitsDeleteResource
-- * Creating a Request
, servicesTenancyUnitsDelete
, ServicesTenancyUnitsDelete
-- * Request Lenses
, studXgafv
, studUploadProtocol
, studAccessToken
, studUploadType
, studName
, studCallback
) where
import Network.Google.Prelude
import Network.Google.ServiceConsumerManagement.Types
-- | A resource alias for @serviceconsumermanagement.services.tenancyUnits.delete@ method which the
-- 'ServicesTenancyUnitsDelete' request conforms to.
type ServicesTenancyUnitsDeleteResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Operation
-- | Delete a tenancy unit. Before you delete the tenancy unit, there should
-- be no tenant resources in it that aren\'t in a DELETED state. Operation.
--
-- /See:/ 'servicesTenancyUnitsDelete' smart constructor.
data ServicesTenancyUnitsDelete =
ServicesTenancyUnitsDelete'
{ _studXgafv :: !(Maybe Xgafv)
, _studUploadProtocol :: !(Maybe Text)
, _studAccessToken :: !(Maybe Text)
, _studUploadType :: !(Maybe Text)
, _studName :: !Text
, _studCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ServicesTenancyUnitsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'studXgafv'
--
-- * 'studUploadProtocol'
--
-- * 'studAccessToken'
--
-- * 'studUploadType'
--
-- * 'studName'
--
-- * 'studCallback'
servicesTenancyUnitsDelete
:: Text -- ^ 'studName'
-> ServicesTenancyUnitsDelete
servicesTenancyUnitsDelete pStudName_ =
ServicesTenancyUnitsDelete'
{ _studXgafv = Nothing
, _studUploadProtocol = Nothing
, _studAccessToken = Nothing
, _studUploadType = Nothing
, _studName = pStudName_
, _studCallback = Nothing
}
-- | V1 error format.
studXgafv :: Lens' ServicesTenancyUnitsDelete (Maybe Xgafv)
studXgafv
= lens _studXgafv (\ s a -> s{_studXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
studUploadProtocol :: Lens' ServicesTenancyUnitsDelete (Maybe Text)
studUploadProtocol
= lens _studUploadProtocol
(\ s a -> s{_studUploadProtocol = a})
-- | OAuth access token.
studAccessToken :: Lens' ServicesTenancyUnitsDelete (Maybe Text)
studAccessToken
= lens _studAccessToken
(\ s a -> s{_studAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
studUploadType :: Lens' ServicesTenancyUnitsDelete (Maybe Text)
studUploadType
= lens _studUploadType
(\ s a -> s{_studUploadType = a})
-- | Required. Name of the tenancy unit to be deleted.
studName :: Lens' ServicesTenancyUnitsDelete Text
studName = lens _studName (\ s a -> s{_studName = a})
-- | JSONP
studCallback :: Lens' ServicesTenancyUnitsDelete (Maybe Text)
studCallback
= lens _studCallback (\ s a -> s{_studCallback = a})
instance GoogleRequest ServicesTenancyUnitsDelete
where
type Rs ServicesTenancyUnitsDelete = Operation
type Scopes ServicesTenancyUnitsDelete =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ServicesTenancyUnitsDelete'{..}
= go _studName _studXgafv _studUploadProtocol
_studAccessToken
_studUploadType
_studCallback
(Just AltJSON)
serviceConsumerManagementService
where go
= buildClient
(Proxy :: Proxy ServicesTenancyUnitsDeleteResource)
mempty
| brendanhay/gogol | gogol-serviceconsumermanagement/gen/Network/Google/Resource/ServiceConsumerManagement/Services/TenancyUnits/Delete.hs | mpl-2.0 | 5,114 | 0 | 15 | 1,079 | 697 | 408 | 289 | 101 | 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.CloudTasks.Projects.Locations.Queues.Pause
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Pauses the queue. If a queue is paused then the system will stop
-- dispatching tasks until the queue is resumed via ResumeQueue. Tasks can
-- still be added when the queue is paused. A queue is paused if its state
-- is PAUSED.
--
-- /See:/ <https://cloud.google.com/tasks/ Cloud Tasks API Reference> for @cloudtasks.projects.locations.queues.pause@.
module Network.Google.Resource.CloudTasks.Projects.Locations.Queues.Pause
(
-- * REST Resource
ProjectsLocationsQueuesPauseResource
-- * Creating a Request
, projectsLocationsQueuesPause
, ProjectsLocationsQueuesPause
-- * Request Lenses
, proXgafv
, proUploadProtocol
, proAccessToken
, proUploadType
, proPayload
, proName
, proCallback
) where
import Network.Google.CloudTasks.Types
import Network.Google.Prelude
-- | A resource alias for @cloudtasks.projects.locations.queues.pause@ method which the
-- 'ProjectsLocationsQueuesPause' request conforms to.
type ProjectsLocationsQueuesPauseResource =
"v2" :>
CaptureMode "name" "pause" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] PauseQueueRequest :>
Post '[JSON] Queue
-- | Pauses the queue. If a queue is paused then the system will stop
-- dispatching tasks until the queue is resumed via ResumeQueue. Tasks can
-- still be added when the queue is paused. A queue is paused if its state
-- is PAUSED.
--
-- /See:/ 'projectsLocationsQueuesPause' smart constructor.
data ProjectsLocationsQueuesPause =
ProjectsLocationsQueuesPause'
{ _proXgafv :: !(Maybe Xgafv)
, _proUploadProtocol :: !(Maybe Text)
, _proAccessToken :: !(Maybe Text)
, _proUploadType :: !(Maybe Text)
, _proPayload :: !PauseQueueRequest
, _proName :: !Text
, _proCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsQueuesPause' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'proXgafv'
--
-- * 'proUploadProtocol'
--
-- * 'proAccessToken'
--
-- * 'proUploadType'
--
-- * 'proPayload'
--
-- * 'proName'
--
-- * 'proCallback'
projectsLocationsQueuesPause
:: PauseQueueRequest -- ^ 'proPayload'
-> Text -- ^ 'proName'
-> ProjectsLocationsQueuesPause
projectsLocationsQueuesPause pProPayload_ pProName_ =
ProjectsLocationsQueuesPause'
{ _proXgafv = Nothing
, _proUploadProtocol = Nothing
, _proAccessToken = Nothing
, _proUploadType = Nothing
, _proPayload = pProPayload_
, _proName = pProName_
, _proCallback = Nothing
}
-- | V1 error format.
proXgafv :: Lens' ProjectsLocationsQueuesPause (Maybe Xgafv)
proXgafv = lens _proXgafv (\ s a -> s{_proXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
proUploadProtocol :: Lens' ProjectsLocationsQueuesPause (Maybe Text)
proUploadProtocol
= lens _proUploadProtocol
(\ s a -> s{_proUploadProtocol = a})
-- | OAuth access token.
proAccessToken :: Lens' ProjectsLocationsQueuesPause (Maybe Text)
proAccessToken
= lens _proAccessToken
(\ s a -> s{_proAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
proUploadType :: Lens' ProjectsLocationsQueuesPause (Maybe Text)
proUploadType
= lens _proUploadType
(\ s a -> s{_proUploadType = a})
-- | Multipart request metadata.
proPayload :: Lens' ProjectsLocationsQueuesPause PauseQueueRequest
proPayload
= lens _proPayload (\ s a -> s{_proPayload = a})
-- | Required. The queue name. For example:
-- \`projects\/PROJECT_ID\/location\/LOCATION_ID\/queues\/QUEUE_ID\`
proName :: Lens' ProjectsLocationsQueuesPause Text
proName = lens _proName (\ s a -> s{_proName = a})
-- | JSONP
proCallback :: Lens' ProjectsLocationsQueuesPause (Maybe Text)
proCallback
= lens _proCallback (\ s a -> s{_proCallback = a})
instance GoogleRequest ProjectsLocationsQueuesPause
where
type Rs ProjectsLocationsQueuesPause = Queue
type Scopes ProjectsLocationsQueuesPause =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsQueuesPause'{..}
= go _proName _proXgafv _proUploadProtocol
_proAccessToken
_proUploadType
_proCallback
(Just AltJSON)
_proPayload
cloudTasksService
where go
= buildClient
(Proxy :: Proxy ProjectsLocationsQueuesPauseResource)
mempty
| brendanhay/gogol | gogol-cloudtasks/gen/Network/Google/Resource/CloudTasks/Projects/Locations/Queues/Pause.hs | mpl-2.0 | 5,633 | 0 | 16 | 1,235 | 785 | 461 | 324 | 112 | 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.Logging.Projects.Locations.Buckets.Views.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists views on a bucket.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.projects.locations.buckets.views.list@.
module Network.Google.Resource.Logging.Projects.Locations.Buckets.Views.List
(
-- * REST Resource
ProjectsLocationsBucketsViewsListResource
-- * Creating a Request
, projectsLocationsBucketsViewsList
, ProjectsLocationsBucketsViewsList
-- * Request Lenses
, plbvlParent
, plbvlXgafv
, plbvlUploadProtocol
, plbvlAccessToken
, plbvlUploadType
, plbvlPageToken
, plbvlPageSize
, plbvlCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.projects.locations.buckets.views.list@ method which the
-- 'ProjectsLocationsBucketsViewsList' request conforms to.
type ProjectsLocationsBucketsViewsListResource =
"v2" :>
Capture "parent" Text :>
"views" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListViewsResponse
-- | Lists views on a bucket.
--
-- /See:/ 'projectsLocationsBucketsViewsList' smart constructor.
data ProjectsLocationsBucketsViewsList =
ProjectsLocationsBucketsViewsList'
{ _plbvlParent :: !Text
, _plbvlXgafv :: !(Maybe Xgafv)
, _plbvlUploadProtocol :: !(Maybe Text)
, _plbvlAccessToken :: !(Maybe Text)
, _plbvlUploadType :: !(Maybe Text)
, _plbvlPageToken :: !(Maybe Text)
, _plbvlPageSize :: !(Maybe (Textual Int32))
, _plbvlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsBucketsViewsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plbvlParent'
--
-- * 'plbvlXgafv'
--
-- * 'plbvlUploadProtocol'
--
-- * 'plbvlAccessToken'
--
-- * 'plbvlUploadType'
--
-- * 'plbvlPageToken'
--
-- * 'plbvlPageSize'
--
-- * 'plbvlCallback'
projectsLocationsBucketsViewsList
:: Text -- ^ 'plbvlParent'
-> ProjectsLocationsBucketsViewsList
projectsLocationsBucketsViewsList pPlbvlParent_ =
ProjectsLocationsBucketsViewsList'
{ _plbvlParent = pPlbvlParent_
, _plbvlXgafv = Nothing
, _plbvlUploadProtocol = Nothing
, _plbvlAccessToken = Nothing
, _plbvlUploadType = Nothing
, _plbvlPageToken = Nothing
, _plbvlPageSize = Nothing
, _plbvlCallback = Nothing
}
-- | Required. The bucket whose views are to be listed:
-- \"projects\/[PROJECT_ID]\/locations\/[LOCATION_ID]\/buckets\/[BUCKET_ID]\"
plbvlParent :: Lens' ProjectsLocationsBucketsViewsList Text
plbvlParent
= lens _plbvlParent (\ s a -> s{_plbvlParent = a})
-- | V1 error format.
plbvlXgafv :: Lens' ProjectsLocationsBucketsViewsList (Maybe Xgafv)
plbvlXgafv
= lens _plbvlXgafv (\ s a -> s{_plbvlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plbvlUploadProtocol :: Lens' ProjectsLocationsBucketsViewsList (Maybe Text)
plbvlUploadProtocol
= lens _plbvlUploadProtocol
(\ s a -> s{_plbvlUploadProtocol = a})
-- | OAuth access token.
plbvlAccessToken :: Lens' ProjectsLocationsBucketsViewsList (Maybe Text)
plbvlAccessToken
= lens _plbvlAccessToken
(\ s a -> s{_plbvlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plbvlUploadType :: Lens' ProjectsLocationsBucketsViewsList (Maybe Text)
plbvlUploadType
= lens _plbvlUploadType
(\ s a -> s{_plbvlUploadType = a})
-- | Optional. If present, then retrieve the next batch of results from the
-- preceding call to this method. pageToken must be the value of
-- nextPageToken from the previous response. The values of other method
-- parameters should be identical to those in the previous call.
plbvlPageToken :: Lens' ProjectsLocationsBucketsViewsList (Maybe Text)
plbvlPageToken
= lens _plbvlPageToken
(\ s a -> s{_plbvlPageToken = a})
-- | Optional. The maximum number of results to return from this request.
-- Non-positive values are ignored. The presence of nextPageToken in the
-- response indicates that more results might be available.
plbvlPageSize :: Lens' ProjectsLocationsBucketsViewsList (Maybe Int32)
plbvlPageSize
= lens _plbvlPageSize
(\ s a -> s{_plbvlPageSize = a})
. mapping _Coerce
-- | JSONP
plbvlCallback :: Lens' ProjectsLocationsBucketsViewsList (Maybe Text)
plbvlCallback
= lens _plbvlCallback
(\ s a -> s{_plbvlCallback = a})
instance GoogleRequest
ProjectsLocationsBucketsViewsList
where
type Rs ProjectsLocationsBucketsViewsList =
ListViewsResponse
type Scopes ProjectsLocationsBucketsViewsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read"]
requestClient ProjectsLocationsBucketsViewsList'{..}
= go _plbvlParent _plbvlXgafv _plbvlUploadProtocol
_plbvlAccessToken
_plbvlUploadType
_plbvlPageToken
_plbvlPageSize
_plbvlCallback
(Just AltJSON)
loggingService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsBucketsViewsListResource)
mempty
| brendanhay/gogol | gogol-logging/gen/Network/Google/Resource/Logging/Projects/Locations/Buckets/Views/List.hs | mpl-2.0 | 6,645 | 0 | 18 | 1,477 | 895 | 521 | 374 | 134 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Moonbase.Util.Css
( Scope(..)
, Id(..)
, combine, (&)
, RuleM(..)
, css, cssRules, (%)
, withCss
, bgColor, fgColor
) where
import Moonbase.Theme
import Control.Applicative
import Control.Monad.Writer
import Data.List
import Data.Monoid
import Data.String
import qualified Graphics.UI.Gtk as Gtk
import qualified Graphics.UI.Gtk.General.StyleContext as Gtk
import qualified Graphics.UI.Gtk.General.CssProvider as Gtk
data Scope = KleenStar
| Class
| Identifier
| Type
deriving (Show)
data Id = Id Scope String
| Nested [Id]
| Refinement Id [String]
| Actions [String]
deriving (Show)
instance IsString Id where
fromString ('.': xs) = Id Class xs
fromString ('#': xs) = Id Identifier xs
fromString (':': xs) = Actions [xs]
fromString str = Id Type str
renderId :: Id -> String
renderId (Id KleenStar _) = "*"
renderId (Id Class id) = "." ++ id
renderId (Id Identifier id) = "#" ++ id
renderId (Id Type id) = id
renderId (Nested n) = intercalate ", " $ map renderId n
renderId (Actions xs) = concatMap (":" ++) xs
renderId (Refinement (Nested ps) n) = intercalate ", " $ map (\p ->
renderId p ++ concatMap (":" ++) n ) ps
renderId (Refinement p n) = renderId p ++ concatMap (":" ++) n
combine :: Id -> Id -> Id
combine (Actions x) (Actions y) = Actions (x ++ y)
combine (Refinement p xs) (Actions ys) = Nested [Refinement p xs, Refinement p (xs ++ ys)]
combine (Nested x) (Nested y) = Nested (x ++ y)
combine p (Actions xs) = Refinement p xs
combine (Actions xs) p = Refinement p xs
combine (Nested xs) p = Nested (p : xs)
combine p (Nested x) = Nested (map (combine p) x)
combine p a = Nested (p : [a])
(&) :: Id -> Id -> Id
(&) = combine
data Rule = Property String String
| Rule Id [Rule]
| Root [Rule]
deriving (Show)
isProperty :: Rule -> Bool
isProperty (Property _ _) = True
isProperty _ = False
isRule :: Rule -> Bool
isRule (Rule _ _) = True
isRule _ = False
prepareRule :: Rule -> [Rule]
prepareRule (Root childs) = concatMap prepareRule childs
prepareRule (Property k v) = [Property k v]
prepareRule (Rule id sub) = withoutSubRules : concatMap apply subRules
where
withoutSubRules = Rule id (filter isProperty sub)
subRules = filter isRule sub
apply (Rule id' sub') = prepareRule $
Rule (combine id id') sub'
renderRule :: Rule -> String
renderRule (Root childs) = concatMap renderRule childs
renderRule (Property k v) = k ++ ": " ++ v ++ ";"
renderRule (Rule id subs) = renderId id ++ " {\n"
++ concatMap renderRule subs
++ "}\n"
newtype RuleM a = R (Writer [Rule] a)
deriving (Functor, Applicative, Monad)
type Css = RuleM ()
rule :: Rule -> Css
rule r = R (tell [r])
generate :: Css -> [Rule]
generate (R f) = execWriter f
cssRules :: Css -> Css
cssRules c = rule $ Root (generate c)
(%) :: Id -> Css -> Css
(%) id c = rule $ Rule id (generate c)
css :: Css -> String
css c = concatMap renderRule $ concatMap prepareRule (generate c)
withCss :: (Gtk.WidgetClass widget, MonadIO m) => widget -> Css -> m ()
withCss widget c = liftIO $ do
name <- Gtk.widgetGetName widget :: IO String
provider <- Gtk.cssProviderNew
context <- Gtk.widgetGetStyleContext widget
Gtk.cssProviderLoadFromString provider $
css $ rule $ Rule (Id Identifier name) (generate c)
Gtk.styleContextAddProvider context provider 800
class Colorize c where
renderColor :: c -> String
instance Colorize String where
renderColor c = c
colorProperty :: (Colorize color) => String -> color -> Css
colorProperty key color = rule $ Property key (renderColor color)
bgColor :: (Colorize color) => color -> Css
bgColor = colorProperty "background-color"
fgColor :: (Colorize color) => color -> Css
fgColor = colorProperty "color"
{-
background-color
background-image
color
border-color
border-image
border-radius
border-width
border-style
padding
margin
transition -}
| felixsch/moonbase-ng | src/Moonbase/Util/Css.hs | lgpl-2.1 | 4,396 | 0 | 12 | 1,187 | 1,586 | 835 | 751 | 111 | 1 |
import AdventOfCode (readInputFile)
import Control.Monad (foldM)
import Data.Char (isDigit)
import Text.Read (readMaybe)
data JsonNest = Object Bool | Array deriving (Show)
-- Left are for possible but malformed input strings, like } or ].
-- error are for invalid states that no input string, well-formed or malformed, should ever cause.
sums :: String -> Either String (Int, Int)
sums s = foldM parse empty s >>= expectOneSum
where expectOneSum r = case objSum r of
[a] -> Right (total r, a)
[] -> error ("should always have 1+ objSums: " ++ show r)
_ -> Left ("too many sums (unclosed object): " ++ show r)
data ParseState = ParseState {
objSum :: [Int]
, total :: !Int
, nest :: [JsonNest]
, inString :: Bool
, numBuf :: String
, redStart :: Int
, redGood :: Int
, idx :: Int
} deriving Show
empty :: ParseState
empty = ParseState {
objSum = [0]
, total = 0
, nest = []
, inString = False
, numBuf = ""
, redStart = 0
, redGood = 0
, idx = 0
}
pushNest :: JsonNest -> ParseState -> ParseState
pushNest state ps = ps { nest = state : nest ps }
parseNum :: ParseState -> Either String ParseState
parseNum ps@ParseState { numBuf = "" } = Right ps
parseNum ps@ParseState { objSum = [] } = error ("should always have 1+ objSums: " ++ show ps)
parseNum ps@ParseState { total = t, objSum = o:os, numBuf = bf } = case readMaybe (reverse bf) of
Just i -> Right (ps { total = t + i, objSum = (o + i):os, numBuf = "" })
Nothing -> Left ("not a number: " ++ bf)
closeObj :: ParseState -> Either String ParseState
closeObj ps@ParseState { objSum = a:b:os, nest = Object red:ns } =
Right (ps { objSum = (b + if red then 0 else a):os, nest = ns })
closeObj ps@ParseState { nest = Object _:_ } = error ("should always have 2+ objSums when closing obj: " ++ show ps)
closeObj ps = Left ("invalid close obj: " ++ show ps)
closeArray :: ParseState -> Either String ParseState
closeArray ps@ParseState { nest = Array:ns } = Right (ps { nest = ns })
closeArray ps = Left ("invalid close array: " ++ show ps)
parse :: ParseState -> Char -> Either String ParseState
parse ps c = fmap (\p -> p { idx = idx p + 1 }) (parseC c ps)
incRedGood :: ParseState -> Either a ParseState
incRedGood ps = Right (ps { redGood = redGood ps + 1 })
parseC :: Char -> ParseState -> Either String ParseState
-- in string
parseC c ps@ParseState { inString = True } = case (c, ps) of
('r', _) | redStart ps + 1 == idx ps -> incRedGood ps
('e', _) | redStart ps + 2 == idx ps -> incRedGood ps
('d', _) | redStart ps + 3 == idx ps -> incRedGood ps
-- "red"
('"', ParseState { nest = Object _:ns, redGood = 3 }) | redStart ps + 4 == idx ps ->
-- assumes that there is never a key "red"
Right (ps { nest = Object True:ns, inString = False })
-- any other close quote
('"', _) -> Right (ps { inString = False })
_ -> Right ps
-- not in string
parseC '{' ps = Right (pushNest (Object False) ps { objSum = 0:objSum ps })
parseC '}' ps = parseNum ps >>= closeObj
parseC '[' ps = Right (pushNest Array ps)
parseC ']' ps = parseNum ps >>= closeArray
parseC ',' ps = parseNum ps
parseC '"' ps = Right (ps { inString = True, redGood = 0, redStart = idx ps })
parseC c ps | c == '-' || isDigit c = Right (ps { numBuf = c:numBuf ps })
parseC ':' ps = Right ps
parseC '\n' ps = Right ps
parseC c _ = Left ("invalid char: " ++ [c])
main :: IO ()
main = do
s <- readInputFile
case sums s of
Right (a, b) -> print a >> print b
Left err -> putStrLn err
| petertseng/adventofcode-hs | bin/12_json_numbers.hs | apache-2.0 | 3,487 | 0 | 14 | 790 | 1,460 | 769 | 691 | 78 | 6 |
{-
Copyright 2015 Tristan Aubrey-Jones
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 Compiler.Front.Common
import Compiler.Front.Indices (IdxMonad)
import Compiler.Planner.SolExec
import Compiler.Planner.SearchCache
import Compiler.Planner.Searches
import Data.List (isSuffixOf, intercalate)
import qualified Data.Map.Strict as Data.Map
import qualified Data.IntMap.Strict as IM
import System.Directory
import Control.Monad.State.Strict (lift)
import Data.Functor.Identity (runIdentity)
import Data.Maybe (isJust, isNothing)
import System.IO
import System.Exit (exitFailure)
import Data.Time.Clock
import System.Environment (getArgs)
putStrE = hPutStr stderr
search :: String -> SCacheM String
search dir = do
-- load cache
loadCache dir
-- do exaustive search
tryAllSearches
-- display result
return ""
main2 :: IdxMonad IO ()
main2 = do
-- get dir from command line args
args <- lift $ getArgs
let subDir = (if (length args < 1) then "search7" else head args)
-- init dir
lift $ putStrE $ "PerformanceFeedback code gen from solution source: " ++ subDir ++ "\n"
let relDir = "/Compiler/Tests/PfFb/" ++ subDir
curDir <- lift $ getCurrentDirectory
let dir = curDir ++ relDir
-- load context
ctx <- loadContext dir
-- run with cache
msg <- lift $ runWithCache (setSolCtx ctx >> search dir)
-- display message
lift $ putStr $ msg
return ()
main :: IO ()
main = do
evalIdxStateT 0 main2
return ()
| flocc-net/flocc | v0.1/Compiler/Tests/PfFb/Run2.hs | apache-2.0 | 1,951 | 0 | 14 | 347 | 397 | 214 | 183 | 38 | 2 |
data Position t = Position t deriving (Show)
stagger (Position d) = Position (d + 2)
crawl (Position d) = Position (d + 1)
rtn x = x
x >>== f = f x | fbartnitzek/notes | 7_languages/Haskell/drunken-monad.hs | apache-2.0 | 149 | 0 | 7 | 35 | 88 | 44 | 44 | 5 | 1 |
module Routes.Header where
import Text.Blaze.Html
-- local
import Session
import Html.Header
buildHeaderHtml :: ServerT Html
buildHeaderHtml = do
return $ headerHtml
| mcmaniac/blog.nils.cc | src/Routes/Header.hs | apache-2.0 | 173 | 0 | 7 | 28 | 41 | 24 | 17 | 7 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module Model.JsonTypes.Turn
( Turn(..)
, jsonTurn
)
where
import Data.Aeson (ToJSON)
import Database.Persist.Sql (Entity(..))
import Data.Time.Clock (UTCTime)
import GHC.Generics (Generic)
import qualified Model.SqlTypes as SqlT
import Query.Util (integerKey)
data Turn =
Turn { userId :: Integer
, startDate :: UTCTime
} deriving (Show, Generic)
instance ToJSON Turn
jsonTurn :: Entity SqlT.Turn -> Turn
jsonTurn (Entity _turnId turn) =
Turn { userId = integerKey . SqlT.turnUserId $ turn
, startDate = SqlT.turnStartDate turn
}
| flatrapp/core | app/Model/JsonTypes/Turn.hs | apache-2.0 | 717 | 0 | 9 | 233 | 182 | 108 | 74 | 19 | 1 |
s :: [Int]
s = map (2^) [0..]
bin :: Int -> [Int]
bin 0 = []
bin x = (x `mod` 2):(bin $ x `div` 2)
tak [] = []
tak ((0,s):xs) = tak xs
tak ((1,s):xs) = s:(tak xs)
ans x = tak $ zip (bin x) s
main = do
c <- getContents
let i = map read $ lines c :: [Int]
o = map ans i
mapM_ putStrLn $ map unwords $ map (map show) o
| a143753/AOJ | 0031.hs | apache-2.0 | 334 | 0 | 11 | 99 | 247 | 129 | 118 | 14 | 1 |
-- Copyright 2020 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- 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.
-- An alternate version of chain3 that depends on Chain2Conflict.
module Chain3Alternate (chain3) where
import qualified Chain2Conflict as X
chain3 o = appendFile o "3"
| google/hrepl | hrepl/tests/Chain3Alternate.hs | apache-2.0 | 760 | 0 | 5 | 128 | 42 | 31 | 11 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- This is needed so that we can have constraints in type synonyms.
{-# LANGUAGE RankNTypes #-}
module Main where
import Network.Wreq
import Control.Lens
import Data.Aeson.Lens (_String, _Array, key)
main :: IO()
main = do
r <- get "https://api.github.com/users/prt2121/repos"
putStrLn $ show $ r ^.. responseBody . _Array . traverse . key "git_url" . _String
-- putStrLn $ show $ r ^? responseBody . _Array . traverse . key "git_url" . _String
-- ^?
-- Perform a safe head of a Fold or Traversal or retrieve Just the result from a Getter or Lens.
-- ^..
-- (^..) :: s -> Getting (Endo [a]) s a -> [a]
-- A convenient infix (flipped) version of toListOf
-- toListOf :: Getting (Endo [a]) s a -> s -> [a] Source
--
-- Extract a list of the targets of a Fold. See also (^..).
--
-- toList ≡ toListOf folded
-- (^..) ≡ flip toListOf
-- Traversals are Lenses which focus on multiple targets simultaneously
-- Operators that begin with ^ are kinds of views.
-- https://www.schoolofhaskell.com/school/to-infinity-and-beyond/pick-of-the-week/a-little-lens-starter-tutorial
| prt2121/haskell-practice | httpee/src/Main.hs | apache-2.0 | 1,117 | 0 | 13 | 192 | 108 | 66 | 42 | -1 | -1 |
{-# LANGUAGE TupleSections #-}
module Evolution where
import System.Random
import Control.Monad
import Control.Arrow
import Data.List
import Data.Ord
--import Data.MList
type Probability = Double
type FitnessValue = Double
type Quantile = Double
type FitnessFunction a = a -> FitnessValue
type ReproducingFunction a = [a] -> [a]
type ReproductivePressureFunction = Quantile -> Probability
type Population a = [a]
boolChance :: Double -> IO Bool
boolChance p = liftM (p <) (randomRIO (0.0,100.0))
assignQuantile :: [a]
-> [(a, Quantile)]
assignQuantile xs = zipWith divByLen xs ([0..]::[Integer])
where len = fromIntegral $ length xs
divByLen e i = (e, fromIntegral i / len)
deleteAt :: Int -> [a] -> [a]
deleteAt i xs = take (i-1) xs ++ drop (i+1) xs
shuffle :: [a] -> IO [a]
shuffle [] = return []
shuffle xs = do ind <- randomRIO (0, length xs - 1)
rest <- shuffle (deleteAt ind xs)
return $! (xs !! ind) : rest
chop :: Int -> [a] -> [[a]]
chop _ [] = []
chop n xs = take n xs : chop n (drop n xs)
evolution :: FitnessFunction a
-> ReproducingFunction a
-> ReproductivePressureFunction
-> Population a
-> IO (Population a)
evolution fitness reproduce pressure pop =
let
doesReproduce = second (boolChance . pressure)
fitnessSorted = assignQuantile $ sortBy (comparing fitness) pop
chosenPop = liftM (map fst) $ filterM snd $ map doesReproduce fitnessSorted
chosenPairs = liftM (chop 2) $ shuffle =<< chosenPop
newGen = liftM (concatMap reproduce) chosenPairs
--futureGens = newGen >>= evolution fitness reproduce pressure
in
--newGen :# futureGens
newGen
| jtapolczai/Scratchpad | src/Evolution.hs | apache-2.0 | 1,717 | 0 | 13 | 415 | 612 | 326 | 286 | 44 | 1 |
module Data.IORef (
IORef, newIORef, readIORef, writeIORef, modifyIORef, modifyIORef', atomicModifyIORef, atomicModifyIORef', atomicWriteIORef
) where
import System.Mock.IO.Internal
| 3of8/mockio | New_IORef.hs | bsd-2-clause | 190 | 0 | 4 | 24 | 42 | 28 | 14 | 3 | 0 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QCursor.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:16
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QCursor (
QqCursor(..)
,QqCursor_nf(..)
,bitmap
,qCursorPos, qqCursorPos
,QqCursorSetPos(..), qqCursorSetPos
,qCursor_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqCursor x1 where
qCursor :: x1 -> IO (QCursor ())
instance QqCursor (()) where
qCursor ()
= withQCursorResult $
qtc_QCursor
foreign import ccall "qtc_QCursor" qtc_QCursor :: IO (Ptr (TQCursor ()))
instance QqCursor ((QPixmap t1)) where
qCursor (x1)
= withQCursorResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCursor1 cobj_x1
foreign import ccall "qtc_QCursor1" qtc_QCursor1 :: Ptr (TQPixmap t1) -> IO (Ptr (TQCursor ()))
instance QqCursor ((QCursor t1)) where
qCursor (x1)
= withQCursorResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCursor2 cobj_x1
foreign import ccall "qtc_QCursor2" qtc_QCursor2 :: Ptr (TQCursor t1) -> IO (Ptr (TQCursor ()))
instance QqCursor ((CursorShape)) where
qCursor (x1)
= withQCursorResult $
qtc_QCursor3 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QCursor3" qtc_QCursor3 :: CLong -> IO (Ptr (TQCursor ()))
instance QqCursor ((QBitmap t1, QBitmap t2)) where
qCursor (x1, x2)
= withQCursorResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCursor4 cobj_x1 cobj_x2
foreign import ccall "qtc_QCursor4" qtc_QCursor4 :: Ptr (TQBitmap t1) -> Ptr (TQBitmap t2) -> IO (Ptr (TQCursor ()))
instance QqCursor ((QPixmap t1, Int)) where
qCursor (x1, x2)
= withQCursorResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCursor5 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QCursor5" qtc_QCursor5 :: Ptr (TQPixmap t1) -> CInt -> IO (Ptr (TQCursor ()))
instance QqCursor ((QBitmap t1, QBitmap t2, Int)) where
qCursor (x1, x2, x3)
= withQCursorResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCursor6 cobj_x1 cobj_x2 (toCInt x3)
foreign import ccall "qtc_QCursor6" qtc_QCursor6 :: Ptr (TQBitmap t1) -> Ptr (TQBitmap t2) -> CInt -> IO (Ptr (TQCursor ()))
instance QqCursor ((QPixmap t1, Int, Int)) where
qCursor (x1, x2, x3)
= withQCursorResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCursor7 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QCursor7" qtc_QCursor7 :: Ptr (TQPixmap t1) -> CInt -> CInt -> IO (Ptr (TQCursor ()))
instance QqCursor ((QBitmap t1, QBitmap t2, Int, Int)) where
qCursor (x1, x2, x3, x4)
= withQCursorResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCursor8 cobj_x1 cobj_x2 (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QCursor8" qtc_QCursor8 :: Ptr (TQBitmap t1) -> Ptr (TQBitmap t2) -> CInt -> CInt -> IO (Ptr (TQCursor ()))
class QqCursor_nf x1 where
qCursor_nf :: x1 -> IO (QCursor ())
instance QqCursor_nf (()) where
qCursor_nf ()
= withObjectRefResult $
qtc_QCursor
instance QqCursor_nf ((QPixmap t1)) where
qCursor_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCursor1 cobj_x1
instance QqCursor_nf ((QCursor t1)) where
qCursor_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCursor2 cobj_x1
instance QqCursor_nf ((CursorShape)) where
qCursor_nf (x1)
= withObjectRefResult $
qtc_QCursor3 (toCLong $ qEnum_toInt x1)
instance QqCursor_nf ((QBitmap t1, QBitmap t2)) where
qCursor_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCursor4 cobj_x1 cobj_x2
instance QqCursor_nf ((QPixmap t1, Int)) where
qCursor_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCursor5 cobj_x1 (toCInt x2)
instance QqCursor_nf ((QBitmap t1, QBitmap t2, Int)) where
qCursor_nf (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCursor6 cobj_x1 cobj_x2 (toCInt x3)
instance QqCursor_nf ((QPixmap t1, Int, Int)) where
qCursor_nf (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCursor7 cobj_x1 (toCInt x2) (toCInt x3)
instance QqCursor_nf ((QBitmap t1, QBitmap t2, Int, Int)) where
qCursor_nf (x1, x2, x3, x4)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCursor8 cobj_x1 cobj_x2 (toCInt x3) (toCInt x4)
bitmap :: QCursor a -> (()) -> IO (QBitmap ())
bitmap x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_bitmap cobj_x0
foreign import ccall "qtc_QCursor_bitmap" qtc_QCursor_bitmap :: Ptr (TQCursor a) -> IO (Ptr (TQBitmap ()))
instance QhotSpot (QCursor a) (()) where
hotSpot x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_hotSpot_qth cobj_x0 cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QCursor_hotSpot_qth" qtc_QCursor_hotSpot_qth :: Ptr (TQCursor a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QqhotSpot (QCursor a) (()) where
qhotSpot x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_hotSpot cobj_x0
foreign import ccall "qtc_QCursor_hotSpot" qtc_QCursor_hotSpot :: Ptr (TQCursor a) -> IO (Ptr (TQPoint ()))
instance Qmask (QCursor a) (()) (IO (QBitmap ())) where
mask x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_mask cobj_x0
foreign import ccall "qtc_QCursor_mask" qtc_QCursor_mask :: Ptr (TQCursor a) -> IO (Ptr (TQBitmap ()))
instance Qmask_nf (QCursor a) (()) (IO (QBitmap ())) where
mask_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_mask cobj_x0
instance Qpixmap (QCursor ()) (()) where
pixmap x0 ()
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_pixmap cobj_x0
foreign import ccall "qtc_QCursor_pixmap" qtc_QCursor_pixmap :: Ptr (TQCursor a) -> IO (Ptr (TQPixmap ()))
instance Qpixmap (QCursorSc a) (()) where
pixmap x0 ()
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_pixmap cobj_x0
instance Qpixmap_nf (QCursor ()) (()) where
pixmap_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_pixmap cobj_x0
instance Qpixmap_nf (QCursorSc a) (()) where
pixmap_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_pixmap cobj_x0
qCursorPos :: (()) -> IO (Point)
qCursorPos ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
qtc_QCursor_pos_qth cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QCursor_pos_qth" qtc_QCursor_pos_qth :: Ptr CInt -> Ptr CInt -> IO ()
qqCursorPos :: (()) -> IO (QPoint ())
qqCursorPos ()
= withQPointResult $
qtc_QCursor_pos
foreign import ccall "qtc_QCursor_pos" qtc_QCursor_pos :: IO (Ptr (TQPoint ()))
class QqCursorSetPos x1 where
qCursorSetPos :: x1 -> IO ()
instance QqCursorSetPos ((Int, Int)) where
qCursorSetPos (x1, x2)
= qtc_QCursor_setPos1 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QCursor_setPos1" qtc_QCursor_setPos1 :: CInt -> CInt -> IO ()
instance QqCursorSetPos ((Point)) where
qCursorSetPos (x1)
= withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QCursor_setPos_qth cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QCursor_setPos_qth" qtc_QCursor_setPos_qth :: CInt -> CInt -> IO ()
qqCursorSetPos :: ((QPoint t1)) -> IO ()
qqCursorSetPos (x1)
= withObjectPtr x1 $ \cobj_x1 ->
qtc_QCursor_setPos cobj_x1
foreign import ccall "qtc_QCursor_setPos" qtc_QCursor_setPos :: Ptr (TQPoint t1) -> IO ()
instance QsetShape (QCursor a) ((CursorShape)) where
setShape x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_setShape cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QCursor_setShape" qtc_QCursor_setShape :: Ptr (TQCursor a) -> CLong -> IO ()
instance Qshape (QCursor a) (()) (IO (CursorShape)) where
shape x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_shape cobj_x0
foreign import ccall "qtc_QCursor_shape" qtc_QCursor_shape :: Ptr (TQCursor a) -> IO CLong
qCursor_delete :: QCursor a -> IO ()
qCursor_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCursor_delete cobj_x0
foreign import ccall "qtc_QCursor_delete" qtc_QCursor_delete :: Ptr (TQCursor a) -> IO ()
| keera-studios/hsQt | Qtc/Gui/QCursor.hs | bsd-2-clause | 8,833 | 0 | 15 | 1,608 | 3,079 | 1,590 | 1,489 | -1 | -1 |
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
-- | An example of how to do LDAP logins with ldap-client.
--
-- First, the assumptions this example makes. It defaults to LDAP over TLS,
-- so if you only have a plaintext server, please replace `Secure` with `Plain`.
-- It also assumes the accounts you may want to log in as all have
-- `objectClass` "Person".
--
-- To run the example you have to provide a bunch of environment variables:
--
-- - `HOST` is the LDAP host to connect to (without "ldap://", "ldaps://", etc).
-- - `POST` is the port LDAP server listens on.
-- - `MANAGER_DN` is the DN of the account the first bind is made with.
-- - `MANAGER_PASSWORD` is its password.
-- - `BASE_OBJECT` is the search root
module Main (main) where
import Control.Exception (bracket_) -- base
import Control.Monad (when) -- base
import Data.Function (fix) -- base
import Data.Text (Text) -- text
import qualified Data.Text.Encoding as Text -- text
import qualified Data.Text.IO as Text -- text
import Env -- envparse
import Ldap.Client as Ldap -- ldap-client
import qualified Ldap.Client.Bind as Ldap -- ldap-client
import System.Exit (die) -- base
import qualified System.IO as IO -- base
data Conf = Conf
{ host :: String
, port :: PortNumber
, dn :: Dn
, password :: Password
, base :: Dn
} deriving (Show, Eq)
getConf :: IO Conf
getConf = Env.parse (header "LDAP login example") $ Conf
<$> var str "HOST" (help "LDAP hostname")
<*> var (fmap fromIntegral . auto) "PORT" (help "LDAP port")
<*> var (fmap Ldap.Dn . str) "MANAGER_DN" (help "Manager login DN")
<*> var (fmap Ldap.Password . str) "MANAGER_PASSWORD" (help "Manager password")
<*> var (fmap Ldap.Dn . str) "BASE_OBJECT" (help "Search root")
main :: IO ()
main = do
conf <- getConf
res <- login conf
case res of
Left e -> die (show e)
Right _ -> return ()
login :: Conf -> IO (Either LdapError ())
login conf =
Ldap.with (Ldap.Secure (host conf)) (port conf) $ \l -> do
Ldap.bind l (dn conf) (password conf)
fix $ \loop -> do
uid <- prompt "Username: "
us <- Ldap.search l (base conf)
(typesOnly True)
(And [ Attr "objectClass" := "Person"
, Attr "uid" := Text.encodeUtf8 uid
])
[]
case us of
SearchEntry udn _ : _ ->
fix $ \loop' -> do
pwd <- bracket_ hideOutput
showOutput
(do pwd <- prompt ("Password for ‘" <> uid <> "’: ")
Text.putStr "\n"
return pwd)
res <- Ldap.bindEither l udn (Password (Text.encodeUtf8 pwd))
case res of
Left _ -> do again <- question "Invalid password. Try again? [y/n] "
when again loop'
Right _ -> Text.putStrLn "OK"
[] -> do again <- question "Invalid username. Try again? [y/n] "
when again loop
prompt :: Text -> IO Text
prompt msg = do Text.putStr msg; IO.hFlush IO.stdout; Text.getLine
question :: Text -> IO Bool
question msg = fix $ \loop -> do
res <- prompt msg
case res of
"y" -> return True
"n" -> return False
_ -> do Text.putStrLn "Please, answer either ‘y’ or ‘n’."; loop
hideOutput, showOutput :: IO ()
hideOutput = IO.hSetEcho IO.stdout False
showOutput = IO.hSetEcho IO.stdout True
| VictorDenisov/ldap-client | example/login.hs | bsd-2-clause | 3,786 | 0 | 29 | 1,293 | 942 | 485 | 457 | 73 | 3 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
module Math.Budget.Lens.FixedIntervalL where
import Math.Budget.FixedPeriod
class FixedIntervalL cat target | target -> cat where
fixedIntervalL :: cat target FixedPeriod
| tonymorris/hbudget | src/Math/Budget/Lens/FixedIntervalL.hs | bsd-3-clause | 239 | 0 | 7 | 29 | 42 | 25 | 17 | 5 | 0 |
{-# LANGUAGE FlexibleContexts #-} -- for parsec 3
import SICP.LispParser
import SICP.DB
import Text.Parsec hiding (space)
import Data.MultiSet (MultiSet)
import qualified Data.MultiSet as MultiSet
import Control.Monad
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck as QC
dbTests :: DB -> TestTree
dbTests db = testGroup "DB"
-- assertions
[ testCase "case 1" $ (runQuery "?x" "(начальник ?x (Битобор Бен))")
@?= parseMultiSet "(Хакер Лиза П) (Фект Пабло Э) (Поправич Дайко)"
, testCase "case 2" $ (runQuery "?x" "(должность ?x (бухгалтерия . ?y))")
@?= parseMultiSet "(Крэтчит Роберт) (Скрудж Эбин)"
, testCase "case 3" $ (runQuery "?x" "(адрес ?x (Сламервилл . ?y))")
@?= parseMultiSet "(Фиден Кон) (Дум Хьюго) (Битобор Бен)"
, testCase "case AND" $ (runQuery "(?x ?y)" "(and (начальник ?x (Битобор Бен)) (адрес ?x ?y))")
@?= parseMultiSet
"((Поправич Дайко) (Бостон (Бэй Стейт Роуд) 22))\
\((Фект Пабло Э) (Кембридж (Эймс Стрит) 3))\
\((Хакер Лиза П) (Кембридж (Массачусетс Авеню) 78))"
, testCase "case NOT" $ (runQuery "(?person ?his-boss ?z2)"
"(and \
\(начальник ?person ?his-boss) \
\(not (должность ?his-boss (компьютеры . ?z1))) \
\(должность ?his-boss ?z2))")
@?= parseMultiSet
"((Фиден Кон) (Уорбак Оливер) (администрация большая шишка))\
\((Крэтчит Роберт) (Скрудж Эбин) (бухгалтерия главный бухгалтер))\
\((Скрудж Эбин) (Уорбак Оливер) (администрация большая шишка))\
\((Битобор Бен) (Уорбак Оливер) (администрация большая шишка))"
-- rules
, testCase "rule 1" $ (runQuery "?x" "(живет-около ?x (Битобор Бен))")
@?= parseMultiSet "(Фиден Кон) (Дум Хьюго)"
, testCase "rule 2 can-replace" $ (runQuery "?x" "(can-replace ?x (Фект Пабло Э))")
@?= parseMultiSet "(Битобор Бен) (Хакер Лиза П)"
, testCase "rule 3 independent" $ (runQuery "?x" "(independent ?x)")
@?= parseMultiSet "(Скрудж Эбин) (Уорбак Оливер) (Битобор Бен)"
, testCase "rule 4 " $ (runQuery "(?time ?who)" "(совещание ?who (пятница ?time))")
@?= parseMultiSet "(13 администрация)"
, testCase "rule 5" $ (runQuery "?day-and-time" "(время-совещания (Хакер Лиза П) ?day-and-time)")
@?= parseMultiSet "(среда 16) (среда 15)"
, testCase "rule 6" $ (runQuery "?time" "(время-совещания (Хакер Лиза П) (среда ?time))")
@?= parseMultiSet "16 15"
, testCase "rule 7" $ (runQuery "(?p1 ?p2)" "(живет-около ?p1 ?p2)")
@?= parseMultiSet
"((Фиден Кон) (Дум Хьюго))\
\((Фиден Кон) (Битобор Бен))\
\((Дум Хьюго) (Фиден Кон))\
\((Дум Хьюго) (Битобор Бен))\
\((Хакер Лиза П) (Фект Пабло Э))\
\((Фект Пабло Э) (Хакер Лиза П))\
\((Битобор Бен) (Фиден Кон))\
\((Битобор Бен) (Дум Хьюго))"
, testCase "rule 8 append-to-form" $ (runQuery "?z" "(append-to-form (a b) (c d) ?z)")
@?= parseMultiSet "(a b c d)"
, testCase "rule 9 append-to-form" $ (runQuery "?y" "(append-to-form (a b) ?y (a b c d))")
@?= parseMultiSet "(c d)"
, testCase "rule 10 append-to-form" $ (runQuery "(?x ?y)" "(append-to-form ?x ?y (a b c d))")
@?= parseMultiSet
"((a b c d) ())\
\(() (a b c d))\
\((a) (b c d))\
\((a b) (c d))\
\((a b c) (d))"
, testCase "rule 11 last-pair" $ (runQuery "?x" "(last-pair (3) ?x)")
@?= parseMultiSet "3"
, testCase "rule 12 last-pair" $ (runQuery "?x" "(last-pair (1 2 3) ?x)")
@?= parseMultiSet "3"
, testCase "rule 13 last-pair" $ (runQuery "?x" "(last-pair (2 ?x) (3))")
@?= parseMultiSet "(3)"
, testCase "rule 14 next-to" $ (runQuery "(?x ?y)" "(?x next-to ?y in (1 (2 3) 4))")
@?= parseMultiSet "((2 3) 4) (1 (2 3))"
, testCase "rule 15 next-to" $ (runQuery "?x" "(?x next-to 1 in (2 1 3 1))")
@?= parseMultiSet "2 3"
, testCase "rule 16" $ (runQuery "?x" "(подчиняется (Битобор Бен) ?x)")
@?= parseMultiSet "(Уорбак Оливер)"
, testCase "rule 17" $ (runQuery "?x" "(подчиняется1 (Битобор Бен) ?x)")
@?= parseMultiSet "(Уорбак Оливер)"
, testCase "rule 18 reverse" $ (runQuery "?x" "(reverse () ?x)")
@?= parseMultiSet "()"
, testCase "rule 19 reverse" $ (runQuery "?x" "(reverse ?x ())")
@?= parseMultiSet "()"
, testCase "rule 20 reverse" $ (runQuery "?x" "(reverse (a) ?x)")
@?= parseMultiSet "(a)"
, testCase "rule 21 reverse" $ (runQuery "?x" "(reverse ?x (a))")
@?= parseMultiSet "(a)"
, testCase "rule 22 reverse" $ (runQuery "?x" "(reverse (a b c d) ?x)")
@?= parseMultiSet "(d c b a)"
, testCase "rule 23 reverse" $ (runQuery "?x" "(reverse ?x (a b c d))")
@?= parseMultiSet "(d c b a)"
, testCase "rule 24 reverse" $ (runQuery "?x" "(reverse (a b c d e) ?x)")
@?= parseMultiSet "(e d c b a)"
, testCase "rule 25 reverse" $ (runQuery "?x" "(reverse ?x (a b c d e))")
@?= parseMultiSet "(e d c b a)"
-- lisp-value
{-
, test $ runQuery "(?name ?y ?x)"
"(and (зарплата (Битобор Бен) ?x)\
\(зарплата ?name ?y) (lisp-value < ?y ?x))" >>=
(@?= "caseLV1" (parseMultiSet
"((Фиден Кон) 25000 60000)\
\((Крэтчит Роберт) 18000 60000)\
\((Дум Хьюго) 30000 60000)\
\((Поправич Дайко) 25000 60000)\
\((Фект Пабло Э) 35000 60000)\
\((Хакер Лиза П) 40000 60000)")
, test $ runQuery "(?x ?sx ?sy)"
"(and\
\(can-replace ?x ?y)\
\(зарплата ?x ?sx)\
\(зарплата ?y ?sy)\
\(lisp-value > ?sy ?sx))" >>=
(@?= "caseLV2" (parseMultiSet
"((Фиден Кон) 25000 150000) ((Фект Пабло Э) 35000 40000)")
-}
]
where
runQuery :: String -> String -> MultiSet Value
runQuery o q = foldl (flip MultiSet.insert) MultiSet.empty $ evaluate db (parseExpr q) (parseExpr o)
parseExpr s = case parse (space >> expr <* eof) "" s of
Left e -> error $ show e
Right x -> x
parseMultiSet :: String -> MultiSet Value
parseMultiSet s = case parse (space >> many expr <* eof) "" s of
Left e -> error $ show e
Right x -> MultiSet.fromList x
propValue' :: Value -> Bool
propValue' x = either (const False) (== x) $ parse expr "" $ show $ toDoc x
propValue :: TestTree
propValue = QC.testProperty "LispParser QuickCheck" propValue'
main :: IO ()
main = do
edb <- fmap compileDB `liftM` parseFile "data.txt"
case edb of
Left e -> print e
Right db -> defaultMain $ testGroup "Tests" [ SICP.LispParser.tests, propValue, SICP.DB.tests db, dbTests db ]
| feumilieu/sicp-haskell | test/test.hs | bsd-3-clause | 7,633 | 32 | 11 | 1,667 | 1,187 | 593 | 594 | 96 | 3 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module SIGyM.Store.Generation (
Generation
, GenEnv (..)
, GenState (..)
, GenError (..)
, Registry
, mkEnvironment
, runGen
, evalGen
, getTime
, findStore
, findContext
, noMsg
, strMsg
, throwError
, catchError
, liftIO
) where
import Control.Monad.Reader hiding (liftIO)
import Control.Monad.State hiding (liftIO)
import Control.Monad.Error hiding (liftIO)
import Data.Time.Clock (UTCTime, getCurrentTime)
import SIGyM.Store.Registry
import SIGyM.Store.Types
mkEnvironment :: Maybe UTCTime -> Maybe Registry -> IO (GenEnv)
mkEnvironment t r = do
defaultTime <- getCurrentTime
return GenEnv {
currentTime = maybe defaultTime id t
, registry = maybe emptyRegistry id r
}
runGen :: GenEnv -> GenState -> Generation a -> IO (Either GenError a, GenState)
runGen e s (Generation g) = runStateT (runErrorT (runReaderT g e)) s
evalGen :: GenEnv -> GenState -> Generation a -> IO (Either GenError a)
evalGen e s g = runGen e s g >>= return . fst
liftIO :: IO a -> Generation a
liftIO = Generation . lift . lift . lift
getTime :: Generation UTCTime
getTime = asks currentTime
findStore :: StoreID -> Generation Store
findStore k = do
mv <- asks (lookupStore k . registry)
maybe (throwError$ RegistryLookupError$ "No such store: "++show k) return mv
findContext :: ContextID -> Generation Context
findContext k = do
mv <- asks (lookupContext k . registry)
maybe (throwError$ RegistryLookupError$ "No such context: "++show k) return mv
| meteogrid/sigym-core | src/SIGyM/Store/Generation.hs | bsd-3-clause | 1,612 | 0 | 11 | 368 | 521 | 277 | 244 | 46 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Text.Parsec.Char.Extras where
import Control.Applicative ((*>), (<*))
import Data.Char (isSpace)
import Text.Parsec (ParsecT, Stream, between, char, letter, many, sepBy1, satisfy, spaces)
csv :: Stream s m Char => ParsecT s u m a -> ParsecT s u m [a]
csv = (`sepBy1` comma)
comma :: Stream s m Char => ParsecT s u m Char
comma = char ','
notSpace :: Stream s m Char => ParsecT s u m Char
notSpace = satisfy (not . isSpace)
notSpaces :: Stream s m Char => ParsecT s u m String
notSpaces = many notSpace
word :: Stream s m Char => ParsecT s u m String
word = many letter
token :: Stream s m Char => ParsecT s u m a -> ParsecT s u m a
token = between spaces spaces
| mitchellwrosen/Sloch | src/lang-gen/Text/Parsec/Char/Extras.hs | bsd-3-clause | 711 | 0 | 8 | 144 | 309 | 166 | 143 | 17 | 1 |
module Main where
import Control.Exception (bracket)
import Data.ByteString (hGetSome)
import Data.Serialize (decode)
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Minecraft.Anvil (AnvilHeader(..), ChunkLocation(..), getAnvilHeader, readChunkData, decompressChunkData, showAnvilHeader)
import System.IO (Handle, openFile, hClose, IOMode(ReadMode))
import System.Environment (getArgs)
main :: IO ()
main =
do [fp] <- getArgs
bracket (openFile fp ReadMode) hClose $ \h -> do
bs <- hGetSome h 8192 -- ^ header size is a fixed 8KiB
case decode bs of
(Left err) -> putStrLn err
(Right ah) ->
do putStrLn (showAnvilHeader ah)
-- bs <- hGetSome h 1024
-- print bs
dumpChunks h ah
dumpChunk :: Handle -> ChunkLocation -> IO ()
dumpChunk h chunkLocation =
do ecd <- readChunkData h chunkLocation
case ecd of
(Left e) -> putStrLn e
(Right cd) -> print (decompressChunkData cd)
dumpChunks :: Handle -> AnvilHeader -> IO ()
dumpChunks h ah =
do mapM_ (dumpChunk h) (locations ah)
| stepcut/minecraft-data | utils/DumpAnvil.hs | bsd-3-clause | 1,117 | 0 | 18 | 268 | 371 | 196 | 175 | 28 | 2 |
module D5Lib where
import Text.Megaparsec (ParseError, Dec, endBy)
import Text.Megaparsec.String (Parser)
import Text.Megaparsec.Char as C
import Text.Megaparsec.Lexer as L
import Data.List (splitAt)
type ParseResult = Either (ParseError Char Dec) Jmps
type Jmps = [Int]
data State = State
{ pos :: Int
, jmps :: Jmps
} deriving (Show, Eq)
parser :: Parser Jmps
parser = (L.signed C.space pInt) `endBy` eol
where
pInt = fromIntegral <$> L.integer
start :: Jmps -> State
start js = State { pos = 0, jmps = js }
-- returns Nothing if pos is outside list
step :: (Int -> Int) -> State -> Maybe State
step _ State { pos = p } | p < 0 = Nothing
step _ State { pos = p, jmps = js } | p >= length js = Nothing
step jmpIncr State { pos = p, jmps = js } =
Just $ State { pos = p', jmps = js' }
where
(h, (curJmp : t)) = splitAt p js
js' = h ++ ((jmpIncr curJmp) : t)
p' = p + curJmp
stepP1 = step (+ 1)
stepP2 =
step f
where
f x = if x >= 3 then x - 1 else x + 1
-- starting from a given state, run until a terminal state
run :: (State -> Maybe State) -> State -> [State]
run stepper s0 =
s0 : rest
where
rest = case stepper s0 of
Nothing -> []
Just s -> run stepper s
-- starting from a given state, run until a terminal state
-- don't track intermediate states, just count the number of steps taken
run' :: (State -> Maybe State) -> State -> Int
run' stepper s0 =
1 + rest
where
rest = case stepper s0 of
Nothing -> 0
Just s -> run' stepper s
| wfleming/advent-of-code-2016 | 2017/D5/src/D5Lib.hs | bsd-3-clause | 1,538 | 0 | 11 | 406 | 583 | 320 | 263 | 41 | 2 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Temperature.EN.Tests
( tests
) where
import Prelude
import Data.String
import Test.Tasty
import Test.Tasty.HUnit
import Duckling.Dimensions.Types
import Duckling.Temperature.EN.Corpus
import Duckling.Testing.Asserts
import Duckling.Testing.Types (testContext, testOptions)
import Duckling.Types (Range(..))
tests :: TestTree
tests = testGroup "EN Tests"
[ makeCorpusTest [Seal Temperature] corpus
, rangeTests
]
rangeTests :: TestTree
rangeTests = testCase "Range Test" $
mapM_ (analyzedRangeTest testContext testOptions
. withTargets [Seal Temperature]) xs
where
xs = [ ("between 40 and 30 degrees", Range 15 25 )
, ("30 degrees degrees", Range 0 10 )
]
| facebookincubator/duckling | tests/Duckling/Temperature/EN/Tests.hs | bsd-3-clause | 928 | 0 | 11 | 170 | 194 | 115 | 79 | 21 | 1 |
-- | Display mode is for drawing a static picture.
module Graphics.Gloss.Interface.Pure.Display
( module Graphics.Gloss.Data.Display
, module Graphics.Gloss.Data.Picture
, module Graphics.Gloss.Data.Color
, display)
where
import Graphics.Gloss.Data.Display
import Graphics.Gloss.Data.Picture
import Graphics.Gloss.Data.Color
import Graphics.Gloss.Internals.Interface.Display
import Graphics.Gloss.Internals.Interface.Backend
-- | Open a new window and display the given picture.
--
-- Use the following commands once the window is open:
--
-- * Quit - esc-key.
-- * Move Viewport - left-click drag, arrow keys.
-- * Rotate Viewport - right-click drag, control-left-click drag, or home\/end-keys.
-- * Zoom Viewport - mouse wheel, or page up\/down-keys.
--
display :: Display -- ^ Display mode.
-> Color -- ^ Background color.
-> Picture -- ^ The picture to draw.
-> IO ()
display = displayWithBackend defaultBackendState
| ardumont/snake | deps/gloss/Graphics/Gloss/Interface/Pure/Display.hs | bsd-3-clause | 1,032 | 0 | 9 | 231 | 118 | 83 | 35 | 15 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Eleco.Slave.Backend.Repa where
import Data.Vector.Unboxed
( Vector
, imap
, fromList
)
import qualified Data.Vector.Unboxed as V
import Data.Vector.Binary
import Data.Array.Repa
( Array
, DIM1
, U
, Z(..)
, (:.)(..)
, fromUnboxed
, fromListUnboxed
, toUnboxed
, computeP
)
import qualified Data.Array.Repa as R
import Data.Array.Repa.Algorithms.Matrix
import Control.Distributed.Process (Process)
import Control.Distributed.Process.Node (initRemoteTable)
import Control.Distributed.Process.Closure (remotable)
import Control.Distributed.Process.Backend.SimpleLocalnet
( initializeBackend
, startSlave
)
import Eleco.Core.Entity
import Eleco.Slave
import Eleco.Slave.State
import Eleco.Slave.Backend
type Vec2D = (Double, Double)
{-# INLINE vecAdd #-}
vecAdd :: Vec2D -> Vec2D -> Vec2D
vecAdd (!x1, !y1) (!x2, !y2) = (x1 + x2, y1 + y2)
{-# INLINE vecSub #-}
vecSub :: Vec2D -> Vec2D -> Vec2D
vecSub (!x1, !y1) (!x2, !y2) = (x1 - x2, y1 - y2)
{-# INLINE vecDis #-}
vecDis :: Vec2D -> Vec2D -> Double
vecDis (!x1, !y1) (!x2, !y2) =
let dx = x1 - x2
dy = y1 - y2 in
dx * dx + dy * dy
{-# INLINE vecMul #-}
vecMul :: Vec2D -> Double -> Vec2D
vecMul (!vx, !vy) !x = (vx * x, vy * x)
{-# INLINE vecDiv #-}
vecDiv :: Vec2D -> Double -> Vec2D
vecDiv (!vx, !vy) !x = (vx / x, vy / x)
{-# INLINE vecLen2 #-}
vecLen2 :: Vec2D -> Double
vecLen2 (!vx, !vy) = vx * vx + vy * vy
{-# INLINE vecLen #-}
vecLen :: Vec2D -> Double
vecLen = sqrt . vecLen2
{-# INLINE vecNorm #-}
vecNorm :: Vec2D -> Vec2D
vecNorm vec =
let len = vecLen vec in
if len /= 0
then vecDiv vec len
else vec
data RepaBackend = RepaBackend
{ positions :: !(Array U DIM1 RawEntity)
, velocities :: !(Array U DIM1 Vec2D)
, masses :: !(Vector Double)
, gravity :: {-# UNPACK #-} !Double }
instance Backend (Vector RawEntity) RepaBackend where
type CrossNodeData RepaBackend = (Vector RawEntity, Vector Double)
updateBackend simState@SimulationState{..} = do
datas <- expectCrossNodeDatas simState
newvs <- computeP $ R.zipWith (calNewVel datas) positions velocities
newps <- computeP $ R.zipWith calNewPos positions newvs
return b
{ positions = newps
, velocities = newvs }
where
b@RepaBackend{..} = simBackend
vecPositions = toUnboxed positions
interactions = [gravityInteraction]
indeces = [0..entityCount-1]
gravityInteraction !ent1 !m1 !ent2 !m2 !dir_vec !dis =
let !co = gravity * m1 * m2 / (dis * dis) in
dir_vec `vecMul` co
calNewVel !datas !ent1 (!vx, !vy) =
let ents = map (V.unsafeIndex vecPositions) $ filter (/=eid) indeces
tvel = foldl (go masses) (0, 0) ents in
foldl (\acc (cnEnts, cnMasses) -> V.foldl' (go cnMasses) acc cnEnts) tvel datas
where
!e1pos = position ent1
!eid = localId ent1
!e1m = V.unsafeIndex masses eid
go e2masses acc ent2 =
let !e2pos = position ent2
!e2m = V.unsafeIndex e2masses $ localId ent2
!vec = e1pos `vecSub` e2pos
!dir_vec = vecNorm vec
!dis = vecLen vec in
foldl (\v f -> f ent1 e1m ent2 e2m dir_vec dis `vecAdd` v) acc interactions
calNewPos (!px, !py, !i) (!vx, !vy) = (px + vx, py + vy, i)
backendInfo = const BackendInfo
{ backendName = "Repa"
, backendVersion = (0, 0, 0, 1)
, backendBehaviours = ["Gravity"] }
entitySeq = toUnboxed . positions
fullCrossNodeData RepaBackend{..} =
(toUnboxed positions, masses)
regionalCrossNodeData RepaBackend{..} indeces =
( fromList $ fmap (V.unsafeIndex poss) indeces
, fromList $ fmap (V.unsafeIndex masses) indeces )
where poss = toUnboxed positions
repaSlaveSimulator :: Process ()
repaSlaveSimulator = slaveSimulatorProcess emptyBackend
where
emptyBackend = RepaBackend
{ positions = fromListUnboxed (Z :. 0 :: DIM1) []
, velocities = fromListUnboxed (Z :. 0 :: DIM1) []
, masses = fromList []
, gravity = 1.0
}
remotable ['repaSlaveSimulator]
| cikusa/Eleco | Eleco/Slave/Backend/Repa.hs | bsd-3-clause | 4,224 | 0 | 16 | 1,061 | 1,436 | 773 | 663 | -1 | -1 |
module Arimaa
( module Types
, module Parser
) where
import Types
import Parser | Saulzar/arimaa | src/Arimaa.hs | bsd-3-clause | 91 | 0 | 4 | 25 | 20 | 14 | 6 | 5 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Util.Timer
-- Description : A module for setting up timers.
-- Copyright : (c) Andrea Rossato and David Roundy 2007
-- License : BSD-style (see xmonad/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : unportable
--
-- A module for setting up timers
-----------------------------------------------------------------------------
module XMonad.Util.Timer
( -- * Usage
-- $usage
startTimer
, handleTimer
, TimerId
) where
import XMonad
import Control.Concurrent
import Data.Unique
-- $usage
-- This module can be used to setup a timer to handle deferred events.
-- See 'XMonad.Layout.ShowWName' for an usage example.
type TimerId = Int
-- | Start a timer, which will send a ClientMessageEvent after some
-- time (in seconds).
startTimer :: Rational -> X TimerId
startTimer s = io $ do
u <- hashUnique <$> newUnique
xfork $ do
d <- openDisplay ""
rw <- rootWindow d $ defaultScreen d
threadDelay (fromEnum $ s * 1000000)
a <- internAtom d "XMONAD_TIMER" False
allocaXEvent $ \e -> do
setEventType e clientMessage
setClientMessageEvent e rw a 32 (fromIntegral u) 0
sendEvent d rw False structureNotifyMask e
sync d False
return u
-- | Given a 'TimerId' and an 'Event', run an action when the 'Event'
-- has been sent by the timer specified by the 'TimerId'
handleTimer :: TimerId -> Event -> X (Maybe a) -> X (Maybe a)
handleTimer ti ClientMessageEvent{ev_message_type = mt, ev_data = dt} action = do
d <- asks display
a <- io $ internAtom d "XMONAD_TIMER" False
if mt == a && dt /= [] && fromIntegral (head dt) == ti
then action
else return Nothing
handleTimer _ _ _ = return Nothing
| xmonad/xmonad-contrib | XMonad/Util/Timer.hs | bsd-3-clause | 1,857 | 0 | 17 | 408 | 379 | 194 | 185 | 31 | 2 |
module Language.Haskell.GhcMod.Lang where
import DynFlags (supportedLanguagesAndExtensions)
import Language.Haskell.GhcMod.Types
import Language.Haskell.GhcMod.Convert
-- | Listing language extensions.
listLanguages :: Options -> IO String
listLanguages opt = return $ convert opt supportedLanguagesAndExtensions
| darthdeus/ghc-mod-ng | Language/Haskell/GhcMod/Lang.hs | bsd-3-clause | 316 | 0 | 6 | 32 | 60 | 36 | 24 | 6 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.PixelBufferObject
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/pixel_buffer_object.txt ARB_pixel_buffer_object> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.PixelBufferObject (
-- * Enums
gl_PIXEL_PACK_BUFFER_ARB,
gl_PIXEL_PACK_BUFFER_BINDING_ARB,
gl_PIXEL_UNPACK_BUFFER_ARB,
gl_PIXEL_UNPACK_BUFFER_BINDING_ARB
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/PixelBufferObject.hs | bsd-3-clause | 779 | 0 | 4 | 87 | 46 | 37 | 9 | 6 | 0 |
{-# LANGUAGE CPP #-}
-- | This module provides remote monitoring of a running process over
-- HTTP. It can be used to run an HTTP server that provides both a
-- web-based user interface and a machine-readable API (e.g. JSON.)
-- The former can be used by a human to get an overview of what the
-- program is doing and the latter can be used by automated monitoring
-- tools.
--
-- Typical usage is to start the monitoring server at program startup
--
-- > main = do
-- > forkServer "localhost" 8000
-- > ...
--
-- and then periodically check the stats using a web browser or a
-- command line tool (e.g. curl)
--
-- > $ curl -H "Accept: application/json" http://localhost:8000/
module System.Remote.Monitoring
(
-- * Required configuration
-- $configuration
-- * REST API
-- $api
-- * The monitoring server
Server
, serverThreadId
, forkServer
-- * User-defined counters, gauges, and labels
-- $userdefined
, getCounter
, getGauge
, getLabel
) where
import Control.Concurrent (ThreadId, forkIO)
import qualified Data.ByteString as S
import qualified Data.HashMap.Strict as M
import Data.IORef (newIORef)
import Prelude hiding (read)
import System.Remote.Common
#if USE_WAI
import System.Remote.Wai
#else
import System.Remote.Snap
#endif
-- $configuration
--
-- To use this module you must first enable GC statistics collection
-- in the run-time system. To enable GC statistics collection, either
-- run your program with
--
-- > +RTS -T
--
-- or compile it with
--
-- > -with-rtsopts=-T
--
-- The runtime overhead of @-T@ is very small so it's safe to always
-- leave it enabled.
-- $api
-- To use the machine-readable REST API, send an HTTP GET request to
-- the host and port passed to 'forkServer'. The following resources
-- (i.e. URLs) are available:
--
-- [\/] JSON object containing all counters and gauges. Counters and
-- gauges are stored as nested objects under the @counters@ and
-- @gauges@ attributes, respectively. Content types: \"text\/html\"
-- (default), \"application\/json\"
--
-- [\/combined] Flattened JSON object containing all counters, gauges,
-- and labels. Content types: \"application\/json\"
--
-- [\/counters] JSON object containing all counters. Content types:
-- \"application\/json\"
--
-- [\/counters/\<counter name\>] Value of a single counter, as a
-- string. The name should be UTF-8 encoded. Content types:
-- \"text\/plain\"
--
-- [\/gauges] JSON object containing all gauges. Content types:
-- \"application\/json\"
--
-- [\/gauges/\<gauge name\>] Value of a single gauge, as a string.
-- The name should be UTF-8 encoded. Content types: \"text\/plain\"
--
-- [\/labels] JSON object containing all labels. Content types:
-- \"application\/json\"
--
-- [\/labels/\<label name\>] Value of a single label, as a string.
-- The name should be UTF-8 encoded. Content types: \"text\/plain\"
--
-- Counters, gauges and labels are stored as attributes of the
-- returned JSON objects, one attribute per counter, gauge or label.
-- In addition to user-defined counters, gauges, and labels, the below
-- built-in counters and gauges are also returned. Furthermore, the
-- top-level JSON object of any resource contains the
-- @server_timestamp_millis@ attribute, which indicates the server
-- time, in milliseconds, when the sample was taken.
--
-- Built-in counters:
--
-- [@bytes_allocated@] Total number of bytes allocated
--
-- [@num_gcs@] Number of garbage collections performed
--
-- [@num_bytes_usage_samples@] Number of byte usage samples taken
--
-- [@cumulative_bytes_used@] Sum of all byte usage samples, can be
-- used with @numByteUsageSamples@ to calculate averages with
-- arbitrary weighting (if you are sampling this record multiple
-- times).
--
-- [@bytes_copied@] Number of bytes copied during GC
--
-- [@mutator_cpu_seconds@] CPU time spent running mutator threads.
-- This does not include any profiling overhead or initialization.
--
-- [@mutator_wall_seconds@] Wall clock time spent running mutator
-- threads. This does not include initialization.
--
-- [@gc_cpu_seconds@] CPU time spent running GC
--
-- [@gc_wall_seconds@] Wall clock time spent running GC
--
-- [@cpu_seconds@] Total CPU time elapsed since program start
--
-- [@wall_seconds@] Total wall clock time elapsed since start
--
-- Built-in gauges:
--
-- [@max_bytes_used@] Maximum number of live bytes seen so far
--
-- [@current_bytes_used@] Current number of live bytes
--
-- [@current_bytes_slop@] Current number of bytes lost to slop
--
-- [@max_bytes_slop@] Maximum number of bytes lost to slop at any one time so far
--
-- [@peak_megabytes_allocated@] Maximum number of megabytes allocated
--
#if MIN_VERSION_base(4,6,0)
-- [@par_tot_bytes_copied@] Number of bytes copied during GC, minus
-- space held by mutable lists held by the capabilities. Can be used
-- with 'parMaxBytesCopied' to determine how well parallel GC utilized
-- all cores.
--
-- [@par_avg_bytes_copied@] Deprecated alias for
-- @par_tot_bytes_copied@.
#else
-- [@par_avg_bytes_copied@] Number of bytes copied during GC, minus
-- space held by mutable lists held by the capabilities. Can be used
-- with 'parMaxBytesCopied' to determine how well parallel GC utilized
-- all cores.
#endif
--
-- [@par_max_bytes_copied@] Sum of number of bytes copied each GC by
-- the most active GC thread each GC. The ratio of
#if MIN_VERSION_base(4,6,0)
-- 'parTotBytesCopied' divided by 'parMaxBytesCopied' approaches 1 for
#else
-- 'parAvgBytesCopied' divided by 'parMaxBytesCopied' approaches 1 for
#endif
-- a maximally sequential run and approaches the number of threads
-- (set by the RTS flag @-N@) for a maximally parallel run.
------------------------------------------------------------------------
-- * The monitoring server
-- | The thread ID of the server. You can kill the server by killing
-- this thread (i.e. by throwing it an asynchronous exception.)
serverThreadId :: Server -> ThreadId
serverThreadId = threadId
-- | Start an HTTP server in a new thread. The server replies to GET
-- requests to the given host and port. The host argument can be
-- either a numeric network address (dotted quad for IPv4,
-- colon-separated hex for IPv6) or a hostname (e.g. \"localhost\".)
-- The client can control the Content-Type used in responses by
-- setting the Accept header. At the moment three content types are
-- available: \"application\/json\", \"text\/html\", and
-- \"text\/plain\".
forkServer :: S.ByteString -- ^ Host to listen on (e.g. \"localhost\")
-> Int -- ^ Port to listen on (e.g. 8000)
-> IO Server
forkServer host port = do
counters <- newIORef M.empty
gauges <- newIORef M.empty
labels <- newIORef M.empty
tid <- forkIO $ startServer counters gauges labels host port
return $! Server tid counters gauges labels
| fpco/ekg | System/Remote/Monitoring.hs | bsd-3-clause | 6,893 | 0 | 9 | 1,211 | 360 | 269 | 91 | 27 | 1 |
{-|
Module : PP.Grammars.Ebnf
Description : Defines a AST and parser for the EBNF language
Copyright : (c) 2017 Patrick Champion
License : see LICENSE file
Maintainer : [email protected]
Stability : provisional
Portability : portable
AST for the EBNF language.
Based on the grammar given in the ISO/IEC 14977:1996, page 10, part 8.2.
Comments are valid in EBNF, but are not present in this AST.
-}
module PP.Grammars.Ebnf
( -- * AST
Syntax(..)
-- ** Inner ASTs
, SyntaxRule(..)
, DefinitionsList(..)
, SingleDefinition(..)
, Term(..)
, Exception(..)
, Factor(..)
, Primary(..)
, MetaIdentifier(..)
) where
import Control.Applicative ((<$>), (<*>))
import qualified Data.List as L
import Data.Maybe
import Data.Text (pack, strip, unpack)
import PP.Grammar
import PP.Grammars.LexicalHelper (LexicalRule,
lexicalString)
import qualified PP.Rule as R
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Language (emptyDef)
import qualified Text.ParserCombinators.Parsec.Token as Token
-- |Start rule
newtype Syntax = Syntax [SyntaxRule]
deriving (Show, Eq)
-- |Syntax rule
data SyntaxRule
-- |Defines the sequence of symbols represented by a MetaIdentifier
= SyntaxRule MetaIdentifier DefinitionsList
-- |Defines a lexical definition inside the EBNF grammar
| LexicalInner LexicalRule
deriving (Show, Eq)
-- |Separates alternative SingleDefinition
newtype DefinitionsList = DefinitionsList [SingleDefinition]
deriving (Show, Eq)
-- |Separates successive Term
newtype SingleDefinition = SingleDefinition [Term]
deriving (Show, Eq)
-- |Represents any sequence of symbols that is defined by the Factor
-- but not defined by the Exception
data Term = Term Factor (Maybe Exception)
deriving (Show, Eq)
-- |A Factor may be used as an Exception if it could be replaced by a
-- Factor containing no MetaIdentifier
newtype Exception = Exception Factor
deriving (Show, Eq)
-- |The Integer specifies the number of repetitions of the Primay
data Factor = Factor (Maybe Integer) Primary
deriving (Show, Eq)
-- |Primary
data Primary
-- |Encloses symbols which are optional
= OptionalSequence DefinitionsList
-- |Encloses symbols which may be repeated any number of times
| RepeatedSequence DefinitionsList
-- |Allows any DefinitionsList to be a Primary
| GroupedSequence DefinitionsList
-- |A Primary can be a MetaIdentifier
| PrimaryMetaIdentifier MetaIdentifier
-- |Represents the characters between the quote symbols '...' or "..."
| TerminalString String
-- |Empty Primary
| Empty
deriving (Show, Eq)
-- |A MetaIdentifier is the name of a syntactic element of the langage being defined
newtype MetaIdentifier = MetaIdentifier String
deriving (Show, Eq)
-- |Lexer definitions for EBNF
lexer = Token.makeTokenParser def
where
def = emptyDef {
Token.commentStart = "(*"
, Token.commentEnd = "*)"
, Token.commentLine = ""
, Token.nestedComments = False
, Token.identStart = letter
, Token.identLetter = alphaNum <|> oneOf "_- "
, Token.reservedNames = []
, Token.reservedOpNames = ["=", ";", "|", ",", "-", "*"]
, Token.caseSensitive = True
}
identifier = Token.identifier lexer
reservedOp = Token.reservedOp lexer
stringLiteral = Token.stringLiteral lexer
natural = Token.natural lexer
whiteSpace = Token.whiteSpace lexer
parens = Token.parens lexer
braces = Token.braces lexer
angles = Token.angles lexer
brackets = Token.brackets lexer
-- |Syntax parser
syntax :: Parser Syntax
syntax = whiteSpace *> (Syntax <$> many1 syntaxRule) <?> "syntax"
-- |SyntaxRule parser
syntaxRule :: Parser SyntaxRule
syntaxRule = try (SyntaxRule <$> (metaIdentifier <* reservedOp "=")
<*> (definitionsList <* reservedOp ";"))
<|> LexicalInner <$> parser
<?> "syntax rule"
-- |DefinitionsList parser
definitionsList :: Parser DefinitionsList
definitionsList = DefinitionsList <$> sepBy1 singleDefinition (reservedOp "|")
<?> "definitions list"
-- |SingleDefinition parser
singleDefinition :: Parser SingleDefinition
singleDefinition = SingleDefinition <$> sepBy1 term (reservedOp ",")
<?> "single definition"
-- |Term parser
term :: Parser Term
term = Term <$> factor <*> optionMaybe (reservedOp "-" *> exception)
<?> "term"
-- |Exception parser
exception :: Parser Exception
exception = Exception <$> factor <?> "exception"
-- |Factor parser
factor :: Parser Factor
factor = Factor <$> optionMaybe (natural <* reservedOp "*") <*> primary
<?> "factor"
-- |Primary parser
primary :: Parser Primary
primary = option Empty (
OptionalSequence <$> brackets definitionsList
<|> RepeatedSequence <$> braces definitionsList
<|> GroupedSequence <$> parens definitionsList
<|> PrimaryMetaIdentifier <$> metaIdentifier
<|> TerminalString <$> stringLiteral
) -- end of option
<?> "primary"
-- |MetaIdentifier parser
metaIdentifier :: Parser MetaIdentifier
metaIdentifier = trimMetaIdentifier <$> (angles identifier <|> identifier)
<?> "meta identifier"
where
trimMetaIdentifier = MetaIdentifier . unpack . strip . pack
-- |Lexify an EBNF syntax tree
lexifySyntax :: Syntax -> Syntax
lexifySyntax s = replaceTerm tok $ addLexicalInner tok s
where
tok = generateTokens $ findTerm s
findTerm (Syntax srs) = L.concatMap findTerm' srs
findTerm' (SyntaxRule _ dl) = findTerm'' dl
findTerm' (LexicalInner _) = []
findTerm'' (DefinitionsList sds) = L.concatMap findTerm''' sds
findTerm''' (SingleDefinition ts) = L.concatMap findTerm'''' ts
findTerm'''' (Term f _) = findTerm''''' f
findTerm''''' (Factor _ p) = findTerm'''''' p
findTerm'''''' (OptionalSequence dl) = findTerm'' dl
findTerm'''''' (RepeatedSequence dl) = findTerm'' dl
findTerm'''''' (GroupedSequence dl) = findTerm'' dl
findTerm'''''' (PrimaryMetaIdentifier mi) = []
findTerm'''''' (TerminalString term) = [term]
findTerm'''''' Empty = []
generateTokens = map (\t -> (t, "__token_" ++ t)) . L.nub
addLexicalInner [] s = s
addLexicalInner ((n, t):ts) (Syntax srs) =
addLexicalInner ts $ Syntax $ LexicalInner (lexicalString t n) : srs
replaceTerm [] s = s
replaceTerm (t:ts) (Syntax srs) =
replaceTerm ts $ Syntax $ L.map (replaceTerm' t) srs
replaceTerm' t (SyntaxRule r dl) = SyntaxRule r $ replaceTerm'' t dl
replaceTerm' _ li@(LexicalInner _) = li
replaceTerm'' t (DefinitionsList sds) =
DefinitionsList $ L.map (replaceTerm''' t) sds
replaceTerm''' t (SingleDefinition ts) =
SingleDefinition $ L.map (replaceTerm'''' t) ts
replaceTerm'''' t (Term f e) = Term (replaceTerm''''' t f) e
replaceTerm''''' t (Factor f p) = Factor f $ replaceTerm'''''' t p
replaceTerm'''''' t (OptionalSequence dl) =
OptionalSequence $ replaceTerm'' t dl
replaceTerm'''''' t (RepeatedSequence dl) =
RepeatedSequence $ replaceTerm'' t dl
replaceTerm'''''' t (GroupedSequence dl) =
GroupedSequence $ replaceTerm'' t dl
replaceTerm'''''' (n, t) ts@(TerminalString s) =
if n == s then PrimaryMetaIdentifier (MetaIdentifier t) else ts
replaceTerm'''''' _ p = p
-- * InputGrammar instances for EBNF AST
instance InputGrammar Syntax where
parser = syntax
stringify (Syntax []) = ""
stringify (Syntax [sr]) = stringify sr
stringify (Syntax (sr:r)) = stringify sr ++ "\n" ++ stringify (Syntax r)
rules (Syntax srs) = R.uniformize $ L.concatMap rules srs
lexify = lexifySyntax
instance InputGrammar SyntaxRule where
parser = syntaxRule
stringify (SyntaxRule mi dl) = stringify mi ++ "=" ++ stringify dl ++ ";"
stringify (LexicalInner lr) = stringify lr
rules (SyntaxRule (MetaIdentifier mi) dl) =
[R.Rule mi [r, R.Empty] | r <- rules dl]
rules (LexicalInner lr) = rules lr
instance InputGrammar DefinitionsList where
parser = definitionsList
stringify (DefinitionsList []) = ""
stringify (DefinitionsList [sd]) = stringify sd
stringify (DefinitionsList (sd:r)) =
stringify sd ++ "|" ++ stringify (DefinitionsList r)
rules (DefinitionsList sds) = L.concatMap rules sds
instance InputGrammar SingleDefinition where
parser = singleDefinition
stringify (SingleDefinition []) = ""
stringify (SingleDefinition [t]) = stringify t
stringify (SingleDefinition (t:r)) =
stringify t ++ "," ++ stringify (SingleDefinition r)
rules (SingleDefinition [t]) = rules t
rules (SingleDefinition (t:ts)) =
[R.Concat [r,n] | r <- rules t, n <- rules (SingleDefinition ts)]
instance InputGrammar Term where
parser = term
stringify (Term f Nothing) = stringify f
stringify (Term f (Just e)) = stringify f ++ "-" ++ stringify e
rules (Term f Nothing) = rules f
rules _ = error "no translation for exception" -- ... yet
instance InputGrammar Exception where
parser = exception
stringify (Exception f) = stringify f
rules _ = undefined -- should not be called, look at the Term instance
instance InputGrammar Factor where
parser = factor
stringify (Factor Nothing p) = stringify p
stringify (Factor (Just i) p) = show i ++ "*" ++ stringify p
rules (Factor Nothing p) = rules p
rules (Factor (Just i) p) =
[R.Concat . concat $ replicate (fromIntegral i) (rules p)]
instance InputGrammar Primary where
parser = primary
stringify (OptionalSequence dl) = "[" ++ stringify dl ++ "]"
stringify (RepeatedSequence dl) = "{" ++ stringify dl ++ "}"
stringify (GroupedSequence dl) = "(" ++ stringify dl ++ ")"
stringify (PrimaryMetaIdentifier mi) = stringify mi
stringify (TerminalString s) = show s
stringify Empty = ""
rules a@(OptionalSequence dl) = let x = stringify a in
R.NonTerm x : R.Rule x [R.Empty] : [R.Rule x [r, R.Empty] | r <- rules dl]
rules a@(RepeatedSequence dl) = let x = stringify a in
R.NonTerm x : R.Rule x [R.Empty] :
[R.Rule x [r, R.NonTerm x, R.Empty] | r <- rules dl]
rules a@(GroupedSequence dl) = let x = stringify a in
R.NonTerm x : [R.Rule x [r, R.Empty] | r <- rules dl]
rules (PrimaryMetaIdentifier mi) = rules mi
rules (TerminalString s) = [R.Concat $ L.map R.Term s]
rules Empty = [R.Empty]
instance InputGrammar MetaIdentifier where
parser = metaIdentifier
stringify (MetaIdentifier s) = "<" ++ s ++ ">"
rules (MetaIdentifier s) = [R.NonTerm s]
| chlablak/platinum-parsing | src/PP/Grammars/Ebnf.hs | bsd-3-clause | 10,858 | 0 | 17 | 2,529 | 3,066 | 1,602 | 1,464 | 210 | 15 |
module Cases.DeclDependencyTest where
import Language.Haskell.Exts hiding (name)
import Test.HUnit
import Cases.BaseDir
import Utils.DependencyAnalysis
import Utils.Nameable
testdecldependency1 = testdecldependency test1
testdecldependency :: (String, String) -> Assertion
testdecldependency (f,s)
= do
r <- parseFileWithExts exts f
let
r' = parseResult decls undefined r
ns = show $ map (map name) (dependencyAnalysis TypeAnalysis r')
assertEqual "Type Dependency Result:" s ns
test1 = (baseDir ++ "/mptc/test/Data/TestCase1DeclDependence.hs", "[[a],[b],[h,g,f],[c,d]]")
decls (Module _ _ _ _ _ _ ds) = ds
-- pattern matching function over parser results
parseResult :: (a -> b) -> (SrcLoc -> String -> b) -> ParseResult a -> b
parseResult f g (ParseOk m) = f m
parseResult f g (ParseFailed l s) = g l s
-- always enabled extensions
exts :: [Extension]
exts = map EnableExtension [MultiParamTypeClasses, RankNTypes, FlexibleContexts]
| rodrigogribeiro/mptc | test/Cases/DeclDependencyTest.hs | bsd-3-clause | 1,013 | 0 | 13 | 207 | 295 | 157 | 138 | 22 | 1 |
module Agon.Data.Types where
data UUIDs = UUIDs [String]
data CouchUpdateResult = CouchUpdateResult {
curRev :: String
} deriving Show
data CouchList e = CouchList {
clItems :: [CouchListItem e]
} deriving Show
data CouchListItem e = CouchListItem {
cliItem :: e
} deriving Show
| Feeniks/Agon | app/Agon/Data/Types.hs | bsd-3-clause | 296 | 0 | 10 | 61 | 81 | 50 | 31 | 11 | 0 |
{-# LANGUAGE StandaloneDeriving, DeriveFunctor, OverloadedStrings #-}
module Web.Rest (
Request(..),
Method(..),Location,Accept,ContentType,Body,
Response(..),
ResponseCode,
RestT,Rest,rest,
runRestT,Hostname,Port,RestError(..)) where
import Web.Rest.Internal (
Request(..),
Method(..),Location,Accept,ContentType,Body,
Response(..),
ResponseCode,
RestT,Rest,rest)
import Web.Rest.HTTP (
runRestT,Hostname,Port,RestError(..))
| phischu/haskell-rest | src/Web/Rest.hs | bsd-3-clause | 476 | 0 | 6 | 78 | 147 | 100 | 47 | 16 | 0 |
{-# LANGUAGE DataKinds, DeriveDataTypeable, FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances, FunctionalDependencies, MagicHash #-}
{-# LANGUAGE MultiParamTypeClasses, PolyKinds, QuasiQuotes, RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables, StandaloneDeriving, TemplateHaskell #-}
{-# LANGUAGE TypeFamilies, TypeOperators #-}
module Messaging.Core ((:>)(..), cast, Object(..), withTypeableSymbol,
Selector(..), send, (#), (#.), (===), unsafeDownCast) where
import Data.Typeable.Internal (Proxy (..), Typeable (..), mkTyCon3, mkTyConApp)
import Foreign.ForeignPtr (ForeignPtr)
import GHC.Base (Proxy#)
import GHC.TypeLits (Symbol)
import GHC.TypeLits (symbolVal)
import GHC.TypeLits (KnownSymbol)
import Unsafe.Coerce (unsafeCoerce)
newtype Object (a :: k) = Object (ForeignPtr ())
deriving (Typeable, Show, Eq)
-- | @a ':>' b@ indicates that @a@ is a super-class of @b@.
class (a :: k) :> (b :: k2)
newtype Typing sym a = Typing (Typeable (sym :: Symbol) => a)
unsafeDownCast :: (a :> b) => Object a -> Object b
unsafeDownCast (Object a) = Object a
withTypeableSymbol :: forall sym a proxy. KnownSymbol sym
=> proxy sym -> (Typeable sym => a) -> a
withTypeableSymbol _ f = unsafeCoerce (Typing f :: Typing sym a) inst
where
inst pxy =
let _ = pxy :: Proxy# sym
in mkTyConApp (mkTyCon3 "base" "GHC.TypeLits" ('"': symbolVal (Proxy :: Proxy sym) ++ "\"")) []
instance (a :> b, c :> d) => (b -> c) :> (a -> d)
instance a :> a
instance (a :> b) => [a] :> [b]
class Selector cls msg | msg -> cls where
data Message (msg :: k') :: *
type Returns msg :: *
send' :: Object cls -> Message msg -> Returns msg
cast :: (a :> b) => Object b -> Object a
cast (Object ptr) = Object ptr
send :: (a :> b, Selector a msg) => Object b -> Message msg -> Returns msg
send = send' . cast
infixl 4 #
(#) :: (a :> b, Selector a msg) => Object b -> Message msg -> Returns msg
(#) = send
infixl 4 #.
(#.) :: (a :> b, Selector a msg, Returns msg ~ IO c) => IO (Object b) -> Message msg -> IO c
recv #. sel = recv >>= flip send sel
infix 4 ===
(===) :: Object t -> Object t1 -> Bool
Object fptr === Object fptr' = fptr == fptr'
| konn/reactive-objc | Messaging/Core.hs | bsd-3-clause | 2,309 | 0 | 17 | 569 | 836 | 457 | 379 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module OAuthHandlers
( routes ) where
------------------------------------------------------------------------------
import Control.Applicative
import Control.Monad
import Control.Monad.Trans
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.Auth
import Snap.Snaplet.Auth.Backends.JsonFile
import Snap.Snaplet.Heist
import Snap.Snaplet.OAuth
import Text.Templating.Heist
import qualified Snap.Snaplet.OAuth.Github as GH
import qualified Snap.Snaplet.OAuth.Google as G
import qualified Snap.Snaplet.OAuth.Weibo as W
import Application
import Splices
----------------------------------------------------------------------
-- Weibo
----------------------------------------------------------------------
-- | Logs out and redirects the user to the site index.
weiboOauthCallbackH :: AppHandler ()
weiboOauthCallbackH = W.weiboUserH
>>= success
where success Nothing = writeBS "No user info found"
success (Just usr) = do
with auth $ createOAuthUser weibo $ W.wUidStr usr
--writeText $ T.pack $ show usr
toHome usr
----------------------------------------------------------------------
-- Google
----------------------------------------------------------------------
googleOauthCallbackH :: AppHandler ()
googleOauthCallbackH = G.googleUserH
>>= googleUserId
googleUserId :: Maybe G.GoogleUser -> AppHandler ()
googleUserId Nothing = redirect "/"
googleUserId (Just user) = with auth (createOAuthUser google (G.gid user))
>> toHome user
----------------------------------------------------------------------
-- Github
----------------------------------------------------------------------
githubOauthCallbackH :: AppHandler ()
githubOauthCallbackH = GH.githubUserH
>>= githubUser
githubUser :: Maybe GH.GithubUser -> AppHandler ()
githubUser Nothing = redirect "/"
githubUser (Just user) = with auth (createOAuthUser github uid)
>> toHome user
where uid = intToText $ GH.gid user
intToText = T.pack . show
----------------------------------------------------------------------
-- Create User per oAuth response
----------------------------------------------------------------------
-- | Create new user for Weibo User to local
--
createOAuthUser :: OAuthKey
-> T.Text -- ^ oauth user id
-> Handler App (AuthManager App) ()
createOAuthUser key name = do
let name' = textToBS name
passwd = ClearText name'
role = Role (BS.pack $ show key)
exists <- usernameExists name
unless exists (void (createUser name name'))
res <- loginByUsername name' passwd False
case res of
Left l -> liftIO $ print l
Right r -> do
res2 <- saveUser (r {userRoles = [ role ]})
return ()
--either (liftIO . print) (const $ return ()) res2
----------------------------------------------------------------------
-- Routes
----------------------------------------------------------------------
-- | The application's routes.
routes :: [(ByteString, AppHandler ())]
routes = [ ("/oauthCallback", weiboOauthCallbackH)
, ("/googleCallback", googleOauthCallbackH)
, ("/githubCallback", githubOauthCallbackH)
]
-- | NOTE: when use such way to show callback result,
-- the url does not change, which can not be invoke twice.
-- This is quite awkful thing and only for testing purpose.
--
toHome a = heistLocal (bindRawResponseSplices a) $ render "index"
----------------------------------------------------------------------
--
----------------------------------------------------------------------
| HaskellCNOrg/snaplet-oauth | example/src/OAuthHandlers.hs | bsd-3-clause | 4,350 | 0 | 17 | 1,169 | 721 | 399 | 322 | 66 | 2 |
module Math.Matrix where
import Math.Vector
import Data.List ( intercalate )
import Data.Maybe ( fromJust, fromMaybe )
import qualified Data.List as L
type Matrix a = [Vector a]
-- Projection Matrices
orthoMatrix :: (Num t, Fractional t) => t -> t -> t -> t -> t -> t -> Matrix t
orthoMatrix left right top bottom near far = [ [ 2/(right-left), 0, 0, -(right+left)/(right-left) ]
, [ 0, 2/(top-bottom), 0, -(top+bottom)/(top-bottom) ]
, [ 0, 0, -2/(far-near), -(far+near)/(far-near) ]
, [ 0, 0, 0, 1]
]
-- Affine Transformation Matrices
scaleMatrix3d :: Num t => t -> t -> t -> Matrix t
scaleMatrix3d x y z = [ [x, 0, 0, 0]
, [0, y, 0, 0]
, [0, 0, z, 0]
, [0, 0, 0, 1]
]
rotationMatrix3d :: Floating t => t -> t -> t -> Matrix t
rotationMatrix3d x y z = [ [cy*cz, -cx*sz+sx*sy*sz, sx*sz+cx*sy*cz, 0]
, [cy*sz, cx*cz+sx*sy*sz, -sx*cz+cx*sy*sz, 0]
, [ -sy, sx*cy, cx*cy, 0]
, [ 0, 0, 0, 1]
]
where [cx, cy, cz] = map cos [x, y, z]
[sx, sy, sz] = map sin [x, y, z]
translationMatrix3d :: Num t => t -> t -> t -> Matrix t
translationMatrix3d x y z = [ [1, 0, 0, x]
, [0, 1, 0, y]
, [0, 0, 1, z]
, [0, 0, 0, 1]
]
-- Basic Matrix Math
fromVector :: Int -> Int -> [a] -> Maybe [[a]]
fromVector r c v = if length v `mod` r*c == 0
then Just $ groupByRowsOf c v
else Nothing
-- | The identity of an NxN matrix.
identityN :: (Num a) => Int -> Matrix a
identityN n = groupByRowsOf n $ modList n
where modList l = [ if x `mod` (l+1) == 0 then 1 else 0 | x <- [0..(l*l)-1] ]
-- | The identity of the given matrix.
identity :: (Num a) => Matrix a -> Matrix a
identity m = groupByRowsOf rows modList
where modList = [ if x `mod` (cols+1) == 0 then 1 else 0 | x <- [0..len-1] ]
len = sum $ map length m
rows = numRows m
cols = numColumns m
-- | The number of columns in the matrix.
numColumns :: Matrix a -> Int
numColumns = length
-- | The number of rows in the matrix.
numRows :: Matrix a -> Int
numRows [] = 0
numRows (r:_) = length r
-- | A list of the columns.
toColumns :: Matrix a -> [[a]]
toColumns = transpose
-- | A list of the rows.
toRows :: Matrix a -> [[a]]
toRows = id
-- | The minor for an element of `a` at the given row and column.
minorAt :: Floating a => [Vector a] -> Int -> Int -> a
minorAt m x y = let del = deleteColRow m x y
in determinant del
-- | The Matrix created by deleting column x and row y of the given matrix.
deleteColRow :: Matrix a -> Int -> Int -> Matrix a
deleteColRow m x y = let nRws = numRows m
nCls = numColumns m
rNdxs = [ row + x | row <- [0,nCls..nCls*(nCls-1)] ]
cNdxs = [ nRws*y + col | col <- [0..nRws-1] ]
ndxs = rNdxs ++ cNdxs
(_, vec) = foldl filtNdx (0,[]) $ concat m
filtNdx (i, acc) el = if i `elem` ndxs
then (i+1, acc)
else (i+1, acc++[el])
in groupByRowsOf (nRws-1) vec
-- | The transpose of the matrix.
transpose :: Matrix a -> Matrix a
transpose = L.transpose
-- | Computes the inverse of the matrix.
inverse :: (Num a, Eq a, Fractional a, Floating a) => Matrix a -> Maybe (Matrix a)
inverse m = let det = determinant m
one_det = 1/ det
cofacts = cofactors m
adjoint = transpose cofacts
inv = (map . map) (*one_det) adjoint
in if det /= 0
then Just inv
else Nothing
-- | The matrix of cofactors of the given matrix.
cofactors :: (Num a, Floating a) => Matrix a -> Matrix a
cofactors m = fromJust $ fromVector (numRows m) (numColumns m) [ cofactorAt m x y | y <- [0..numRows m -1], x <- [0..numColumns m -1] ]
-- | Computes the multiplication of two matrices.
multiply :: (Num a, Show a) => Matrix a -> Matrix a -> Matrix a
multiply m1 m2 = let element row col = sum $ zipWith (*) row col
rows = toRows m1
cols = toColumns m2
nRows = numRows m1
nCols = numColumns m2
vec = take (nRows*nCols) [ element r c | r <- rows, c <- cols ]
mM = fromVector nRows nCols vec
err = error $ intercalate "\n" [ "Could not multiply matrices:"
, "m1:"
, show m1
, "m2:"
, show m2
, "from vector:"
, show vec
]
in fromMaybe err mM
-- | The cofactor for an element of `a` at the given row and column.
cofactorAt :: (Num a, Floating a) => Matrix a -> Int -> Int -> a
cofactorAt m x y = let pow = fromIntegral $ x + y + 2 -- I think zero indexed.
in (-1)**pow * minorAt m x y
-- | Computes the determinant of the matrix.
determinant :: (Num a, Floating a) => Matrix a -> a
determinant [[a]] = a
determinant m = let rowCofactors = [ cofactorAt m x 0 | x <- [0..numColumns m -1] ]
row = head $ toRows m
in sum $ zipWith (*) rowCofactors row
-- Helpers
groupByRowsOf :: Int -> [a] -> [[a]]
groupByRowsOf _ [] = []
groupByRowsOf cols xs = take cols xs : groupByRowsOf cols (drop cols xs)
| schell/blocks | src/Math/Matrix.hs | bsd-3-clause | 6,213 | 0 | 15 | 2,660 | 2,184 | 1,183 | 1,001 | 104 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module VirtualDom.Prim where
import Control.Applicative
import Control.Lens
import Control.Monad.State
import Data.String (IsString(fromString))
import GHCJS.DOM.Event
import GHCJS.Foreign
import GHCJS.Types
import System.IO.Unsafe
import qualified Data.Immutable as Immutable
import qualified GHCJS.DOM.HTMLElement as DOM
-- | An opaque data-type representing a foreign @VNode@ object.
data VNode
-- | A HTML node - either an element with attributes, or a piece of text.
newtype Node =
Node (JSRef VNode)
foreign import javascript safe
"new virtualdom.VText($1)" ffiNewVText :: JSString -> JSRef VNode
-- | Construct a 'HTML' text node.
text :: ToJSString t => t -> Node
text = Node . ffiNewVText . toJSString
foreign import javascript safe
"new virtualdom.VNode($1)"
ffiNewVNode :: JSString -> JSRef VNode
-- | Construct a new 'HTML' element consisting of a given element, with no
-- child content or attributes.
emptyElement :: JSString -> Node
emptyElement = Node . ffiNewVNode
-- | Strings are considered HTML nodes by converting them to text nodes.
instance IsString Node where
fromString = text
-- | Witness that a 'HTML' node is pointing to a VNode.
newtype HTMLElement = HTMLElement (JSRef VNode)
foreign import javascript safe
"$r = $1.type"
ffiGetVNodeType :: JSRef VNode -> JSString
-- A zero-or-one traversal into a 'HTML' fragment to determine if it is an
-- element or not.
_HTMLElement :: Traversal' Node HTMLElement
_HTMLElement f (Node vNode)
| fromJSString (ffiGetVNodeType vNode) == ("VirtualNode" :: String) =
fmap (\(HTMLElement vNode') -> Node vNode')
(f (HTMLElement vNode))
| otherwise = pure (Node vNode)
foreign import javascript safe
"Immutable.Map($1.properties)"
ffiVNodeGetProperties :: JSRef VNode -> Immutable.Map
foreign import javascript safe
"new virtualdom.VNode($1.tagName, $2.toJS(), $1.children, $1.key, $1.namespace)"
ffiVNodeSetProperties :: JSRef VNode -> Immutable.Map -> JSRef VNode
properties :: Lens' HTMLElement Immutable.Map
properties f (HTMLElement vNode) =
fmap (HTMLElement . ffiVNodeSetProperties vNode)
(f (ffiVNodeGetProperties vNode))
foreign import javascript safe
"Immutable.Map($1.properties.attributes)"
ffiVNodeGetAttributes :: JSRef VNode -> Immutable.Map
foreign import javascript safe
"new virtualdom.VNode($1.tagName, Immutable.Map($1.properties).set('attributes', $2).toJS(), $1.children, $1.key)"
ffiVNodeSetAttributes :: JSRef VNode -> Immutable.Map -> JSRef VNode
attributes :: Lens' HTMLElement Immutable.Map
attributes f (HTMLElement vNode) =
fmap (HTMLElement . ffiVNodeSetAttributes vNode)
(f (ffiVNodeGetAttributes vNode))
foreign import javascript safe
"$1.children"
ffiGetVNodeChildren :: JSRef VNode -> JSArray (JSRef VNode)
foreign import javascript safe
"new virtualdom.VNode($1.tagName, $1.properties, $2, $1.key, $1.namespace)"
ffiSetVNodeChildren :: JSRef VNode -> JSArray (JSRef VNode) -> JSRef VNode
children :: Lens' HTMLElement (JSArray (JSRef VNode))
children f (HTMLElement vNode) =
fmap (HTMLElement . ffiSetVNodeChildren vNode)
(f (ffiGetVNodeChildren vNode))
foreign import javascript safe
"$1.key"
ffiGetVNodeKey :: JSRef VNode -> JSString
foreign import javascript safe
"new virtualdom.VNode($1.tagName, $1.properties, $1.children, $2, $1.namespace)"
ffiSetVNodeKey :: JSRef VNode -> JSString -> JSRef VNode
key :: Lens' HTMLElement JSString
key f (HTMLElement vNode) =
fmap (HTMLElement . ffiSetVNodeKey vNode)
(f (ffiGetVNodeKey vNode))
foreign import javascript safe
"$1.namespace"
ffiGetVNodeNamespace :: JSRef VNode -> JSString
foreign import javascript safe
"new virtualdom.VNode($1.tagName, $1.properties, $1.children, $1.children, $2)"
ffiSetVNodeNamespace :: JSRef VNode -> JSString -> JSRef VNode
namespace :: Lens' HTMLElement JSString
namespace f (HTMLElement vNode) =
fmap (HTMLElement . ffiSetVNodeKey vNode)
(f (ffiGetVNodeKey vNode))
foreign import javascript safe
"new virtualdom.VNode($1.tagName, Immutable.Map($1.properties).set('ev-' + $2, evHook($3)).toJS(), $1.children, $1.key, $1.namespace)"
ffiSetVNodeEvent :: JSRef VNode -> JSString -> JSFun (JSRef Event -> IO ()) -> JSRef VNode
on :: MonadState HTMLElement m => JSString -> (JSRef Event -> IO ()) -> m ()
on ev f =
modify (\(HTMLElement vnode) ->
HTMLElement
(ffiSetVNodeEvent vnode
ev
(unsafePerformIO (syncCallback1 AlwaysRetain True f))))
foreign import javascript safe
"new virtualdom.VNode($1.tagName, Immutable.Map($1.properties).set('hook-' + $2, Object.create({ hook: $3 })).toJS(), $1.children, $1.key, $1.namespace)"
ffiRegisterVNodeHook :: JSRef VNode -> JSString -> JSFun (JSRef DOM.HTMLElement -> JSString -> IO ()) -> JSRef VNode
registerHook :: MonadState HTMLElement m
=> JSString -> (JSRef DOM.HTMLElement -> JSString -> IO ()) -> m ()
registerHook hookName f =
modify (\(HTMLElement vnode) ->
HTMLElement
(ffiRegisterVNodeHook vnode
hookName
(unsafePerformIO (syncCallback2 AlwaysRetain True f))))
| ocharles/virtual-dom | src/VirtualDom/Prim.hs | bsd-3-clause | 5,318 | 68 | 14 | 986 | 1,198 | 619 | 579 | -1 | -1 |
module Twitch.Run where
import Prelude hiding (FilePath, log)
import Twitch.Internal ( Dep, runDep )
import Twitch.InternalRule
( Config(dirs, logger), InternalRule, toInternalRule, setupRules )
import Twitch.Rule ( RuleIssue )
import Data.Either ( partitionEithers )
import System.FilePath ( FilePath )
import System.FSNotify ( WatchManager )
import System.Directory ( getCurrentDirectory )
import Twitch.Path ( findAllDirs )
import Data.Default ( Default(def) )
-- This the main interface for running a Dep
run :: Dep -> IO WatchManager
run dep = do
currentDir <- getCurrentDirectory
dirs' <- findAllDirs currentDir
runWithConfig currentDir (def { logger = print, dirs = dirs' }) dep
runWithConfig :: FilePath -> Config -> Dep -> IO WatchManager
runWithConfig root config dep = do
let (_issues, rules) = depToRules root dep
-- TODO handle the issues somehow
-- Log and perhaps error
setupRules config rules
depToRulesWithCurrentDir :: Dep -> IO ([RuleIssue], [InternalRule])
depToRulesWithCurrentDir dep = do
currentDir <- getCurrentDirectory
return $ depToRules currentDir dep
depToRules :: FilePath -> Dep -> ([RuleIssue], [InternalRule])
depToRules currentDir
= partitionEithers . map (toInternalRule currentDir) . runDep
| jfischoff/twitch | src/Twitch/Run.hs | mit | 1,264 | 0 | 10 | 207 | 359 | 199 | 160 | 28 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Chapter2.Section2.LabInteractive where
import Prelude
{- Ex 1: Which of the following implementations defines a
function putStr' :: String -> IO () that takes a
String as its parameter and writes it to the
standard output?
Note: The helper function putChar :: Char -> IO ()
takes a character as its parameter and writes it to
the standard output.
-}
putStr' :: String -> IO ()
-- WRONG
--putStr' [] = return ""
--putStr' (x : xs) = putChar x >> putStr' xs
-- RIGHT
putStr' [] = return ()
putStr' (x : xs) = putChar x >> putStr' xs
-- WRONG
--putStr' [] = return ()
--putStr' (x : xs) = putChar x >>= putStr' xs
-- WRONG
--putStr' [] = return ()
--putStr' (x : xs) = putStr' xs >>= putChar x
{- Ex 2: Choose all possible implementations for a function
putStrLn' :: String -> IO () that takes a String
parameter and writes it to the standard output,
followed by a newline character.
Assume "fast and loose" reasoning where there are no
bottoms involved, and all functions are total, and all
values are finite.
-}
putStrLn' :: String -> IO ()
-- RIGHT
putStrLn' [] = putChar '\n'
putStrLn' xs = putStr' xs >> putStrLn' ""
-- RIGHT
--putStrLn' [] = putChar '\n'
--putStrLn' xs = putStr' xs >> putChar '\n'
-- RIGHT
--putStrLn' [] = putChar '\n'
--putStrLn' xs = putStr' xs >>= \ x -> putChar '\n'
-- WRONG
--putStrLn' [] = putChar '\n'
--putStrLn' xs = putStr' xs >> \ x -> putChar '\n'
-- RIGHT
-- NOTE: "" instead of '' has been used!!!
--putStrLn' [] = putChar '\n'
--putStrLn' xs = putStr' xs >> putStr' "\n"
-- WRONG
--putStrLn' [] = putChar '\n'
--putStrLn' xs = putStr' xs >> putStrLn' "\n"
-- WRONG
--putStrLn' [] = return ""
--putStrLn' xs = putStrLn' xs >> putStr' "\n"
-- WRONG
--putStrLn' [] = putChar "\n"
--putStrLn' xs = putStr' xs >> putChar '\n'
{- Ex 3: Which of the following implementation defines a function
getLine' :: IO String that reads a line, up to the first
\n character, from the standard input?
Note: The helper function getChar :: IO Char reads a single
character from the standard input.
Test #1:
Type: getLine'
Wait for prompt on new line to appear
Type: ab c\nabc
It should only return: "abc"
-}
-- WRONG - returns "abc\\nabc" for INPUT abc\nabc
-- WRONG - returns "ab" for INPUT ab c\nabc
{-
getLine' :: IO String
getLine' = get ""
get :: String -> IO String
get xs
= do x <- getChar
case x of
' ' -> return xs
'\n' -> return xs
_ -> get (xs ++ [x])
-}
-- WRONG - returns "cban\\cba"
{-
getLine' :: IO String
getLine' = get ""
get :: String -> IO String
get xs
= do x <- getChar
case x of
'\n' -> return xs
_ -> get (x : xs)
-}
-- - returns "abc\\nabc"
-- RIGHT - returns "ab c\\nabc" for INPUT ab c\nabc
getLine' :: IO String
getLine' = get []
get :: String -> IO String
get xs
= do x <- getChar
case x of
'\n' -> return xs
_ -> get (xs ++ [x])
-- WRONG - returns "\nabc\\nabc"
{-
getLine' :: IO String
getLine' = get []
get :: String -> IO String
get xs
= do x <- getChar
case x of
'\n' -> return (x : xs)
_ -> get (xs ++ [x])
-}
{- Ex 4: Which of the following implementations defines a function
interact' :: (String -> String) -> IO () that takes as its argument a function
of type String -> String, and reads a line from the standard input,
and passes it to this function, and then prints the resulting output followed
by a newline on the standard output?
Note: Quick tip: the ' is there because sequence_ is a built-in function.
You can use that to see what the behaviour should be.
Prelude> :t interact
interact :: (String -> String) -> IO ()
-}
-- NO IDEA
{-
interact' :: (String -> String) -> IO ()
interact' f
= do input <- getLine'
putStrLn' (f input)
-}
{- Ex. 5: Choose all possible implementations of the function
sequence_' :: Monad m => [m a] -> m () that takes a finite, non-partial,
list of non-bottom, monadic values, and evaluates them in sequence,
from left to right, ignoring all (intermediate) results?
Hint: Make sure you type in all these definitions in GHCi and play around
with a variety of possible input.
Test with: sequence_' [(>4), (<10), odd] 7
sequence_' [putChar 'a', putChar 'b', putChar 'c', putChar 'd']
-}
sequence_' :: Monad m => [m a] -> m ()
-- WRONG
{-
sequence_' [] = return []
sequence_' (m : ms) = m >> \ _ -> sequence_' ms
-}
{-
Test output:
<interactive>:2:14: Warning:
Defaulting the following constraint(s) to type ‘Integer’
(Ord a0) arising from a use of ‘>’ at <interactive>:2:14
(Num a0) arising from the literal ‘4’ at <interactive>:2:15
(Integral a0) arising from a use of ‘odd’ at <interactive>:2:26-28
In the expression: (> 4)
In the first argument of ‘sequence_'’, namely
‘[(> 4), (< 10), odd]’
In the expression: sequence_' [(> 4), (< 10), odd] 7
()
-}
-- MAYBE
{-
Check Type Signature
Prelude> let sequence_' [] = return ()
Prelude> let sequence_' (m : ms) = (foldl (>>) m ms) >> return ()
Prelude> :t sequence_'
sequence_' :: Monad m => [m a] -> m ()
-}
sequence_' [] = return ()
sequence_' (m : ms) = (foldl (>>) m ms) >> return ()
-- WRONG
{-
Check Type Signature:
Prelude> let sequence_' ms = foldl (>>) (return ()) ms
Prelude> :t sequence_'
sequence_' :: Monad m => [m ()] -> m ()
-}
{-
sequence_' ms = foldl (>>) (return ()) ms
-}
{-
Test output:
<interactive>:9:14: Warning:
Defaulting the following constraint(s) to type ‘Integer’
(Ord a0) arising from a use of ‘>’ at <interactive>:9:14
(Num a0) arising from the literal ‘4’ at <interactive>:9:16
(Integral a0) arising from a use of ‘odd’ at <interactive>:9:28-30
In the expression: (> 4)
In the first argument of ‘sequence_'’, namely
‘[(> 4), (< 10), odd]’
In the expression: sequence_' [(> 4), (< 10), odd] 7
()
-}
-- WRONG !! MAYBE
{-
Check Type:
Prelude> letsequence_' (m : ms) = m >> sequence_' ms
Prelude> let sequence_' (m : ms) = m >> sequence_' ms
Prelude> :t sequence_'
sequence_' :: Monad m => [m a] -> m b
-}
{-
sequence_' [] = return ()
sequence_' (m : ms) = m >> sequence_' ms
-}
{-
Test output:
<interactive>:19:14: Warning:
Defaulting the following constraint(s) to type ‘Integer’
(Ord a0) arising from a use of ‘>’ at <interactive>:19:14
(Num a0) arising from the literal ‘4’ at <interactive>:19:16
(Integral a0) arising from a use of ‘odd’ at <interactive>:19:28-30
In the expression: (> 4)
In the first argument of ‘sequence_'’, namely
‘[(> 4), (< 10), odd]’
In the expression: sequence_' [(> 4), (< 10), odd] 7
()
-}
-- WRONG !! MAYBE
{-
Check Type:
Prelude> let sequence_' [] = return ()
Prelude> let sequence_' (m : ms) = m >>= \ _ -> sequence_' ms
Prelude> :t sequence_'
sequence_' :: Monad m => [m a] -> m b
-}
{-
sequence_' [] = return ()
sequence_' (m : ms) = m >>= \ _ -> sequence_' ms
-}
{-
Test output:
Couldn't match type ‘m ()’ with ‘()’
Expected type: m a -> m () -> m ()
Actual type: m a -> (a -> m ()) -> m ()
-}
-- WRONG
{-
sequence_' ms = foldr (>>=) (return ()) ms
-}
{-
Test output:
<interactive>:29:14: Warning:
Defaulting the following constraint(s) to type ‘Integer’
(Ord a0) arising from a use of ‘>’ at <interactive>:29:14
(Num a0) arising from the literal ‘4’ at <interactive>:29:16
(Integral a0) arising from a use of ‘odd’ at <interactive>:29:28-30
In the expression: (> 4)
In the first argument of ‘sequence_'’, namely
‘[(> 4), (< 10), odd]’
In the expression: sequence_' [(> 4), (< 10), odd] 7
()
-}
-- MAYBE
{-
Check Type:
Prelude> let sequence_' ms = foldr (>>) (return ()) ms
Prelude> :t sequence_'
sequence_' :: Monad m => [m a] -> m ()
-}
{-
sequence_' ms = foldr (>>) (return ()) ms
-}
-- WRONG
-- Couldn't match expected type ‘()’ with actual type ‘[t0]’
--sequence_' ms = foldr (>>=) (return []) ms
{- Ex. 6: Choose all possible implementations of the function
sequence' :: Monad m => [m a] -> m [a] that takes a finite, non-partial,
list of non-bottom, monadic values, and evaluates them in sequence,
from left to right, collecting all (intermediate) results into a list?
Hint: Make sure you type in all these definitions in GHCi and play around
with a variety of possible input.
Test with: sequence' [(>4), (<10), odd] 7
-}
sequence' :: Monad m => [m a] -> m [a]
{- RIGHT -}
sequence' [] = return []
sequence' (m : ms)
= m >>=
\ a ->
do as <- sequence' ms
return (a : as)
{- WRONG
sequence' ms = foldr func (return ()) ms
where
func :: (Monad m) => m a -> m [a] -> m [a]
func m acc
= do x <- m
xs <- acc
return (x : xs)
-}
{- WRONG
sequence' ms = foldr func (return []) ms
where
func :: (Monad m) => m a -> m [a] -> m [a]
func m acc = m : acc
-}
{- WRONG
sequence' [] = return []
sequence' (m : ms) = return (a : as)
where
a <- m
as <- sequence' ms
-}
{- RIGHT
sequence' ms = foldr func (return []) ms
where
func :: (Monad m) => m a -> m [a] -> m [a]
func m acc
= do x <- m
xs <- acc
return (x : xs)
-}
{- WRONG
sequence' [] = return []
sequence' (m : ms)
= m >>
\ a ->
do as <- sequence' ms
return (a : as)
-}
{- WRONG
sequence' [] = return []
sequence' (m : ms) = m >>= \a ->
as <- sequence' ms
return (a : as)
-}
{- RIGHT
sequence' [] = return []
sequence' (m : ms)
= do a <- m
as <- sequence' ms
return (a : as)
-}
{- Ex. 7:
Choose all possible implementations of a function
mapM' :: Monad m => (a -> m b) -> [a] -> m [b] which takes a non-bottom
function of type a -> m b, and a finite, non-partial list of non-bottom
elements of type a and (similarly to map) applies the function to every
element of the list, but produces the resulting list wrapped inside a monadic
action?
Note: mapM' must preserve the order of the elements of the input list.
Hint: Make sure you try each of these options in GHCi and play around with
a variety of inputs to experiment with the behaviour. It's easiest to use the
IO Monad for the function passed into mapM'
Test with:
mapM' reverse ["ab","3","12"]
Expect:
["b32","b31","a32","a31"]
Also test with:
mapM' (putChar) ['a', 'b', 'c']
Gives:
abc[(),(),()]
Also test with:
mapM' (\x -> putChar x >> return x) ['a', 'b', 'c']
Gives:
abc"abc"
-}
mapM' :: Monad m => (a -> m b) -> [a] -> m [b]
{- RIGHT -}
mapM' f as = sequence' (map f as)
{- RIGHT
mapM' f [] = return []
mapM' f (a : as)
= f a >>= \ b -> mapM' f as >>= \ bs -> return (b : bs)
-}
{- WRONG
mapM' f as = sequence_' (map f as)
-}
{- WRONG
mapM' f [] = return []
mapM' f (a : as)
= f a >> \ b -> mapM' f as >> \ bs -> return (b : bs)
-}
{- WRONG
mapM' f [] = return []
mapM' f (a : as) =
do
f a -> b
mapM' f as -> bs
return (b : bs)
-}
{- RIGHT
mapM' f [] = return []
mapM' f (a : as)
= do b <- f a
bs <- mapM' f as
return (b : bs)
-}
{- RIGHT
mapM' f [] = return []
mapM' f (a : as)
= f a >>=
\ b ->
do bs <- mapM' f as
return (b : bs)
-}
{- WRONG
mapM' f [] = return []
mapM' f (a : as )
= f a >>=
\ b ->
do bs <- mapM' f as
return (bs ++ [b])
-}
{- Ex. 8:
Which of the following definitions implements the function
filterM' :: Monad m => (a -> m Bool) -> [a] -> m [a], that takes a
"predicate" of type Monad m => a -> m Bool and uses this to filter a
finite, non-partial list of non-bottom elements of type a.
Note: filterM' must preserve the order of the elements of the input list,
as far as they appear in the result.
Test with:
filterM' True [False,True,False]
filterM (const [True, False])
Expect:
.
-}
-- NO IDEA!!!
--filterM' :: Monad m => (a -> m Bool) -> [a] -> m [a]
{-
filterM' _ [] = return []
filterM' p (x : xs)
= do flag <- p x
ys <- filterM' p xs
return (x : ys)
-}
{-
filterM' _ [] = return []
filterM' p (x : xs)
= do flag <- p x
ys <- filterM' p xs
if flag then return (x : ys) else return ys
-}
{- WRONG
filterM' _ [] = return []
filterM' p (x : xs)
= do ys <- filterM' p xs
if p x then return (x : ys) else return ys
-}
{-
filterM' _ [] = return []
filterM' p (x : xs)
= do flag <- p x
ys <- filterM' p xs
if flag then return ys else return (x : ys)
-}
{- Ex. 9
Implement the function foldLeftM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a
that takes an accumulation function a -> b -> m a, and a seed of type a and
left folds a finite, non-partial list of non-bottom elements of type b into a
single result of type m a
Hint: The recursive structure of foldLeftM looks as follows:
foldLeftM f a [] = ... a ...
foldLeftM f a (x:xs) = foldLeftM f (... f ... a ... (>>=) ...) xs
Remember the definition of foldl:
foldl f a [] = ... a ...
foldl f a (x:xs) = foldl f (... f ... a ...) xs
What is the result of evaluating the expression:
haskellhaskell
lleksahhaskell
haskellhaskellhaskell
haskelllleksahhaskell
-}
{- Proposed approach:
Apply the function with the default accumulator
and the leftmost element of the list
and bind its return (to get rid of the monadic)
then proceed to apply the function recursively,
passing the same f, but instead of the default accumulator
pass it b and the remainder of the list.
Noting to 'return a' for the base case
-}
--foldLeftM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a
--foldLeftM (\a b -> putChar b >> return (b : a ++ [b])) [] "haskell" >>= \r -> putStrLn r
{- Ex. 10
Implement the function foldRightM :: Monad m => (a -> b -> m b) -> b -> [a] -> m b
which is like to foldLeftM from the previous exercise, except that it folds a finite,
non-partial list of non-bottom elements of type a into a single monadic value of type m b.
Hint: look up the definition of foldr.
What is the result of evaluating the expression:
]9,7,5,3,1[[1,3,5,7,9]
[9,7,5,3,1][1,3,5,7,9]
[1,3,5,7,9][9,7,5,3,1]
[1,3,5,7,9][1,3,5,7,9]
Note: A simple test like the following won't reveal the flaw in the code
foldLeftM (\a b -> Just (a + b)) 0 [1..10]
Proper test in GHCi
foldRightM' (\a b -> putChar a >> return (a : b)) [] (show [1,3..10]) >>= \r -> putStrLn r
Returns:
]9,7,5,3,1[[1,3,5,7,9]
-}
foldRightM' :: Monad m => (a -> b -> m b) -> b -> [a] -> m b
-- carefully compare with the implementation of foldr
-- foldRightM' |operator| |init_value| |list|
-- Note: the code must be associating to the right and implementing the right fold correctly
foldRightM' f d [] = return d
foldRightM' f d (x:xs) = (\z -> f x z) <<= foldRightM' f d xs
where (<<=) = flip (>>=)
--
{- Ex. 11
Choose all possible implementations that define a function
liftM :: Monad m => (a -> b) -> m a -> m b that takes a
function of type a -> b and "maps" it over a non-bottom
monadic value of type m a to produce a value of type m b?
-}
liftM :: Monad m => (a -> b) -> m a -> m b
-- liftM (+1) [1,2] ===> [2,3]
-- liftM (+1) [] ===> []
-- RIGHT
liftM f m
= do x <- m
return (f x)
-- WRONG
--liftM f m = m >>= \ a -> f a
-- RIGHT
--liftM f m = m >>= \ a -> return (f a)
-- WRONG
--liftM f m = return (f m)
{- WRONG - doesn't map correctly
liftM (+1) [1,2] ===> [2,2,3,3]
-}
--liftM f m = m >>= \ a -> m >>= \ b -> return (f a)
{- WRONG - doesn't map correctly
liftM (+1) [1,2] ===> [2,3,2,3]
-}
--liftM f m = m >>= \ a -> m >>= \ b -> return (f b)
--WRONG
--liftM f m = mapM f [m]
--WRONG
--liftM f m = m >> \ a -> return (f a)
| ltfschoen/HelloHaskell | src/Chapter2/Section2/LabInteractive.hs | mit | 17,861 | 0 | 13 | 6,045 | 725 | 424 | 301 | 37 | 2 |
module FrontEnd.Tc.Module (tiModules,TiData(..)) where
import Control.Monad.Writer
import Data.Char
import Text.PrettyPrint.HughesPJ as PPrint
import qualified Data.Foldable as T
import qualified Data.Map as Map
import qualified Data.Set as Set
import DataConstructors
import DerivingDrift.Drift
import Doc.PPrint as PPrint
import FrontEnd.Class
import FrontEnd.DataConsAssump (dataConsEnv)
import FrontEnd.DeclsDepends (getDeclDeps, debugDeclBindGroups)
import FrontEnd.DependAnalysis (getBindGroups)
import FrontEnd.Exports
import FrontEnd.HsSyn
import FrontEnd.Infix
import FrontEnd.KindInfer
import FrontEnd.Rename
import FrontEnd.Tc.Main
import FrontEnd.Tc.Monad
import FrontEnd.Tc.Type
import FrontEnd.TypeSigs (collectSigs, listSigsToSigEnv)
import FrontEnd.TypeSynonyms
import FrontEnd.TypeSyns
import FrontEnd.Utils
import FrontEnd.Warning
import Ho.Type
import Info.Types
import Name.Name as Name
import Name.Names
import Options
import Util.Gen
import Util.Inst()
import Util.SetLike
import qualified FlagDump as FD
import qualified FrontEnd.HsPretty as HsPretty
trimEnv env = Map.filterWithKey (\k _ -> isGlobal k) env
getDeclNames :: HsDecl -> [Name]
getDeclNames (HsTypeSig _ ns _ ) = map (toName Val) ns
getDeclNames d = maybeGetDeclName d
-- Extra data produced by the front end, used to fill in the Ho file.
data TiData = TiData {
tiDataDecls :: [HsDecl],
tiDataModules :: [(Module,HsModule)],
tiModuleOptions :: [(Module,Opt)],
tiCheckedRules :: [Rule],
tiCoerce :: Map.Map Name CoerceTerm,
tiProps :: Map.Map Name Properties,
tiAllAssumptions :: Map.Map Name Type
}
isGlobal x | (_,(_::String,(h:_))) <- fromName x = not $ isDigit h
isGlobal _ = error "isGlobal"
buildFieldMap :: [ModInfo] -> FieldMap
buildFieldMap ms = FieldMap ans' ans where
allDefs = [ (x,z) | (x,_,z) <- concat $ map modInfoDefs ms,
nameType x == DataConstructor ]
ans = Map.fromList $ sortGroupUnderFG fst snd $ concat
[ [ (y,(x,i)) | y <- ys | i <- [0..] ] | (x,ys) <- allDefs ]
ans' = Map.fromList $ concatMap modInfoConsArity ms
processModule :: FieldMap -> ModInfo -> IO (ModInfo,[Warning])
processModule defs m = do
when (dump FD.Parsed) $ do
putStrLn " \n ---- parsed code ---- \n";
putStrLn $ HsPretty.render
$ HsPretty.ppHsModule
$ modInfoHsModule m
let mod = modInfoHsModule m
let imp = modInfoImport m
let (((mod',inst),rmap),errs) = runWriter $ renameModule (modInfoOptions m) defs imp mod
when (dump FD.Derived && (not $ null inst)) $ do
putStrLn " \n ---- derived instances ---- \n"
putStrLn $ HsPretty.render $ HsPretty.ppHsDecls $ inst
wdump FD.Renamed $ do
putStrLn " \n ---- renamed code ---- \n"
putStrLn $ HsPretty.render $ HsPretty.ppHsModule $ mod'
return (m { modInfoReverseMap = rmap,
modInfoImport = imp ++ driftResolvedNames,
modInfoHsModule = mod' }, errs)
-- type check a set of mutually recursive modules.
-- assume all dependencies are met in the
-- ModEnv parameter and export lists have been calculated.
or' :: [(a -> Bool)] -> a -> Bool
or' fs x = or [ f x | f <- fs ]
-- Very broad information on a data type.
data DatDesc
= DatEnum [Name]
| DatMany [(Name,Int)]
| DatNewT Name
getDataDesc :: Monad m => HsDecl -> m (Name,DatDesc)
getDataDesc d = g d where
g desc = do
r <- f d
return (hsDeclName desc,r)
f HsDataDecl { hsDeclDeclType = DeclTypeNewtype, hsDeclCons = (hsConDeclName . head -> cn) } = return $ DatNewT cn
f HsDataDecl { hsDeclCons = cs }
| all null $ map hsConDeclArgs cs = return $ DatEnum (map hsConDeclName cs)
f HsDataDecl { hsDeclCons = cs } = return $
DatMany [ (hsConDeclName c, (length . hsConDeclArgs) c) | c <- cs]
f _ = fail "getDataDesc: not a data declaration"
{-# NOINLINE tiModules #-}
tiModules :: HoTcInfo -> [ModInfo] -> IO (HoTcInfo,TiData)
tiModules htc ms = do
let importClassHierarchy = hoClassHierarchy htc
importKindEnv = hoKinds htc
let nfm = buildFieldMap ms `mappend` hoFieldMap htc
mserrs <- mapM (processModule nfm) ms
processErrors (concatMap snd mserrs)
let ms = fsts mserrs
let thisFixityMap = buildFixityMap . concat $
[filter isHsInfixDecl (hsModuleDecls $ modInfoHsModule m) | m <- ms]
let fixityMap = thisFixityMap `mappend` hoFixities htc
thisTypeSynonyms <- declsToTypeSynonyms (hoTypeSynonyms htc) $ concat
[ filter isHsTypeDecl (hsModuleDecls $ modInfoHsModule m) | m <- ms]
let ts = thisTypeSynonyms `mappend` hoTypeSynonyms htc
let f x = expandTypeSyns ts (modInfoHsModule x) >>=
return . FrontEnd.Infix.infixHsModule fixityMap >>=
\z -> return x { modInfoHsModule = z }
ms <- mapM f ms
processIOErrors
let ds = concat [ hsModuleDecls $ modInfoHsModule m | m <- ms ]
wdump FD.Decls $ do
putStrLn " ---- processed decls ---- "
putStrLn $ HsPretty.render (HsPretty.ppHsDecls ds)
-- kind inference for all type constructors type variables and classes in the module
let classAndDataDecls = filter (or' [isHsDataDecl, isHsClassDecl, isHsClassAliasDecl]) ds
kindInfo <- kiDecls importKindEnv ds -- classAndDataDecls
when (dump FD.Kind) $
do {putStrLn " \n ---- kind information ---- \n";
putStrLn $ PPrint.render $ pprint kindInfo}
processIOErrors
let localDConsEnv = dataConsEnv kindInfo classAndDataDecls
wdump FD.Dcons $ do
putStr "\n ---- data constructor assumptions ---- \n"
mapM_ putStrLn [ show n ++ " :: " ++ prettyPrintType s |
(n,s) <- Map.toList localDConsEnv]
cHierarchy <- makeClassHierarchy importClassHierarchy kindInfo ds
let smallClassHierarchy = foldr addInstanceToHierarchy cHierarchy dinsts where
derivingClauses = collectDeriving ds
dataInfo = Map.fromList $ concatMap getDataDesc ds
dinsts = concatMap g derivingClauses where
g r@(_,c,t) | c `elem` enumDerivableClasses,
Just (DatEnum (_:_:_)) <- Map.lookup t dataInfo = [f r]
| c `elem` enumDerivableClasses,
t `elem` [tc_Bool, tc_Ordering, tc_IOErrorType, tc_IOMode] = [f r]
--g r@(_,c,t) | c `notElem` noNewtypeDerivable, Just (DatMany True [_]) <- Map.lookup t dataInfo = [f r]
g _ = []
f (sl,c,t) = emptyInstance {
instSrcLoc = sl,
instDerived = True,
instHead = [] :=> IsIn c (TCon (Tycon t kindStar))
}
smallClassHierarchy <- checkForDuplicateInstaces importClassHierarchy smallClassHierarchy
let cHierarchyWithInstances = scatterAliasInstances $
smallClassHierarchy `mappend` importClassHierarchy
when (dump FD.ClassSummary) $ do
putStrLn " ---- class summary ---- "
printClassSummary cHierarchyWithInstances
when (dump FD.Class) $
do {putStrLn " ---- class hierarchy ---- ";
printClassHierarchy smallClassHierarchy}
-- lift the instance methods up to top-level decls
let cDefBinds = concat [ [ z | z <- ds] | HsClassDecl _ _ ds <- ds]
let myClassAssumps = concat [ classAssumps as | as <- classRecords cHierarchyWithInstances ]
instanceEnv = Map.fromList instAssumps
classDefs = snub (concatMap getDeclNames cDefBinds)
classEnv = Map.fromList $ [ (x,y) | (x,y) <- myClassAssumps, x `elem` classDefs ]
(liftedInstances,instAssumps) = mconcatMap
(instanceToTopDecls kindInfo cHierarchyWithInstances) ds
when (not (null liftedInstances) && (dump FD.Instance) ) $ do
putStrLn " ---- lifted instance declarations ---- "
putStr $ unlines $ map (HsPretty.render . HsPretty.ppHsDecl) liftedInstances
putStrLn $ PPrint.render $ pprintEnvMap instanceEnv
let funPatBinds = [ d | d <- ds, or' [isHsFunBind, isHsPatBind, isHsForeignDecl, isHsActionDecl] d]
let rTySigs = [ d | d <- ds, or' [isHsTypeSig] d]
-- build an environment of assumptions for all the type signatures
let allTypeSigs = collectSigs (funPatBinds ++ liftedInstances) ++ rTySigs
when (dump FD.Srcsigs) $
do {putStrLn " ---- type signatures from source code (after renaming) ---- ";
putStr $ unlines $ map (HsPretty.render . HsPretty.ppHsDecl) allTypeSigs}
let sigEnv = Map.unions [listSigsToSigEnv kindInfo allTypeSigs,instanceEnv, classEnv]
when (dump FD.Sigenv) $
do {putStrLn " ---- initial sigEnv information ---- ";
putStrLn $ PPrint.render $ pprintEnvMap sigEnv}
let bindings = (funPatBinds ++ liftedInstances)
--classDefaults = snub [ getDeclName z | z <- cDefBinds, isHsFunBind z || isHsPatBind z ]
classNoDefaults = snub (concat [ getDeclNames z | z <- cDefBinds ]) -- List.\\ classDefaults
noDefaultSigs = Map.fromList [ (n,maybe (error $ "sigEnv:" ++ show n) id $ Map.lookup n sigEnv) | n <- classNoDefaults ]
--when verbose2 $ putStrLn (show bindings)
let programBgs = getBindGroups bindings (nameName . getDeclName) getDeclDeps
when (dump FD.Bindgroups) $
do {putStrLn " \n ---- toplevel variable binding groups ---- ";
putStrLn " ---- Bindgroup # = [members] [vars depended on] [missing vars] ---- \n";
putStr $ debugDeclBindGroups programBgs}
let program = makeProgram sigEnv programBgs
when (dump FD.Program) $ do
putStrLn " ---- Program ---- "
mapM_ putStrLn $ map (PPrint.render . PPrint.pprint) $ program
when (dump FD.AllTypes) $ do
putStrLn " ---- all types ---- "
putStrLn $ PPrint.render $ pprintEnvMap
(sigEnv `mappend` localDConsEnv `mappend` hoAssumps htc)
let moduleName = modInfoName tms
(tms:_) = ms
let tcInfo = tcInfoEmpty {
tcInfoEnv = hoAssumps htc `mappend` localDConsEnv,
tcInfoSigEnv = sigEnv,
tcInfoModName = moduleName,
tcInfoKindInfo = kindInfo,
tcInfoClassHierarchy = cHierarchyWithInstances
}
(localVarEnv,checkedRules,coercions,tcDs) <- withOptionsT (modInfoOptions tms) $ runTc tcInfo $ do
--mapM_ addWarning (concatMap snd mserrs)
(tcDs,out) <- listen (tiProgram program ds)
env <- getCollectedEnv
cc <- getCollectedCoerce
let cc' = Map.union cc $ Map.fromList [ (as,lup v) | (as,v) <- outKnots out ]
lup v = case Map.lookup v cc of
Just (CTAbs xs) -> ctAp (map TVar xs)
_ -> ctId
return (env,T.toList $ checkedRules out,cc',tcDs)
when (dump FD.Decls) $ do
putStrLn " \n ---- typechecked code ---- \n"
mapM_ (putStrLn . HsPretty.render . HsPretty.ppHsDecl) tcDs
when (dump FD.Types) $ do
putStrLn " ---- the types of identifiers ---- "
mapM_ putStrLn [ show n ++ " :: " ++ prettyPrintType s |
(n,s) <- Map.toList (if verbose2 then localVarEnv else trimEnv localVarEnv)]
when (dump FD.Types) $ do
putStrLn " ---- the coersions of identifiers ---- "
mapM_ putStrLn [ show n ++ " --> " ++ show s | (n,s) <- Map.toList coercions]
localVarEnv <- return $ localVarEnv `Map.union` noDefaultSigs
let pragmaProps = fromList $ Map.toList $ Map.fromListWith mappend
[(toName Name.Val x,fromList $ readProp w) | HsPragmaProps _ w xs <- ds, x <- xs]
let allAssumps = localDConsEnv `Map.union` localVarEnv
allExports = Set.fromList (concatMap modInfoExport ms)
externalKindEnv = restrictKindEnv (\ x -> isGlobal x && (getModule x `elem` map (Just . modInfoName) ms)) kindInfo
let hoEx = HoTcInfo {
hoExports = Map.fromList [ (modInfoName m,modInfoExport m) | m <- ms ],
hoDefs = Map.fromList [ (x,(y,filter (`member` allExports) z)) | (x,y,z) <- concat $ map modInfoDefs ms, x `member` allExports],
hoAssumps = Map.filterWithKey (\k _ -> k `member` allExports) allAssumps,
hoFixities = restrictFixityMap (`member` allExports) thisFixityMap,
-- TODO - this contains unexported names, we should filter these before writing to disk.
--hoKinds = restrictKindEnv (`member` allExports) kindInfo,
hoKinds = externalKindEnv,
hoClassHierarchy = smallClassHierarchy,
hoFieldMap = buildFieldMap ms,
hoTypeSynonyms = restrictTypeSynonyms (`member` allExports) thisTypeSynonyms
}
tiData = TiData {
tiDataDecls = tcDs ++ filter isHsClassDecl ds,
tiDataModules = [ (modInfoName m, modInfoHsModule m) | m <- ms],
tiModuleOptions = [ (modInfoName m, modInfoOptions m) | m <- ms],
tiCheckedRules = checkedRules,
tiCoerce = coercions,
tiProps = pragmaProps,
tiAllAssumptions = allAssumps
}
processIOErrors
return (hoEx,tiData)
| dec9ue/jhc_copygc | src/FrontEnd/Tc/Module.hs | gpl-2.0 | 13,185 | 32 | 22 | 3,406 | 3,740 | 1,961 | 1,779 | -1 | -1 |
{-
This source file is a part of the noisefunge programming environment.
Copyright (C) 2015 Rev. Johnny Healey <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
import Language.NoiseFunge.API
main :: IO ()
main = do
withAPIConnection requestReset
| wolfspyre/noisefunge | nfreset/nfreset.hs | gpl-3.0 | 890 | 1 | 7 | 191 | 32 | 15 | 17 | 4 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
@Uniques@ are used to distinguish entities in the compiler (@Ids@,
@Classes@, etc.) from each other. Thus, @Uniques@ are the basic
comparison key in the compiler.
If there is any single operation that needs to be fast, it is @Unique@
comparison. Unsurprisingly, there is quite a bit of huff-and-puff
directed to that end.
Some of the other hair in this code is to be able to use a
``splittable @UniqueSupply@'' if requested/possible (not standard
Haskell).
-}
{-# LANGUAGE CPP, BangPatterns, MagicHash #-}
module Unique (
-- * Main data types
Unique, Uniquable(..),
-- ** Constructors, desctructors and operations on 'Unique's
hasKey, cmpByUnique,
pprUnique,
mkUniqueGrimily, -- Used in UniqSupply only!
getKey, -- Used in Var, UniqFM, Name only!
mkUnique, unpkUnique, -- Used in BinIface only
incrUnique, -- Used for renumbering
deriveUnique, -- Ditto
newTagUnique, -- Used in CgCase
initTyVarUnique,
-- ** Making built-in uniques
-- now all the built-in Uniques (and functions to make them)
-- [the Oh-So-Wonderful Haskell module system wins again...]
mkAlphaTyVarUnique,
mkPrimOpIdUnique,
mkTupleTyConUnique, mkTupleDataConUnique,
mkCTupleTyConUnique,
mkPreludeMiscIdUnique, mkPreludeDataConUnique,
mkPreludeTyConUnique, mkPreludeClassUnique,
mkPArrDataConUnique, mkCoVarUnique,
mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique,
mkRegSingleUnique, mkRegPairUnique, mkRegClassUnique, mkRegSubUnique,
mkCostCentreUnique,
tyConRepNameUnique,
dataConWorkerUnique, dataConRepNameUnique,
mkBuiltinUnique,
mkPseudoUniqueD,
mkPseudoUniqueE,
mkPseudoUniqueH
) where
#include "HsVersions.h"
import BasicTypes
import FastString
import Outputable
import Util
-- just for implementing a fast [0,61) -> Char function
import GHC.Exts (indexCharOffAddr#, Char(..), Int(..))
import Data.Char ( chr, ord )
import Data.Bits
{-
************************************************************************
* *
\subsection[Unique-type]{@Unique@ type and operations}
* *
************************************************************************
The @Chars@ are ``tag letters'' that identify the @UniqueSupply@.
Fast comparison is everything on @Uniques@:
-}
--why not newtype Int?
-- | The type of unique identifiers that are used in many places in GHC
-- for fast ordering and equality tests. You should generate these with
-- the functions from the 'UniqSupply' module
data Unique = MkUnique {-# UNPACK #-} !Int
{-
Now come the functions which construct uniques from their pieces, and vice versa.
The stuff about unique *supplies* is handled further down this module.
-}
unpkUnique :: Unique -> (Char, Int) -- The reverse
mkUniqueGrimily :: Int -> Unique -- A trap-door for UniqSupply
getKey :: Unique -> Int -- for Var
incrUnique :: Unique -> Unique
stepUnique :: Unique -> Int -> Unique
deriveUnique :: Unique -> Int -> Unique
newTagUnique :: Unique -> Char -> Unique
mkUniqueGrimily = MkUnique
{-# INLINE getKey #-}
getKey (MkUnique x) = x
incrUnique (MkUnique i) = MkUnique (i + 1)
stepUnique (MkUnique i) n = MkUnique (i + n)
-- deriveUnique uses an 'X' tag so that it won't clash with
-- any of the uniques produced any other way
-- SPJ says: this looks terribly smelly to me!
deriveUnique (MkUnique i) delta = mkUnique 'X' (i + delta)
-- newTagUnique changes the "domain" of a unique to a different char
newTagUnique u c = mkUnique c i where (_,i) = unpkUnique u
-- pop the Char in the top 8 bits of the Unique(Supply)
-- No 64-bit bugs here, as long as we have at least 32 bits. --JSM
-- and as long as the Char fits in 8 bits, which we assume anyway!
mkUnique :: Char -> Int -> Unique -- Builds a unique from pieces
-- NOT EXPORTED, so that we can see all the Chars that
-- are used in this one module
mkUnique c i
= MkUnique (tag .|. bits)
where
tag = ord c `shiftL` 24
bits = i .&. 16777215 {-``0x00ffffff''-}
unpkUnique (MkUnique u)
= let
-- as long as the Char may have its eighth bit set, we
-- really do need the logical right-shift here!
tag = chr (u `shiftR` 24)
i = u .&. 16777215 {-``0x00ffffff''-}
in
(tag, i)
{-
************************************************************************
* *
\subsection[Uniquable-class]{The @Uniquable@ class}
* *
************************************************************************
-}
-- | Class of things that we can obtain a 'Unique' from
class Uniquable a where
getUnique :: a -> Unique
hasKey :: Uniquable a => a -> Unique -> Bool
x `hasKey` k = getUnique x == k
instance Uniquable FastString where
getUnique fs = mkUniqueGrimily (uniqueOfFS fs)
instance Uniquable Int where
getUnique i = mkUniqueGrimily i
cmpByUnique :: Uniquable a => a -> a -> Ordering
cmpByUnique x y = (getUnique x) `cmpUnique` (getUnique y)
{-
************************************************************************
* *
\subsection[Unique-instances]{Instance declarations for @Unique@}
* *
************************************************************************
And the whole point (besides uniqueness) is fast equality. We don't
use `deriving' because we want {\em precise} control of ordering
(equality on @Uniques@ is v common).
-}
-- Note [Unique Determinism]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~
-- The order of allocated @Uniques@ is not stable across rebuilds.
-- The main reason for that is that typechecking interface files pulls
-- @Uniques@ from @UniqSupply@ and the interface file for the module being
-- currently compiled can, but doesn't have to exist.
--
-- It gets more complicated if you take into account that the interface
-- files are loaded lazily and that building multiple files at once has to
-- work for any subset of interface files present. When you add parallelism
-- this makes @Uniques@ hopelessly random.
--
-- As such, to get deterministic builds, the order of the allocated
-- @Uniques@ should not affect the final result.
-- see also wiki/DeterministicBuilds
eqUnique, ltUnique, leUnique :: Unique -> Unique -> Bool
eqUnique (MkUnique u1) (MkUnique u2) = u1 == u2
ltUnique (MkUnique u1) (MkUnique u2) = u1 < u2
leUnique (MkUnique u1) (MkUnique u2) = u1 <= u2
cmpUnique :: Unique -> Unique -> Ordering
cmpUnique (MkUnique u1) (MkUnique u2)
= if u1 == u2 then EQ else if u1 < u2 then LT else GT
instance Eq Unique where
a == b = eqUnique a b
a /= b = not (eqUnique a b)
instance Ord Unique where
a < b = ltUnique a b
a <= b = leUnique a b
a > b = not (leUnique a b)
a >= b = not (ltUnique a b)
compare a b = cmpUnique a b
-----------------
instance Uniquable Unique where
getUnique u = u
-- We do sometimes make strings with @Uniques@ in them:
showUnique :: Unique -> String
showUnique uniq
= case unpkUnique uniq of
(tag, u) -> finish_show tag u (iToBase62 u)
finish_show :: Char -> Int -> String -> String
finish_show 't' u _pp_u | u < 26
= -- Special case to make v common tyvars, t1, t2, ...
-- come out as a, b, ... (shorter, easier to read)
[chr (ord 'a' + u)]
finish_show tag _ pp_u = tag : pp_u
pprUnique :: Unique -> SDoc
pprUnique u = text (showUnique u)
instance Outputable Unique where
ppr = pprUnique
instance Show Unique where
show uniq = showUnique uniq
{-
************************************************************************
* *
\subsection[Utils-base62]{Base-62 numbers}
* *
************************************************************************
A character-stingy way to read/write numbers (notably Uniques).
The ``62-its'' are \tr{[0-9a-zA-Z]}. We don't handle negative Ints.
Code stolen from Lennart.
-}
iToBase62 :: Int -> String
iToBase62 n_
= ASSERT(n_ >= 0) go n_ ""
where
go n cs | n < 62
= let !c = chooseChar62 n in c : cs
| otherwise
= go q (c : cs) where (q, r) = quotRem n 62
!c = chooseChar62 r
chooseChar62 :: Int -> Char
{-# INLINE chooseChar62 #-}
chooseChar62 (I# n) = C# (indexCharOffAddr# chars62 n)
chars62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"#
{-
************************************************************************
* *
\subsection[Uniques-prelude]{@Uniques@ for wired-in Prelude things}
* *
************************************************************************
Allocation of unique supply characters:
v,t,u : for renumbering value-, type- and usage- vars.
B: builtin
C-E: pseudo uniques (used in native-code generator)
X: uniques derived by deriveUnique
_: unifiable tyvars (above)
0-9: prelude things below
(no numbers left any more..)
:: (prelude) parallel array data constructors
other a-z: lower case chars for unique supplies. Used so far:
d desugarer
f AbsC flattener
g SimplStg
n Native codegen
r Hsc name cache
s simplifier
-}
mkAlphaTyVarUnique :: Int -> Unique
mkPreludeClassUnique :: Int -> Unique
mkPreludeTyConUnique :: Int -> Unique
mkTupleTyConUnique :: Boxity -> Arity -> Unique
mkCTupleTyConUnique :: Arity -> Unique
mkPreludeDataConUnique :: Arity -> Unique
mkTupleDataConUnique :: Boxity -> Arity -> Unique
mkPrimOpIdUnique :: Int -> Unique
mkPreludeMiscIdUnique :: Int -> Unique
mkPArrDataConUnique :: Int -> Unique
mkCoVarUnique :: Int -> Unique
mkAlphaTyVarUnique i = mkUnique '1' i
mkCoVarUnique i = mkUnique 'g' i
mkPreludeClassUnique i = mkUnique '2' i
--------------------------------------------------
-- Wired-in type constructor keys occupy *two* slots:
-- * u: the TyCon itself
-- * u+1: the TyConRepName of the TyCon
mkPreludeTyConUnique i = mkUnique '3' (2*i)
mkTupleTyConUnique Boxed a = mkUnique '4' (2*a)
mkTupleTyConUnique Unboxed a = mkUnique '5' (2*a)
mkCTupleTyConUnique a = mkUnique 'k' (2*a)
tyConRepNameUnique :: Unique -> Unique
tyConRepNameUnique u = incrUnique u
-- Data constructor keys occupy *two* slots. The first is used for the
-- data constructor itself and its wrapper function (the function that
-- evaluates arguments as necessary and calls the worker). The second is
-- used for the worker function (the function that builds the constructor
-- representation).
--------------------------------------------------
-- Wired-in data constructor keys occupy *three* slots:
-- * u: the DataCon itself
-- * u+1: its worker Id
-- * u+2: the TyConRepName of the promoted TyCon
-- Prelude data constructors are too simple to need wrappers.
mkPreludeDataConUnique i = mkUnique '6' (3*i) -- Must be alphabetic
mkTupleDataConUnique Boxed a = mkUnique '7' (3*a) -- ditto (*may* be used in C labels)
mkTupleDataConUnique Unboxed a = mkUnique '8' (3*a)
dataConRepNameUnique, dataConWorkerUnique :: Unique -> Unique
dataConWorkerUnique u = incrUnique u
dataConRepNameUnique u = stepUnique u 2
--------------------------------------------------
mkPrimOpIdUnique op = mkUnique '9' op
mkPreludeMiscIdUnique i = mkUnique '0' i
-- No numbers left anymore, so I pick something different for the character tag
mkPArrDataConUnique a = mkUnique ':' (2*a)
-- The "tyvar uniques" print specially nicely: a, b, c, etc.
-- See pprUnique for details
initTyVarUnique :: Unique
initTyVarUnique = mkUnique 't' 0
mkPseudoUniqueD, mkPseudoUniqueE, mkPseudoUniqueH,
mkBuiltinUnique :: Int -> Unique
mkBuiltinUnique i = mkUnique 'B' i
mkPseudoUniqueD i = mkUnique 'D' i -- used in NCG for getUnique on RealRegs
mkPseudoUniqueE i = mkUnique 'E' i -- used in NCG spiller to create spill VirtualRegs
mkPseudoUniqueH i = mkUnique 'H' i -- used in NCG spiller to create spill VirtualRegs
mkRegSingleUnique, mkRegPairUnique, mkRegSubUnique, mkRegClassUnique :: Int -> Unique
mkRegSingleUnique = mkUnique 'R'
mkRegSubUnique = mkUnique 'S'
mkRegPairUnique = mkUnique 'P'
mkRegClassUnique = mkUnique 'L'
mkCostCentreUnique :: Int -> Unique
mkCostCentreUnique = mkUnique 'C'
mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique :: FastString -> Unique
-- See Note [The Unique of an OccName] in OccName
mkVarOccUnique fs = mkUnique 'i' (uniqueOfFS fs)
mkDataOccUnique fs = mkUnique 'd' (uniqueOfFS fs)
mkTvOccUnique fs = mkUnique 'v' (uniqueOfFS fs)
mkTcOccUnique fs = mkUnique 'c' (uniqueOfFS fs)
| nushio3/ghc | compiler/basicTypes/Unique.hs | bsd-3-clause | 13,652 | 0 | 12 | 3,576 | 2,043 | 1,112 | 931 | 163 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Setup
-- Copyright : Isaac Jones 2003-2004
-- Duncan Coutts 2007
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This is a big module, but not very complicated. The code is very regular
-- and repetitive. It defines the command line interface for all the Cabal
-- commands. For each command (like @configure@, @build@ etc) it defines a type
-- that holds all the flags, the default set of flags and a 'CommandUI' that
-- maps command line flags to and from the corresponding flags type.
--
-- All the flags types are instances of 'Monoid', see
-- <http://www.haskell.org/pipermail/cabal-devel/2007-December/001509.html>
-- for an explanation.
--
-- The types defined here get used in the front end and especially in
-- @cabal-install@ which has to do quite a bit of manipulating sets of command
-- line flags.
--
-- This is actually relatively nice, it works quite well. The main change it
-- needs is to unify it with the code for managing sets of fields that can be
-- read and written from files. This would allow us to save configure flags in
-- config files.
module Distribution.Simple.Setup (
GlobalFlags(..), emptyGlobalFlags, defaultGlobalFlags, globalCommand,
ConfigFlags(..), emptyConfigFlags, defaultConfigFlags, configureCommand,
configAbsolutePaths, readPackageDbList, showPackageDbList,
CopyFlags(..), emptyCopyFlags, defaultCopyFlags, copyCommand,
InstallFlags(..), emptyInstallFlags, defaultInstallFlags, installCommand,
HaddockFlags(..), emptyHaddockFlags, defaultHaddockFlags, haddockCommand,
HscolourFlags(..), emptyHscolourFlags, defaultHscolourFlags, hscolourCommand,
BuildFlags(..), emptyBuildFlags, defaultBuildFlags, buildCommand,
buildVerbose,
ReplFlags(..), defaultReplFlags, replCommand,
CleanFlags(..), emptyCleanFlags, defaultCleanFlags, cleanCommand,
RegisterFlags(..), emptyRegisterFlags, defaultRegisterFlags, registerCommand,
unregisterCommand,
SDistFlags(..), emptySDistFlags, defaultSDistFlags, sdistCommand,
TestFlags(..), emptyTestFlags, defaultTestFlags, testCommand,
TestShowDetails(..),
BenchmarkFlags(..), emptyBenchmarkFlags,
defaultBenchmarkFlags, benchmarkCommand,
CopyDest(..),
configureArgs, configureOptions, configureCCompiler, configureLinker,
buildOptions, haddockOptions, installDirsOptions,
programConfigurationOptions, programConfigurationPaths',
splitArgs,
defaultDistPref, optionDistPref,
Flag(..),
toFlag,
fromFlag,
fromFlagOrDefault,
flagToMaybe,
flagToList,
boolOpt, boolOpt', trueArg, falseArg, optionVerbosity, optionNumJobs ) where
import Distribution.Compiler ()
import Distribution.ReadE
import Distribution.Text
( Text(..), display )
import qualified Distribution.Compat.ReadP as Parse
import qualified Text.PrettyPrint as Disp
import Distribution.ModuleName
import Distribution.Package ( Dependency(..)
, PackageName
, ComponentId(..) )
import Distribution.PackageDescription
( FlagName(..), FlagAssignment )
import Distribution.Simple.Command hiding (boolOpt, boolOpt')
import qualified Distribution.Simple.Command as Command
import Distribution.Simple.Compiler
( CompilerFlavor(..), defaultCompilerFlavor, PackageDB(..)
, DebugInfoLevel(..), flagToDebugInfoLevel
, OptimisationLevel(..), flagToOptimisationLevel
, ProfDetailLevel(..), flagToProfDetailLevel, showProfDetailLevel
, absolutePackageDBPath )
import Distribution.Simple.Utils
( wrapText, wrapLine, lowercase, intercalate )
import Distribution.Simple.Program (Program(..), ProgramConfiguration,
requireProgram,
programInvocation, progInvokePath, progInvokeArgs,
knownPrograms,
addKnownProgram, emptyProgramConfiguration,
haddockProgram, ghcProgram, gccProgram, ldProgram)
import Distribution.Simple.InstallDirs
( InstallDirs(..), CopyDest(..),
PathTemplate, toPathTemplate, fromPathTemplate )
import Distribution.Verbosity
import Distribution.Utils.NubList
import Control.Monad (liftM)
import Distribution.Compat.Binary (Binary)
import Distribution.Compat.Semigroup as Semi
import Data.List ( sort )
import Data.Char ( isSpace, isAlpha )
import GHC.Generics (Generic)
-- FIXME Not sure where this should live
defaultDistPref :: FilePath
defaultDistPref = "dist"
-- ------------------------------------------------------------
-- * Flag type
-- ------------------------------------------------------------
-- | All flags are monoids, they come in two flavours:
--
-- 1. list flags eg
--
-- > --ghc-option=foo --ghc-option=bar
--
-- gives us all the values ["foo", "bar"]
--
-- 2. singular value flags, eg:
--
-- > --enable-foo --disable-foo
--
-- gives us Just False
-- So this Flag type is for the latter singular kind of flag.
-- Its monoid instance gives us the behaviour where it starts out as
-- 'NoFlag' and later flags override earlier ones.
--
data Flag a = Flag a | NoFlag deriving (Eq, Generic, Show, Read)
instance Binary a => Binary (Flag a)
instance Functor Flag where
fmap f (Flag x) = Flag (f x)
fmap _ NoFlag = NoFlag
instance Monoid (Flag a) where
mempty = NoFlag
mappend = (Semi.<>)
instance Semigroup (Flag a) where
_ <> f@(Flag _) = f
f <> NoFlag = f
instance Bounded a => Bounded (Flag a) where
minBound = toFlag minBound
maxBound = toFlag maxBound
instance Enum a => Enum (Flag a) where
fromEnum = fromEnum . fromFlag
toEnum = toFlag . toEnum
enumFrom (Flag a) = map toFlag . enumFrom $ a
enumFrom _ = []
enumFromThen (Flag a) (Flag b) = toFlag `map` enumFromThen a b
enumFromThen _ _ = []
enumFromTo (Flag a) (Flag b) = toFlag `map` enumFromTo a b
enumFromTo _ _ = []
enumFromThenTo (Flag a) (Flag b) (Flag c) = toFlag `map` enumFromThenTo a b c
enumFromThenTo _ _ _ = []
toFlag :: a -> Flag a
toFlag = Flag
fromFlag :: Flag a -> a
fromFlag (Flag x) = x
fromFlag NoFlag = error "fromFlag NoFlag. Use fromFlagOrDefault"
fromFlagOrDefault :: a -> Flag a -> a
fromFlagOrDefault _ (Flag x) = x
fromFlagOrDefault def NoFlag = def
flagToMaybe :: Flag a -> Maybe a
flagToMaybe (Flag x) = Just x
flagToMaybe NoFlag = Nothing
flagToList :: Flag a -> [a]
flagToList (Flag x) = [x]
flagToList NoFlag = []
allFlags :: [Flag Bool] -> Flag Bool
allFlags flags = if all (\f -> fromFlagOrDefault False f) flags
then Flag True
else NoFlag
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------
-- In fact since individual flags types are monoids and these are just sets of
-- flags then they are also monoids pointwise. This turns out to be really
-- useful. The mempty is the set of empty flags and mappend allows us to
-- override specific flags. For example we can start with default flags and
-- override with the ones we get from a file or the command line, or both.
-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
globalVersion :: Flag Bool,
globalNumericVersion :: Flag Bool
}
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags = GlobalFlags {
globalVersion = Flag False,
globalNumericVersion = Flag False
}
globalCommand :: [Command action] -> CommandUI GlobalFlags
globalCommand commands = CommandUI
{ commandName = ""
, commandSynopsis = ""
, commandUsage = \pname ->
"This Setup program uses the Haskell Cabal Infrastructure.\n"
++ "See http://www.haskell.org/cabal/ for more information.\n"
++ "\n"
++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n"
, commandDescription = Just $ \pname ->
let
commands' = commands ++ [commandAddAction helpCommandUI undefined]
cmdDescs = getNormalCommandDescriptions commands'
maxlen = maximum $ [length name | (name, _) <- cmdDescs]
align str = str ++ replicate (maxlen - length str) ' '
in
"Commands:\n"
++ unlines [ " " ++ align name ++ " " ++ description
| (name, description) <- cmdDescs ]
++ "\n"
++ "For more information about a command use\n"
++ " " ++ pname ++ " COMMAND --help\n\n"
++ "Typical steps for installing Cabal packages:\n"
++ concat [ " " ++ pname ++ " " ++ x ++ "\n"
| x <- ["configure", "build", "install"]]
, commandNotes = Nothing
, commandDefaultFlags = defaultGlobalFlags
, commandOptions = \_ ->
[option ['V'] ["version"]
"Print version information"
globalVersion (\v flags -> flags { globalVersion = v })
trueArg
,option [] ["numeric-version"]
"Print just the version number"
globalNumericVersion (\v flags -> flags { globalNumericVersion = v })
trueArg
]
}
emptyGlobalFlags :: GlobalFlags
emptyGlobalFlags = mempty
instance Monoid GlobalFlags where
mempty = GlobalFlags {
globalVersion = mempty,
globalNumericVersion = mempty
}
mappend = (Semi.<>)
instance Semigroup GlobalFlags where
a <> b = GlobalFlags {
globalVersion = combine globalVersion,
globalNumericVersion = combine globalNumericVersion
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Config flags
-- ------------------------------------------------------------
-- | Flags to @configure@ command.
--
-- IMPORTANT: every time a new flag is added, 'D.C.Setup.filterConfigureFlags'
-- should be updated.
data ConfigFlags = ConfigFlags {
--FIXME: the configPrograms is only here to pass info through to configure
-- because the type of configure is constrained by the UserHooks.
-- when we change UserHooks next we should pass the initial
-- ProgramConfiguration directly and not via ConfigFlags
configPrograms :: ProgramConfiguration, -- ^All programs that cabal may
-- run
configProgramPaths :: [(String, FilePath)], -- ^user specified programs paths
configProgramArgs :: [(String, [String])], -- ^user specified programs args
configProgramPathExtra :: NubList FilePath, -- ^Extend the $PATH
configHcFlavor :: Flag CompilerFlavor, -- ^The \"flavor\" of the
-- compiler, such as GHC or
-- JHC.
configHcPath :: Flag FilePath, -- ^given compiler location
configHcPkg :: Flag FilePath, -- ^given hc-pkg location
configVanillaLib :: Flag Bool, -- ^Enable vanilla library
configProfLib :: Flag Bool, -- ^Enable profiling in the library
configSharedLib :: Flag Bool, -- ^Build shared library
configDynExe :: Flag Bool, -- ^Enable dynamic linking of the
-- executables.
configProfExe :: Flag Bool, -- ^Enable profiling in the
-- executables.
configProf :: Flag Bool, -- ^Enable profiling in the library
-- and executables.
configProfDetail :: Flag ProfDetailLevel, -- ^Profiling detail level
-- in the library and executables.
configProfLibDetail :: Flag ProfDetailLevel, -- ^Profiling detail level
-- in the library
configConfigureArgs :: [String], -- ^Extra arguments to @configure@
configOptimization :: Flag OptimisationLevel, -- ^Enable optimization.
configProgPrefix :: Flag PathTemplate, -- ^Installed executable prefix.
configProgSuffix :: Flag PathTemplate, -- ^Installed executable suffix.
configInstallDirs :: InstallDirs (Flag PathTemplate), -- ^Installation
-- paths
configScratchDir :: Flag FilePath,
configExtraLibDirs :: [FilePath], -- ^ path to search for extra libraries
configExtraIncludeDirs :: [FilePath], -- ^ path to search for header files
configIPID :: Flag String, -- ^ explicit IPID to be used
configDistPref :: Flag FilePath, -- ^"dist" prefix
configVerbosity :: Flag Verbosity, -- ^verbosity level
configUserInstall :: Flag Bool, -- ^The --user\/--global flag
configPackageDBs :: [Maybe PackageDB], -- ^Which package DBs to use
configGHCiLib :: Flag Bool, -- ^Enable compiling library for GHCi
configSplitObjs :: Flag Bool, -- ^Enable -split-objs with GHC
configStripExes :: Flag Bool, -- ^Enable executable stripping
configStripLibs :: Flag Bool, -- ^Enable library stripping
configConstraints :: [Dependency], -- ^Additional constraints for
-- dependencies.
configDependencies :: [(PackageName, ComponentId)],
configInstantiateWith :: [(ModuleName, (ComponentId, ModuleName))],
-- ^The packages depended on.
configConfigurationsFlags :: FlagAssignment,
configTests :: Flag Bool, -- ^Enable test suite compilation
configBenchmarks :: Flag Bool, -- ^Enable benchmark compilation
configCoverage :: Flag Bool, -- ^Enable program coverage
configLibCoverage :: Flag Bool, -- ^Enable program coverage (deprecated)
configExactConfiguration :: Flag Bool,
-- ^All direct dependencies and flags are provided on the command line by
-- the user via the '--dependency' and '--flags' options.
configFlagError :: Flag String,
-- ^Halt and show an error message indicating an error in flag assignment
configRelocatable :: Flag Bool, -- ^ Enable relocatable package built
configDebugInfo :: Flag DebugInfoLevel -- ^ Emit debug info.
}
deriving (Generic, Read, Show)
instance Binary ConfigFlags
configAbsolutePaths :: ConfigFlags -> IO ConfigFlags
configAbsolutePaths f =
(\v -> f { configPackageDBs = v })
`liftM` mapM (maybe (return Nothing) (liftM Just . absolutePackageDBPath))
(configPackageDBs f)
defaultConfigFlags :: ProgramConfiguration -> ConfigFlags
defaultConfigFlags progConf = emptyConfigFlags {
configPrograms = progConf,
configHcFlavor = maybe NoFlag Flag defaultCompilerFlavor,
configVanillaLib = Flag True,
configProfLib = NoFlag,
configSharedLib = NoFlag,
configDynExe = Flag False,
configProfExe = NoFlag,
configProf = NoFlag,
configProfDetail = NoFlag,
configProfLibDetail= NoFlag,
configOptimization = Flag NormalOptimisation,
configProgPrefix = Flag (toPathTemplate ""),
configProgSuffix = Flag (toPathTemplate ""),
configDistPref = NoFlag,
configVerbosity = Flag normal,
configUserInstall = Flag False, --TODO: reverse this
#if defined(mingw32_HOST_OS)
-- See #1589.
configGHCiLib = Flag True,
#else
configGHCiLib = NoFlag,
#endif
configSplitObjs = Flag False, -- takes longer, so turn off by default
configStripExes = Flag True,
configStripLibs = Flag True,
configTests = Flag False,
configBenchmarks = Flag False,
configCoverage = Flag False,
configLibCoverage = NoFlag,
configExactConfiguration = Flag False,
configFlagError = NoFlag,
configRelocatable = Flag False,
configDebugInfo = Flag NoDebugInfo
}
configureCommand :: ProgramConfiguration -> CommandUI ConfigFlags
configureCommand progConf = CommandUI
{ commandName = "configure"
, commandSynopsis = "Prepare to build the package."
, commandDescription = Just $ \_ -> wrapText $
"Configure how the package is built by setting "
++ "package (and other) flags.\n"
++ "\n"
++ "The configuration affects several other commands, "
++ "including build, test, bench, run, repl.\n"
, commandNotes = Just $ \_pname -> programFlagsDescription progConf
, commandUsage = \pname ->
"Usage: " ++ pname ++ " configure [FLAGS]\n"
, commandDefaultFlags = defaultConfigFlags progConf
, commandOptions = \showOrParseArgs ->
configureOptions showOrParseArgs
++ programConfigurationPaths progConf showOrParseArgs
configProgramPaths (\v fs -> fs { configProgramPaths = v })
++ programConfigurationOption progConf showOrParseArgs
configProgramArgs (\v fs -> fs { configProgramArgs = v })
++ programConfigurationOptions progConf showOrParseArgs
configProgramArgs (\v fs -> fs { configProgramArgs = v })
}
configureOptions :: ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions showOrParseArgs =
[optionVerbosity configVerbosity
(\v flags -> flags { configVerbosity = v })
,optionDistPref
configDistPref (\d flags -> flags { configDistPref = d })
showOrParseArgs
,option [] ["compiler"] "compiler"
configHcFlavor (\v flags -> flags { configHcFlavor = v })
(choiceOpt [ (Flag GHC, ("g", ["ghc"]), "compile with GHC")
, (Flag GHCJS, ([] , ["ghcjs"]), "compile with GHCJS")
, (Flag JHC, ([] , ["jhc"]), "compile with JHC")
, (Flag LHC, ([] , ["lhc"]), "compile with LHC")
, (Flag UHC, ([] , ["uhc"]), "compile with UHC")
-- "haskell-suite" compiler id string will be replaced
-- by a more specific one during the configure stage
, (Flag (HaskellSuite "haskell-suite"), ([] , ["haskell-suite"]),
"compile with a haskell-suite compiler")])
,option "w" ["with-compiler"]
"give the path to a particular compiler"
configHcPath (\v flags -> flags { configHcPath = v })
(reqArgFlag "PATH")
,option "" ["with-hc-pkg"]
"give the path to the package tool"
configHcPkg (\v flags -> flags { configHcPkg = v })
(reqArgFlag "PATH")
]
++ map liftInstallDirs installDirsOptions
++ [option "" ["program-prefix"]
"prefix to be applied to installed executables"
configProgPrefix
(\v flags -> flags { configProgPrefix = v })
(reqPathTemplateArgFlag "PREFIX")
,option "" ["program-suffix"]
"suffix to be applied to installed executables"
configProgSuffix (\v flags -> flags { configProgSuffix = v } )
(reqPathTemplateArgFlag "SUFFIX")
,option "" ["library-vanilla"]
"Vanilla libraries"
configVanillaLib (\v flags -> flags { configVanillaLib = v })
(boolOpt [] [])
,option "p" ["library-profiling"]
"Library profiling"
configProfLib (\v flags -> flags { configProfLib = v })
(boolOpt "p" [])
,option "" ["shared"]
"Shared library"
configSharedLib (\v flags -> flags { configSharedLib = v })
(boolOpt [] [])
,option "" ["executable-dynamic"]
"Executable dynamic linking"
configDynExe (\v flags -> flags { configDynExe = v })
(boolOpt [] [])
,option "" ["profiling"]
"Executable and library profiling"
configProf (\v flags -> flags { configProf = v })
(boolOpt [] [])
,option "" ["executable-profiling"]
"Executable profiling (DEPRECATED)"
configProfExe (\v flags -> flags { configProfExe = v })
(boolOpt [] [])
,option "" ["profiling-detail"]
("Profiling detail level for executable and library (default, " ++
"none, exported-functions, toplevel-functions, all-functions).")
configProfDetail (\v flags -> flags { configProfDetail = v })
(reqArg' "level" (Flag . flagToProfDetailLevel)
showProfDetailLevelFlag)
,option "" ["library-profiling-detail"]
"Profiling detail level for libraries only."
configProfLibDetail (\v flags -> flags { configProfLibDetail = v })
(reqArg' "level" (Flag . flagToProfDetailLevel)
showProfDetailLevelFlag)
,multiOption "optimization"
configOptimization (\v flags -> flags { configOptimization = v })
[optArg' "n" (Flag . flagToOptimisationLevel)
(\f -> case f of
Flag NoOptimisation -> []
Flag NormalOptimisation -> [Nothing]
Flag MaximumOptimisation -> [Just "2"]
_ -> [])
"O" ["enable-optimization","enable-optimisation"]
"Build with optimization (n is 0--2, default is 1)",
noArg (Flag NoOptimisation) []
["disable-optimization","disable-optimisation"]
"Build without optimization"
]
,multiOption "debug-info"
configDebugInfo (\v flags -> flags { configDebugInfo = v })
[optArg' "n" (Flag . flagToDebugInfoLevel)
(\f -> case f of
Flag NoDebugInfo -> []
Flag MinimalDebugInfo -> [Just "1"]
Flag NormalDebugInfo -> [Nothing]
Flag MaximalDebugInfo -> [Just "3"]
_ -> [])
"" ["enable-debug-info"]
"Emit debug info (n is 0--3, default is 0)",
noArg (Flag NoDebugInfo) []
["disable-debug-info"]
"Don't emit debug info"
]
,option "" ["library-for-ghci"]
"compile library for use with GHCi"
configGHCiLib (\v flags -> flags { configGHCiLib = v })
(boolOpt [] [])
,option "" ["split-objs"]
"split library into smaller objects to reduce binary sizes (GHC 6.6+)"
configSplitObjs (\v flags -> flags { configSplitObjs = v })
(boolOpt [] [])
,option "" ["executable-stripping"]
"strip executables upon installation to reduce binary sizes"
configStripExes (\v flags -> flags { configStripExes = v })
(boolOpt [] [])
,option "" ["library-stripping"]
"strip libraries upon installation to reduce binary sizes"
configStripLibs (\v flags -> flags { configStripLibs = v })
(boolOpt [] [])
,option "" ["configure-option"]
"Extra option for configure"
configConfigureArgs (\v flags -> flags { configConfigureArgs = v })
(reqArg' "OPT" (\x -> [x]) id)
,option "" ["user-install"]
"doing a per-user installation"
configUserInstall (\v flags -> flags { configUserInstall = v })
(boolOpt' ([],["user"]) ([], ["global"]))
,option "" ["package-db"]
( "Append the given package database to the list of package"
++ " databases used (to satisfy dependencies and register into)."
++ " May be a specific file, 'global' or 'user'. The initial list"
++ " is ['global'], ['global', 'user'], or ['global', $sandbox],"
++ " depending on context. Use 'clear' to reset the list to empty."
++ " See the user guide for details.")
configPackageDBs (\v flags -> flags { configPackageDBs = v })
(reqArg' "DB" readPackageDbList showPackageDbList)
,option "f" ["flags"]
"Force values for the given flags in Cabal conditionals in the .cabal file. E.g., --flags=\"debug -usebytestrings\" forces the flag \"debug\" to true and \"usebytestrings\" to false."
configConfigurationsFlags (\v flags -> flags { configConfigurationsFlags = v })
(reqArg' "FLAGS" readFlagList showFlagList)
,option "" ["extra-include-dirs"]
"A list of directories to search for header files"
configExtraIncludeDirs (\v flags -> flags {configExtraIncludeDirs = v})
(reqArg' "PATH" (\x -> [x]) id)
,option "" ["ipid"]
"Installed package ID to compile this package as"
configIPID (\v flags -> flags {configIPID = v})
(reqArgFlag "IPID")
,option "" ["extra-lib-dirs"]
"A list of directories to search for external libraries"
configExtraLibDirs (\v flags -> flags {configExtraLibDirs = v})
(reqArg' "PATH" (\x -> [x]) id)
,option "" ["extra-prog-path"]
"A list of directories to search for required programs (in addition to the normal search locations)"
configProgramPathExtra (\v flags -> flags {configProgramPathExtra = v})
(reqArg' "PATH" (\x -> toNubList [x]) fromNubList)
,option "" ["constraint"]
"A list of additional constraints on the dependencies."
configConstraints (\v flags -> flags { configConstraints = v})
(reqArg "DEPENDENCY"
(readP_to_E (const "dependency expected") ((\x -> [x]) `fmap` parse))
(map (\x -> display x)))
,option "" ["dependency"]
"A list of exact dependencies. E.g., --dependency=\"void=void-0.5.8-177d5cdf20962d0581fe2e4932a6c309\""
configDependencies (\v flags -> flags { configDependencies = v})
(reqArg "NAME=ID"
(readP_to_E (const "dependency expected") ((\x -> [x]) `fmap` parseDependency))
(map (\x -> display (fst x) ++ "=" ++ display (snd x))))
,option "" ["instantiate-with"]
"A mapping of signature names to concrete module instantiations. E.g., --instantiate-with=\"[email protected]\""
configInstantiateWith (\v flags -> flags { configInstantiateWith = v })
(reqArg "NAME=PKG:MOD"
(readP_to_E (const "signature mapping expected") ((\x -> [x]) `fmap` parseHoleMapEntry))
(map (\(n,(p,m)) -> display n ++ "=" ++ display m ++ "@" ++ display p)))
,option "" ["tests"]
"dependency checking and compilation for test suites listed in the package description file."
configTests (\v flags -> flags { configTests = v })
(boolOpt [] [])
,option "" ["coverage"]
"build package with Haskell Program Coverage. (GHC only)"
configCoverage (\v flags -> flags { configCoverage = v })
(boolOpt [] [])
,option "" ["library-coverage"]
"build package with Haskell Program Coverage. (GHC only) (DEPRECATED)"
configLibCoverage (\v flags -> flags { configLibCoverage = v })
(boolOpt [] [])
,option "" ["exact-configuration"]
"All direct dependencies and flags are provided on the command line."
configExactConfiguration
(\v flags -> flags { configExactConfiguration = v })
trueArg
,option "" ["benchmarks"]
"dependency checking and compilation for benchmarks listed in the package description file."
configBenchmarks (\v flags -> flags { configBenchmarks = v })
(boolOpt [] [])
,option "" ["relocatable"]
"building a package that is relocatable. (GHC only)"
configRelocatable (\v flags -> flags { configRelocatable = v})
(boolOpt [] [])
]
where
readFlagList :: String -> FlagAssignment
readFlagList = map tagWithValue . words
where tagWithValue ('-':fname) = (FlagName (lowercase fname), False)
tagWithValue fname = (FlagName (lowercase fname), True)
showFlagList :: FlagAssignment -> [String]
showFlagList fs = [ if not set then '-':fname else fname
| (FlagName fname, set) <- fs]
liftInstallDirs =
liftOption configInstallDirs (\v flags -> flags { configInstallDirs = v })
reqPathTemplateArgFlag title _sf _lf d get set =
reqArgFlag title _sf _lf d
(fmap fromPathTemplate . get) (set . fmap toPathTemplate)
readPackageDbList :: String -> [Maybe PackageDB]
readPackageDbList "clear" = [Nothing]
readPackageDbList "global" = [Just GlobalPackageDB]
readPackageDbList "user" = [Just UserPackageDB]
readPackageDbList other = [Just (SpecificPackageDB other)]
showPackageDbList :: [Maybe PackageDB] -> [String]
showPackageDbList = map showPackageDb
where
showPackageDb Nothing = "clear"
showPackageDb (Just GlobalPackageDB) = "global"
showPackageDb (Just UserPackageDB) = "user"
showPackageDb (Just (SpecificPackageDB db)) = db
showProfDetailLevelFlag :: Flag ProfDetailLevel -> [String]
showProfDetailLevelFlag NoFlag = []
showProfDetailLevelFlag (Flag dl) = [showProfDetailLevel dl]
parseDependency :: Parse.ReadP r (PackageName, ComponentId)
parseDependency = do
x <- parse
_ <- Parse.char '='
y <- parse
return (x, y)
parseHoleMapEntry :: Parse.ReadP r (ModuleName, (ComponentId, ModuleName))
parseHoleMapEntry = do
x <- parse
_ <- Parse.char '='
y <- parse
_ <- Parse.char '@'
z <- parse
return (x, (z, y))
installDirsOptions :: [OptionField (InstallDirs (Flag PathTemplate))]
installDirsOptions =
[ option "" ["prefix"]
"bake this prefix in preparation of installation"
prefix (\v flags -> flags { prefix = v })
installDirArg
, option "" ["bindir"]
"installation directory for executables"
bindir (\v flags -> flags { bindir = v })
installDirArg
, option "" ["libdir"]
"installation directory for libraries"
libdir (\v flags -> flags { libdir = v })
installDirArg
, option "" ["libsubdir"]
"subdirectory of libdir in which libs are installed"
libsubdir (\v flags -> flags { libsubdir = v })
installDirArg
, option "" ["libexecdir"]
"installation directory for program executables"
libexecdir (\v flags -> flags { libexecdir = v })
installDirArg
, option "" ["datadir"]
"installation directory for read-only data"
datadir (\v flags -> flags { datadir = v })
installDirArg
, option "" ["datasubdir"]
"subdirectory of datadir in which data files are installed"
datasubdir (\v flags -> flags { datasubdir = v })
installDirArg
, option "" ["docdir"]
"installation directory for documentation"
docdir (\v flags -> flags { docdir = v })
installDirArg
, option "" ["htmldir"]
"installation directory for HTML documentation"
htmldir (\v flags -> flags { htmldir = v })
installDirArg
, option "" ["haddockdir"]
"installation directory for haddock interfaces"
haddockdir (\v flags -> flags { haddockdir = v })
installDirArg
, option "" ["sysconfdir"]
"installation directory for configuration files"
sysconfdir (\v flags -> flags { sysconfdir = v })
installDirArg
]
where
installDirArg _sf _lf d get set =
reqArgFlag "DIR" _sf _lf d
(fmap fromPathTemplate . get) (set . fmap toPathTemplate)
emptyConfigFlags :: ConfigFlags
emptyConfigFlags = mempty
instance Monoid ConfigFlags where
mempty = ConfigFlags {
configPrograms = error "FIXME: remove configPrograms",
configProgramPaths = mempty,
configProgramArgs = mempty,
configProgramPathExtra = mempty,
configHcFlavor = mempty,
configHcPath = mempty,
configHcPkg = mempty,
configVanillaLib = mempty,
configProfLib = mempty,
configSharedLib = mempty,
configDynExe = mempty,
configProfExe = mempty,
configProf = mempty,
configProfDetail = mempty,
configProfLibDetail = mempty,
configConfigureArgs = mempty,
configOptimization = mempty,
configProgPrefix = mempty,
configProgSuffix = mempty,
configInstallDirs = mempty,
configScratchDir = mempty,
configDistPref = mempty,
configVerbosity = mempty,
configUserInstall = mempty,
configPackageDBs = mempty,
configGHCiLib = mempty,
configSplitObjs = mempty,
configStripExes = mempty,
configStripLibs = mempty,
configExtraLibDirs = mempty,
configConstraints = mempty,
configDependencies = mempty,
configInstantiateWith = mempty,
configExtraIncludeDirs = mempty,
configIPID = mempty,
configConfigurationsFlags = mempty,
configTests = mempty,
configCoverage = mempty,
configLibCoverage = mempty,
configExactConfiguration = mempty,
configBenchmarks = mempty,
configFlagError = mempty,
configRelocatable = mempty,
configDebugInfo = mempty
}
mappend = (Semi.<>)
instance Semigroup ConfigFlags where
a <> b = ConfigFlags {
configPrograms = configPrograms b,
configProgramPaths = combine configProgramPaths,
configProgramArgs = combine configProgramArgs,
configProgramPathExtra = combine configProgramPathExtra,
configHcFlavor = combine configHcFlavor,
configHcPath = combine configHcPath,
configHcPkg = combine configHcPkg,
configVanillaLib = combine configVanillaLib,
configProfLib = combine configProfLib,
configSharedLib = combine configSharedLib,
configDynExe = combine configDynExe,
configProfExe = combine configProfExe,
configProf = combine configProf,
configProfDetail = combine configProfDetail,
configProfLibDetail = combine configProfLibDetail,
configConfigureArgs = combine configConfigureArgs,
configOptimization = combine configOptimization,
configProgPrefix = combine configProgPrefix,
configProgSuffix = combine configProgSuffix,
configInstallDirs = combine configInstallDirs,
configScratchDir = combine configScratchDir,
configDistPref = combine configDistPref,
configVerbosity = combine configVerbosity,
configUserInstall = combine configUserInstall,
configPackageDBs = combine configPackageDBs,
configGHCiLib = combine configGHCiLib,
configSplitObjs = combine configSplitObjs,
configStripExes = combine configStripExes,
configStripLibs = combine configStripLibs,
configExtraLibDirs = combine configExtraLibDirs,
configConstraints = combine configConstraints,
configDependencies = combine configDependencies,
configInstantiateWith = combine configInstantiateWith,
configExtraIncludeDirs = combine configExtraIncludeDirs,
configIPID = combine configIPID,
configConfigurationsFlags = combine configConfigurationsFlags,
configTests = combine configTests,
configCoverage = combine configCoverage,
configLibCoverage = combine configLibCoverage,
configExactConfiguration = combine configExactConfiguration,
configBenchmarks = combine configBenchmarks,
configFlagError = combine configFlagError,
configRelocatable = combine configRelocatable,
configDebugInfo = combine configDebugInfo
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Copy flags
-- ------------------------------------------------------------
-- | Flags to @copy@: (destdir, copy-prefix (backwards compat), verbosity)
data CopyFlags = CopyFlags {
copyDest :: Flag CopyDest,
copyDistPref :: Flag FilePath,
copyVerbosity :: Flag Verbosity
}
deriving Show
defaultCopyFlags :: CopyFlags
defaultCopyFlags = CopyFlags {
copyDest = Flag NoCopyDest,
copyDistPref = NoFlag,
copyVerbosity = Flag normal
}
copyCommand :: CommandUI CopyFlags
copyCommand = CommandUI
{ commandName = "copy"
, commandSynopsis = "Copy the files into the install locations."
, commandDescription = Just $ \_ -> wrapText $
"Does not call register, and allows a prefix at install time. "
++ "Without the --destdir flag, configure determines location.\n"
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " copy [FLAGS]\n"
, commandDefaultFlags = defaultCopyFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity copyVerbosity (\v flags -> flags { copyVerbosity = v })
,optionDistPref
copyDistPref (\d flags -> flags { copyDistPref = d })
showOrParseArgs
,option "" ["destdir"]
"directory to copy files to, prepended to installation directories"
copyDest (\v flags -> flags { copyDest = v })
(reqArg "DIR" (succeedReadE (Flag . CopyTo))
(\f -> case f of Flag (CopyTo p) -> [p]; _ -> []))
]
}
emptyCopyFlags :: CopyFlags
emptyCopyFlags = mempty
instance Monoid CopyFlags where
mempty = CopyFlags {
copyDest = mempty,
copyDistPref = mempty,
copyVerbosity = mempty
}
mappend = (Semi.<>)
instance Semigroup CopyFlags where
a <> b = CopyFlags {
copyDest = combine copyDest,
copyDistPref = combine copyDistPref,
copyVerbosity = combine copyVerbosity
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Install flags
-- ------------------------------------------------------------
-- | Flags to @install@: (package db, verbosity)
data InstallFlags = InstallFlags {
installPackageDB :: Flag PackageDB,
installDistPref :: Flag FilePath,
installUseWrapper :: Flag Bool,
installInPlace :: Flag Bool,
installVerbosity :: Flag Verbosity
}
deriving Show
defaultInstallFlags :: InstallFlags
defaultInstallFlags = InstallFlags {
installPackageDB = NoFlag,
installDistPref = NoFlag,
installUseWrapper = Flag False,
installInPlace = Flag False,
installVerbosity = Flag normal
}
installCommand :: CommandUI InstallFlags
installCommand = CommandUI
{ commandName = "install"
, commandSynopsis =
"Copy the files into the install locations. Run register."
, commandDescription = Just $ \_ -> wrapText $
"Unlike the copy command, install calls the register command."
++ "If you want to install into a location that is not what was"
++ "specified in the configure step, use the copy command.\n"
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " install [FLAGS]\n"
, commandDefaultFlags = defaultInstallFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity installVerbosity (\v flags -> flags { installVerbosity = v })
,optionDistPref
installDistPref (\d flags -> flags { installDistPref = d })
showOrParseArgs
,option "" ["inplace"]
"install the package in the install subdirectory of the dist prefix, so it can be used without being installed"
installInPlace (\v flags -> flags { installInPlace = v })
trueArg
,option "" ["shell-wrappers"]
"using shell script wrappers around executables"
installUseWrapper (\v flags -> flags { installUseWrapper = v })
(boolOpt [] [])
,option "" ["package-db"] ""
installPackageDB (\v flags -> flags { installPackageDB = v })
(choiceOpt [ (Flag UserPackageDB, ([],["user"]),
"upon configuration register this package in the user's local package database")
, (Flag GlobalPackageDB, ([],["global"]),
"(default) upon configuration register this package in the system-wide package database")])
]
}
emptyInstallFlags :: InstallFlags
emptyInstallFlags = mempty
instance Monoid InstallFlags where
mempty = InstallFlags{
installPackageDB = mempty,
installDistPref = mempty,
installUseWrapper = mempty,
installInPlace = mempty,
installVerbosity = mempty
}
mappend = (Semi.<>)
instance Semigroup InstallFlags where
a <> b = InstallFlags{
installPackageDB = combine installPackageDB,
installDistPref = combine installDistPref,
installUseWrapper = combine installUseWrapper,
installInPlace = combine installInPlace,
installVerbosity = combine installVerbosity
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * SDist flags
-- ------------------------------------------------------------
-- | Flags to @sdist@: (snapshot, verbosity)
data SDistFlags = SDistFlags {
sDistSnapshot :: Flag Bool,
sDistDirectory :: Flag FilePath,
sDistDistPref :: Flag FilePath,
sDistListSources :: Flag FilePath,
sDistVerbosity :: Flag Verbosity
}
deriving Show
defaultSDistFlags :: SDistFlags
defaultSDistFlags = SDistFlags {
sDistSnapshot = Flag False,
sDistDirectory = mempty,
sDistDistPref = NoFlag,
sDistListSources = mempty,
sDistVerbosity = Flag normal
}
sdistCommand :: CommandUI SDistFlags
sdistCommand = CommandUI
{ commandName = "sdist"
, commandSynopsis =
"Generate a source distribution file (.tar.gz)."
, commandDescription = Nothing
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " sdist [FLAGS]\n"
, commandDefaultFlags = defaultSDistFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity sDistVerbosity (\v flags -> flags { sDistVerbosity = v })
,optionDistPref
sDistDistPref (\d flags -> flags { sDistDistPref = d })
showOrParseArgs
,option "" ["list-sources"]
"Just write a list of the package's sources to a file"
sDistListSources (\v flags -> flags { sDistListSources = v })
(reqArgFlag "FILE")
,option "" ["snapshot"]
"Produce a snapshot source distribution"
sDistSnapshot (\v flags -> flags { sDistSnapshot = v })
trueArg
,option "" ["output-directory"]
("Generate a source distribution in the given directory, "
++ "without creating a tarball")
sDistDirectory (\v flags -> flags { sDistDirectory = v })
(reqArgFlag "DIR")
]
}
emptySDistFlags :: SDistFlags
emptySDistFlags = mempty
instance Monoid SDistFlags where
mempty = SDistFlags {
sDistSnapshot = mempty,
sDistDirectory = mempty,
sDistDistPref = mempty,
sDistListSources = mempty,
sDistVerbosity = mempty
}
mappend = (Semi.<>)
instance Semigroup SDistFlags where
a <> b = SDistFlags {
sDistSnapshot = combine sDistSnapshot,
sDistDirectory = combine sDistDirectory,
sDistDistPref = combine sDistDistPref,
sDistListSources = combine sDistListSources,
sDistVerbosity = combine sDistVerbosity
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Register flags
-- ------------------------------------------------------------
-- | Flags to @register@ and @unregister@: (user package, gen-script,
-- in-place, verbosity)
data RegisterFlags = RegisterFlags {
regPackageDB :: Flag PackageDB,
regGenScript :: Flag Bool,
regGenPkgConf :: Flag (Maybe FilePath),
regInPlace :: Flag Bool,
regDistPref :: Flag FilePath,
regPrintId :: Flag Bool,
regVerbosity :: Flag Verbosity
}
deriving Show
defaultRegisterFlags :: RegisterFlags
defaultRegisterFlags = RegisterFlags {
regPackageDB = NoFlag,
regGenScript = Flag False,
regGenPkgConf = NoFlag,
regInPlace = Flag False,
regDistPref = NoFlag,
regPrintId = Flag False,
regVerbosity = Flag normal
}
registerCommand :: CommandUI RegisterFlags
registerCommand = CommandUI
{ commandName = "register"
, commandSynopsis =
"Register this package with the compiler."
, commandDescription = Nothing
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " register [FLAGS]\n"
, commandDefaultFlags = defaultRegisterFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity regVerbosity (\v flags -> flags { regVerbosity = v })
,optionDistPref
regDistPref (\d flags -> flags { regDistPref = d })
showOrParseArgs
,option "" ["packageDB"] ""
regPackageDB (\v flags -> flags { regPackageDB = v })
(choiceOpt [ (Flag UserPackageDB, ([],["user"]),
"upon registration, register this package in the user's local package database")
, (Flag GlobalPackageDB, ([],["global"]),
"(default)upon registration, register this package in the system-wide package database")])
,option "" ["inplace"]
"register the package in the build location, so it can be used without being installed"
regInPlace (\v flags -> flags { regInPlace = v })
trueArg
,option "" ["gen-script"]
"instead of registering, generate a script to register later"
regGenScript (\v flags -> flags { regGenScript = v })
trueArg
,option "" ["gen-pkg-config"]
"instead of registering, generate a package registration file"
regGenPkgConf (\v flags -> flags { regGenPkgConf = v })
(optArg' "PKG" Flag flagToList)
,option "" ["print-ipid"]
"print the installed package ID calculated for this package"
regPrintId (\v flags -> flags { regPrintId = v })
trueArg
]
}
unregisterCommand :: CommandUI RegisterFlags
unregisterCommand = CommandUI
{ commandName = "unregister"
, commandSynopsis =
"Unregister this package with the compiler."
, commandDescription = Nothing
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " unregister [FLAGS]\n"
, commandDefaultFlags = defaultRegisterFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity regVerbosity (\v flags -> flags { regVerbosity = v })
,optionDistPref
regDistPref (\d flags -> flags { regDistPref = d })
showOrParseArgs
,option "" ["user"] ""
regPackageDB (\v flags -> flags { regPackageDB = v })
(choiceOpt [ (Flag UserPackageDB, ([],["user"]),
"unregister this package in the user's local package database")
, (Flag GlobalPackageDB, ([],["global"]),
"(default) unregister this package in the system-wide package database")])
,option "" ["gen-script"]
"Instead of performing the unregister command, generate a script to unregister later"
regGenScript (\v flags -> flags { regGenScript = v })
trueArg
]
}
emptyRegisterFlags :: RegisterFlags
emptyRegisterFlags = mempty
instance Monoid RegisterFlags where
mempty = RegisterFlags {
regPackageDB = mempty,
regGenScript = mempty,
regGenPkgConf = mempty,
regInPlace = mempty,
regPrintId = mempty,
regDistPref = mempty,
regVerbosity = mempty
}
mappend = (Semi.<>)
instance Semigroup RegisterFlags where
a <> b = RegisterFlags {
regPackageDB = combine regPackageDB,
regGenScript = combine regGenScript,
regGenPkgConf = combine regGenPkgConf,
regInPlace = combine regInPlace,
regPrintId = combine regPrintId,
regDistPref = combine regDistPref,
regVerbosity = combine regVerbosity
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * HsColour flags
-- ------------------------------------------------------------
data HscolourFlags = HscolourFlags {
hscolourCSS :: Flag FilePath,
hscolourExecutables :: Flag Bool,
hscolourTestSuites :: Flag Bool,
hscolourBenchmarks :: Flag Bool,
hscolourDistPref :: Flag FilePath,
hscolourVerbosity :: Flag Verbosity
}
deriving Show
emptyHscolourFlags :: HscolourFlags
emptyHscolourFlags = mempty
defaultHscolourFlags :: HscolourFlags
defaultHscolourFlags = HscolourFlags {
hscolourCSS = NoFlag,
hscolourExecutables = Flag False,
hscolourTestSuites = Flag False,
hscolourBenchmarks = Flag False,
hscolourDistPref = NoFlag,
hscolourVerbosity = Flag normal
}
instance Monoid HscolourFlags where
mempty = HscolourFlags {
hscolourCSS = mempty,
hscolourExecutables = mempty,
hscolourTestSuites = mempty,
hscolourBenchmarks = mempty,
hscolourDistPref = mempty,
hscolourVerbosity = mempty
}
mappend = (Semi.<>)
instance Semigroup HscolourFlags where
a <> b = HscolourFlags {
hscolourCSS = combine hscolourCSS,
hscolourExecutables = combine hscolourExecutables,
hscolourTestSuites = combine hscolourTestSuites,
hscolourBenchmarks = combine hscolourBenchmarks,
hscolourDistPref = combine hscolourDistPref,
hscolourVerbosity = combine hscolourVerbosity
}
where combine field = field a `mappend` field b
hscolourCommand :: CommandUI HscolourFlags
hscolourCommand = CommandUI
{ commandName = "hscolour"
, commandSynopsis =
"Generate HsColour colourised code, in HTML format."
, commandDescription = Just (\_ -> "Requires the hscolour program.\n")
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " hscolour [FLAGS]\n"
, commandDefaultFlags = defaultHscolourFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity hscolourVerbosity
(\v flags -> flags { hscolourVerbosity = v })
,optionDistPref
hscolourDistPref (\d flags -> flags { hscolourDistPref = d })
showOrParseArgs
,option "" ["executables"]
"Run hscolour for Executables targets"
hscolourExecutables (\v flags -> flags { hscolourExecutables = v })
trueArg
,option "" ["tests"]
"Run hscolour for Test Suite targets"
hscolourTestSuites (\v flags -> flags { hscolourTestSuites = v })
trueArg
,option "" ["benchmarks"]
"Run hscolour for Benchmark targets"
hscolourBenchmarks (\v flags -> flags { hscolourBenchmarks = v })
trueArg
,option "" ["all"]
"Run hscolour for all targets"
(\f -> allFlags [ hscolourExecutables f
, hscolourTestSuites f
, hscolourBenchmarks f])
(\v flags -> flags { hscolourExecutables = v
, hscolourTestSuites = v
, hscolourBenchmarks = v })
trueArg
,option "" ["css"]
"Use a cascading style sheet"
hscolourCSS (\v flags -> flags { hscolourCSS = v })
(reqArgFlag "PATH")
]
}
-- ------------------------------------------------------------
-- * Haddock flags
-- ------------------------------------------------------------
data HaddockFlags = HaddockFlags {
haddockProgramPaths :: [(String, FilePath)],
haddockProgramArgs :: [(String, [String])],
haddockHoogle :: Flag Bool,
haddockHtml :: Flag Bool,
haddockHtmlLocation :: Flag String,
haddockForHackage :: Flag Bool,
haddockExecutables :: Flag Bool,
haddockTestSuites :: Flag Bool,
haddockBenchmarks :: Flag Bool,
haddockInternal :: Flag Bool,
haddockCss :: Flag FilePath,
haddockHscolour :: Flag Bool,
haddockHscolourCss :: Flag FilePath,
haddockContents :: Flag PathTemplate,
haddockDistPref :: Flag FilePath,
haddockKeepTempFiles:: Flag Bool,
haddockVerbosity :: Flag Verbosity
}
deriving Show
defaultHaddockFlags :: HaddockFlags
defaultHaddockFlags = HaddockFlags {
haddockProgramPaths = mempty,
haddockProgramArgs = [],
haddockHoogle = Flag False,
haddockHtml = Flag False,
haddockHtmlLocation = NoFlag,
haddockForHackage = Flag False,
haddockExecutables = Flag False,
haddockTestSuites = Flag False,
haddockBenchmarks = Flag False,
haddockInternal = Flag False,
haddockCss = NoFlag,
haddockHscolour = Flag False,
haddockHscolourCss = NoFlag,
haddockContents = NoFlag,
haddockDistPref = NoFlag,
haddockKeepTempFiles= Flag False,
haddockVerbosity = Flag normal
}
haddockCommand :: CommandUI HaddockFlags
haddockCommand = CommandUI
{ commandName = "haddock"
, commandSynopsis = "Generate Haddock HTML documentation."
, commandDescription = Just $ \_ ->
"Requires the program haddock, version 2.x.\n"
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " haddock [FLAGS]\n"
, commandDefaultFlags = defaultHaddockFlags
, commandOptions = \showOrParseArgs ->
haddockOptions showOrParseArgs
++ programConfigurationPaths progConf ParseArgs
haddockProgramPaths (\v flags -> flags { haddockProgramPaths = v})
++ programConfigurationOption progConf showOrParseArgs
haddockProgramArgs (\v fs -> fs { haddockProgramArgs = v })
++ programConfigurationOptions progConf ParseArgs
haddockProgramArgs (\v flags -> flags { haddockProgramArgs = v})
}
where
progConf = addKnownProgram haddockProgram
$ addKnownProgram ghcProgram
$ emptyProgramConfiguration
haddockOptions :: ShowOrParseArgs -> [OptionField HaddockFlags]
haddockOptions showOrParseArgs =
[optionVerbosity haddockVerbosity
(\v flags -> flags { haddockVerbosity = v })
,optionDistPref
haddockDistPref (\d flags -> flags { haddockDistPref = d })
showOrParseArgs
,option "" ["keep-temp-files"]
"Keep temporary files"
haddockKeepTempFiles (\b flags -> flags { haddockKeepTempFiles = b })
trueArg
,option "" ["hoogle"]
"Generate a hoogle database"
haddockHoogle (\v flags -> flags { haddockHoogle = v })
trueArg
,option "" ["html"]
"Generate HTML documentation (the default)"
haddockHtml (\v flags -> flags { haddockHtml = v })
trueArg
,option "" ["html-location"]
"Location of HTML documentation for pre-requisite packages"
haddockHtmlLocation (\v flags -> flags { haddockHtmlLocation = v })
(reqArgFlag "URL")
,option "" ["for-hackage"]
"Collection of flags to generate documentation suitable for upload to hackage"
haddockForHackage (\v flags -> flags { haddockForHackage = v })
trueArg
,option "" ["executables"]
"Run haddock for Executables targets"
haddockExecutables (\v flags -> flags { haddockExecutables = v })
trueArg
,option "" ["tests"]
"Run haddock for Test Suite targets"
haddockTestSuites (\v flags -> flags { haddockTestSuites = v })
trueArg
,option "" ["benchmarks"]
"Run haddock for Benchmark targets"
haddockBenchmarks (\v flags -> flags { haddockBenchmarks = v })
trueArg
,option "" ["all"]
"Run haddock for all targets"
(\f -> allFlags [ haddockExecutables f
, haddockTestSuites f
, haddockBenchmarks f])
(\v flags -> flags { haddockExecutables = v
, haddockTestSuites = v
, haddockBenchmarks = v })
trueArg
,option "" ["internal"]
"Run haddock for internal modules and include all symbols"
haddockInternal (\v flags -> flags { haddockInternal = v })
trueArg
,option "" ["css"]
"Use PATH as the haddock stylesheet"
haddockCss (\v flags -> flags { haddockCss = v })
(reqArgFlag "PATH")
,option "" ["hyperlink-source","hyperlink-sources"]
"Hyperlink the documentation to the source code (using HsColour)"
haddockHscolour (\v flags -> flags { haddockHscolour = v })
trueArg
,option "" ["hscolour-css"]
"Use PATH as the HsColour stylesheet"
haddockHscolourCss (\v flags -> flags { haddockHscolourCss = v })
(reqArgFlag "PATH")
,option "" ["contents-location"]
"Bake URL in as the location for the contents page"
haddockContents (\v flags -> flags { haddockContents = v })
(reqArg' "URL"
(toFlag . toPathTemplate)
(flagToList . fmap fromPathTemplate))
]
emptyHaddockFlags :: HaddockFlags
emptyHaddockFlags = mempty
instance Monoid HaddockFlags where
mempty = HaddockFlags {
haddockProgramPaths = mempty,
haddockProgramArgs = mempty,
haddockHoogle = mempty,
haddockHtml = mempty,
haddockHtmlLocation = mempty,
haddockForHackage = mempty,
haddockExecutables = mempty,
haddockTestSuites = mempty,
haddockBenchmarks = mempty,
haddockInternal = mempty,
haddockCss = mempty,
haddockHscolour = mempty,
haddockHscolourCss = mempty,
haddockContents = mempty,
haddockDistPref = mempty,
haddockKeepTempFiles= mempty,
haddockVerbosity = mempty
}
mappend = (Semi.<>)
instance Semigroup HaddockFlags where
a <> b = HaddockFlags {
haddockProgramPaths = combine haddockProgramPaths,
haddockProgramArgs = combine haddockProgramArgs,
haddockHoogle = combine haddockHoogle,
haddockHtml = combine haddockHtml,
haddockHtmlLocation = combine haddockHtmlLocation,
haddockForHackage = combine haddockForHackage,
haddockExecutables = combine haddockExecutables,
haddockTestSuites = combine haddockTestSuites,
haddockBenchmarks = combine haddockBenchmarks,
haddockInternal = combine haddockInternal,
haddockCss = combine haddockCss,
haddockHscolour = combine haddockHscolour,
haddockHscolourCss = combine haddockHscolourCss,
haddockContents = combine haddockContents,
haddockDistPref = combine haddockDistPref,
haddockKeepTempFiles= combine haddockKeepTempFiles,
haddockVerbosity = combine haddockVerbosity
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Clean flags
-- ------------------------------------------------------------
data CleanFlags = CleanFlags {
cleanSaveConf :: Flag Bool,
cleanDistPref :: Flag FilePath,
cleanVerbosity :: Flag Verbosity
}
deriving Show
defaultCleanFlags :: CleanFlags
defaultCleanFlags = CleanFlags {
cleanSaveConf = Flag False,
cleanDistPref = NoFlag,
cleanVerbosity = Flag normal
}
cleanCommand :: CommandUI CleanFlags
cleanCommand = CommandUI
{ commandName = "clean"
, commandSynopsis = "Clean up after a build."
, commandDescription = Just $ \_ ->
"Removes .hi, .o, preprocessed sources, etc.\n"
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " clean [FLAGS]\n"
, commandDefaultFlags = defaultCleanFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity cleanVerbosity (\v flags -> flags { cleanVerbosity = v })
,optionDistPref
cleanDistPref (\d flags -> flags { cleanDistPref = d })
showOrParseArgs
,option "s" ["save-configure"]
"Do not remove the configuration file (dist/setup-config) during cleaning. Saves need to reconfigure."
cleanSaveConf (\v flags -> flags { cleanSaveConf = v })
trueArg
]
}
emptyCleanFlags :: CleanFlags
emptyCleanFlags = mempty
instance Monoid CleanFlags where
mempty = CleanFlags {
cleanSaveConf = mempty,
cleanDistPref = mempty,
cleanVerbosity = mempty
}
mappend = (Semi.<>)
instance Semigroup CleanFlags where
a <> b = CleanFlags {
cleanSaveConf = combine cleanSaveConf,
cleanDistPref = combine cleanDistPref,
cleanVerbosity = combine cleanVerbosity
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------
data BuildFlags = BuildFlags {
buildProgramPaths :: [(String, FilePath)],
buildProgramArgs :: [(String, [String])],
buildDistPref :: Flag FilePath,
buildVerbosity :: Flag Verbosity,
buildNumJobs :: Flag (Maybe Int),
-- TODO: this one should not be here, it's just that the silly
-- UserHooks stop us from passing extra info in other ways
buildArgs :: [String]
}
deriving Show
{-# DEPRECATED buildVerbose "Use buildVerbosity instead" #-}
buildVerbose :: BuildFlags -> Verbosity
buildVerbose = fromFlagOrDefault normal . buildVerbosity
defaultBuildFlags :: BuildFlags
defaultBuildFlags = BuildFlags {
buildProgramPaths = mempty,
buildProgramArgs = [],
buildDistPref = mempty,
buildVerbosity = Flag normal,
buildNumJobs = mempty,
buildArgs = []
}
buildCommand :: ProgramConfiguration -> CommandUI BuildFlags
buildCommand progConf = CommandUI
{ commandName = "build"
, commandSynopsis = "Compile all/specific components."
, commandDescription = Just $ \_ -> wrapText $
"Components encompass executables, tests, and benchmarks.\n"
++ "\n"
++ "Affected by configuration options, see `configure`.\n"
, commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " build "
++ " All the components in the package\n"
++ " " ++ pname ++ " build foo "
++ " A component (i.e. lib, exe, test suite)\n\n"
++ programFlagsDescription progConf
--TODO: re-enable once we have support for module/file targets
-- ++ " " ++ pname ++ " build Foo.Bar "
-- ++ " A module\n"
-- ++ " " ++ pname ++ " build Foo/Bar.hs"
-- ++ " A file\n\n"
-- ++ "If a target is ambiguous it can be qualified with the component "
-- ++ "name, e.g.\n"
-- ++ " " ++ pname ++ " build foo:Foo.Bar\n"
-- ++ " " ++ pname ++ " build testsuite1:Foo/Bar.hs\n"
, commandUsage = usageAlternatives "build" $
[ "[FLAGS]"
, "COMPONENTS [FLAGS]"
]
, commandDefaultFlags = defaultBuildFlags
, commandOptions = \showOrParseArgs ->
[ optionVerbosity
buildVerbosity (\v flags -> flags { buildVerbosity = v })
, optionDistPref
buildDistPref (\d flags -> flags { buildDistPref = d }) showOrParseArgs
]
++ buildOptions progConf showOrParseArgs
}
buildOptions :: ProgramConfiguration -> ShowOrParseArgs
-> [OptionField BuildFlags]
buildOptions progConf showOrParseArgs =
[ optionNumJobs
buildNumJobs (\v flags -> flags { buildNumJobs = v })
]
++ programConfigurationPaths progConf showOrParseArgs
buildProgramPaths (\v flags -> flags { buildProgramPaths = v})
++ programConfigurationOption progConf showOrParseArgs
buildProgramArgs (\v fs -> fs { buildProgramArgs = v })
++ programConfigurationOptions progConf showOrParseArgs
buildProgramArgs (\v flags -> flags { buildProgramArgs = v})
emptyBuildFlags :: BuildFlags
emptyBuildFlags = mempty
instance Monoid BuildFlags where
mempty = BuildFlags {
buildProgramPaths = mempty,
buildProgramArgs = mempty,
buildVerbosity = mempty,
buildDistPref = mempty,
buildNumJobs = mempty,
buildArgs = mempty
}
mappend = (Semi.<>)
instance Semigroup BuildFlags where
a <> b = BuildFlags {
buildProgramPaths = combine buildProgramPaths,
buildProgramArgs = combine buildProgramArgs,
buildVerbosity = combine buildVerbosity,
buildDistPref = combine buildDistPref,
buildNumJobs = combine buildNumJobs,
buildArgs = combine buildArgs
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * REPL Flags
-- ------------------------------------------------------------
data ReplFlags = ReplFlags {
replProgramPaths :: [(String, FilePath)],
replProgramArgs :: [(String, [String])],
replDistPref :: Flag FilePath,
replVerbosity :: Flag Verbosity,
replReload :: Flag Bool
}
deriving Show
defaultReplFlags :: ReplFlags
defaultReplFlags = ReplFlags {
replProgramPaths = mempty,
replProgramArgs = [],
replDistPref = NoFlag,
replVerbosity = Flag normal,
replReload = Flag False
}
instance Monoid ReplFlags where
mempty = ReplFlags {
replProgramPaths = mempty,
replProgramArgs = mempty,
replVerbosity = mempty,
replDistPref = mempty,
replReload = mempty
}
mappend = (Semi.<>)
instance Semigroup ReplFlags where
a <> b = ReplFlags {
replProgramPaths = combine replProgramPaths,
replProgramArgs = combine replProgramArgs,
replVerbosity = combine replVerbosity,
replDistPref = combine replDistPref,
replReload = combine replReload
}
where combine field = field a `mappend` field b
replCommand :: ProgramConfiguration -> CommandUI ReplFlags
replCommand progConf = CommandUI
{ commandName = "repl"
, commandSynopsis =
"Open an interpreter session for the given component."
, commandDescription = Just $ \pname -> wrapText $
"If the current directory contains no package, ignores COMPONENT "
++ "parameters and opens an interactive interpreter session; if a "
++ "sandbox is present, its package database will be used.\n"
++ "\n"
++ "Otherwise, (re)configures with the given or default flags, and "
++ "loads the interpreter with the relevant modules. For executables, "
++ "tests and benchmarks, loads the main module (and its "
++ "dependencies); for libraries all exposed/other modules.\n"
++ "\n"
++ "The default component is the library itself, or the executable "
++ "if that is the only component.\n"
++ "\n"
++ "Support for loading specific modules is planned but not "
++ "implemented yet. For certain scenarios, `" ++ pname
++ " exec -- ghci :l Foo` may be used instead. Note that `exec` will "
++ "not (re)configure and you will have to specify the location of "
++ "other modules, if required.\n"
, commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " repl "
++ " The first component in the package\n"
++ " " ++ pname ++ " repl foo "
++ " A named component (i.e. lib, exe, test suite)\n"
++ " " ++ pname ++ " repl --ghc-options=\"-lstdc++\""
++ " Specifying flags for interpreter\n"
--TODO: re-enable once we have support for module/file targets
-- ++ " " ++ pname ++ " repl Foo.Bar "
-- ++ " A module\n"
-- ++ " " ++ pname ++ " repl Foo/Bar.hs"
-- ++ " A file\n\n"
-- ++ "If a target is ambiguous it can be qualified with the component "
-- ++ "name, e.g.\n"
-- ++ " " ++ pname ++ " repl foo:Foo.Bar\n"
-- ++ " " ++ pname ++ " repl testsuite1:Foo/Bar.hs\n"
, commandUsage = \pname -> "Usage: " ++ pname ++ " repl [COMPONENT] [FLAGS]\n"
, commandDefaultFlags = defaultReplFlags
, commandOptions = \showOrParseArgs ->
optionVerbosity replVerbosity (\v flags -> flags { replVerbosity = v })
: optionDistPref
replDistPref (\d flags -> flags { replDistPref = d })
showOrParseArgs
: programConfigurationPaths progConf showOrParseArgs
replProgramPaths (\v flags -> flags { replProgramPaths = v})
++ programConfigurationOption progConf showOrParseArgs
replProgramArgs (\v flags -> flags { replProgramArgs = v})
++ programConfigurationOptions progConf showOrParseArgs
replProgramArgs (\v flags -> flags { replProgramArgs = v})
++ case showOrParseArgs of
ParseArgs ->
[ option "" ["reload"]
"Used from within an interpreter to update files."
replReload (\v flags -> flags { replReload = v })
trueArg
]
_ -> []
}
-- ------------------------------------------------------------
-- * Test flags
-- ------------------------------------------------------------
data TestShowDetails = Never | Failures | Always | Streaming | Direct
deriving (Eq, Ord, Enum, Bounded, Show)
knownTestShowDetails :: [TestShowDetails]
knownTestShowDetails = [minBound..maxBound]
instance Text TestShowDetails where
disp = Disp.text . lowercase . show
parse = maybe Parse.pfail return . classify =<< ident
where
ident = Parse.munch1 (\c -> isAlpha c || c == '_' || c == '-')
classify str = lookup (lowercase str) enumMap
enumMap :: [(String, TestShowDetails)]
enumMap = [ (display x, x)
| x <- knownTestShowDetails ]
--TODO: do we need this instance?
instance Monoid TestShowDetails where
mempty = Never
mappend = (Semi.<>)
instance Semigroup TestShowDetails where
a <> b = if a < b then b else a
data TestFlags = TestFlags {
testDistPref :: Flag FilePath,
testVerbosity :: Flag Verbosity,
testHumanLog :: Flag PathTemplate,
testMachineLog :: Flag PathTemplate,
testShowDetails :: Flag TestShowDetails,
testKeepTix :: Flag Bool,
-- TODO: think about if/how options are passed to test exes
testOptions :: [PathTemplate]
}
defaultTestFlags :: TestFlags
defaultTestFlags = TestFlags {
testDistPref = NoFlag,
testVerbosity = Flag normal,
testHumanLog = toFlag $ toPathTemplate $ "$pkgid-$test-suite.log",
testMachineLog = toFlag $ toPathTemplate $ "$pkgid.log",
testShowDetails = toFlag Failures,
testKeepTix = toFlag False,
testOptions = []
}
testCommand :: CommandUI TestFlags
testCommand = CommandUI
{ commandName = "test"
, commandSynopsis =
"Run all/specific tests in the test suite."
, commandDescription = Just $ \pname -> wrapText $
"If necessary (re)configures with `--enable-tests` flag and builds"
++ " the test suite.\n"
++ "\n"
++ "Remember that the tests' dependencies must be installed if there"
++ " are additional ones; e.g. with `" ++ pname
++ " install --only-dependencies --enable-tests`.\n"
++ "\n"
++ "By defining UserHooks in a custom Setup.hs, the package can"
++ " define actions to be executed before and after running tests.\n"
, commandNotes = Nothing
, commandUsage = usageAlternatives "test"
[ "[FLAGS]"
, "TESTCOMPONENTS [FLAGS]"
]
, commandDefaultFlags = defaultTestFlags
, commandOptions = \showOrParseArgs ->
[ optionVerbosity testVerbosity (\v flags -> flags { testVerbosity = v })
, optionDistPref
testDistPref (\d flags -> flags { testDistPref = d })
showOrParseArgs
, option [] ["log"]
("Log all test suite results to file (name template can use "
++ "$pkgid, $compiler, $os, $arch, $test-suite, $result)")
testHumanLog (\v flags -> flags { testHumanLog = v })
(reqArg' "TEMPLATE"
(toFlag . toPathTemplate)
(flagToList . fmap fromPathTemplate))
, option [] ["machine-log"]
("Produce a machine-readable log file (name template can use "
++ "$pkgid, $compiler, $os, $arch, $result)")
testMachineLog (\v flags -> flags { testMachineLog = v })
(reqArg' "TEMPLATE"
(toFlag . toPathTemplate)
(flagToList . fmap fromPathTemplate))
, option [] ["show-details"]
("'always': always show results of individual test cases. "
++ "'never': never show results of individual test cases. "
++ "'failures': show results of failing test cases. "
++ "'streaming': show results of test cases in real time."
++ "'direct': send results of test cases in real time; no log file.")
testShowDetails (\v flags -> flags { testShowDetails = v })
(reqArg "FILTER"
(readP_to_E (\_ -> "--show-details flag expects one of "
++ intercalate ", "
(map display knownTestShowDetails))
(fmap toFlag parse))
(flagToList . fmap display))
, option [] ["keep-tix-files"]
"keep .tix files for HPC between test runs"
testKeepTix (\v flags -> flags { testKeepTix = v})
trueArg
, option [] ["test-options"]
("give extra options to test executables "
++ "(name templates can use $pkgid, $compiler, "
++ "$os, $arch, $test-suite)")
testOptions (\v flags -> flags { testOptions = v })
(reqArg' "TEMPLATES" (map toPathTemplate . splitArgs)
(const []))
, option [] ["test-option"]
("give extra option to test executables "
++ "(no need to quote options containing spaces, "
++ "name template can use $pkgid, $compiler, "
++ "$os, $arch, $test-suite)")
testOptions (\v flags -> flags { testOptions = v })
(reqArg' "TEMPLATE" (\x -> [toPathTemplate x])
(map fromPathTemplate))
]
}
emptyTestFlags :: TestFlags
emptyTestFlags = mempty
instance Monoid TestFlags where
mempty = TestFlags {
testDistPref = mempty,
testVerbosity = mempty,
testHumanLog = mempty,
testMachineLog = mempty,
testShowDetails = mempty,
testKeepTix = mempty,
testOptions = mempty
}
mappend = (Semi.<>)
instance Semigroup TestFlags where
a <> b = TestFlags {
testDistPref = combine testDistPref,
testVerbosity = combine testVerbosity,
testHumanLog = combine testHumanLog,
testMachineLog = combine testMachineLog,
testShowDetails = combine testShowDetails,
testKeepTix = combine testKeepTix,
testOptions = combine testOptions
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Benchmark flags
-- ------------------------------------------------------------
data BenchmarkFlags = BenchmarkFlags {
benchmarkDistPref :: Flag FilePath,
benchmarkVerbosity :: Flag Verbosity,
benchmarkOptions :: [PathTemplate]
}
defaultBenchmarkFlags :: BenchmarkFlags
defaultBenchmarkFlags = BenchmarkFlags {
benchmarkDistPref = NoFlag,
benchmarkVerbosity = Flag normal,
benchmarkOptions = []
}
benchmarkCommand :: CommandUI BenchmarkFlags
benchmarkCommand = CommandUI
{ commandName = "bench"
, commandSynopsis =
"Run all/specific benchmarks."
, commandDescription = Just $ \pname -> wrapText $
"If necessary (re)configures with `--enable-benchmarks` flag and"
++ " builds the benchmarks.\n"
++ "\n"
++ "Remember that the benchmarks' dependencies must be installed if"
++ " there are additional ones; e.g. with `" ++ pname
++ " install --only-dependencies --enable-benchmarks`.\n"
++ "\n"
++ "By defining UserHooks in a custom Setup.hs, the package can"
++ " define actions to be executed before and after running"
++ " benchmarks.\n"
, commandNotes = Nothing
, commandUsage = usageAlternatives "bench"
[ "[FLAGS]"
, "BENCHCOMPONENTS [FLAGS]"
]
, commandDefaultFlags = defaultBenchmarkFlags
, commandOptions = \showOrParseArgs ->
[ optionVerbosity benchmarkVerbosity
(\v flags -> flags { benchmarkVerbosity = v })
, optionDistPref
benchmarkDistPref (\d flags -> flags { benchmarkDistPref = d })
showOrParseArgs
, option [] ["benchmark-options"]
("give extra options to benchmark executables "
++ "(name templates can use $pkgid, $compiler, "
++ "$os, $arch, $benchmark)")
benchmarkOptions (\v flags -> flags { benchmarkOptions = v })
(reqArg' "TEMPLATES" (map toPathTemplate . splitArgs)
(const []))
, option [] ["benchmark-option"]
("give extra option to benchmark executables "
++ "(no need to quote options containing spaces, "
++ "name template can use $pkgid, $compiler, "
++ "$os, $arch, $benchmark)")
benchmarkOptions (\v flags -> flags { benchmarkOptions = v })
(reqArg' "TEMPLATE" (\x -> [toPathTemplate x])
(map fromPathTemplate))
]
}
emptyBenchmarkFlags :: BenchmarkFlags
emptyBenchmarkFlags = mempty
instance Monoid BenchmarkFlags where
mempty = BenchmarkFlags {
benchmarkDistPref = mempty,
benchmarkVerbosity = mempty,
benchmarkOptions = mempty
}
mappend = (Semi.<>)
instance Semigroup BenchmarkFlags where
a <> b = BenchmarkFlags {
benchmarkDistPref = combine benchmarkDistPref,
benchmarkVerbosity = combine benchmarkVerbosity,
benchmarkOptions = combine benchmarkOptions
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Shared options utils
-- ------------------------------------------------------------
programFlagsDescription :: ProgramConfiguration -> String
programFlagsDescription progConf =
"The flags --with-PROG and --PROG-option(s) can be used with"
++ " the following programs:"
++ (concatMap (\line -> "\n " ++ unwords line) . wrapLine 77 . sort)
[ programName prog | (prog, _) <- knownPrograms progConf ]
++ "\n"
-- | For each known program @PROG@ in 'progConf', produce a @with-PROG@
-- 'OptionField'.
programConfigurationPaths
:: ProgramConfiguration
-> ShowOrParseArgs
-> (flags -> [(String, FilePath)])
-> ([(String, FilePath)] -> (flags -> flags))
-> [OptionField flags]
programConfigurationPaths progConf showOrParseArgs get set =
programConfigurationPaths' ("with-" ++) progConf showOrParseArgs get set
-- | Like 'programConfigurationPaths', but allows to customise the option name.
programConfigurationPaths'
:: (String -> String)
-> ProgramConfiguration
-> ShowOrParseArgs
-> (flags -> [(String, FilePath)])
-> ([(String, FilePath)] -> (flags -> flags))
-> [OptionField flags]
programConfigurationPaths' mkName progConf showOrParseArgs get set =
case showOrParseArgs of
-- we don't want a verbose help text list so we just show a generic one:
ShowArgs -> [withProgramPath "PROG"]
ParseArgs -> map (withProgramPath . programName . fst)
(knownPrograms progConf)
where
withProgramPath prog =
option "" [mkName prog]
("give the path to " ++ prog)
get set
(reqArg' "PATH" (\path -> [(prog, path)])
(\progPaths -> [ path | (prog', path) <- progPaths, prog==prog' ]))
-- | For each known program @PROG@ in 'progConf', produce a @PROG-option@
-- 'OptionField'.
programConfigurationOption
:: ProgramConfiguration
-> ShowOrParseArgs
-> (flags -> [(String, [String])])
-> ([(String, [String])] -> (flags -> flags))
-> [OptionField flags]
programConfigurationOption progConf showOrParseArgs get set =
case showOrParseArgs of
-- we don't want a verbose help text list so we just show a generic one:
ShowArgs -> [programOption "PROG"]
ParseArgs -> map (programOption . programName . fst)
(knownPrograms progConf)
where
programOption prog =
option "" [prog ++ "-option"]
("give an extra option to " ++ prog ++
" (no need to quote options containing spaces)")
get set
(reqArg' "OPT" (\arg -> [(prog, [arg])])
(\progArgs -> concat [ args
| (prog', args) <- progArgs, prog==prog' ]))
-- | For each known program @PROG@ in 'progConf', produce a @PROG-options@
-- 'OptionField'.
programConfigurationOptions
:: ProgramConfiguration
-> ShowOrParseArgs
-> (flags -> [(String, [String])])
-> ([(String, [String])] -> (flags -> flags))
-> [OptionField flags]
programConfigurationOptions progConf showOrParseArgs get set =
case showOrParseArgs of
-- we don't want a verbose help text list so we just show a generic one:
ShowArgs -> [programOptions "PROG"]
ParseArgs -> map (programOptions . programName . fst)
(knownPrograms progConf)
where
programOptions prog =
option "" [prog ++ "-options"]
("give extra options to " ++ prog)
get set
(reqArg' "OPTS" (\args -> [(prog, splitArgs args)]) (const []))
-- ------------------------------------------------------------
-- * GetOpt Utils
-- ------------------------------------------------------------
boolOpt :: SFlags -> SFlags
-> MkOptDescr (a -> Flag Bool) (Flag Bool -> a -> a) a
boolOpt = Command.boolOpt flagToMaybe Flag
boolOpt' :: OptFlags -> OptFlags
-> MkOptDescr (a -> Flag Bool) (Flag Bool -> a -> a) a
boolOpt' = Command.boolOpt' flagToMaybe Flag
trueArg, falseArg :: MkOptDescr (a -> Flag Bool) (Flag Bool -> a -> a) a
trueArg sfT lfT = boolOpt' (sfT, lfT) ([], []) sfT lfT
falseArg sfF lfF = boolOpt' ([], []) (sfF, lfF) sfF lfF
reqArgFlag :: ArgPlaceHolder -> SFlags -> LFlags -> Description ->
(b -> Flag String) -> (Flag String -> b -> b) -> OptDescr b
reqArgFlag ad = reqArg ad (succeedReadE Flag) flagToList
optionDistPref :: (flags -> Flag FilePath)
-> (Flag FilePath -> flags -> flags)
-> ShowOrParseArgs
-> OptionField flags
optionDistPref get set = \showOrParseArgs ->
option "" (distPrefFlagName showOrParseArgs)
( "The directory where Cabal puts generated build files "
++ "(default " ++ defaultDistPref ++ ")")
get set
(reqArgFlag "DIR")
where
distPrefFlagName ShowArgs = ["builddir"]
distPrefFlagName ParseArgs = ["builddir", "distdir", "distpref"]
optionVerbosity :: (flags -> Flag Verbosity)
-> (Flag Verbosity -> flags -> flags)
-> OptionField flags
optionVerbosity get set =
option "v" ["verbose"]
"Control verbosity (n is 0--3, default verbosity level is 1)"
get set
(optArg "n" (fmap Flag flagToVerbosity)
(Flag verbose) -- default Value if no n is given
(fmap (Just . showForCabal) . flagToList))
optionNumJobs :: (flags -> Flag (Maybe Int))
-> (Flag (Maybe Int) -> flags -> flags)
-> OptionField flags
optionNumJobs get set =
option "j" ["jobs"]
"Run NUM jobs simultaneously (or '$ncpus' if no NUM is given)."
get set
(optArg "NUM" (fmap Flag numJobsParser)
(Flag Nothing)
(map (Just . maybe "$ncpus" show) . flagToList))
where
numJobsParser :: ReadE (Maybe Int)
numJobsParser = ReadE $ \s ->
case s of
"$ncpus" -> Right Nothing
_ -> case reads s of
[(n, "")]
| n < 1 -> Left "The number of jobs should be 1 or more."
| n > 64 -> Left "You probably don't want that many jobs."
| otherwise -> Right (Just n)
_ -> Left "The jobs value should be a number or '$ncpus'"
-- ------------------------------------------------------------
-- * Other Utils
-- ------------------------------------------------------------
-- | Arguments to pass to a @configure@ script, e.g. generated by
-- @autoconf@.
configureArgs :: Bool -> ConfigFlags -> [String]
configureArgs bcHack flags
= hc_flag
++ optFlag "with-hc-pkg" configHcPkg
++ optFlag' "prefix" prefix
++ optFlag' "bindir" bindir
++ optFlag' "libdir" libdir
++ optFlag' "libexecdir" libexecdir
++ optFlag' "datadir" datadir
++ optFlag' "sysconfdir" sysconfdir
++ configConfigureArgs flags
where
hc_flag = case (configHcFlavor flags, configHcPath flags) of
(_, Flag hc_path) -> [hc_flag_name ++ hc_path]
(Flag hc, NoFlag) -> [hc_flag_name ++ display hc]
(NoFlag,NoFlag) -> []
hc_flag_name
--TODO kill off thic bc hack when defaultUserHooks is removed.
| bcHack = "--with-hc="
| otherwise = "--with-compiler="
optFlag name config_field = case config_field flags of
Flag p -> ["--" ++ name ++ "=" ++ p]
NoFlag -> []
optFlag' name config_field = optFlag name (fmap fromPathTemplate
. config_field
. configInstallDirs)
configureCCompiler :: Verbosity -> ProgramConfiguration
-> IO (FilePath, [String])
configureCCompiler verbosity lbi = configureProg verbosity lbi gccProgram
configureLinker :: Verbosity -> ProgramConfiguration -> IO (FilePath, [String])
configureLinker verbosity lbi = configureProg verbosity lbi ldProgram
configureProg :: Verbosity -> ProgramConfiguration -> Program
-> IO (FilePath, [String])
configureProg verbosity programConfig prog = do
(p, _) <- requireProgram verbosity prog programConfig
let pInv = programInvocation p []
return (progInvokePath pInv, progInvokeArgs pInv)
-- | Helper function to split a string into a list of arguments.
-- It's supposed to handle quoted things sensibly, eg:
--
-- > splitArgs "--foo=\"C:\Program Files\Bar\" --baz"
-- > = ["--foo=C:\Program Files\Bar", "--baz"]
--
splitArgs :: String -> [String]
splitArgs = space []
where
space :: String -> String -> [String]
space w [] = word w []
space w ( c :s)
| isSpace c = word w (space [] s)
space w ('"':s) = string w s
space w s = nonstring w s
string :: String -> String -> [String]
string w [] = word w []
string w ('"':s) = space w s
string w ( c :s) = string (c:w) s
nonstring :: String -> String -> [String]
nonstring w [] = word w []
nonstring w ('"':s) = string w s
nonstring w ( c :s) = space (c:w) s
word [] s = s
word w s = reverse w : s
-- The test cases kinda have to be rewritten from the ground up... :/
--hunitTests :: [Test]
--hunitTests =
-- let m = [("ghc", GHC), ("nhc98", NHC), ("hugs", Hugs)]
-- (flags, commands', unkFlags, ers)
-- = getOpt Permute options ["configure", "foobar", "--prefix=/foo", "--ghc", "--nhc98", "--hugs", "--with-compiler=/comp", "--unknown1", "--unknown2", "--install-prefix=/foo", "--user", "--global"]
-- in [TestLabel "very basic option parsing" $ TestList [
-- "getOpt flags" ~: "failed" ~:
-- [Prefix "/foo", GhcFlag, NhcFlag, HugsFlag,
-- WithCompiler "/comp", InstPrefix "/foo", UserFlag, GlobalFlag]
-- ~=? flags,
-- "getOpt commands" ~: "failed" ~: ["configure", "foobar"] ~=? commands',
-- "getOpt unknown opts" ~: "failed" ~:
-- ["--unknown1", "--unknown2"] ~=? unkFlags,
-- "getOpt errors" ~: "failed" ~: [] ~=? ers],
--
-- TestLabel "test location of various compilers" $ TestList
-- ["configure parsing for prefix and compiler flag" ~: "failed" ~:
-- (Right (ConfigCmd (Just comp, Nothing, Just "/usr/local"), []))
-- ~=? (parseArgs ["--prefix=/usr/local", "--"++name, "configure"])
-- | (name, comp) <- m],
--
-- TestLabel "find the package tool" $ TestList
-- ["configure parsing for prefix comp flag, withcompiler" ~: "failed" ~:
-- (Right (ConfigCmd (Just comp, Just "/foo/comp", Just "/usr/local"), []))
-- ~=? (parseArgs ["--prefix=/usr/local", "--"++name,
-- "--with-compiler=/foo/comp", "configure"])
-- | (name, comp) <- m],
--
-- TestLabel "simpler commands" $ TestList
-- [flag ~: "failed" ~: (Right (flagCmd, [])) ~=? (parseArgs [flag])
-- | (flag, flagCmd) <- [("build", BuildCmd),
-- ("install", InstallCmd Nothing False),
-- ("sdist", SDistCmd),
-- ("register", RegisterCmd False)]
-- ]
-- ]
{- Testing ideas:
* IO to look for hugs and hugs-pkg (which hugs, etc)
* quickCheck to test permutations of arguments
* what other options can we over-ride with a command-line flag?
-}
| randen/cabal | Cabal/Distribution/Simple/Setup.hs | bsd-3-clause | 89,397 | 0 | 26 | 24,015 | 18,104 | 10,250 | 7,854 | 1,738 | 10 |
{-
(c) The University of Glasgow, 2000-2006
\section{Fast booleans}
-}
{-# LANGUAGE CPP, MagicHash #-}
module Eta.Utils.FastBool (
--fastBool could be called bBox; isFastTrue, bUnbox; but they're not
FastBool, fastBool, isFastTrue, fastOr, fastAnd
) where
-- Import the beggars
import GHC.Exts
#ifdef DEBUG
import Eta.Utils.Panic
#endif
type FastBool = Int#
fastBool True = 1#
fastBool False = 0#
#ifdef DEBUG
--then waste time deciding whether to panic. FastBool should normally
--be at least as fast as Bool, one would hope...
isFastTrue 1# = True
isFastTrue 0# = False
isFastTrue _ = panic "FastTypes: isFastTrue"
-- note that fastOr and fastAnd are strict in both arguments
-- since they are unboxed
fastOr 1# _ = 1#
fastOr 0# x = x
fastOr _ _ = panicFastInt "FastTypes: fastOr"
fastAnd 0# _ = 0#
fastAnd 1# x = x
fastAnd _ _ = panicFastInt "FastTypes: fastAnd"
--these "panicFastInt"s (formerly known as "panic#") rely on
--FastInt = FastBool ( = Int# presumably),
--haha, true enough when __GLASGOW_HASKELL__. Why can't we have functions
--that return _|_ be kind-polymorphic ( ?? to be precise ) ?
#else /* ! DEBUG */
--Isn't comparison to zero sometimes faster on CPUs than comparison to 1?
-- (since using Int# as _synonym_ fails to guarantee that it will
-- only take on values of 0 and 1)
isFastTrue 0# = False
isFastTrue _ = True
-- note that fastOr and fastAnd are strict in both arguments
-- since they are unboxed
-- Also, to avoid incomplete-pattern warning
-- (and avoid wasting time with redundant runtime checks),
-- we don't pattern-match on both 0# and 1# .
fastOr 0# x = x
fastOr _ _ = 1#
fastAnd 0# _ = 0#
fastAnd _ x = x
#endif /* ! DEBUG */
fastBool :: Bool -> FastBool
isFastTrue :: FastBool -> Bool
fastOr :: FastBool -> FastBool -> FastBool
fastAnd :: FastBool -> FastBool -> FastBool
| rahulmutt/ghcvm | compiler/Eta/Utils/FastBool.hs | bsd-3-clause | 1,846 | 0 | 6 | 350 | 211 | 121 | 90 | 17 | 1 |
-- | see http://www.cs.cmu.edu/~emc/15414-f11/assignments/hw2.pdf
module DPLL.Pigeon where
import DPLL.Data
import DPLL.Solve
import DPLL.Trace (modus0)
pigeon :: Int -> Int -> CNF
pigeon pigs holes =
let encode p h = Literal $ (p - 1) * holes + h
in do p <- [ 1 .. pigs ]
return $ do h <- [ 1 .. holes ] ; return $ encode p h
++ do h <- [ 1 .. holes ]
p <- [ 1.. pigs ] ; q <- [p+1 .. pigs]
return [ opposite $ encode p h, opposite $ encode q h ]
| marcellussiegburg/autotool | collection/src/FD/Pigeon.hs | gpl-2.0 | 523 | 0 | 14 | 173 | 208 | 108 | 100 | 12 | 1 |
{-# language ViewPatterns, ScopedTypeVariables, FlexibleInstances, DeriveDataTypeable #-}
module Sorts.Nikki.Types where
import Prelude hiding (lookup)
import Data.Map (Map)
import Data.Data
import Data.Initial
import Data.Abelian
import Data.Directions
import qualified Data.Strict as Strict
import Data.Accessor
import Graphics.Qt as Qt hiding (rotate, scale)
import Sound.SFML
import Physics.Chipmunk hiding (position, Position)
import Utils
import Base
data NSort = NSort {
pixmaps :: Map String [Pixmap],
jumpSound :: PolySound,
batteryCollectSound :: PolySound
}
deriving (Show, Typeable)
isNikki :: Sort sort o => sort -> Bool
isNikki (cast -> Just _ :: Maybe NSort) = True
isNikki (cast -> Just (Sort_ inner) :: Maybe Sort_) = isNikki inner
isNikki _ = False
data Nikki
= Nikki {
chipmunk :: Chipmunk,
feetShape :: !(Strict.Maybe Shape), -- Nothing if Nikki isn't in the main layer
state :: !State,
startTime :: !Seconds -- time the State was last changed
}
deriving (Show, Typeable)
unwrapNikki :: Object_ -> Maybe Nikki
unwrapNikki (Object_ sort o) = cast o
instance Show (Ptr QPainter -> Offset Double -> IO ()) where
show _ = "<Ptr QPainter -> Offset Double -> IO ()>"
data State = State {
action :: !Action,
direction :: !HorizontalDirection, -- the direction nikki faces
feetVelocity :: !CpFloat,
jumpInformation :: !JumpInformation,
ghostTimes :: !GhostTimes
-- dustClouds :: [DustCloud]
}
deriving (Show)
instance Initial State where
initial = State Airborne HRight 0 initial initial
data Action
= Wait {collision :: !NikkiCollision, ghost :: !Bool}
| Walk {afterAirborne :: !Bool, collision :: !NikkiCollision, ghost :: !Bool}
-- state for one frame (when a jump starts)
| JumpImpulse !NikkiCollision
| Airborne
| WallSlide_ [NikkiCollision] !NikkiCollision -- use wallSlide to be strict
| UsingTerminal
| SlideToGrip !HorizontalDirection -- to which side is the collision
| Grip -- when Nikki uses the paws to hold on to something
| GripImpulse -- state for one frame (when grip state is ended)
| NikkiLevelFinished LevelResult
deriving (Show)
wallSlide angles = seq (foldr seq () angles) $ WallSlide_ angles
toActionNumber Wait{} = 0
toActionNumber Walk{} = 1
toActionNumber JumpImpulse{} = 2
toActionNumber Airborne{} = 3
toActionNumber WallSlide_{} = 4
toActionNumber UsingTerminal = 5
toActionNumber SlideToGrip{} = 6
toActionNumber Grip = 7
toActionNumber GripImpulse = 8
toActionNumber NikkiLevelFinished{} = 9
isWaitAction, isWalkAction, isJumpImpulseAction,
isAirborneAction, isWallSlideAction, isSlideToGripAction :: Action -> Bool
isWaitAction = (0 ==) . toActionNumber
isWalkAction = (1 ==) . toActionNumber
isJumpImpulseAction = (2 ==) . toActionNumber
isAirborneAction = (3 ==) . toActionNumber
isWallSlideAction = (4 ==) . toActionNumber
isSlideToGripAction = (6 ==) . toActionNumber
data JumpInformation =
JumpInformation {
jumpStartTime :: !(Strict.Maybe Seconds),
jumpCollisionAngle :: !(Strict.Maybe Angle),
jumpNikkiVelocity :: !Velocity,
jumpButtonDirection :: !(Strict.Maybe HorizontalDirection)
}
deriving (Show)
instance Initial JumpInformation where
initial = JumpInformation Strict.Nothing Strict.Nothing zero Strict.Nothing
data GhostTimes
= GhostTimes {
standingGhostTime_ :: !(Strict.Maybe (Pair Seconds NikkiCollision)),
wallSlideGhostTime_ :: !(Strict.Maybe (Pair Seconds NikkiCollision))
}
deriving (Show)
standingGhostTime, wallSlideGhostTime ::
Accessor GhostTimes (Strict.Maybe (Pair Seconds NikkiCollision))
standingGhostTime = accessor standingGhostTime_ (\ a r -> r{standingGhostTime_ = a})
wallSlideGhostTime = accessor wallSlideGhostTime_ (\ a r -> r{wallSlideGhostTime_ = a})
instance Initial GhostTimes where
initial = GhostTimes Strict.Nothing Strict.Nothing
instance PP GhostTimes where
pp (GhostTimes a b) = i a <~> "|" <~> i b
where
i Strict.Nothing = "-"
i (Strict.Just (_ :!: c)) = pp (nikkiCollisionAngle c)
flattenGhostTime :: GhostTimes -> Strict.Maybe (Pair Seconds NikkiCollision)
flattenGhostTime (GhostTimes a b) =
a <|> b
data DustCloud
= DustCloud {
creationTime :: Seconds,
cloudPosition :: Qt.Position Double
}
deriving (Show)
| geocurnoff/nikki | src/Sorts/Nikki/Types.hs | lgpl-3.0 | 4,541 | 0 | 13 | 999 | 1,192 | 656 | 536 | 151 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Bits
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- This module defines bitwise operations for signed and unsigned
-- integers. Instances of the class 'Bits' for the 'Int' and
-- 'Integer' types are available from this module, and instances for
-- explicitly sized integral types are available from the
-- "Data.Int" and "Data.Word" modules.
--
-----------------------------------------------------------------------------
module Data.Bits (
Bits(
(.&.), (.|.), xor,
complement,
shift,
rotate,
zeroBits,
bit,
setBit,
clearBit,
complementBit,
testBit,
bitSizeMaybe,
bitSize,
isSigned,
shiftL, shiftR,
unsafeShiftL, unsafeShiftR,
rotateL, rotateR,
popCount
),
FiniteBits(
finiteBitSize,
countLeadingZeros,
countTrailingZeros
),
bitDefault,
testBitDefault,
popCountDefault,
toIntegralSized
) where
-- Defines the @Bits@ class containing bit-based operations.
-- See library document for details on the semantics of the
-- individual operations.
#define WORD_SIZE_IN_BITS 32
import Data.Maybe
import GHC.Enum
import GHC.Num
import GHC.Base
import GHC.Real
infixl 8 `shift`, `rotate`, `shiftL`, `shiftR`, `rotateL`, `rotateR`
infixl 7 .&.
infixl 6 `xor`
infixl 5 .|.
{-# DEPRECATED bitSize "Use 'bitSizeMaybe' or 'finiteBitSize' instead" #-} -- deprecated in 7.8
-- | The 'Bits' class defines bitwise operations over integral types.
--
-- * Bits are numbered from 0 with bit 0 being the least
-- significant bit.
class Eq a => Bits a where
{-# MINIMAL (.&.), (.|.), xor, complement,
(shift | (shiftL, shiftR)),
(rotate | (rotateL, rotateR)),
bitSize, bitSizeMaybe, isSigned, testBit, bit, popCount #-}
-- | Bitwise \"and\"
(.&.) :: a -> a -> a
-- | Bitwise \"or\"
(.|.) :: a -> a -> a
-- | Bitwise \"xor\"
xor :: a -> a -> a
{-| Reverse all the bits in the argument -}
complement :: a -> a
{-| @'shift' x i@ shifts @x@ left by @i@ bits if @i@ is positive,
or right by @-i@ bits otherwise.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
An instance can define either this unified 'shift' or 'shiftL' and
'shiftR', depending on which is more convenient for the type in
question. -}
shift :: a -> Int -> a
x `shift` i | i<0 = x `shiftR` (-i)
| i>0 = x `shiftL` i
| otherwise = x
{-| @'rotate' x i@ rotates @x@ left by @i@ bits if @i@ is positive,
or right by @-i@ bits otherwise.
For unbounded types like 'Integer', 'rotate' is equivalent to 'shift'.
An instance can define either this unified 'rotate' or 'rotateL' and
'rotateR', depending on which is more convenient for the type in
question. -}
rotate :: a -> Int -> a
x `rotate` i | i<0 = x `rotateR` (-i)
| i>0 = x `rotateL` i
| otherwise = x
{-
-- Rotation can be implemented in terms of two shifts, but care is
-- needed for negative values. This suggested implementation assumes
-- 2's-complement arithmetic. It is commented out because it would
-- require an extra context (Ord a) on the signature of 'rotate'.
x `rotate` i | i<0 && isSigned x && x<0
= let left = i+bitSize x in
((x `shift` i) .&. complement ((-1) `shift` left))
.|. (x `shift` left)
| i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x))
| i==0 = x
| i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x))
-}
-- | 'zeroBits' is the value with all bits unset.
--
-- The following laws ought to hold (for all valid bit indices @/n/@):
--
-- * @'clearBit' 'zeroBits' /n/ == 'zeroBits'@
-- * @'setBit' 'zeroBits' /n/ == 'bit' /n/@
-- * @'testBit' 'zeroBits' /n/ == False@
-- * @'popCount' 'zeroBits' == 0@
--
-- This method uses @'clearBit' ('bit' 0) 0@ as its default
-- implementation (which ought to be equivalent to 'zeroBits' for
-- types which possess a 0th bit).
--
-- @since 4.7.0.0
zeroBits :: a
zeroBits = clearBit (bit 0) 0
-- | @bit /i/@ is a value with the @/i/@th bit set and all other bits clear.
--
-- Can be implemented using `bitDefault' if @a@ is also an
-- instance of 'Num'.
--
-- See also 'zeroBits'.
bit :: Int -> a
-- | @x \`setBit\` i@ is the same as @x .|. bit i@
setBit :: a -> Int -> a
-- | @x \`clearBit\` i@ is the same as @x .&. complement (bit i)@
clearBit :: a -> Int -> a
-- | @x \`complementBit\` i@ is the same as @x \`xor\` bit i@
complementBit :: a -> Int -> a
-- | Return 'True' if the @n@th bit of the argument is 1
--
-- Can be implemented using `testBitDefault' if @a@ is also an
-- instance of 'Num'.
testBit :: a -> Int -> Bool
{-| Return the number of bits in the type of the argument. The actual
value of the argument is ignored. Returns Nothing
for types that do not have a fixed bitsize, like 'Integer'.
@since 4.7.0.0
-}
bitSizeMaybe :: a -> Maybe Int
{-| Return the number of bits in the type of the argument. The actual
value of the argument is ignored. The function 'bitSize' is
undefined for types that do not have a fixed bitsize, like 'Integer'.
-}
bitSize :: a -> Int
{-| Return 'True' if the argument is a signed type. The actual
value of the argument is ignored -}
isSigned :: a -> Bool
{-# INLINE setBit #-}
{-# INLINE clearBit #-}
{-# INLINE complementBit #-}
x `setBit` i = x .|. bit i
x `clearBit` i = x .&. complement (bit i)
x `complementBit` i = x `xor` bit i
{-| Shift the argument left by the specified number of bits
(which must be non-negative).
An instance can define either this and 'shiftR' or the unified
'shift', depending on which is more convenient for the type in
question. -}
shiftL :: a -> Int -> a
{-# INLINE shiftL #-}
x `shiftL` i = x `shift` i
{-| Shift the argument left by the specified number of bits. The
result is undefined for negative shift amounts and shift amounts
greater or equal to the 'bitSize'.
Defaults to 'shiftL' unless defined explicitly by an instance.
@since 4.5.0.0 -}
unsafeShiftL :: a -> Int -> a
{-# INLINE unsafeShiftL #-}
x `unsafeShiftL` i = x `shiftL` i
{-| Shift the first argument right by the specified number of bits. The
result is undefined for negative shift amounts and shift amounts
greater or equal to the 'bitSize'.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
An instance can define either this and 'shiftL' or the unified
'shift', depending on which is more convenient for the type in
question. -}
shiftR :: a -> Int -> a
{-# INLINE shiftR #-}
x `shiftR` i = x `shift` (-i)
{-| Shift the first argument right by the specified number of bits, which
must be non-negative an smaller than the number of bits in the type.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
Defaults to 'shiftR' unless defined explicitly by an instance.
@since 4.5.0.0 -}
unsafeShiftR :: a -> Int -> a
{-# INLINE unsafeShiftR #-}
x `unsafeShiftR` i = x `shiftR` i
{-| Rotate the argument left by the specified number of bits
(which must be non-negative).
An instance can define either this and 'rotateR' or the unified
'rotate', depending on which is more convenient for the type in
question. -}
rotateL :: a -> Int -> a
{-# INLINE rotateL #-}
x `rotateL` i = x `rotate` i
{-| Rotate the argument right by the specified number of bits
(which must be non-negative).
An instance can define either this and 'rotateL' or the unified
'rotate', depending on which is more convenient for the type in
question. -}
rotateR :: a -> Int -> a
{-# INLINE rotateR #-}
x `rotateR` i = x `rotate` (-i)
{-| Return the number of set bits in the argument. This number is
known as the population count or the Hamming weight.
Can be implemented using `popCountDefault' if @a@ is also an
instance of 'Num'.
@since 4.5.0.0 -}
popCount :: a -> Int
-- |The 'FiniteBits' class denotes types with a finite, fixed number of bits.
--
-- @since 4.7.0.0
class Bits b => FiniteBits b where
-- | Return the number of bits in the type of the argument.
-- The actual value of the argument is ignored. Moreover, 'finiteBitSize'
-- is total, in contrast to the deprecated 'bitSize' function it replaces.
--
-- @
-- 'finiteBitSize' = 'bitSize'
-- 'bitSizeMaybe' = 'Just' . 'finiteBitSize'
-- @
--
-- @since 4.7.0.0
finiteBitSize :: b -> Int
-- | Count number of zero bits preceding the most significant set bit.
--
-- @
-- 'countLeadingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)
-- @
--
-- 'countLeadingZeros' can be used to compute log base 2 via
--
-- @
-- logBase2 x = 'finiteBitSize' x - 1 - 'countLeadingZeros' x
-- @
--
-- Note: The default implementation for this method is intentionally
-- naive. However, the instances provided for the primitive
-- integral types are implemented using CPU specific machine
-- instructions.
--
-- @since 4.8.0.0
countLeadingZeros :: b -> Int
countLeadingZeros x = (w-1) - go (w-1)
where
go i | i < 0 = i -- no bit set
| testBit x i = i
| otherwise = go (i-1)
w = finiteBitSize x
-- | Count number of zero bits following the least significant set bit.
--
-- @
-- 'countTrailingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)
-- 'countTrailingZeros' . 'negate' = 'countTrailingZeros'
-- @
--
-- The related
-- <http://en.wikipedia.org/wiki/Find_first_set find-first-set operation>
-- can be expressed in terms of 'countTrailingZeros' as follows
--
-- @
-- findFirstSet x = 1 + 'countTrailingZeros' x
-- @
--
-- Note: The default implementation for this method is intentionally
-- naive. However, the instances provided for the primitive
-- integral types are implemented using CPU specific machine
-- instructions.
--
-- @since 4.8.0.0
countTrailingZeros :: b -> Int
countTrailingZeros x = go 0
where
go i | i >= w = i
| testBit x i = i
| otherwise = go (i+1)
w = finiteBitSize x
-- The defaults below are written with lambdas so that e.g.
-- bit = bitDefault
-- is fully applied, so inlining will happen
-- | Default implementation for 'bit'.
--
-- Note that: @bitDefault i = 1 `shiftL` i@
--
-- @since 4.6.0.0
bitDefault :: (Bits a, Num a) => Int -> a
bitDefault = \i -> 1 `shiftL` i
{-# INLINE bitDefault #-}
-- | Default implementation for 'testBit'.
--
-- Note that: @testBitDefault x i = (x .&. bit i) /= 0@
--
-- @since 4.6.0.0
testBitDefault :: (Bits a, Num a) => a -> Int -> Bool
testBitDefault = \x i -> (x .&. bit i) /= 0
{-# INLINE testBitDefault #-}
-- | Default implementation for 'popCount'.
--
-- This implementation is intentionally naive. Instances are expected to provide
-- an optimized implementation for their size.
--
-- @since 4.6.0.0
popCountDefault :: (Bits a, Num a) => a -> Int
popCountDefault = go 0
where
go !c 0 = c
go c w = go (c+1) (w .&. (w - 1)) -- clear the least significant
{-# INLINABLE popCountDefault #-}
-- Interpret 'Bool' as 1-bit bit-field; @since 4.7.0.0
instance Bits Bool where
(.&.) = (&&)
(.|.) = (||)
xor = (/=)
complement = not
shift x 0 = x
shift _ _ = False
rotate x _ = x
bit 0 = True
bit _ = False
testBit x 0 = x
testBit _ _ = False
bitSizeMaybe _ = Just 1
bitSize _ = 1
isSigned _ = False
popCount False = 0
popCount True = 1
instance FiniteBits Bool where
finiteBitSize _ = 1
countTrailingZeros x = if x then 0 else 1
countLeadingZeros x = if x then 0 else 1
instance Bits Int where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
zeroBits = 0
bit = bitDefault
testBit = testBitDefault
(I# x#) .&. (I# y#) = I# (x# `andI#` y#)
(I# x#) .|. (I# y#) = I# (x# `orI#` y#)
(I# x#) `xor` (I# y#) = I# (x# `xorI#` y#)
complement (I# x#) = I# (notI# x#)
(I# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = I# (x# `iShiftL#` i#)
| otherwise = I# (x# `iShiftRA#` negateInt# i#)
(I# x#) `shiftL` (I# i#) = I# (x# `iShiftL#` i#)
(I# x#) `unsafeShiftL` (I# i#) = I# (x# `uncheckedIShiftL#` i#)
(I# x#) `shiftR` (I# i#) = I# (x# `iShiftRA#` i#)
(I# x#) `unsafeShiftR` (I# i#) = I# (x# `uncheckedIShiftRA#` i#)
{-# INLINE rotate #-} -- See Note [Constant folding for rotate]
(I# x#) `rotate` (I# i#) =
I# ((x# `uncheckedIShiftL#` i'#) `orI#` (x# `uncheckedIShiftRL#` (wsib -# i'#)))
where
!i'# = i# `andI#` (wsib -# 1#)
!wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -}
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
popCount (I# x#) = I# (word2Int# (popCnt# (int2Word# x#)))
isSigned _ = True
instance FiniteBits Int where
finiteBitSize _ = WORD_SIZE_IN_BITS
countLeadingZeros (I# x#) = I# (word2Int# (clz# (int2Word# x#)))
countTrailingZeros (I# x#) = I# (word2Int# (ctz# (int2Word# x#)))
instance Bits Word where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W# x#) .&. (W# y#) = W# (x# `and#` y#)
(W# x#) .|. (W# y#) = W# (x# `or#` y#)
(W# x#) `xor` (W# y#) = W# (x# `xor#` y#)
complement (W# x#) = W# (x# `xor#` mb#)
where !(W# mb#) = maxBound
(W# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W# (x# `shiftL#` i#)
| otherwise = W# (x# `shiftRL#` negateInt# i#)
(W# x#) `shiftL` (I# i#) = W# (x# `shiftL#` i#)
(W# x#) `unsafeShiftL` (I# i#) = W# (x# `uncheckedShiftL#` i#)
(W# x#) `shiftR` (I# i#) = W# (x# `shiftRL#` i#)
(W# x#) `unsafeShiftR` (I# i#) = W# (x# `uncheckedShiftRL#` i#)
(W# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W# x#
| otherwise = W# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (wsib -# i'#)))
where
!i'# = i# `andI#` (wsib -# 1#)
!wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -}
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W# x#) = I# (word2Int# (popCnt# x#))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Word where
finiteBitSize _ = WORD_SIZE_IN_BITS
countLeadingZeros (W# x#) = I# (word2Int# (clz# x#))
countTrailingZeros (W# x#) = I# (word2Int# (ctz# x#))
instance Bits Integer where
(.&.) = andInteger
(.|.) = orInteger
xor = xorInteger
complement = complementInteger
shift x i@(I# i#) | i >= 0 = shiftLInteger x i#
| otherwise = shiftRInteger x (negateInt# i#)
shiftL x i@(I# i#)
| i < 0 = error "Bits.shiftL(Integer): negative shift"
| otherwise = shiftLInteger x i#
shiftR x i@(I# i#)
| i < 0 = error "Bits.shiftR(Integer): negative shift"
| otherwise = shiftRInteger x i#
testBit x (I# i) = testBitInteger x i
zeroBits = 0
bit = bitDefault
popCount = popCountDefault
rotate x i = shift x i -- since an Integer never wraps around
bitSizeMaybe _ = Nothing
bitSize _ = error "Data.Bits.bitSize(Integer)"
isSigned _ = True
-----------------------------------------------------------------------------
-- | Attempt to convert an 'Integral' type @a@ to an 'Integral' type @b@ using
-- the size of the types as measured by 'Bits' methods.
--
-- A simpler version of this function is:
--
-- > toIntegral :: (Integral a, Integral b) => a -> Maybe b
-- > toIntegral x
-- > | toInteger x == y = Just (fromInteger y)
-- > | otherwise = Nothing
-- > where
-- > y = toInteger x
--
-- This version requires going through 'Integer', which can be inefficient.
-- However, @toIntegralSized@ is optimized to allow GHC to statically determine
-- the relative type sizes (as measured by 'bitSizeMaybe' and 'isSigned') and
-- avoid going through 'Integer' for many types. (The implementation uses
-- 'fromIntegral', which is itself optimized with rules for @base@ types but may
-- go through 'Integer' for some type pairs.)
--
-- @since 4.8.0.0
toIntegralSized :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b
toIntegralSized x -- See Note [toIntegralSized optimization]
| maybe True (<= x) yMinBound
, maybe True (x <=) yMaxBound = Just y
| otherwise = Nothing
where
y = fromIntegral x
xWidth = bitSizeMaybe x
yWidth = bitSizeMaybe y
yMinBound
| isBitSubType x y = Nothing
| isSigned x, not (isSigned y) = Just 0
| isSigned x, isSigned y
, Just yW <- yWidth = Just (negate $ bit (yW-1)) -- Assumes sub-type
| otherwise = Nothing
yMaxBound
| isBitSubType x y = Nothing
| isSigned x, not (isSigned y)
, Just xW <- xWidth, Just yW <- yWidth
, xW <= yW+1 = Nothing -- Max bound beyond a's domain
| Just yW <- yWidth = if isSigned y
then Just (bit (yW-1)-1)
else Just (bit yW-1)
| otherwise = Nothing
{-# INLINEABLE toIntegralSized #-}
-- | 'True' if the size of @a@ is @<=@ the size of @b@, where size is measured
-- by 'bitSizeMaybe' and 'isSigned'.
isBitSubType :: (Bits a, Bits b) => a -> b -> Bool
isBitSubType x y
-- Reflexive
| xWidth == yWidth, xSigned == ySigned = True
-- Every integer is a subset of 'Integer'
| ySigned, Nothing == yWidth = True
| not xSigned, not ySigned, Nothing == yWidth = True
-- Sub-type relations between fixed-with types
| xSigned == ySigned, Just xW <- xWidth, Just yW <- yWidth = xW <= yW
| not xSigned, ySigned, Just xW <- xWidth, Just yW <- yWidth = xW < yW
| otherwise = False
where
xWidth = bitSizeMaybe x
xSigned = isSigned x
yWidth = bitSizeMaybe y
ySigned = isSigned y
{-# INLINE isBitSubType #-}
{- Note [Constant folding for rotate]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The INLINE on the Int instance of rotate enables it to be constant
folded. For example:
sumU . mapU (`rotate` 3) . replicateU 10000000 $ (7 :: Int)
goes to:
Main.$wfold =
\ (ww_sO7 :: Int#) (ww1_sOb :: Int#) ->
case ww1_sOb of wild_XM {
__DEFAULT -> Main.$wfold (+# ww_sO7 56) (+# wild_XM 1);
10000000 -> ww_sO7
whereas before it was left as a call to $wrotate.
All other Bits instances seem to inline well enough on their
own to enable constant folding; for example 'shift':
sumU . mapU (`shift` 3) . replicateU 10000000 $ (7 :: Int)
goes to:
Main.$wfold =
\ (ww_sOb :: Int#) (ww1_sOf :: Int#) ->
case ww1_sOf of wild_XM {
__DEFAULT -> Main.$wfold (+# ww_sOb 56) (+# wild_XM 1);
10000000 -> ww_sOb
}
-}
-- Note [toIntegralSized optimization]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- The code in 'toIntegralSized' relies on GHC optimizing away statically
-- decidable branches.
--
-- If both integral types are statically known, GHC will be able optimize the
-- code significantly (for @-O1@ and better).
--
-- For instance (as of GHC 7.8.1) the following definitions:
--
-- > w16_to_i32 = toIntegralSized :: Word16 -> Maybe Int32
-- >
-- > i16_to_w16 = toIntegralSized :: Int16 -> Maybe Word16
--
-- are translated into the following (simplified) /GHC Core/ language:
--
-- > w16_to_i32 = \x -> Just (case x of _ { W16# x# -> I32# (word2Int# x#) })
-- >
-- > i16_to_w16 = \x -> case eta of _
-- > { I16# b1 -> case tagToEnum# (<=# 0 b1) of _
-- > { False -> Nothing
-- > ; True -> Just (W16# (narrow16Word# (int2Word# b1)))
-- > }
-- > }
| alexander-at-github/eta | libraries/base/Data/Bits.hs | bsd-3-clause | 21,596 | 0 | 14 | 6,360 | 3,688 | 2,043 | 1,645 | 260 | 2 |
{-# LANGUAGE CPP #-}
module ETA.Rename.RnSplice (
rnTopSpliceDecls,
rnSpliceType, rnSpliceExpr, rnSplicePat, rnSpliceDecl,
rnBracket,
checkThLocalName
) where
import ETA.BasicTypes.Name
import ETA.BasicTypes.NameSet
import ETA.HsSyn.HsSyn
import ETA.BasicTypes.RdrName
import ETA.TypeCheck.TcRnMonad
import ETA.Types.Kind
#ifdef GHCI
import ETA.Main.ErrUtils ( dumpIfSet_dyn_printer )
import Control.Monad ( unless, when )
import ETA.Main.DynFlags
import ETA.DeSugar.DsMeta ( decsQTyConName, expQTyConName, patQTyConName, typeQTyConName )
import ETA.Iface.LoadIface ( loadInterfaceForName )
import ETA.BasicTypes.Module
import ETA.Rename.RnEnv
import ETA.Rename.RnPat ( rnPat )
import ETA.Rename.RnSource ( rnSrcDecls, findSplice )
import ETA.Rename.RnTypes ( rnLHsType )
import ETA.BasicTypes.SrcLoc
import ETA.TypeCheck.TcEnv ( checkWellStaged, tcMetaTy )
import ETA.Utils.Outputable
import ETA.BasicTypes.BasicTypes ( TopLevelFlag, isTopLevel )
import ETA.Utils.FastString
import ETA.Main.Hooks
import {-# SOURCE #-} ETA.Rename.RnExpr ( rnLExpr )
import {-# SOURCE #-} ETA.TypeCheck.TcExpr ( tcMonoExpr )
import {-# SOURCE #-} ETA.TypeCheck.TcSplice ( runMetaD, runMetaE, runMetaP, runMetaT, tcTopSpliceExpr )
#endif
#ifndef GHCI
rnBracket :: HsExpr RdrName -> HsBracket RdrName -> RnM (HsExpr Name, FreeVars)
rnBracket e _ = failTH e "Template Haskell bracket"
rnTopSpliceDecls :: HsSplice RdrName -> RnM ([LHsDecl RdrName], FreeVars)
rnTopSpliceDecls e = failTH e "Template Haskell top splice"
rnSpliceType :: HsSplice RdrName -> PostTc Name Kind
-> RnM (HsType Name, FreeVars)
rnSpliceType e _ = failTH e "Template Haskell type splice"
rnSpliceExpr :: Bool -> HsSplice RdrName -> RnM (HsExpr Name, FreeVars)
rnSpliceExpr _ e = failTH e "Template Haskell splice"
rnSplicePat :: HsSplice RdrName -> RnM (Either (Pat RdrName) (Pat Name), FreeVars)
rnSplicePat e = failTH e "Template Haskell pattern splice"
rnSpliceDecl :: SpliceDecl RdrName -> RnM (SpliceDecl Name, FreeVars)
rnSpliceDecl e = failTH e "Template Haskell declaration splice"
#else
{-
*********************************************************
* *
Splices
* *
*********************************************************
Note [Free variables of typed splices]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider renaming this:
f = ...
h = ...$(thing "f")...
where the splice is a *typed* splice. The splice can expand into
literally anything, so when we do dependency analysis we must assume
that it might mention 'f'. So we simply treat all locally-defined
names as mentioned by any splice. This is terribly brutal, but I
don't see what else to do. For example, it'll mean that every
locally-defined thing will appear to be used, so no unused-binding
warnings. But if we miss the dependency, then we might typecheck 'h'
before 'f', and that will crash the type checker because 'f' isn't in
scope.
Currently, I'm not treating a splice as also mentioning every import,
which is a bit inconsistent -- but there are a lot of them. We might
thereby get some bogus unused-import warnings, but we won't crash the
type checker. Not very satisfactory really.
Note [Renamer errors]
~~~~~~~~~~~~~~~~~~~~~
It's important to wrap renamer calls in checkNoErrs, because the
renamer does not fail for out of scope variables etc. Instead it
returns a bogus term/type, so that it can report more than one error.
We don't want the type checker to see these bogus unbound variables.
-}
rnSpliceGen :: Bool -- Typed splice?
-> (HsSplice Name -> RnM (a, FreeVars)) -- Outside brackets, run splice
-> (HsSplice Name -> (PendingRnSplice, a)) -- Inside brackets, make it pending
-> HsSplice RdrName
-> RnM (a, FreeVars)
rnSpliceGen is_typed_splice run_splice pend_splice splice@(HsSplice _ expr)
= addErrCtxt (spliceCtxt (HsSpliceE is_typed_splice splice)) $
setSrcSpan (getLoc expr) $ do
{ stage <- getStage
; case stage of
Brack pop_stage RnPendingTyped
-> do { checkTc is_typed_splice illegalUntypedSplice
; (splice', fvs) <- setStage pop_stage $
rnSplice splice
; let (_pending_splice, result) = pend_splice splice'
; return (result, fvs) }
Brack pop_stage (RnPendingUntyped ps_var)
-> do { checkTc (not is_typed_splice) illegalTypedSplice
; (splice', fvs) <- setStage pop_stage $
rnSplice splice
; let (pending_splice, result) = pend_splice splice'
; ps <- readMutVar ps_var
; writeMutVar ps_var (pending_splice : ps)
; return (result, fvs) }
_ -> do { (splice', fvs1) <- setStage (Splice is_typed_splice) $
rnSplice splice
; (result, fvs2) <- run_splice splice'
; return (result, fvs1 `plusFV` fvs2) } }
---------------------
rnSplice :: HsSplice RdrName -> RnM (HsSplice Name, FreeVars)
-- Not exported...used for all
rnSplice (HsSplice splice_name expr)
= do { checkTH expr "Template Haskell splice"
; loc <- getSrcSpanM
; n' <- newLocalBndrRn (L loc splice_name)
; (expr', fvs) <- rnLExpr expr
; return (HsSplice n' expr', fvs) }
---------------------
rnSpliceExpr :: Bool -> HsSplice RdrName -> RnM (HsExpr Name, FreeVars)
rnSpliceExpr is_typed splice
= rnSpliceGen is_typed run_expr_splice pend_expr_splice splice
where
pend_expr_splice :: HsSplice Name -> (PendingRnSplice, HsExpr Name)
pend_expr_splice rn_splice@(HsSplice n e)
= (PendingRnExpSplice (PendSplice n e), HsSpliceE is_typed rn_splice)
run_expr_splice :: HsSplice Name -> RnM (HsExpr Name, FreeVars)
run_expr_splice rn_splice@(HsSplice _ expr')
| is_typed -- Run it later, in the type checker
= do { -- Ugh! See Note [Splices] above
lcl_rdr <- getLocalRdrEnv
; gbl_rdr <- getGlobalRdrEnv
; let gbl_names = mkNameSet [gre_name gre | gre <- globalRdrEnvElts gbl_rdr
, isLocalGRE gre]
lcl_names = mkNameSet (localRdrEnvElts lcl_rdr)
; return (HsSpliceE is_typed rn_splice, lcl_names `plusFV` gbl_names) }
| otherwise -- Run it here
= do { expr <- getHooked runRnSpliceHook return >>= ($ expr')
-- The splice must have type ExpQ
; meta_exp_ty <- tcMetaTy expQTyConName
-- Typecheck the expression
; zonked_q_expr <- tcTopSpliceExpr False $
tcMonoExpr expr meta_exp_ty
-- Run the expression
; expr2 <- runMetaE zonked_q_expr
; showSplice "expression" expr (ppr expr2)
; (lexpr3, fvs) <- checkNoErrs $
rnLExpr expr2
; return (unLoc lexpr3, fvs) }
----------------------
rnSpliceType :: HsSplice RdrName -> PostTc Name Kind
-> RnM (HsType Name, FreeVars)
rnSpliceType splice k
= rnSpliceGen False run_type_splice pend_type_splice splice
where
pend_type_splice rn_splice@(HsSplice n e)
= (PendingRnTypeSplice (PendSplice n e), HsSpliceTy rn_splice k)
run_type_splice (HsSplice _ expr')
= do { expr <- getHooked runRnSpliceHook return >>= ($ expr')
; meta_exp_ty <- tcMetaTy typeQTyConName
-- Typecheck the expression
; zonked_q_expr <- tcTopSpliceExpr False $
tcMonoExpr expr meta_exp_ty
-- Run the expression
; hs_ty2 <- runMetaT zonked_q_expr
; showSplice "type" expr (ppr hs_ty2)
; (hs_ty3, fvs) <- do { let doc = SpliceTypeCtx hs_ty2
; checkNoErrs $ rnLHsType doc hs_ty2
-- checkNoErrs: see Note [Renamer errors]
}
; return (unLoc hs_ty3, fvs) }
{-
Note [rnSplicePat]
~~~~~~~~~~~~~~~~~~
Renaming a pattern splice is a bit tricky, because we need the variables
bound in the pattern to be in scope in the RHS of the pattern. This scope
management is effectively done by using continuation-passing style in
RnPat, through the CpsRn monad. We don't wish to be in that monad here
(it would create import cycles and generally conflict with renaming other
splices), so we really want to return a (Pat RdrName) -- the result of
running the splice -- which can then be further renamed in RnPat, in
the CpsRn monad.
The problem is that if we're renaming a splice within a bracket, we
*don't* want to run the splice now. We really do just want to rename
it to an HsSplice Name. Of course, then we can't know what variables
are bound within the splice, so pattern splices within brackets aren't
all that useful.
In any case, when we're done in rnSplicePat, we'll either have a
Pat RdrName (the result of running a top-level splice) or a Pat Name
(the renamed nested splice). Thus, the awkward return type of
rnSplicePat.
-}
-- | Rename a splice pattern. See Note [rnSplicePat]
rnSplicePat :: HsSplice RdrName -> RnM ( Either (Pat RdrName) (Pat Name)
, FreeVars)
rnSplicePat splice
= rnSpliceGen False run_pat_splice pend_pat_splice splice
where
pend_pat_splice rn_splice@(HsSplice n e)
= (PendingRnPatSplice (PendSplice n e), Right $ SplicePat rn_splice)
run_pat_splice (HsSplice _ expr')
= do { expr <- getHooked runRnSpliceHook return >>= ($ expr')
; meta_exp_ty <- tcMetaTy patQTyConName
-- Typecheck the expression
; zonked_q_expr <- tcTopSpliceExpr False $
tcMonoExpr expr meta_exp_ty
-- Run the expression
; pat <- runMetaP zonked_q_expr
; showSplice "pattern" expr (ppr pat)
; return (Left $ unLoc pat, emptyFVs) }
----------------------
rnSpliceDecl :: SpliceDecl RdrName -> RnM (SpliceDecl Name, FreeVars)
rnSpliceDecl (SpliceDecl (L loc splice) flg)
= rnSpliceGen False run_decl_splice pend_decl_splice splice
where
pend_decl_splice rn_splice@(HsSplice n e)
= (PendingRnDeclSplice (PendSplice n e), SpliceDecl(L loc rn_splice) flg)
run_decl_splice rn_splice = pprPanic "rnSpliceDecl" (ppr rn_splice)
rnTopSpliceDecls :: HsSplice RdrName -> RnM ([LHsDecl RdrName], FreeVars)
-- Declaration splice at the very top level of the module
rnTopSpliceDecls (HsSplice _ expr'')
= do { (expr, fvs) <- setStage (Splice False) $
rnLExpr expr''
; expr' <- getHooked runRnSpliceHook return >>= ($ expr)
; list_q <- tcMetaTy decsQTyConName -- Q [Dec]
; zonked_q_expr <- tcTopSpliceExpr False (tcMonoExpr expr' list_q)
-- Run the expression
; decls <- runMetaD zonked_q_expr
; traceSplice $ SpliceInfo True
"declarations"
(Just (getLoc expr))
(Just $ ppr expr')
(vcat (map ppr decls))
; return (decls,fvs) }
{-
************************************************************************
* *
Template Haskell brackets
* *
************************************************************************
-}
rnBracket :: HsExpr RdrName -> HsBracket RdrName -> RnM (HsExpr Name, FreeVars)
rnBracket e br_body
= addErrCtxt (quotationCtxtDoc br_body) $
do { -- Check that Template Haskell is enabled and available
thEnabled <- xoptM Opt_TemplateHaskell
; unless thEnabled $
failWith ( vcat [ ptext (sLit "Syntax error on") <+> ppr e
, ptext (sLit "Perhaps you intended to use TemplateHaskell") ] )
; checkTH e "Template Haskell bracket"
-- Check for nested brackets
; cur_stage <- getStage
; case cur_stage of
{ Splice True -> checkTc (isTypedBracket br_body) illegalUntypedBracket
; Splice False -> checkTc (not (isTypedBracket br_body)) illegalTypedBracket
; Comp -> return ()
; Brack {} -> failWithTc illegalBracket
}
-- Brackets are desugared to code that mentions the TH package
; recordThUse
; case isTypedBracket br_body of
True -> do { (body', fvs_e) <- setStage (Brack cur_stage RnPendingTyped) $
rn_bracket cur_stage br_body
; return (HsBracket body', fvs_e) }
False -> do { ps_var <- newMutVar []
; (body', fvs_e) <- setStage (Brack cur_stage (RnPendingUntyped ps_var)) $
rn_bracket cur_stage br_body
; pendings <- readMutVar ps_var
; return (HsRnBracketOut body' pendings, fvs_e) }
}
rn_bracket :: ThStage -> HsBracket RdrName -> RnM (HsBracket Name, FreeVars)
rn_bracket outer_stage br@(VarBr flg rdr_name)
= do { name <- lookupOccRn rdr_name
; this_mod <- getModule
; case flg of
{ -- Type variables can be quoted in TH. See #5721.
False -> return ()
; True | nameIsLocalOrFrom this_mod name ->
do { mb_bind_lvl <- lookupLocalOccThLvl_maybe name
; case mb_bind_lvl of
{ Nothing -> return () -- Can happen for data constructors,
-- but nothing needs to be done for them
; Just (top_lvl, bind_lvl) -- See Note [Quoting names]
| isTopLevel top_lvl
-> when (isExternalName name) (keepAlive name)
| otherwise
-> do { traceRn (text "rn_bracket VarBr" <+> ppr name <+> ppr bind_lvl <+> ppr outer_stage)
; checkTc (thLevel outer_stage + 1 == bind_lvl)
(quotedNameStageErr br) }
}
}
; True | otherwise -> -- Imported thing
discardResult (loadInterfaceForName msg name)
-- Reason for loadInterface: deprecation checking
-- assumes that the home interface is loaded, and
-- this is the only way that is going to happen
}
; return (VarBr flg name, unitFV name) }
where
msg = ptext (sLit "Need interface for Template Haskell quoted Name")
rn_bracket _ (ExpBr e) = do { (e', fvs) <- rnLExpr e
; return (ExpBr e', fvs) }
rn_bracket _ (PatBr p) = rnPat ThPatQuote p $ \ p' -> return (PatBr p', emptyFVs)
rn_bracket _ (TypBr t) = do { (t', fvs) <- rnLHsType TypBrCtx t
; return (TypBr t', fvs) }
rn_bracket _ (DecBrL decls)
= do { group <- groupDecls decls
; gbl_env <- getGblEnv
; let new_gbl_env = gbl_env { tcg_dus = emptyDUs }
-- The emptyDUs is so that we just collect uses for this
-- group alone in the call to rnSrcDecls below
; (tcg_env, group') <- setGblEnv new_gbl_env $
rnSrcDecls [] group
-- The empty list is for extra dependencies coming from .hs-boot files
-- See Note [Extra dependencies from .hs-boot files] in RnSource
-- Discard the tcg_env; it contains only extra info about fixity
; traceRn (text "rn_bracket dec" <+> (ppr (tcg_dus tcg_env) $$
ppr (duUses (tcg_dus tcg_env))))
; return (DecBrG group', duUses (tcg_dus tcg_env)) }
where
groupDecls :: [LHsDecl RdrName] -> RnM (HsGroup RdrName)
groupDecls decls
= do { (group, mb_splice) <- findSplice decls
; case mb_splice of
{ Nothing -> return group
; Just (splice, rest) ->
do { group' <- groupDecls rest
; let group'' = appendGroups group group'
; return group'' { hs_splcds = noLoc splice : hs_splcds group' }
}
}}
rn_bracket _ (DecBrG _) = panic "rn_bracket: unexpected DecBrG"
rn_bracket _ (TExpBr e) = do { (e', fvs) <- rnLExpr e
; return (TExpBr e', fvs) }
spliceCtxt :: HsExpr RdrName -> SDoc
spliceCtxt expr= hang (ptext (sLit "In the splice:")) 2 (ppr expr)
showSplice :: String -> LHsExpr Name -> SDoc -> TcM ()
-- Note that 'before' is *renamed* but not *typechecked*
-- Reason (a) less typechecking crap
-- (b) data constructors after type checking have been
-- changed to their *wrappers*, and that makes them
-- print always fully qualified
showSplice what before after =
traceSplice $ SpliceInfo False what Nothing (Just $ ppr before) after
-- | The splice data to be logged
--
-- duplicates code in TcSplice.lhs
data SpliceInfo
= SpliceInfo
{ spliceIsDeclaration :: Bool
, spliceDescription :: String
, spliceLocation :: Maybe SrcSpan
, spliceSource :: Maybe SDoc
, spliceGenerated :: SDoc
}
-- | outputs splice information for 2 flags which have different output formats:
-- `-ddump-splices` and `-dth-dec-file`
--
-- This duplicates code in TcSplice.lhs
traceSplice :: SpliceInfo -> TcM ()
traceSplice sd = do
loc <- case sd of
SpliceInfo { spliceLocation = Nothing } -> getSrcSpanM
SpliceInfo { spliceLocation = Just loc } -> return loc
traceOptTcRn Opt_D_dump_splices (spliceDebugDoc loc sd)
when (spliceIsDeclaration sd) $ do
dflags <- getDynFlags
liftIO $ dumpIfSet_dyn_printer alwaysQualify dflags Opt_D_th_dec_file
(spliceCodeDoc loc sd)
where
-- `-ddump-splices`
spliceDebugDoc :: SrcSpan -> SpliceInfo -> SDoc
spliceDebugDoc loc sd
= let code = case spliceSource sd of
Nothing -> ending
Just b -> nest 2 b : ending
ending = [ text "======>", nest 2 (spliceGenerated sd) ]
in (vcat [ ppr loc <> colon
<+> text "Splicing" <+> text (spliceDescription sd)
, nest 2 (sep code)
])
-- `-dth-dec-file`
spliceCodeDoc :: SrcSpan -> SpliceInfo -> SDoc
spliceCodeDoc loc sd
= (vcat [ text "--" <+> ppr loc <> colon
<+> text "Splicing" <+> text (spliceDescription sd)
, sep [spliceGenerated sd]
])
illegalBracket :: SDoc
illegalBracket = ptext (sLit "Template Haskell brackets cannot be nested (without intervening splices)")
illegalTypedBracket :: SDoc
illegalTypedBracket = ptext (sLit "Typed brackets may only appear in typed slices.")
illegalUntypedBracket :: SDoc
illegalUntypedBracket = ptext (sLit "Untyped brackets may only appear in untyped slices.")
illegalTypedSplice :: SDoc
illegalTypedSplice = ptext (sLit "Typed splices may not appear in untyped brackets")
illegalUntypedSplice :: SDoc
illegalUntypedSplice = ptext (sLit "Untyped splices may not appear in typed brackets")
quotedNameStageErr :: HsBracket RdrName -> SDoc
quotedNameStageErr br
= sep [ ptext (sLit "Stage error: the non-top-level quoted name") <+> ppr br
, ptext (sLit "must be used at the same stage at which is is bound")]
quotationCtxtDoc :: HsBracket RdrName -> SDoc
quotationCtxtDoc br_body
= hang (ptext (sLit "In the Template Haskell quotation"))
2 (ppr br_body)
-- spliceResultDoc :: OutputableBndr id => LHsExpr id -> SDoc
-- spliceResultDoc expr
-- = vcat [ hang (ptext (sLit "In the splice:"))
-- 2 (char '$' <> pprParendExpr expr)
-- , ptext (sLit "To see what the splice expanded to, use -ddump-splices") ]
#endif
checkThLocalName :: Name -> RnM ()
#ifndef GHCI /* GHCI and TH is off */
--------------------------------------
-- Check for cross-stage lifting
checkThLocalName _name
= return ()
#else /* GHCI and TH is on */
checkThLocalName name
= do { traceRn (text "checkThLocalName" <+> ppr name)
; mb_local_use <- getStageAndBindLevel name
; case mb_local_use of {
Nothing -> return () ; -- Not a locally-bound thing
Just (top_lvl, bind_lvl, use_stage) ->
do { let use_lvl = thLevel use_stage
; checkWellStaged (quotes (ppr name)) bind_lvl use_lvl
; traceRn (text "checkThLocalName" <+> ppr name <+> ppr bind_lvl <+> ppr use_stage <+> ppr use_lvl)
; when (use_lvl > bind_lvl) $
checkCrossStageLifting top_lvl name use_stage } } }
--------------------------------------
checkCrossStageLifting :: TopLevelFlag -> Name -> ThStage -> TcM ()
-- We are inside brackets, and (use_lvl > bind_lvl)
-- Now we must check whether there's a cross-stage lift to do
-- Examples \x -> [| x |]
-- [| map |]
checkCrossStageLifting top_lvl name (Brack _ (RnPendingUntyped ps_var))
| isTopLevel top_lvl
-- Top-level identifiers in this module,
-- (which have External Names)
-- are just like the imported case:
-- no need for the 'lifting' treatment
-- E.g. this is fine:
-- f x = x
-- g y = [| f 3 |]
= when (isExternalName name) (keepAlive name)
-- See Note [Keeping things alive for Template Haskell]
| otherwise
= -- Nested identifiers, such as 'x' in
-- E.g. \x -> [| h x |]
-- We must behave as if the reference to x was
-- h $(lift x)
-- We use 'x' itself as the splice proxy, used by
-- the desugarer to stitch it all back together.
-- If 'x' occurs many times we may get many identical
-- bindings of the same splice proxy, but that doesn't
-- matter, although it's a mite untidy.
do { traceRn (text "checkCrossStageLifting" <+> ppr name)
; -- Update the pending splices
; ps <- readMutVar ps_var
; writeMutVar ps_var (PendingRnCrossStageSplice name : ps) }
checkCrossStageLifting _ _ _ = return ()
#endif /* GHCI */
{-
Note [Keeping things alive for Template Haskell]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f x = x+1
g y = [| f 3 |]
Here 'f' is referred to from inside the bracket, which turns into data
and mentions only f's *name*, not 'f' itself. So we need some other
way to keep 'f' alive, lest it get dropped as dead code. That's what
keepAlive does. It puts it in the keep-alive set, which subsequently
ensures that 'f' stays as a top level binding.
This must be done by the renamer, not the type checker (as of old),
because the type checker doesn't typecheck the body of untyped
brackets (Trac #8540).
A thing can have a bind_lvl of outerLevel, but have an internal name:
foo = [d| op = 3
bop = op + 1 |]
Here the bind_lvl of 'op' is (bogusly) outerLevel, even though it is
bound inside a bracket. That is because we don't even even record
binding levels for top-level things; the binding levels are in the
LocalRdrEnv.
So the occurrence of 'op' in the rhs of 'bop' looks a bit like a
cross-stage thing, but it isn't really. And in fact we never need
to do anything here for top-level bound things, so all is fine, if
a bit hacky.
For these chaps (which have Internal Names) we don't want to put
them in the keep-alive set.
Note [Quoting names]
~~~~~~~~~~~~~~~~~~~~
A quoted name 'n is a bit like a quoted expression [| n |], except that we
have no cross-stage lifting (c.f. TcExpr.thBrackId). So, after incrementing
the use-level to account for the brackets, the cases are:
bind > use Error
bind = use+1 OK
bind < use
Imported things OK
Top-level things OK
Non-top-level Error
where 'use' is the binding level of the 'n quote. (So inside the implied
bracket the level would be use+1.)
Examples:
f 'map -- OK; also for top-level defns of this module
\x. f 'x -- Not ok (bind = 1, use = 1)
-- (whereas \x. f [| x |] might have been ok, by
-- cross-stage lifting
\y. [| \x. $(f 'y) |] -- Not ok (bind =1, use = 1)
[| \x. $(f 'x) |] -- OK (bind = 2, use = 1)
-}
| alexander-at-github/eta | compiler/ETA/Rename/RnSplice.hs | bsd-3-clause | 24,906 | 0 | 10 | 7,501 | 579 | 334 | 245 | 28 | 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="ru-RU">
<title>Дополнение Selenium</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Содержание</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Индекс</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Поиск</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Избранное</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/selenium/src/main/javahelp/org/zaproxy/zap/extension/selenium/resources/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 1,006 | 77 | 66 | 156 | 481 | 241 | 240 | -1 | -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="ar-SA">
<title>Retest Add-On</title>
<maps>
<homeID>retest</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/retest/src/main/javahelp/org/zaproxy/addon/retest/resources/help_ar_SA/helpset_ar_SA.hs | apache-2.0 | 961 | 77 | 67 | 156 | 411 | 208 | 203 | -1 | -1 |
module T16804a where
import Data.Monoid
data Test = A | B
deriving (Show)
instance Monoid Test where
mempty = A
-- empty for linenumbers in T16804 to be correct
-- empty for linenumbers in T16804 to be correct
testFunction :: Test -> Test -> Bool
testFunction A B = True
testFunction B A = True
testFunction _ _ = False
testFunction2 :: Bool -> Test
testFunction2 True = A
testFunction2 False = B
niceValue :: Int
niceValue = getSum (Sum 1 <> Sum 2 <> mempty)
niceValue2 :: Test
niceValue2 = A <> A <> A <> B <> A <> mempty
instance Semigroup Test where
A <> val = val
B <> _ = B
| sdiehl/ghc | testsuite/tests/ghci/scripts/T16804a.hs | bsd-3-clause | 597 | 0 | 9 | 133 | 199 | 105 | 94 | 20 | 1 |
{- $Id: AFRPTestsRPSwitch.hs,v 1.2 2003/11/10 21:28:58 antony Exp $
******************************************************************************
* A F R P *
* *
* Module: AFRPTestsRPSwitch *
* Purpose: Test cases for rpSwitchB and drpSwitchB *
* Authors: Antony Courtney and Henrik Nilsson *
* *
* Copyright (c) Yale University, 2003 *
* *
******************************************************************************
-}
module AFRPTestsRPSwitch (
rpswitch_tr,
rpswitch_trs,
rpswitch_st0,
rpswitch_st0r
) where
import Data.Maybe (fromJust)
import Data.List (findIndex)
import FRP.Yampa
import FRP.Yampa.Internals (Event(NoEvent, Event))
import AFRPTestsCommon
------------------------------------------------------------------------------
-- Test cases for rpSwitchB and drpSwitchB
------------------------------------------------------------------------------
rpswitch_inp1 = (fromJust (head delta_inp), zip (repeat 1.0) (tail delta_inp))
where
delta_inp =
[Just (1.0, NoEvent), Nothing, Nothing,
Just (2.0, Event (integral:)), Just (3.0, NoEvent), Nothing,
Just (4.0, NoEvent), Nothing, Nothing,
Just (5.0, Event ((integral >>> arr (+100.0)):)),
Just (6.0, NoEvent), Nothing,
Just (7.0, NoEvent), Nothing, Nothing,
Just (8.0, Event tail), Just (9.0, NoEvent), Nothing]
++ repeat Nothing
-- This input contains exaples of "continuos switching", i.e. the same
-- switching event ocurring during a a few contiguous time steps.
-- It also starts with an immediate switch.
rpswitch_inp2 = (fromJust (head delta_inp), zip (repeat 1.0) (tail delta_inp))
where
delta_inp =
[Just (1.0, Event (integral:)),
Just (1.0, NoEvent), Nothing,
Just (2.0, Event ((integral >>> arr(+100.0)):)), Nothing, Nothing,
Just (3.0, Event ((integral >>> arr(+200.0)):)), Nothing, Nothing,
Just (4.0, NoEvent), Nothing, Nothing,
Just (5.0, Event ((arr (*3)):)),
Just (5.0, NoEvent), Nothing,
Just (6.0, Event tail), Just (7.0, Event ((arr (*7)):)),
Just (8.0, Event (take 2)),
Just (9.0, NoEvent), Nothing]
++ repeat Nothing
rpswitch_t0 :: [[Double]]
rpswitch_t0 = take 20 $ embed (rpSwitchB []) rpswitch_inp1
rpswitch_t0r =
[[], -- 0 s
[], -- 1 s
[], -- 2 s
[0.0], -- 3 s
[2.0], -- 4 s
[5.0], -- 5 s
[8.0], -- 6 s
[12.0], -- 7 s
[16.0], -- 8 s
[100.0, 20.0], -- 9 s
[105.0, 25.0], -- 10 s
[111.0, 31.0], -- 11 s
[117.0, 37.0], -- 12 s
[124.0, 44.0], -- 13 s
[131.0, 51.0], -- 14 s
[58.0], -- 15 s
[66.0], -- 16 s
[75.0], -- 17 s
[84.0], -- 18 s
[93.0]] -- 19 s
rpswitch_t1 :: [[Double]]
rpswitch_t1 = take 20 $ embed (drpSwitchB []) rpswitch_inp1
rpswitch_t1r =
[[], -- 0 s
[], -- 1 s
[], -- 2 s
[], -- 3 s
[2.0], -- 4 s
[5.0], -- 5 s
[8.0], -- 6 s
[12.0], -- 7 s
[16.0], -- 8 s
[20.0] , -- 9 s
[105.0, 25.0], -- 10 s
[111.0, 31.0], -- 11 s
[117.0, 37.0], -- 12 s
[124.0, 44.0], -- 13 s
[131.0, 51.0], -- 14 s
[138.0, 58.0], -- 15 s
[66.0], -- 16 s
[75.0], -- 17 s
[84.0], -- 18 s
[93.0]] -- 19 s
rpswitch_t2 :: [[Double]]
rpswitch_t2 = take 20 $ embed (rpSwitchB []) rpswitch_inp2
rpswitch_t2r =
[[0.0], -- 0 s
[1.0], -- 1 s
[2.0], -- 2 s
[100.0, 3.0], -- 3 s
[100.0, 102.0, 5.0], -- 4 s
[100.0, 102.0, 104.0, 7.0], -- 5 s
[200.0, 102.0, 104.0, 106.0, 9.0], -- 6 s
[200.0, 203.0, 105.0, 107.0, 109.0, 12.0], -- 7 s
[200.0, 203.0, 206.0, 108.0, 110.0, 112.0, 15.0], -- 8 s
[203.0, 206.0, 209.0, 111.0, 113.0, 115.0, 18.0], -- 9 s
[207.0, 210.0, 213.0, 115.0, 117.0, 119.0, 22.0], -- 10 s
[211.0, 214.0, 217.0, 119.0, 121.0, 123.0, 26.0], -- 11 s
[15.0, 215.0, 218.0, 221.0, 123.0, 125.0, 127.0, 30.0], -- 12 s
[15.0, 220.0, 223.0, 226.0, 128.0, 130.0, 132.0, 35.0], -- 13 s
[15.0, 225.0, 228.0, 231.0, 133.0, 135.0, 137.0, 40.0], -- 14 s
[230.0, 233.0, 236.0, 138.0, 140.0, 142.0, 45.0], -- 15 s
[49.0, 236.0, 239.0, 242.0, 144.0, 146.0, 148.0, 51.0], -- 16 s
[56.0, 243.0], -- 17 s
[63.0, 251.0], -- 18 s
[63.0, 260.0]] -- 19 s
rpswitch_t3 :: [[Double]]
rpswitch_t3 = take 20 $ embed (drpSwitchB []) rpswitch_inp2
rpswitch_t3r =
[[], -- 0 s
[1.0], -- 1 s
[2.0], -- 2 s
[3.0], -- 3 s
[102.0, 5.0], -- 4 s
[102.0, 104.0, 7.0], -- 5 s
[102.0, 104.0, 106.0, 9.0], -- 6 s
[203.0, 105.0, 107.0, 109.0, 12.0], -- 7 s
[203.0, 206.0, 108.0, 110.0, 112.0, 15.0], -- 8 s
[203.0, 206.0, 209.0, 111.0, 113.0, 115.0, 18.0], -- 9 s
[207.0, 210.0, 213.0, 115.0, 117.0, 119.0, 22.0], -- 10 s
[211.0, 214.0, 217.0, 119.0, 121.0, 123.0, 26.0], -- 11 s
[215.0, 218.0, 221.0, 123.0, 125.0, 127.0, 30.0], -- 12 s
[15.0, 220.0, 223.0, 226.0, 128.0, 130.0, 132.0, 35.0], -- 13 s
[15.0, 225.0, 228.0, 231.0, 133.0, 135.0, 137.0, 40.0], -- 14 s
[18.0, 230.0, 233.0, 236.0, 138.0, 140.0, 142.0, 45.0], -- 15 s
[236.0, 239.0, 242.0, 144.0, 146.0, 148.0, 51.0], -- 16 s
[56.0, 243.0, 246.0, 249.0, 151.0, 153.0, 155.0, 58.0], -- 17 s
[63.0, 251.0], -- 18 s
[63.0, 260.0]] -- 19 s
-- Starts three "ramps" with different phase. As soon as one exceeds a
-- threshold, it's restarted, while the others are left alone. The observaton
-- of the output is done via a loop, thus the use of a delayed switch is
-- essential.
rpswitch_ramp :: Double -> SF a Double
rpswitch_ramp phase = constant 2.0 >>> integral >>> arr (+phase)
-- We assume that only one signal function will reach the limit at a time.
rpswitch_limit :: Double -> SF [Double] (Event ([SF a Double]->[SF a Double]))
rpswitch_limit x = arr (findIndex (>=x)) >>> edgeJust >>> arr (fmap restart)
where
restart n = \sfs -> take n sfs ++ [rpswitch_ramp 0.0] ++ drop (n+1) sfs
rpswitch_t4 :: [[Double]]
rpswitch_t4 = take 30 $ embed (loop sf) (deltaEncode 0.1 (repeat ()))
where
sf :: SF (a, [Double]) ([Double],[Double])
sf = (second (rpswitch_limit 2.99)
>>> drpSwitchB [rpswitch_ramp 0.0,
rpswitch_ramp 1.0,
rpswitch_ramp 2.0])
>>> arr dup
rpswitch_t4r =
[[0.0, 1.0, 2.0],
[0.2, 1.2, 2.2],
[0.4, 1.4, 2.4],
[0.6, 1.6, 2.6],
[0.8, 1.8, 2.8],
[1.0, 2.0, 3.0],
[1.2, 2.2, 0.2],
[1.4, 2.4, 0.4],
[1.6, 2.6, 0.6],
[1.8, 2.8, 0.8],
[2.0, 3.0, 1.0],
[2.2, 0.2, 1.2],
[2.4, 0.4, 1.4],
[2.6, 0.6, 1.6],
[2.8, 0.8, 1.8],
[3.0, 1.0, 2.0],
[0.2, 1.2, 2.2],
[0.4, 1.4, 2.4],
[0.6, 1.6, 2.6],
[0.8, 1.8, 2.8],
[1.0, 2.0, 3.0],
[1.2, 2.2, 0.2],
[1.4, 2.4, 0.4],
[1.6, 2.6, 0.6],
[1.8, 2.8, 0.8],
[2.0, 3.0, 1.0],
[2.2, 0.2, 1.2],
[2.4, 0.4, 1.4],
[2.6, 0.6, 1.6],
[2.8, 0.8, 1.8]]
rpswitch_trs =
[ rpswitch_t0 ~= rpswitch_t0r,
rpswitch_t1 ~= rpswitch_t1r,
rpswitch_t2 ~= rpswitch_t2r,
rpswitch_t3 ~= rpswitch_t3r,
rpswitch_t4 ~= rpswitch_t4r
]
rpswitch_tr = and rpswitch_trs
rpswitch_st0 = testSFSpaceLeak 1000000 (loop sf)
where
sf :: SF (a, [Double]) ([Double],[Double])
sf = (second (rpswitch_limit 2.99)
>>> drpSwitchB [rpswitch_ramp 0.0,
rpswitch_ramp 1.0,
rpswitch_ramp 2.0])
>>> arr dup
rpswitch_st0r = [1.5,2.5,0.5]
| ony/Yampa-core | tests/AFRPTestsRPSwitch.hs | bsd-3-clause | 8,137 | 10 | 16 | 2,609 | 2,637 | 1,646 | 991 | 184 | 1 |
-- (c) 2000-2005 by Martin Erwig [see file COPYRIGHT]
module Data.Graph.Inductive.Query.SP(
spTree,spLength,sp,
dijkstra
) where
import qualified Data.Graph.Inductive.Internal.Heap as H
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Internal.RootPath
expand :: Real b => b -> LPath b -> Context a b -> [H.Heap b (LPath b)]
expand d (LP p) (_,_,_,s) = map (\(l,v)->H.unit (l+d) (LP ((v,l+d):p))) s
-- | Implementation of Dijkstra's shortest path algorithm
dijkstra :: (Graph gr, Real b) => H.Heap b (LPath b) -> gr a b -> LRTree b
dijkstra h g | H.isEmpty h || isEmpty g = []
dijkstra h g =
case match v g of
(Just c,g') -> p:dijkstra (H.mergeAll (h':expand d p c)) g'
(Nothing,g') -> dijkstra h' g'
where (_,p@(LP ((v,d):_)),h') = H.splitMin h
spTree :: (Graph gr, Real b) => Node -> gr a b -> LRTree b
spTree v = dijkstra (H.unit 0 (LP [(v,0)]))
spLength :: (Graph gr, Real b) => Node -> Node -> gr a b -> b
spLength s t = getDistance t . spTree s
sp :: (Graph gr, Real b) => Node -> Node -> gr a b -> Path
sp s t = getLPathNodes t . spTree s
| FranklinChen/hugs98-plus-Sep2006 | packages/fgl/Data/Graph/Inductive/Query/SP.hs | bsd-3-clause | 1,114 | 0 | 14 | 249 | 576 | 305 | 271 | 21 | 2 |
import Test.Cabal.Prelude
main = cabalTest $ do
cabal "new-test" []
| themoritz/cabal | cabal-testsuite/PackageTests/TestSuiteTests/ExeV10/cabal.test.hs | bsd-3-clause | 73 | 0 | 9 | 15 | 26 | 13 | 13 | 3 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Doc.Developing
-- Copyright : (C) 2007 Andrea Rossato
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : portable
--
-- This module gives a brief overview of the xmonad internals. It is
-- intended for advanced users who are curious about the xmonad source
-- code and want an brief overview. This document may also be helpful
-- for the beginner\/intermediate Haskell programmer who is motivated
-- to write an xmonad extension as a way to deepen her understanding
-- of this powerful functional language; however, there is not space
-- here to go into much detail. For a more comprehensive document
-- covering some of the same material in more depth, see the guided
-- tour of the xmonad source on the xmonad wiki:
-- <http://haskell.org/haskellwiki/Xmonad/Guided_tour_of_the_xmonad_source>.
--
-- If you write an extension module and think it may be useful for
-- others, consider releasing it. Coding guidelines and licensing
-- policies are covered at the end of this document, and must be
-- followed if you want your code to be included in the official
-- repositories. For a basic tutorial on the nuts and bolts of
-- developing a new extension for xmonad, see the tutorial on the
-- wiki:
-- <http://haskell.org/haskellwiki/Xmonad/xmonad_development_tutorial>.
--
-----------------------------------------------------------------------------
module XMonad.Doc.Developing
(
-- * Writing new extensions
-- $writing
-- * Libraries for writing window managers
-- $xmonad-libs
-- * xmonad internals
-- $internals
-- ** The @main@ entry point
-- $main
-- ** The X monad and the internal state
-- $internalState
-- ** Event handling and messages
-- $events
-- ** The 'LayoutClass'
-- $layoutClass
-- * Coding style
-- $style
-- * Licensing policy
-- $license
) where
--------------------------------------------------------------------------------
--
-- Writing Extensions
--
--------------------------------------------------------------------------------
{- $writing
-}
{- $xmonad-libs
Starting with version 0.5, xmonad and xmonad-contrib are packaged and
distributed as libraries, instead of components which must be compiled
by the user into a binary (as they were prior to version 0.5). This
way of distributing xmonad has many advantages, since it allows
packaging by GNU\/Linux distributions while still allowing the user to
customize the window manager to fit her needs.
Basically, xmonad and the xmonad-contrib libraries let users write
their own window manager in just a few lines of code. While
@~\/.xmonad\/xmonad.hs@ at first seems to be simply a configuration
file, it is actually a complete Haskell program which uses the xmonad
and xmonad-contrib libraries to create a custom window manager.
This makes it possible not only to edit the default xmonad
configuration, as we have seen in the "XMonad.Doc.Extending" document,
but to use the Haskell programming language to extend the window
manager you are writing in any way you see fit.
-}
{- $internals
-}
{- $main
#The_main_entry_point#
xmonad installs a binary, @xmonad@, which must be executed by the
Xsession starting script. This binary, whose code can be read in
@Main.hs@ of the xmonad source tree, will use 'XMonad.Core.recompile'
to run @ghc@ in order to build a binary from @~\/.xmonad\/xmonad.hs@.
If this compilation process fails, for any reason, a default @main@
entry point will be used, which calls the 'XMonad.Main.xmonad'
function with a default configuration.
Thus, the real @main@ entry point, the one that even the users' custom
window manager application in @~\/.xmonad\/xmonad.hs@ must call, is
the 'XMonad.Main.xmonad' function. This function takes a configuration
as its only argument, whose type ('XMonad.Core.XConfig')
is defined in "XMonad.Core".
'XMonad.Main.xmonad' takes care of opening the connection with the X
server, initializing the state (or deserializing it when restarted)
and the configuration, and calling the event handler
('XMonad.Main.handle') that goes into an infinite loop (using
'Prelude.forever') waiting for events and acting accordingly.
-}
{- $internalState
The event loop which calls 'XMonad.Main.handle' to react to events is
run within the 'XMonad.Core.X' monad, which is a
'Control.Monad.State.StateT' transformer over 'IO', encapsulated
within a 'Control.Monad.Reader.ReaderT' transformer. The
'Control.Monad.State.StateT' transformer encapsulates the
(read\/writable) state of the window manager (of type
'XMonad.Core.XState'), whereas the 'Control.Monad.Reader.ReaderT'
transformer encapsulates the (read-only) configuration (of type
'XMonad.Core.XConf').
Thanks to GHC's newtype deriving feature, the instance of the
'Control.Monad.State.MonadState' class parametrized over
'XMonad.Core.XState' and the instance of the
'Control.Monad.Reader.MonadReader' class parametrized over
'XMonad.Core.XConf' are automatically derived for the 'XMonad.Core.X'
monad. This way we can use 'Control.Monad.State.get',
'Control.Monad.State.gets' and 'Control.Monad.State.modify' for the
'XMonad.Core.XState', and 'Control.Monad.Reader.ask' and
'Control.Monad.Reader.asks' for reading the 'XMonad.Core.XConf'.
'XMonad.Core.XState' is where all the sensitive information about
window management is stored. The most important field of the
'XMonad.Core.XState' is the 'XMonad.Core.windowset', whose type
('XMonad.Core.WindowSet') is a synonym for a
'XMonad.StackSet.StackSet' parametrized over a
'XMonad.Core.WorkspaceID' (a 'String'), a layout type wrapped inside
the 'XMonad.Layout.Layout' existential data type, the
'Graphics.X11.Types.Window' type, the 'XMonad.Core.ScreenID' and the
'XMonad.Core.ScreenDetail's.
What a 'XMonad.StackSet.StackSet' is and how it can be manipulated
with pure functions is described in the Haddock documentation of the
"XMonad.StackSet" module.
The 'XMonad.StackSet.StackSet' ('XMonad.Core.WindowSet') has four
fields:
* 'XMonad.StackSet.current', for the current, focused workspace. This
is a 'XMonad.StackSet.Screen', which is composed of a
'XMonad.StackSet.Workspace' together with the screen information (for
Xinerama support).
* 'XMonad.StackSet.visible', a list of 'XMonad.StackSet.Screen's for
the other visible (with Xinerama) workspaces. For non-Xinerama
setups, this list is always empty.
* 'XMonad.StackSet.hidden', the list of non-visible
'XMonad.StackSet.Workspace's.
* 'XMonad.StackSet.floating', a map from floating
'Graphics.X11.Types.Window's to 'XMonad.StackSet.RationalRect's
specifying their geometry.
The 'XMonad.StackSet.Workspace' type is made of a
'XMonad.StackSet.tag', a 'XMonad.StackSet.layout' and
a (possibly empty) 'XMonad.StackSet.stack' of windows.
"XMonad.StackSet" (which should usually be imported qualified, to
avoid name clashes with Prelude functions such as 'Prelude.delete' and
'Prelude.filter') provides many pure functions to manipulate the
'XMonad.StackSet.StackSet'. These functions are most commonly used as
an argument to 'XMonad.Operations.windows', which takes a pure
function to manipulate the 'XMonad.Core.WindowSet' and does all the
needed operations to refresh the screen and save the modified
'XMonad.Core.XState'.
During each 'XMonad.Operations.windows' call, the
'XMonad.StackSet.layout' field of the 'XMonad.StackSet.current' and
'XMonad.StackSet.visible' 'XMonad.StackSet.Workspace's are used to
physically arrange the 'XMonad.StackSet.stack' of windows on each
workspace.
The possibility of manipulating the 'XMonad.StackSet.StackSet'
('XMonad.Core.WindowSet') with pure functions makes it possible to
test all the properties of those functions with QuickCheck, providing
greater reliability of the core code. Every change to the
"XMonad.StackSet" module must be accompanied by appropriate QuickCheck
properties before being applied.
-}
{- $events
Event handling is the core activity of xmonad. Events generated by
the X server are most important, but there may also be events
generated by layouts or the user.
"XMonad.Core" defines a class that generalizes the concept of events,
'XMonad.Core.Message', constrained to types with a
'Data.Typeable.Typeable' instance definition (which can be
automatically derived by GHC). 'XMonad.Core.Message's are wrapped
within an existential type 'XMonad.Core.SomeMessage'. The
'Data.Typeable.Typeable' constraint allows for the definition of a
'XMonad.Core.fromMessage' function that can unwrap the message with
'Data.Typeable.cast'. X Events are instances of this class, along
with any messages used by xmonad itself or by extension modules.
Using the 'Data.Typeable.Typeable' class for any kind of
'XMonad.Core.Message's and events allows us to define polymorphic functions
for processing messages or unhandled events.
This is precisely what happens with X events: xmonad passes them to
'XMonad.Main.handle'. If the main event handling function doesn't have
anything to do with the event, the event is sent to all visible
layouts by 'XMonad.Operations.broadcastMessage'.
This messaging system allows the user to create new message types,
simply declare an instance of the 'Data.Typeable.Typeable' and use
'XMonad.Operations.sendMessage' to send commands to layouts.
And, finally, layouts may handle X events and other messages within the
same function... miracles of polymorphism.
-}
{- $layoutClass
#The_LayoutClass#
to do
-}
{- $style
These are the coding guidelines for contributing to xmonad and the
xmonad contributed extensions.
* Comment every top level function (particularly exported funtions), and
provide a type signature.
* Use Haddock syntax in the comments (see below).
* Follow the coding style of the other modules.
* Code should be compilable with "ghc-options: -Wall -Werror" set in the
xmonad-contrib.cabal file. There should be no warnings.
* Code should be free of any warnings or errors from the Hlint tool; use your
best judgement on some warnings like eta-reduction or bracket removal, though.
* Partial functions should be avoided: the window manager should not
crash, so never call 'error' or 'undefined'.
* Tabs are /illegal/. Use 4 spaces for indenting.
* Any pure function added to the core must have QuickCheck properties
precisely defining its behaviour. Tests for everything else are encouraged.
For examples of Haddock documentation syntax, have a look at other
extensions. Important points are:
* Every exported function (or even better, every function) should have
a Haddock comment explaining what it does, and providing examples.
* Literal chunks of code can be written in comments using
\"birdtrack\" notation (a greater-than symbol at the beginning of
each line). Be sure to leave a blank line before and after each
birdtrack-quoted section.
* Link to functions by surrounding the names in single quotes, modules
in double quotes.
* Literal quote marks and slashes should be escaped with a backslash.
To generate and view the Haddock documentation for your extension, run
> runhaskell Setup haddock
and then point your browser to @\/path\/to\/XMonadContrib\/dist\/doc\/html\/xmonad-contrib\/index.html@.
For more information, see the Haddock documentation:
<http://www.haskell.org/haddock/doc/html/index.html>.
For more information on the nuts and bolts of how to develop your own
extension, see the tutorial on the wiki:
<http://haskell.org/haskellwiki/Xmonad/xmonad_development_tutorial>.
-}
{- $license
New modules should identify the author, and be submitted under the
same license as xmonad (BSD3 license or freer).
-}
| pjones/xmonad-test | vendor/xmonad-contrib/XMonad/Doc/Developing.hs | bsd-2-clause | 11,768 | 0 | 3 | 1,763 | 73 | 70 | 3 | 2 | 0 |
{-|
Code for setting up the RIO environment.
-}
module Urbit.King.App
( KingEnv
, runKingEnvStderr
, runKingEnvStderrRaw
, runKingEnvLogFile
, runKingEnvNoLog
, kingEnvKillSignal
, killKingActionL
, onKillKingSigL
, HostEnv
, runHostEnv
, PierEnv
, runPierEnv
, killPierActionL
, onKillPierSigL
, HasStderrLogFunc(..)
, HasKingId(..)
, HasProcId(..)
, HasKingEnv(..)
, HasMultiEyreApi(..)
, HasHostEnv(..)
, HasPierEnv(..)
, module Urbit.King.Config
)
where
import Urbit.King.Config
import Urbit.Prelude
import RIO (logGeneric)
import System.Directory ( createDirectoryIfMissing
, getXdgDirectory
, XdgDirectory(XdgCache)
)
import System.Posix.Internals (c_getpid)
import System.Posix.Types (CPid(..))
import System.Random (randomIO)
import Urbit.King.App.Class (HasStderrLogFunc(..))
import Urbit.Vere.Eyre.Multi (MultiEyreApi)
import Urbit.Vere.Ports (PortControlApi, HasPortControlApi(..))
-- KingEnv ---------------------------------------------------------------------
class HasKingId a where
kingIdL :: Lens' a Word16
class HasProcId a where
procIdL :: Lens' a Int32
class (HasLogFunc a, HasStderrLogFunc a, HasKingId a, HasProcId a)
=> HasKingEnv a
where
kingEnvL :: Lens' a KingEnv
data KingEnv = KingEnv
{ _kingEnvLogFunc :: !LogFunc
, _kingEnvStderrLogFunc :: !LogFunc
, _kingEnvKingId :: !Word16
, _kingEnvProcId :: !Int32
, _kingEnvKillSignal :: !(TMVar ())
}
makeLenses ''KingEnv
instance HasKingEnv KingEnv where
kingEnvL = id
instance HasLogFunc KingEnv where
logFuncL = kingEnvLogFunc
instance HasStderrLogFunc KingEnv where
stderrLogFuncL = kingEnvStderrLogFunc
instance HasProcId KingEnv where
procIdL = kingEnvProcId
instance HasKingId KingEnv where
kingIdL = kingEnvKingId
-- Running KingEnvs ------------------------------------------------------------
runKingEnvStderr :: Bool -> LogLevel -> RIO KingEnv a -> IO a
runKingEnvStderr verb lvl inner = do
logOptions <-
logOptionsHandle stderr verb
<&> setLogUseTime True
<&> setLogUseLoc False
<&> setLogMinLevel lvl
withLogFunc logOptions $ \logFunc -> runKingEnv logFunc logFunc inner
runKingEnvStderrRaw :: Bool -> LogLevel -> RIO KingEnv a -> IO a
runKingEnvStderrRaw verb lvl inner = do
logOptions <-
logOptionsHandle stderr verb
<&> setLogUseTime True
<&> setLogUseLoc False
<&> setLogMinLevel lvl
withLogFunc logOptions $ \logFunc ->
let lf = wrapCarriage logFunc
in runKingEnv lf lf inner
-- XX loses callstack
wrapCarriage :: LogFunc -> LogFunc
wrapCarriage lf = mkLogFunc $ \_ ls ll bldr ->
runRIO lf $ logGeneric ls ll (bldr <> "\r")
runKingEnvLogFile :: Bool -> LogLevel -> Maybe FilePath -> RIO KingEnv a -> IO a
runKingEnvLogFile verb lvl fileM inner = do
logFile <- case fileM of
Just f -> pure f
Nothing -> defaultLogFile
withLogFileHandle logFile $ \h -> do
logOptions <-
logOptionsHandle h verb
<&> setLogUseTime True
<&> setLogUseLoc False
<&> setLogMinLevel lvl
stderrLogOptions <-
logOptionsHandle stderr verb
<&> setLogUseTime False
<&> setLogUseLoc False
<&> setLogMinLevel lvl
withLogFunc stderrLogOptions $ \stderrLogFunc -> withLogFunc logOptions
$ \logFunc -> runKingEnv logFunc stderrLogFunc inner
withLogFileHandle :: FilePath -> (Handle -> IO a) -> IO a
withLogFileHandle f act =
withFile f AppendMode $ \handle -> do
hSetBuffering handle LineBuffering
act handle
defaultLogFile :: IO FilePath
defaultLogFile = do
logDir <- getXdgDirectory XdgCache "urbit"
createDirectoryIfMissing True logDir
logId :: Word32 <- randomIO
pure (logDir </> "king-" <> show logId <> ".log")
runKingEnvNoLog :: RIO KingEnv a -> IO a
runKingEnvNoLog act = runKingEnv mempty mempty act
runKingEnv :: LogFunc -> LogFunc -> RIO KingEnv a -> IO a
runKingEnv logFunc stderr action = do
kid <- randomIO
CPid pid <- c_getpid
kil <- newEmptyTMVarIO
runRIO (KingEnv logFunc stderr kid pid kil) action
-- KingEnv Utils ---------------------------------------------------------------
onKillKingSigL :: HasKingEnv e => Getter e (STM ())
onKillKingSigL = kingEnvL . kingEnvKillSignal . to readTMVar
killKingActionL :: HasKingEnv e => Getter e (STM ())
killKingActionL =
kingEnvL . kingEnvKillSignal . to (\kil -> void (tryPutTMVar kil ()))
-- HostEnv ------------------------------------------------------------------
-- The host environment is everything in King, eyre configuration shared
-- across ships, and nat punching data.
class HasMultiEyreApi a where
multiEyreApiL :: Lens' a MultiEyreApi
class (HasKingEnv a, HasMultiEyreApi a, HasPortControlApi a) =>
HasHostEnv a where
hostEnvL :: Lens' a HostEnv
data HostEnv = HostEnv
{ _hostEnvKingEnv :: !KingEnv
, _hostEnvMultiEyreApi :: !MultiEyreApi
, _hostEnvPortControlApi :: !PortControlApi
}
makeLenses ''HostEnv
instance HasKingEnv HostEnv where
kingEnvL = hostEnvKingEnv
instance HasLogFunc HostEnv where
logFuncL = kingEnvL . logFuncL
instance HasStderrLogFunc HostEnv where
stderrLogFuncL = kingEnvL . stderrLogFuncL
instance HasProcId HostEnv where
procIdL = kingEnvL . procIdL
instance HasKingId HostEnv where
kingIdL = kingEnvL . kingEnvKingId
instance HasMultiEyreApi HostEnv where
multiEyreApiL = hostEnvMultiEyreApi
instance HasPortControlApi HostEnv where
portControlApiL = hostEnvPortControlApi
-- Running Running Envs --------------------------------------------------------
runHostEnv :: MultiEyreApi -> PortControlApi -> RIO HostEnv a
-> RIO KingEnv a
runHostEnv multi ports action = do
king <- ask
let hostEnv = HostEnv { _hostEnvKingEnv = king
, _hostEnvMultiEyreApi = multi
, _hostEnvPortControlApi = ports
}
io (runRIO hostEnv action)
-- PierEnv ---------------------------------------------------------------------
class (HasKingEnv a, HasHostEnv a, HasPierConfig a, HasNetworkConfig a) =>
HasPierEnv a where
pierEnvL :: Lens' a PierEnv
data PierEnv = PierEnv
{ _pierEnvHostEnv :: !HostEnv
, _pierEnvPierConfig :: !PierConfig
, _pierEnvNetworkConfig :: !NetworkConfig
, _pierEnvKillSignal :: !(TMVar ())
}
makeLenses ''PierEnv
instance HasKingEnv PierEnv where
kingEnvL = pierEnvHostEnv . kingEnvL
instance HasHostEnv PierEnv where
hostEnvL = pierEnvHostEnv
instance HasMultiEyreApi PierEnv where
multiEyreApiL = pierEnvHostEnv . multiEyreApiL
instance HasPortControlApi PierEnv where
portControlApiL = pierEnvHostEnv . portControlApiL
instance HasPierEnv PierEnv where
pierEnvL = id
instance HasKingId PierEnv where
kingIdL = kingEnvL . kingEnvKingId
instance HasStderrLogFunc PierEnv where
stderrLogFuncL = kingEnvL . stderrLogFuncL
instance HasLogFunc PierEnv where
logFuncL = kingEnvL . logFuncL
instance HasPierPath PierEnv where
pierPathL = pierEnvPierConfig . pierPathL
instance HasDryRun PierEnv where
dryRunL = pierEnvPierConfig . dryRunL
instance HasPierConfig PierEnv where
pierConfigL = pierEnvPierConfig
instance HasNetworkConfig PierEnv where
networkConfigL = pierEnvNetworkConfig
instance HasProcId PierEnv where
procIdL = kingEnvL . kingEnvProcId
-- PierEnv Utils ---------------------------------------------------------------
onKillPierSigL :: HasPierEnv e => Getter e (STM ())
onKillPierSigL = pierEnvL . pierEnvKillSignal . to readTMVar
killPierActionL :: HasPierEnv e => Getter e (STM ())
killPierActionL =
pierEnvL . pierEnvKillSignal . to (\kil -> void (tryPutTMVar kil ()))
-- Running Pier Envs -----------------------------------------------------------
runPierEnv
:: PierConfig -> NetworkConfig -> TMVar () -> RIO PierEnv a -> RIO HostEnv a
runPierEnv pierConfig networkConfig vKill action = do
host <- ask
let pierEnv = PierEnv { _pierEnvHostEnv = host
, _pierEnvPierConfig = pierConfig
, _pierEnvNetworkConfig = networkConfig
, _pierEnvKillSignal = vKill
}
io (runRIO pierEnv action)
| urbit/urbit | pkg/hs/urbit-king/lib/Urbit/King/App.hs | mit | 8,381 | 0 | 15 | 1,799 | 2,046 | 1,057 | 989 | -1 | -1 |
{-|
Module : Test.Problem
Description : The Test node for the Problem module
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : [email protected]
Stability : experimental
Portability : Unknown
Contains the node for the tests of the Problem module and its children
-}
module Test.Problem (
tests
) where
import qualified Test.Problem.Instances as Instances
import qualified Test.Problem.Internal as Internal
import qualified Test.Problem.ProblemExpr as ProblemExpr
import qualified Test.Problem.Source as Source
import TestUtils
name :: String
name = "Problem"
tests :: TestTree
tests =
testGroup name [
Internal.tests ,
ProblemExpr.tests,
Source.tests ,
Instances.tests
]
| aburnett88/HSat | tests-src/Test/Problem.hs | mit | 748 | 0 | 7 | 158 | 96 | 64 | 32 | 16 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.DedicatedWorkerGlobalScope (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.DedicatedWorkerGlobalScope
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.DedicatedWorkerGlobalScope
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/DedicatedWorkerGlobalScope.hs | mit | 391 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |