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
EmptyDataDecls
, TypeFamilies
, FlexibleContexts
, FlexibleInstances
, ScopedTypeVariables
#-}
module HFlint.Internal.Flint
( Flint(..)
)
where
import Foreign.Ptr ( Ptr )
class Flint a where
data CFlint a :: *
newFlint :: IO a
withFlint :: a
-> (Ptr (CFlint a) -> IO b)
-> IO (a, b)
{-# INLINE withFlint_ #-}
withFlint_ :: a
-> (Ptr (CFlint a) -> IO b)
-> IO a
withFlint_ a f = fst <$> withFlint a f
{-# INLINE withNewFlint #-}
withNewFlint :: (Ptr (CFlint a) -> IO b)
-> IO (a, b)
withNewFlint f = flip withFlint f =<< newFlint
{-# INLINE withNewFlint_ #-}
withNewFlint_ :: (Ptr (CFlint a) -> IO b)
-> IO a
withNewFlint_ f = fst <$> withNewFlint f
| martinra/hflint | src/HFlint/Internal/Flint.hs | gpl-3.0 | 794 | 0 | 13 | 254 | 249 | 130 | 119 | 28 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE IncoherentInstances #-}
{-# LANGUAGE DeriveGeneric #-}
module Test.QuickFuzz.Gen.Code.C where
import Data.Default
import Language.C
import Test.QuickCheck
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.State
import Data.List
import Test.QuickFuzz.Derive.Arbitrary
import Test.QuickFuzz.Derive.Fixable
import Test.QuickFuzz.Derive.Show
import Test.QuickFuzz.Gen.FormatInfo
import Test.QuickFuzz.Gen.Base.ByteString
import Test.QuickFuzz.Gen.Base.String
import qualified Data.ByteString.Lazy.Char8 as L8
devArbitrary ''CTranslUnit
-- devShow ''
cInfo :: FormatInfo [CTranslUnit] NoActions
cInfo = def
{ encode = L8.pack . concat . (map show) . (map pretty)
, random = arbitrary
, value = show
, ext = "c"
}
| elopez/QuickFuzz | src/Test/QuickFuzz/Gen/Code/C.hs | gpl-3.0 | 848 | 0 | 10 | 122 | 184 | 119 | 65 | 26 | 1 |
module YCbCr (YCbCr, toYcbcr, fromYcbcr, y, cb, cr, r, g, b) where
import Codec.Picture (Pixel8)
import Pixel
type YCbCr = (Double, Double, Double)
type ConvFactors = (Double, Double, Double)
y :: RGB8 -> Double
y rgb = 0.299 * r' + 0.587 * g' + 0.114 * b'
where (r', g', b') = fromIntegral' rgb
cb :: RGB8 -> Double
cb rgb@(r, g, b) = 0.492 * (b' - y rgb)
where b' = fromIntegral b
cr :: RGB8 -> Double
cr rgb@(r, g, b) = 0.877 * (r' - y rgb)
where r' = fromIntegral r
r :: YCbCr -> Pixel8
r (y, cb, cr) = (assertBounded . round) (y + 1.14 * cr)
g :: YCbCr -> Pixel8
g (y, cb, cr) = (assertBounded . round) (y - 0.395 * cb - 0.581 * cr)
b :: YCbCr -> Pixel8
b (y, cb, cr) = (assertBounded . round) (y + 2.033 * cb)
toYcbcr :: RGB8 -> YCbCr
toYcbcr rgb = (y rgb, cb rgb, cr rgb)
fromYcbcr :: YCbCr -> RGB8
fromYcbcr ycbcr = (r ycbcr, g ycbcr, b ycbcr)
| mikolajsacha/HaskellPics | ycbcr.hs | gpl-3.0 | 872 | 0 | 10 | 203 | 458 | 256 | 202 | 24 | 1 |
module Stack where
class Stack stack where
empty :: stack a
isEmpty :: stack a -> Bool
consS :: a -> stack a -> stack a
headS :: stack a -> a
tailS :: stack a -> stack a
instance Stack [] where
empty = []
isEmpty [] = True
isEmpty (_:_) = False
consS x xs = x:xs
headS [] = error "empty stack"
headS (x:_) = x
tailS [] = error "empty stack"
tailS (_:xs) = xs
{-
define stack using a custom datatype
-}
data CustomStack a = Nil
| Cons a (CustomStack a)
deriving (Show)
instance Stack CustomStack where
empty = Nil
isEmpty Nil = True
isEmpty _ = False
consS = Cons
headS (Cons a _) = a
headS Nil = error "empty stack"
tailS Nil = error "empty stack"
tailS (Cons _ xs) = xs
{- append function -}
append :: [a] -> [a] -> [a]
append xs ys = foldr (:) ys xs
appendCustom :: CustomStack a -> CustomStack a -> CustomStack a
appendCustom Nil y = y
appendCustom (Cons h t) y = Cons h (appendCustom t y)
{- appendCustom using foldr -}
instance Foldable CustomStack where
foldr f z Nil = z
foldr f z (Cons h t) = f h (foldr f z t)
appendCustom' :: CustomStack a -> CustomStack a -> CustomStack a
appendCustom' xs ys = foldr Cons ys xs
{-update function-}
update :: [a] -> Int -> a -> Maybe [a]
update [] _ _ = Nothing
update (x:xs) i y
| i < 0 = Nothing
| i == 0 = return (y:xs)
| otherwise = do
new <- update xs (pred i) y
return (x:new)
updateCustom :: CustomStack a -> Int -> a -> Maybe (CustomStack a)
updateCustom Nil _ _ = Nothing
updateCustom (Cons x xs) i y
| i < 0 = Nothing
| i == 0 = return (Cons y xs)
| otherwise = do
new <- updateCustom xs (pred i) y
return (Cons x new)
--exec 2.1
suffixes :: [a] -> [[a]]
suffixes [] = [[]]
suffixes xs = xs : suffixes (tail xs)
| ggarlic/fp-data-structures | src/Stack.hs | gpl-3.0 | 1,817 | 0 | 11 | 504 | 836 | 417 | 419 | 57 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Web.Scotty
import Control.Monad.IO.Class
import Data.Monoid
import Network.Wai.Middleware.RequestLogger
import Network.Wai.Middleware.Static
import Network.Wai.Parse
import Text.Blaze.Html.Renderer.Text (renderHtml)
import qualified Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as B
import System.FilePath ((</>))
main :: IO ()
main = scotty 3000 $ do
middleware logStdoutDev
middleware $ staticPolicy (noDots >-> addBase "uploads")
get "/" $
html $ renderHtml
$ H.html $
H.body $
H.form H.! method "post" H.! enctype "multipart/form-data" H.! action "/upload" $ do
H.input H.! type_ "file" H.! name "foofile"
H.br
H.input H.! type_ "file" H.! name "barfile"
H.br
H.input H.! type_ "submit"
post "/upload" $ do
fs <- files
let fs' = [ (fieldName, BS.unpack (fileName fi), fileContent fi) | (fieldName,fi) <- fs ]
-- write the files to disk, so they will be served by the static middleware
liftIO $ sequence_ [ B.writeFile ("uploads" </> fn) fc | (_,fn,fc) <- fs' ]
-- generate list of links to the files just uploaded
html $ mconcat [ mconcat [ fName
, ": "
, renderHtml $ H.a (H.toHtml fn) H.! href (H.toValue fn) >> H.br
]
| (fName,fn,_) <- fs' ]
| igniting/file-server | Main.hs | gpl-3.0 | 1,849 | 0 | 22 | 732 | 481 | 256 | 225 | 36 | 1 |
module Note
( Letter(..) , Octave , Accidental , Halves , Dots -- Elements of a note
, Note -- the Note type
, letter, octave, accidental, halves, dots -- accessors for a note
, makeNote -- constructor
, durAsNum -- view duration as a number
, Duration(..), Location(..), Pitch(..) -- comparisons
, (@-@), (#-#), (~-~) -- difference operators
, sharp, flat -- change pitch
, raise, lower -- change location
, halve, double, dot, undot -- change duration
, midC -- whole note middle C
, whole, half, quarter, eighth -- common durations
) where
import Test.QuickCheck
import Control.Monad
import Data.Function (on)
import Data.Ord (comparing)
data Letter = C | D | E | F | G | A | B deriving (Eq, Ord, Show, Enum, Bounded)
instance Arbitrary Letter where
arbitrary = elements [ C .. B ]
safeSucc l | l == B = C
| otherwise = succ l
safePred l | l == C = B
| otherwise = pred l
succ' 0 l = l
succ' n l = succ' (n-1) (safeSucc l)
pred' 0 l = l
pred' n l = pred' (n-1) (safePred l)
type Octave = Integer
type Accidental = Integer
type Halves = Integer
type Dots = Integer
newtype Note = N (Letter, Octave, Accidental, Halves, Dots) deriving Eq
letter (N (x,_,_,_,_)) = x
octave (N (_,x,_,_,_)) = x
accidental (N (_,_,x,_,_)) = x
halves (N (_,_,_,x,_)) = x
dots (N (_,_,_,_,x)) = x
runN (N x) = x
makeNote l o a h d = N (l,o,a,h,d)
durAsNum n = (1/2)^^ halves n * (3/2)^^ dots n
instance Arbitrary Note where
arbitrary = liftM5 makeNote arbitrary arbitrary arbitrary (arbitrary `suchThat` (>=0)) (arbitrary `suchThat` (>=0))
instance Show Note where
show n = let (l,o,a,h,d) = runN n in show l ++ show o ++ (if a < 0 then show a else '+':show a) ++ '@':show h ++ 'h':show d ++ "d"
--- Duration comparison
newtype Duration = Duration { runDuration :: Note }
instance Show Duration where
show (Duration n) = show (halves n) ++ 'h': show (dots n) ++ "d"
instance Eq Duration where
(==) = (==) `on` (durAsNum . runDuration)
instance Ord Duration where
compare = comparing (durAsNum . runDuration)
--- Location comparison
loc n = (octave n, letter n)
newtype Location = Location { runLocation :: Note }
instance Show Location where
show (Location n) = show (letter n) ++ show (octave n)
instance Eq Location where
(==) = (==) `on` (loc . runLocation)
instance Ord Location where
compare = comparing (loc . runLocation)
-- Pitch comparison
normalizePitch n@(N (C,o,_,_,_))
| o > 4 = normalizePitch (lower (7*(o-4)) n)
| o < 4 = normalizePitch (raise (7*(4-o)) n)
| otherwise = n
normalizePitch n@(N (l,_,_,_,_)) = normalizePitch (raise distToC n)
where distToC = fromIntegral . length . takeWhile (/=C) . iterate (succ' 1) $ l
pitch = accidental . normalizePitch
newtype Pitch = Pitch { runPitch :: Note }
instance Show Pitch where
show (Pitch n) = show (letter n) ++ show (octave n) ++ let a = accidental n in if a < 0 then show a else '+' : show a
instance Eq Pitch where
(==) = (==) `on` (pitch . runPitch)
instance Ord Pitch where
compare = comparing (pitch . runPitch)
--- Differences
a @-@ b = durAsNum a - durAsNum b
a #-# b = lines a - lines b
where lines = linesFromMidC . loc
linesFromMidC (o,l) = 7*(o-4) + (fromIntegral . fromEnum $ l)
a ~-~ b = pitch a - pitch b
sharp, flat, raise, lower, halve, double, dot, undot :: Integer -> Note -> Note
sharp i n = let (l,o,a,h,d) = runN n in N (l,o,a+i,h,d)
flat i = sharp (negate i)
raise i (N (l,o,a,h,d)) = N (succ' i l, o + octChange, a - offset, h, d)
where notesToOctBorder = fromIntegral . length . takeWhile (/=B) . iterate (succ' 1) $ l -- num notes before octave number changes
nonOctaveNotes = i `mod` 7 -- number of notes that are not part of straight octave increases
numOctavesAdded = i `div` 7 -- number of octaves added
octaveBorderCrossed = nonOctaveNotes > notesToOctBorder -- do we cross the octave border?
oneSteps = fromIntegral . length . filter (`elem`[C,F]) . map (`succ'` l) $ [1..nonOctaveNotes] -- how many one steps in the non octave part?
offset = oneSteps + 2*(nonOctaveNotes - oneSteps) + 12*numOctavesAdded -- the total offset
octChange = numOctavesAdded + if octaveBorderCrossed then 1 else 0 -- total octave change
lower i (N (l,o,a,h,d)) = N (pred' i l, o - octChange, a + offset, h, d)
where notesToOctBorder = fromIntegral . length . takeWhile (/=C) . iterate (pred' 1) $ l
nonOctaveNotes = i `mod` 7
numOctavesAdded = i `div` 7
octaveBorderCrossed = nonOctaveNotes > notesToOctBorder
oneSteps = fromIntegral . length . filter (`elem`[B,E]) . map (`pred'` l) $ [1..nonOctaveNotes]
offset = oneSteps + 2*(nonOctaveNotes - oneSteps) + 12*numOctavesAdded
octChange = numOctavesAdded + if octaveBorderCrossed then 1 else 0
halve i n = let (l,o,a,h,d) = runN n in N (l,o,a,h+i,d)
double i = halve (negate i)
dot i n = let (l,o,a,h,d) = runN n in N (l,o,a,h,d+i)
undot i = dot (negate i)
midC = N (C,4,0,0,0)
-- durations
whole = N (C,4,0,0,0)
half = N (C,4,0,1,0)
quarter = N (C,4,0,2,0)
eighth = N (C,4,0,3,0)
test = do
quickCheck $ \n (NonNegative i) -> n == (sharp i . flat i $ n)
quickCheck $ \n (NonNegative i) -> n == (raise i . lower i $ n)
quickCheck $ \n (NonNegative i) -> n == (halve i . double i $ n)
quickCheck $ \n (NonNegative i) -> n == (dot i . undot i $ n)
quickCheck $ \n (Positive i) -> Duration n > Duration (halve i n)
quickCheck $ \n (Positive i) -> Duration n < Duration (dot i n)
quickCheck $ \n (Positive i) -> Duration n < Duration (double i n)
quickCheck $ \n (Positive i) -> Duration n > Duration (undot i n)
quickCheck $ \n (Positive i) -> Location n < Location (raise i n)
quickCheck $ \n (Positive i) -> Location n > Location (lower i n)
quickCheck $ \n (Positive i) -> Pitch n < Pitch (sharp i n)
quickCheck $ \n (Positive i) -> Pitch n > Pitch (flat i n)
quickCheck $ \n (Positive i) -> i == (sharp i n ~-~ n)
quickCheck $ \n (Positive i) -> i == (raise i n #-# n)
| yousufmsoliman/music | Source (Haskell)/Note.hs | gpl-3.0 | 6,003 | 0 | 17 | 1,315 | 2,925 | 1,599 | 1,326 | 122 | 2 |
module Game.Toliman.Graphical.UI.Widgets where
import Data.Functor ((<$>))
import qualified Data.Map.Strict as Map
import qualified Data.RTree.Strict as RTree
import Game.Toliman.Internal.Sodium
import Game.Toliman.Internal.Lens
import Game.Toliman.Graphical.UI.Types
createWidget :: (Widget a) => UIState' -> (WidgetID -> Reactive a) -> Reactive ()
createWidget s wf = (s^.internal.push) $ NewWidget $ (MkWidget <$>) . wf
| duncanburke/toliman-graphical | src-lib/Game/Toliman/Graphical/UI/Widgets.hs | mpl-2.0 | 427 | 0 | 10 | 52 | 133 | 83 | 50 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AndroidManagement.Enterprises.Devices.IssueCommand
-- 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)
--
-- Issues a command to a device. The Operation resource returned contains a
-- Command in its metadata field. Use the get operation method to get the
-- status of the command.
--
-- /See:/ <https://developers.google.com/android/management Android Management API Reference> for @androidmanagement.enterprises.devices.issueCommand@.
module Network.Google.Resource.AndroidManagement.Enterprises.Devices.IssueCommand
(
-- * REST Resource
EnterprisesDevicesIssueCommandResource
-- * Creating a Request
, enterprisesDevicesIssueCommand
, EnterprisesDevicesIssueCommand
-- * Request Lenses
, edicXgafv
, edicUploadProtocol
, edicAccessToken
, edicUploadType
, edicPayload
, edicName
, edicCallback
) where
import Network.Google.AndroidManagement.Types
import Network.Google.Prelude
-- | A resource alias for @androidmanagement.enterprises.devices.issueCommand@ method which the
-- 'EnterprisesDevicesIssueCommand' request conforms to.
type EnterprisesDevicesIssueCommandResource =
"v1" :>
CaptureMode "name" "issueCommand" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Command :> Post '[JSON] Operation
-- | Issues a command to a device. The Operation resource returned contains a
-- Command in its metadata field. Use the get operation method to get the
-- status of the command.
--
-- /See:/ 'enterprisesDevicesIssueCommand' smart constructor.
data EnterprisesDevicesIssueCommand =
EnterprisesDevicesIssueCommand'
{ _edicXgafv :: !(Maybe Xgafv)
, _edicUploadProtocol :: !(Maybe Text)
, _edicAccessToken :: !(Maybe Text)
, _edicUploadType :: !(Maybe Text)
, _edicPayload :: !Command
, _edicName :: !Text
, _edicCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EnterprisesDevicesIssueCommand' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'edicXgafv'
--
-- * 'edicUploadProtocol'
--
-- * 'edicAccessToken'
--
-- * 'edicUploadType'
--
-- * 'edicPayload'
--
-- * 'edicName'
--
-- * 'edicCallback'
enterprisesDevicesIssueCommand
:: Command -- ^ 'edicPayload'
-> Text -- ^ 'edicName'
-> EnterprisesDevicesIssueCommand
enterprisesDevicesIssueCommand pEdicPayload_ pEdicName_ =
EnterprisesDevicesIssueCommand'
{ _edicXgafv = Nothing
, _edicUploadProtocol = Nothing
, _edicAccessToken = Nothing
, _edicUploadType = Nothing
, _edicPayload = pEdicPayload_
, _edicName = pEdicName_
, _edicCallback = Nothing
}
-- | V1 error format.
edicXgafv :: Lens' EnterprisesDevicesIssueCommand (Maybe Xgafv)
edicXgafv
= lens _edicXgafv (\ s a -> s{_edicXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
edicUploadProtocol :: Lens' EnterprisesDevicesIssueCommand (Maybe Text)
edicUploadProtocol
= lens _edicUploadProtocol
(\ s a -> s{_edicUploadProtocol = a})
-- | OAuth access token.
edicAccessToken :: Lens' EnterprisesDevicesIssueCommand (Maybe Text)
edicAccessToken
= lens _edicAccessToken
(\ s a -> s{_edicAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
edicUploadType :: Lens' EnterprisesDevicesIssueCommand (Maybe Text)
edicUploadType
= lens _edicUploadType
(\ s a -> s{_edicUploadType = a})
-- | Multipart request metadata.
edicPayload :: Lens' EnterprisesDevicesIssueCommand Command
edicPayload
= lens _edicPayload (\ s a -> s{_edicPayload = a})
-- | The name of the device in the form
-- enterprises\/{enterpriseId}\/devices\/{deviceId}.
edicName :: Lens' EnterprisesDevicesIssueCommand Text
edicName = lens _edicName (\ s a -> s{_edicName = a})
-- | JSONP
edicCallback :: Lens' EnterprisesDevicesIssueCommand (Maybe Text)
edicCallback
= lens _edicCallback (\ s a -> s{_edicCallback = a})
instance GoogleRequest EnterprisesDevicesIssueCommand
where
type Rs EnterprisesDevicesIssueCommand = Operation
type Scopes EnterprisesDevicesIssueCommand =
'["https://www.googleapis.com/auth/androidmanagement"]
requestClient EnterprisesDevicesIssueCommand'{..}
= go _edicName _edicXgafv _edicUploadProtocol
_edicAccessToken
_edicUploadType
_edicCallback
(Just AltJSON)
_edicPayload
androidManagementService
where go
= buildClient
(Proxy ::
Proxy EnterprisesDevicesIssueCommandResource)
mempty
| brendanhay/gogol | gogol-androidmanagement/gen/Network/Google/Resource/AndroidManagement/Enterprises/Devices/IssueCommand.hs | mpl-2.0 | 5,672 | 0 | 16 | 1,215 | 782 | 458 | 324 | 113 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
func
:: forall a
. ()
=> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
-> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
func
:: ()
=> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
-> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
| lspitzner/brittany | data/Test330.hs | agpl-3.0 | 309 | 0 | 7 | 36 | 33 | 20 | 13 | 10 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
import Monad
import Functor
import Maybe
import Either
import NonEmpty
import Semigroup
import Monoid
import Applicative
import Base
import GHC.Base hiding (Functor, Maybe, Monad, fmap, return, (>>=))
import Data.Fixed
import GHC.Num
import GHC.Real
import GHC.Float hiding ((**))
import System.IO
import Data.List
import Data.Char (ord)
import GHC.Show
divBy :: Integral t => t -> [t] -> Maybe.Maybe [t]
divBy v [] = Just []
divBy v (0:xs) = Nothing
divBy v (x:xs) =
case divBy v xs of
Nothing -> Nothing
Just rxs -> Just ((v `div` x) : rxs)
demo_Maybe = divBy 3 (take 5 [0..])
demo_Maybe_Functor =
fmap (*2) (Just 2)
demo_Maybe_Monad =
(Just 2) >>= \ x -> Just (x * 2)
isPasswordRightLength :: [Char] -> Either.Either [Char] [Char]
isPasswordRightLength pwd =
let len = length pwd
in
if len >= 6 && len <= 16
then Right pwd
else Left ("the length " ++ (show len) ++ " is not right")
isNumber c =
let ascii = (ord c)
in ascii >= (ord '0') && ascii <= (ord '9')
isPasswordHasNumber :: [Char] -> Either.Either [Char] [Char]
isPasswordHasNumber pwd =
if any isNumber pwd
then (Right pwd)
else (Left "password doesn't contain number")
isPasswordValid :: [Char] -> Either [Char] [Char]
isPasswordValid pwd =
isPasswordHasNumber pwd >>= isPasswordRightLength
demo_Either_Functor :: Either.Either Integer Integer
demo_Either_Functor =
fmap (*2) (Right 2)
demo_Either_Monad = do
print (isPasswordValid "0aaaaa")
print (isPasswordValid "aaaaaa")
print (isPasswordValid "0aaaa")
demo_tuple_Functor = do
fmap (*2) (1,2)
demo_pair_Functor = do
print (fmap id (Pair 2 3))
print (((fmap (*3)) . (fmap (*5))) (Pair 1 2))
print (fmap ((*3) . (*5)) (Pair 1 2))
demo_semigroup1 = do
print (sconcat ((Sum (Complex 1 2)) :| [Sum (Complex 2 3)]))
print (sconcat ((Product (Complex 1 2)) :| [Product (Complex 2 3)]))
print (timeslp 10 (Product (Complex 1 2)))
demo_Complex = do
print ((Complex 1 1) + (Complex 2 2))
print ((Complex 1 1) - (Complex 2 2))
print ((Complex 1 1) * (Complex 2 2))
print ((Complex 1 1) + 0)
print (- (Complex 1 1))
demo_monoid1 = do
print ((Sum (Complex 1 2)) <> mempty)
print ((Sum (Complex 1 2)) <> ((Sum (Complex 2 3)) <> (Sum (Complex 3 4))))
print (((Sum (Complex 1 2)) <> (Sum (Complex 2 3))) <> (Sum (Complex 3 4)))
print (mconcat [(Sum (Complex 1 2)), (Sum (Complex 2 3))])
print (mconcat (map Sum [(Complex 1 2), (Complex 2 3)]))
{-
analysis of precedence:
1. Function application has higher precedence than any infix operator
2. infixr 9 .
3. infixr 0 $
So first apply map with Sum. Then combine mconcat with (map Sum). Finally apply
this combined function to [...]
-}
print (mconcat . map Sum $ [(Complex 1 2), (Complex 2 3)])
print ((mconcat . (map Sum)) [(Complex 1 2), (Complex 2 3)])
genList1 n = take n [1..]
genList2 n = take n [2..]
genList3 n = take n [3..]
demo_monoid2 = do
-- here each function is a monoid. So we concat the function monoid to
-- generate another function and apply it to 3.
-- This example is quite meaningful...
print (mconcat [genList1, genList2, genList3] 3)
demo_monoid_Last = do
print ((Last (Just 3)) <> (Last (Just 4)) <> (Last (Nothing)))
-- local type binding
let x :: (Num a) => (Last a)
x = (Last Nothing)
in print x
cmpLen w1 w2 =
compare (length w1) (length w2)
demo_monoid_Sort = do
-- sort first by length, then alphabatically
print (sortBy (cmpLen <> compare) (words "The reasoning behind this definition"))
demo_applicative = do
print $ (pure id <*> ZipList [1])
let x :: (Num a) => ZipList a
x = pure 1
in print ((pure (\ x -> 2 * x)) <*> x)
print (ZipList [\ x -> 2*x, \ x -> 3*x] <*> pure 1)
print (pure ($ 1) <*> ZipList [\ x -> 2*x, \ x -> 3*x])
-- (+) <$> [1] creates partial function in `f` domain
-- then, this function is applied with [2]
print (pure (+) <*> [1] <*> [2])
print ((+) <$> [1] <*> [2])
main = demo_monoid1
| seckcoder/lang-learn | haskell/lambda-calculus/src/test.hs | unlicense | 4,050 | 0 | 16 | 899 | 1,819 | 942 | 877 | 103 | 2 |
#!/usr/bin/env runghc
dot(x1,y1)(x2,y2)=x1*x2+y1*y2
cross(x1,y1)(x2,y2)=x1*y2-x2*y1
upperArg(x,y)=y>0 || y==0 && x>0
cmpArg l r=compare(upperArg r,0)(upperArg l,cross l r)
| jasy/alglib | Haskell/Vector2D.hs | unlicense | 172 | 0 | 9 | 16 | 142 | 76 | 66 | 4 | 1 |
module Git.Command.PrunePacked (run) where
run :: [String] -> IO ()
run args = return () | wereHamster/yag | Git/Command/PrunePacked.hs | unlicense | 89 | 0 | 7 | 15 | 42 | 23 | 19 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Network.Wai
import Network.HTTP.Types (status200, status404)
import Network.Wai.Handler.Warp (run)
import Data.ByteString.Lazy.Char8
import Text.Proton.Template
consoleLog :: String -> IO ()
consoleLog msg = Prelude.putStrLn msg
application :: Templates -> Application
application tmps request respond = do
case rawPathInfo request of
"/" -> do
resp <- handleGetBasic tmps
respond $ resp
_ -> respond $ notFound
handleGetBasic :: Templates -> IO Response
handleGetBasic tmps = do
tmp <- getTemplate tmps "basic.xhtml"
tmp <- setElementValue tmp "title" "Basic Xhtml Page" 0
tmp <- setElementValue tmp "content" "Content goes here" 0
tmp <- setElementValue tmp "link" "Link goes here" 0
s <- renderTemplate tmp
return (responseLBS status200 [("Content-Type", "text/html")] $ pack s)
notFound :: Response
notFound = responseLBS
status404
[("Content-Type", "text/plain")]
"404 - Not Found"
main = do
tmps <- loadTemplates "."
consoleLog "Started BasicWebExample"
run 3000 (application tmps) | jasonrbriggs/proton | haskell/examples/BasicWebExample.hs | apache-2.0 | 1,148 | 0 | 13 | 257 | 318 | 158 | 160 | 32 | 2 |
module Miscellaneous.A280521 (a280521) where
import HelperSequences.A066628 (a066628)
a280521 :: Integer -> Integer
a280521 n = go n 0 where
go 0 counter = counter
go k counter = go (a066628 $ k + 1) $ counter + 1
| peterokagey/haskellOEIS | src/Miscellaneous/A280521.hs | apache-2.0 | 219 | 0 | 12 | 43 | 87 | 46 | 41 | 6 | 2 |
import System.Random.Shuffle
| ccqpein/Arithmetic-Exercises | Shuffle-an-Array/SAA.hs | apache-2.0 | 40 | 0 | 4 | 13 | 7 | 4 | 3 | 1 | 0 |
solveRPN :: String -> Float
solveRPN = head . foldl parseItem [] . words
parseItem :: (Num a, Read a, Floating a) => [a] -> String -> [a]
parseItem (x:y:xs) "*" = x*y :xs
parseItem (x:y:xs) "/" = y/x :xs -- x=0
parseItem (x:y:xs) "+" = x+y :xs
parseItem (x:y:xs) "-" = y-x :xs
parseItem (x:y:xs) "^" = y**x :xs -- y=0
parseItem (x:xs) "log" = log x :xs -- x=0
parseItem xs n = (read n):xs
| paulbarbu/haskell-ground | rpn.hs | apache-2.0 | 391 | 0 | 8 | 79 | 262 | 137 | 125 | 10 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QDir.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:32
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Core.QDir (
QqDir(..)
,QqDir_nf(..)
,qDirAddResourceSearchPath
,qDirAddSearchPath
,cdUp
,qDirCleanPath
,qDirConvertSeparators
,qDirCurrent
,qDirCurrentPath
,dirName
,qDirDrives
,QentryInfoList(..)
,QentryList(..)
,qDirFromNativeSeparators
,qDirHome
,qDirHomePath
,qDirIsAbsolutePath
,qDirIsRelativePath
,QqDirMatch(..)
,mkpath
,qDirNameFiltersFromString
,relativeFilePath
,rmpath
,qDirRoot
,qDirRootPath
,qDirSearchPaths
,qDirSeparator, qDirSeparator_nf
,qDirSetCurrent
,qDirSetSearchPaths
,qDirTemp
,qDirTempPath
,qDirToNativeSeparators
,qDir_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.QDir
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
class QqDir x1 where
qDir :: x1 -> IO (QDir ())
instance QqDir (()) where
qDir ()
= withQDirResult $
qtc_QDir
foreign import ccall "qtc_QDir" qtc_QDir :: IO (Ptr (TQDir ()))
instance QqDir ((QDir t1)) where
qDir (x1)
= withQDirResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDir1 cobj_x1
foreign import ccall "qtc_QDir1" qtc_QDir1 :: Ptr (TQDir t1) -> IO (Ptr (TQDir ()))
instance QqDir ((String)) where
qDir (x1)
= withQDirResult $
withCWString x1 $ \cstr_x1 ->
qtc_QDir2 cstr_x1
foreign import ccall "qtc_QDir2" qtc_QDir2 :: CWString -> IO (Ptr (TQDir ()))
instance QqDir ((String, String)) where
qDir (x1, x2)
= withQDirResult $
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QDir3 cstr_x1 cstr_x2
foreign import ccall "qtc_QDir3" qtc_QDir3 :: CWString -> CWString -> IO (Ptr (TQDir ()))
instance QqDir ((String, String, SortFlags)) where
qDir (x1, x2, x3)
= withQDirResult $
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QDir4 cstr_x1 cstr_x2 (toCLong $ qFlags_toInt x3)
foreign import ccall "qtc_QDir4" qtc_QDir4 :: CWString -> CWString -> CLong -> IO (Ptr (TQDir ()))
instance QqDir ((String, String, SortFlags, Filters)) where
qDir (x1, x2, x3, x4)
= withQDirResult $
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QDir5 cstr_x1 cstr_x2 (toCLong $ qFlags_toInt x3) (toCLong $ qFlags_toInt x4)
foreign import ccall "qtc_QDir5" qtc_QDir5 :: CWString -> CWString -> CLong -> CLong -> IO (Ptr (TQDir ()))
class QqDir_nf x1 where
qDir_nf :: x1 -> IO (QDir ())
instance QqDir_nf (()) where
qDir_nf ()
= withObjectRefResult $
qtc_QDir
instance QqDir_nf ((QDir t1)) where
qDir_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDir1 cobj_x1
instance QqDir_nf ((String)) where
qDir_nf (x1)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
qtc_QDir2 cstr_x1
instance QqDir_nf ((String, String)) where
qDir_nf (x1, x2)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QDir3 cstr_x1 cstr_x2
instance QqDir_nf ((String, String, SortFlags)) where
qDir_nf (x1, x2, x3)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QDir4 cstr_x1 cstr_x2 (toCLong $ qFlags_toInt x3)
instance QqDir_nf ((String, String, SortFlags, Filters)) where
qDir_nf (x1, x2, x3, x4)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QDir5 cstr_x1 cstr_x2 (toCLong $ qFlags_toInt x3) (toCLong $ qFlags_toInt x4)
instance QabsoluteFilePath (QDir a) ((String)) where
absoluteFilePath x0 (x1)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_absoluteFilePath cobj_x0 cstr_x1
foreign import ccall "qtc_QDir_absoluteFilePath" qtc_QDir_absoluteFilePath :: Ptr (TQDir a) -> CWString -> IO (Ptr (TQString ()))
instance QabsolutePath (QDir a) (()) where
absolutePath x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_absolutePath cobj_x0
foreign import ccall "qtc_QDir_absolutePath" qtc_QDir_absolutePath :: Ptr (TQDir a) -> IO (Ptr (TQString ()))
qDirAddResourceSearchPath :: ((String)) -> IO ()
qDirAddResourceSearchPath (x1)
= withCWString x1 $ \cstr_x1 ->
qtc_QDir_addResourceSearchPath cstr_x1
foreign import ccall "qtc_QDir_addResourceSearchPath" qtc_QDir_addResourceSearchPath :: CWString -> IO ()
qDirAddSearchPath :: ((String, String)) -> IO ()
qDirAddSearchPath (x1, x2)
= withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QDir_addSearchPath cstr_x1 cstr_x2
foreign import ccall "qtc_QDir_addSearchPath" qtc_QDir_addSearchPath :: CWString -> CWString -> IO ()
instance QcanonicalPath (QDir a) (()) where
canonicalPath x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_canonicalPath cobj_x0
foreign import ccall "qtc_QDir_canonicalPath" qtc_QDir_canonicalPath :: Ptr (TQDir a) -> IO (Ptr (TQString ()))
instance Qcd (QDir a) ((String)) (IO (Bool)) where
cd x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_cd cobj_x0 cstr_x1
foreign import ccall "qtc_QDir_cd" qtc_QDir_cd :: Ptr (TQDir a) -> CWString -> IO CBool
cdUp :: QDir a -> (()) -> IO (Bool)
cdUp x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_cdUp cobj_x0
foreign import ccall "qtc_QDir_cdUp" qtc_QDir_cdUp :: Ptr (TQDir a) -> IO CBool
qDirCleanPath :: ((String)) -> IO (String)
qDirCleanPath (x1)
= withStringResult $
withCWString x1 $ \cstr_x1 ->
qtc_QDir_cleanPath cstr_x1
foreign import ccall "qtc_QDir_cleanPath" qtc_QDir_cleanPath :: CWString -> IO (Ptr (TQString ()))
qDirConvertSeparators :: ((String)) -> IO (String)
qDirConvertSeparators (x1)
= withStringResult $
withCWString x1 $ \cstr_x1 ->
qtc_QDir_convertSeparators cstr_x1
foreign import ccall "qtc_QDir_convertSeparators" qtc_QDir_convertSeparators :: CWString -> IO (Ptr (TQString ()))
instance Qcount (QDir a) (()) where
count x0 ()
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_count cobj_x0
foreign import ccall "qtc_QDir_count" qtc_QDir_count :: Ptr (TQDir a) -> IO CUInt
qDirCurrent :: (()) -> IO (QDir ())
qDirCurrent ()
= withQDirResult $
qtc_QDir_current
foreign import ccall "qtc_QDir_current" qtc_QDir_current :: IO (Ptr (TQDir ()))
qDirCurrentPath :: (()) -> IO (String)
qDirCurrentPath ()
= withStringResult $
qtc_QDir_currentPath
foreign import ccall "qtc_QDir_currentPath" qtc_QDir_currentPath :: IO (Ptr (TQString ()))
dirName :: QDir a -> (()) -> IO (String)
dirName x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_dirName cobj_x0
foreign import ccall "qtc_QDir_dirName" qtc_QDir_dirName :: Ptr (TQDir a) -> IO (Ptr (TQString ()))
qDirDrives :: (()) -> IO ([QFileInfo ()])
qDirDrives ()
= withQListObjectRefResult $ \arr ->
qtc_QDir_drives arr
foreign import ccall "qtc_QDir_drives" qtc_QDir_drives :: Ptr (Ptr (TQFileInfo ())) -> IO CInt
class QentryInfoList x1 where
entryInfoList :: QDir a -> x1 -> IO ([QFileInfo ()])
instance QentryInfoList (()) where
entryInfoList x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_entryInfoList cobj_x0 arr
foreign import ccall "qtc_QDir_entryInfoList" qtc_QDir_entryInfoList :: Ptr (TQDir a) -> Ptr (Ptr (TQFileInfo ())) -> IO CInt
instance QentryInfoList ((Filters)) where
entryInfoList x0 (x1)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_entryInfoList1 cobj_x0 (toCLong $ qFlags_toInt x1) arr
foreign import ccall "qtc_QDir_entryInfoList1" qtc_QDir_entryInfoList1 :: Ptr (TQDir a) -> CLong -> Ptr (Ptr (TQFileInfo ())) -> IO CInt
instance QentryInfoList ((Filters, SortFlags)) where
entryInfoList x0 (x1, x2)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_entryInfoList4 cobj_x0 (toCLong $ qFlags_toInt x1) (toCLong $ qFlags_toInt x2) arr
foreign import ccall "qtc_QDir_entryInfoList4" qtc_QDir_entryInfoList4 :: Ptr (TQDir a) -> CLong -> CLong -> Ptr (Ptr (TQFileInfo ())) -> IO CInt
instance QentryInfoList (([String])) where
entryInfoList x0 (x1)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withQListString x1 $ \cqlistlen_x1 cqliststr_x1 ->
qtc_QDir_entryInfoList2 cobj_x0 cqlistlen_x1 cqliststr_x1 arr
foreign import ccall "qtc_QDir_entryInfoList2" qtc_QDir_entryInfoList2 :: Ptr (TQDir a) -> CInt -> Ptr (Ptr CWchar) -> Ptr (Ptr (TQFileInfo ())) -> IO CInt
instance QentryInfoList (([String], Filters)) where
entryInfoList x0 (x1, x2)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withQListString x1 $ \cqlistlen_x1 cqliststr_x1 ->
qtc_QDir_entryInfoList3 cobj_x0 cqlistlen_x1 cqliststr_x1 (toCLong $ qFlags_toInt x2) arr
foreign import ccall "qtc_QDir_entryInfoList3" qtc_QDir_entryInfoList3 :: Ptr (TQDir a) -> CInt -> Ptr (Ptr CWchar) -> CLong -> Ptr (Ptr (TQFileInfo ())) -> IO CInt
instance QentryInfoList (([String], Filters, SortFlags)) where
entryInfoList x0 (x1, x2, x3)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withQListString x1 $ \cqlistlen_x1 cqliststr_x1 ->
qtc_QDir_entryInfoList5 cobj_x0 cqlistlen_x1 cqliststr_x1 (toCLong $ qFlags_toInt x2) (toCLong $ qFlags_toInt x3) arr
foreign import ccall "qtc_QDir_entryInfoList5" qtc_QDir_entryInfoList5 :: Ptr (TQDir a) -> CInt -> Ptr (Ptr CWchar) -> CLong -> CLong -> Ptr (Ptr (TQFileInfo ())) -> IO CInt
class QentryList x1 where
entryList :: QDir a -> x1 -> IO ([String])
instance QentryList (()) where
entryList x0 ()
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_entryList cobj_x0 arr
foreign import ccall "qtc_QDir_entryList" qtc_QDir_entryList :: Ptr (TQDir a) -> Ptr (Ptr (TQString ())) -> IO CInt
instance QentryList ((Filters)) where
entryList x0 (x1)
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_entryList2 cobj_x0 (toCLong $ qFlags_toInt x1) arr
foreign import ccall "qtc_QDir_entryList2" qtc_QDir_entryList2 :: Ptr (TQDir a) -> CLong -> Ptr (Ptr (TQString ())) -> IO CInt
instance QentryList ((Filters, SortFlags)) where
entryList x0 (x1, x2)
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_entryList4 cobj_x0 (toCLong $ qFlags_toInt x1) (toCLong $ qFlags_toInt x2) arr
foreign import ccall "qtc_QDir_entryList4" qtc_QDir_entryList4 :: Ptr (TQDir a) -> CLong -> CLong -> Ptr (Ptr (TQString ())) -> IO CInt
instance QentryList (([String])) where
entryList x0 (x1)
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withQListString x1 $ \cqlistlen_x1 cqliststr_x1 ->
qtc_QDir_entryList1 cobj_x0 cqlistlen_x1 cqliststr_x1 arr
foreign import ccall "qtc_QDir_entryList1" qtc_QDir_entryList1 :: Ptr (TQDir a) -> CInt -> Ptr (Ptr CWchar) -> Ptr (Ptr (TQString ())) -> IO CInt
instance QentryList (([String], Filters)) where
entryList x0 (x1, x2)
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withQListString x1 $ \cqlistlen_x1 cqliststr_x1 ->
qtc_QDir_entryList3 cobj_x0 cqlistlen_x1 cqliststr_x1 (toCLong $ qFlags_toInt x2) arr
foreign import ccall "qtc_QDir_entryList3" qtc_QDir_entryList3 :: Ptr (TQDir a) -> CInt -> Ptr (Ptr CWchar) -> CLong -> Ptr (Ptr (TQString ())) -> IO CInt
instance QentryList (([String], Filters, SortFlags)) where
entryList x0 (x1, x2, x3)
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withQListString x1 $ \cqlistlen_x1 cqliststr_x1 ->
qtc_QDir_entryList5 cobj_x0 cqlistlen_x1 cqliststr_x1 (toCLong $ qFlags_toInt x2) (toCLong $ qFlags_toInt x3) arr
foreign import ccall "qtc_QDir_entryList5" qtc_QDir_entryList5 :: Ptr (TQDir a) -> CInt -> Ptr (Ptr CWchar) -> CLong -> CLong -> Ptr (Ptr (TQString ())) -> IO CInt
instance Qexists (QDir a) (()) where
exists x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_exists cobj_x0
foreign import ccall "qtc_QDir_exists" qtc_QDir_exists :: Ptr (TQDir a) -> IO CBool
instance Qexists (QDir a) ((String)) where
exists x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_exists1 cobj_x0 cstr_x1
foreign import ccall "qtc_QDir_exists1" qtc_QDir_exists1 :: Ptr (TQDir a) -> CWString -> IO CBool
instance QfilePath (QDir a) ((String)) where
filePath x0 (x1)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_filePath cobj_x0 cstr_x1
foreign import ccall "qtc_QDir_filePath" qtc_QDir_filePath :: Ptr (TQDir a) -> CWString -> IO (Ptr (TQString ()))
instance Qqfilter (QDir a) (()) where
qfilter x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_filter cobj_x0
foreign import ccall "qtc_QDir_filter" qtc_QDir_filter :: Ptr (TQDir a) -> IO CLong
qDirFromNativeSeparators :: ((String)) -> IO (String)
qDirFromNativeSeparators (x1)
= withStringResult $
withCWString x1 $ \cstr_x1 ->
qtc_QDir_fromNativeSeparators cstr_x1
foreign import ccall "qtc_QDir_fromNativeSeparators" qtc_QDir_fromNativeSeparators :: CWString -> IO (Ptr (TQString ()))
qDirHome :: (()) -> IO (QDir ())
qDirHome ()
= withQDirResult $
qtc_QDir_home
foreign import ccall "qtc_QDir_home" qtc_QDir_home :: IO (Ptr (TQDir ()))
qDirHomePath :: (()) -> IO (String)
qDirHomePath ()
= withStringResult $
qtc_QDir_homePath
foreign import ccall "qtc_QDir_homePath" qtc_QDir_homePath :: IO (Ptr (TQString ()))
instance QisAbsolute (QDir a) (()) where
isAbsolute x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_isAbsolute cobj_x0
foreign import ccall "qtc_QDir_isAbsolute" qtc_QDir_isAbsolute :: Ptr (TQDir a) -> IO CBool
qDirIsAbsolutePath :: ((String)) -> IO (Bool)
qDirIsAbsolutePath (x1)
= withBoolResult $
withCWString x1 $ \cstr_x1 ->
qtc_QDir_isAbsolutePath cstr_x1
foreign import ccall "qtc_QDir_isAbsolutePath" qtc_QDir_isAbsolutePath :: CWString -> IO CBool
instance QisReadable (QDir a) (()) where
isReadable x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_isReadable cobj_x0
foreign import ccall "qtc_QDir_isReadable" qtc_QDir_isReadable :: Ptr (TQDir a) -> IO CBool
instance QisRelative (QDir a) (()) where
isRelative x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_isRelative cobj_x0
foreign import ccall "qtc_QDir_isRelative" qtc_QDir_isRelative :: Ptr (TQDir a) -> IO CBool
qDirIsRelativePath :: ((String)) -> IO (Bool)
qDirIsRelativePath (x1)
= withBoolResult $
withCWString x1 $ \cstr_x1 ->
qtc_QDir_isRelativePath cstr_x1
foreign import ccall "qtc_QDir_isRelativePath" qtc_QDir_isRelativePath :: CWString -> IO CBool
instance QisRoot (QDir a) (()) where
isRoot x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_isRoot cobj_x0
foreign import ccall "qtc_QDir_isRoot" qtc_QDir_isRoot :: Ptr (TQDir a) -> IO CBool
instance QmakeAbsolute (QDir a) (()) where
makeAbsolute x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_makeAbsolute cobj_x0
foreign import ccall "qtc_QDir_makeAbsolute" qtc_QDir_makeAbsolute :: Ptr (TQDir a) -> IO CBool
class QqDirMatch x1 where
qDirMatch :: x1 -> IO (Bool)
instance QqDirMatch ((String, String)) where
qDirMatch (x1, x2)
= withBoolResult $
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QDir_match cstr_x1 cstr_x2
foreign import ccall "qtc_QDir_match" qtc_QDir_match :: CWString -> CWString -> IO CBool
instance QqDirMatch (([String], String)) where
qDirMatch (x1, x2)
= withBoolResult $
withQListString x1 $ \cqlistlen_x1 cqliststr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QDir_match1 cqlistlen_x1 cqliststr_x1 cstr_x2
foreign import ccall "qtc_QDir_match1" qtc_QDir_match1 :: CInt -> Ptr (Ptr CWchar) -> CWString -> IO CBool
instance Qmkdir (QDir a) ((String)) (IO (Bool)) where
mkdir x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_mkdir cobj_x0 cstr_x1
foreign import ccall "qtc_QDir_mkdir" qtc_QDir_mkdir :: Ptr (TQDir a) -> CWString -> IO CBool
mkpath :: QDir a -> ((String)) -> IO (Bool)
mkpath x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_mkpath cobj_x0 cstr_x1
foreign import ccall "qtc_QDir_mkpath" qtc_QDir_mkpath :: Ptr (TQDir a) -> CWString -> IO CBool
instance QnameFilters (QDir a) (()) where
nameFilters x0 ()
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_nameFilters cobj_x0 arr
foreign import ccall "qtc_QDir_nameFilters" qtc_QDir_nameFilters :: Ptr (TQDir a) -> Ptr (Ptr (TQString ())) -> IO CInt
qDirNameFiltersFromString :: ((String)) -> IO ([String])
qDirNameFiltersFromString (x1)
= withQListStringResult $ \arr ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_nameFiltersFromString cstr_x1 arr
foreign import ccall "qtc_QDir_nameFiltersFromString" qtc_QDir_nameFiltersFromString :: CWString -> Ptr (Ptr (TQString ())) -> IO CInt
instance Qpath (QDir a) (()) (IO (String)) where
path x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_path cobj_x0
foreign import ccall "qtc_QDir_path" qtc_QDir_path :: Ptr (TQDir a) -> IO (Ptr (TQString ()))
instance Qrefresh (QDir a) (()) where
refresh x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_refresh cobj_x0
foreign import ccall "qtc_QDir_refresh" qtc_QDir_refresh :: Ptr (TQDir a) -> IO ()
relativeFilePath :: QDir a -> ((String)) -> IO (String)
relativeFilePath x0 (x1)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_relativeFilePath cobj_x0 cstr_x1
foreign import ccall "qtc_QDir_relativeFilePath" qtc_QDir_relativeFilePath :: Ptr (TQDir a) -> CWString -> IO (Ptr (TQString ()))
instance Qremove (QDir a) ((String)) (IO (Bool)) where
remove x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_remove cobj_x0 cstr_x1
foreign import ccall "qtc_QDir_remove" qtc_QDir_remove :: Ptr (TQDir a) -> CWString -> IO CBool
instance Qrename (QDir a) ((String, String)) (IO (Bool)) where
rename x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QDir_rename cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QDir_rename" qtc_QDir_rename :: Ptr (TQDir a) -> CWString -> CWString -> IO CBool
instance Qrmdir (QDir a) ((String)) (IO (Bool)) where
rmdir x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_rmdir cobj_x0 cstr_x1
foreign import ccall "qtc_QDir_rmdir" qtc_QDir_rmdir :: Ptr (TQDir a) -> CWString -> IO CBool
rmpath :: QDir a -> ((String)) -> IO (Bool)
rmpath x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_rmpath cobj_x0 cstr_x1
foreign import ccall "qtc_QDir_rmpath" qtc_QDir_rmpath :: Ptr (TQDir a) -> CWString -> IO CBool
qDirRoot :: (()) -> IO (QDir ())
qDirRoot ()
= withQDirResult $
qtc_QDir_root
foreign import ccall "qtc_QDir_root" qtc_QDir_root :: IO (Ptr (TQDir ()))
qDirRootPath :: (()) -> IO (String)
qDirRootPath ()
= withStringResult $
qtc_QDir_rootPath
foreign import ccall "qtc_QDir_rootPath" qtc_QDir_rootPath :: IO (Ptr (TQString ()))
qDirSearchPaths :: ((String)) -> IO ([String])
qDirSearchPaths (x1)
= withQListStringResult $ \arr ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_searchPaths cstr_x1 arr
foreign import ccall "qtc_QDir_searchPaths" qtc_QDir_searchPaths :: CWString -> Ptr (Ptr (TQString ())) -> IO CInt
qDirSeparator :: (()) -> IO (QChar ())
qDirSeparator ()
= withQCharResult $
qtc_QDir_separator
foreign import ccall "qtc_QDir_separator" qtc_QDir_separator :: IO (Ptr (TQChar ()))
qDirSeparator_nf :: (()) -> IO (QChar ())
qDirSeparator_nf ()
= withObjectRefResult $
qtc_QDir_separator
qDirSetCurrent :: ((String)) -> IO (Bool)
qDirSetCurrent (x1)
= withBoolResult $
withCWString x1 $ \cstr_x1 ->
qtc_QDir_setCurrent cstr_x1
foreign import ccall "qtc_QDir_setCurrent" qtc_QDir_setCurrent :: CWString -> IO CBool
instance QsetFilter (QDir a) ((Filters)) where
setFilter x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_setFilter cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QDir_setFilter" qtc_QDir_setFilter :: Ptr (TQDir a) -> CLong -> IO ()
instance QsetNameFilters (QDir a) (([String])) where
setNameFilters x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withQListString x1 $ \cqlistlen_x1 cqliststr_x1 ->
qtc_QDir_setNameFilters cobj_x0 cqlistlen_x1 cqliststr_x1
foreign import ccall "qtc_QDir_setNameFilters" qtc_QDir_setNameFilters :: Ptr (TQDir a) -> CInt -> Ptr (Ptr CWchar) -> IO ()
instance QsetPath (QDir a) ((String)) where
setPath x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDir_setPath cobj_x0 cstr_x1
foreign import ccall "qtc_QDir_setPath" qtc_QDir_setPath :: Ptr (TQDir a) -> CWString -> IO ()
qDirSetSearchPaths :: ((String, [String])) -> IO ()
qDirSetSearchPaths (x1, x2)
= withCWString x1 $ \cstr_x1 ->
withQListString x2 $ \cqlistlen_x2 cqliststr_x2 ->
qtc_QDir_setSearchPaths cstr_x1 cqlistlen_x2 cqliststr_x2
foreign import ccall "qtc_QDir_setSearchPaths" qtc_QDir_setSearchPaths :: CWString -> CInt -> Ptr (Ptr CWchar) -> IO ()
instance QsetSorting (QDir a) ((SortFlags)) where
setSorting x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_setSorting cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QDir_setSorting" qtc_QDir_setSorting :: Ptr (TQDir a) -> CLong -> IO ()
instance Qsorting (QDir a) (()) where
sorting x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_sorting cobj_x0
foreign import ccall "qtc_QDir_sorting" qtc_QDir_sorting :: Ptr (TQDir a) -> IO CLong
qDirTemp :: (()) -> IO (QDir ())
qDirTemp ()
= withQDirResult $
qtc_QDir_temp
foreign import ccall "qtc_QDir_temp" qtc_QDir_temp :: IO (Ptr (TQDir ()))
qDirTempPath :: (()) -> IO (String)
qDirTempPath ()
= withStringResult $
qtc_QDir_tempPath
foreign import ccall "qtc_QDir_tempPath" qtc_QDir_tempPath :: IO (Ptr (TQString ()))
qDirToNativeSeparators :: ((String)) -> IO (String)
qDirToNativeSeparators (x1)
= withStringResult $
withCWString x1 $ \cstr_x1 ->
qtc_QDir_toNativeSeparators cstr_x1
foreign import ccall "qtc_QDir_toNativeSeparators" qtc_QDir_toNativeSeparators :: CWString -> IO (Ptr (TQString ()))
qDir_delete :: QDir a -> IO ()
qDir_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDir_delete cobj_x0
foreign import ccall "qtc_QDir_delete" qtc_QDir_delete :: Ptr (TQDir a) -> IO ()
| uduki/hsQt | Qtc/Core/QDir.hs | bsd-2-clause | 23,360 | 0 | 17 | 4,152 | 8,012 | 4,142 | 3,870 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QActionGroup.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:14
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QActionGroup (
qActionGroup
,checkedAction
,isExclusive
,qActionGroup_delete
,qActionGroup_deleteLater
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QActionGroup ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QActionGroup_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QActionGroup_userMethod" qtc_QActionGroup_userMethod :: Ptr (TQActionGroup a) -> CInt -> IO ()
instance QuserMethod (QActionGroupSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QActionGroup_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QActionGroup ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QActionGroup_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QActionGroup_userMethodVariant" qtc_QActionGroup_userMethodVariant :: Ptr (TQActionGroup a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QActionGroupSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QActionGroup_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
qActionGroup :: (QObject t1) -> IO (QActionGroup ())
qActionGroup (x1)
= withQActionGroupResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup cobj_x1
foreign import ccall "qtc_QActionGroup" qtc_QActionGroup :: Ptr (TQObject t1) -> IO (Ptr (TQActionGroup ()))
instance Qactions (QActionGroup a) (()) where
actions x0 ()
= withQListQActionResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_actions cobj_x0 arr
foreign import ccall "qtc_QActionGroup_actions" qtc_QActionGroup_actions :: Ptr (TQActionGroup a) -> Ptr (Ptr (TQAction ())) -> IO CInt
instance QaddAction (QActionGroup ()) ((QAction t1)) (IO (QAction ())) where
addAction x0 (x1)
= withQActionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup_addAction1 cobj_x0 cobj_x1
foreign import ccall "qtc_QActionGroup_addAction1" qtc_QActionGroup_addAction1 :: Ptr (TQActionGroup a) -> Ptr (TQAction t1) -> IO (Ptr (TQAction ()))
instance QaddAction (QActionGroupSc a) ((QAction t1)) (IO (QAction ())) where
addAction x0 (x1)
= withQActionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup_addAction1 cobj_x0 cobj_x1
instance QaddAction (QActionGroup ()) ((QIcon t1, String)) (IO (QAction ())) where
addAction x0 (x1, x2)
= withQActionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QActionGroup_addAction2 cobj_x0 cobj_x1 cstr_x2
foreign import ccall "qtc_QActionGroup_addAction2" qtc_QActionGroup_addAction2 :: Ptr (TQActionGroup a) -> Ptr (TQIcon t1) -> CWString -> IO (Ptr (TQAction ()))
instance QaddAction (QActionGroupSc a) ((QIcon t1, String)) (IO (QAction ())) where
addAction x0 (x1, x2)
= withQActionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QActionGroup_addAction2 cobj_x0 cobj_x1 cstr_x2
instance QaddAction (QActionGroup ()) ((String)) (IO (QAction ())) where
addAction x0 (x1)
= withQActionResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QActionGroup_addAction cobj_x0 cstr_x1
foreign import ccall "qtc_QActionGroup_addAction" qtc_QActionGroup_addAction :: Ptr (TQActionGroup a) -> CWString -> IO (Ptr (TQAction ()))
instance QaddAction (QActionGroupSc a) ((String)) (IO (QAction ())) where
addAction x0 (x1)
= withQActionResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QActionGroup_addAction cobj_x0 cstr_x1
checkedAction :: QActionGroup a -> (()) -> IO (QAction ())
checkedAction x0 ()
= withQActionResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_checkedAction cobj_x0
foreign import ccall "qtc_QActionGroup_checkedAction" qtc_QActionGroup_checkedAction :: Ptr (TQActionGroup a) -> IO (Ptr (TQAction ()))
instance QisEnabled (QActionGroup a) (()) where
isEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_isEnabled cobj_x0
foreign import ccall "qtc_QActionGroup_isEnabled" qtc_QActionGroup_isEnabled :: Ptr (TQActionGroup a) -> IO CBool
isExclusive :: QActionGroup a -> (()) -> IO (Bool)
isExclusive x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_isExclusive cobj_x0
foreign import ccall "qtc_QActionGroup_isExclusive" qtc_QActionGroup_isExclusive :: Ptr (TQActionGroup a) -> IO CBool
instance QisVisible (QActionGroup a) (()) where
isVisible x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_isVisible cobj_x0
foreign import ccall "qtc_QActionGroup_isVisible" qtc_QActionGroup_isVisible :: Ptr (TQActionGroup a) -> IO CBool
instance QremoveAction (QActionGroup a) ((QAction t1)) where
removeAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup_removeAction cobj_x0 cobj_x1
foreign import ccall "qtc_QActionGroup_removeAction" qtc_QActionGroup_removeAction :: Ptr (TQActionGroup a) -> Ptr (TQAction t1) -> IO ()
instance QsetDisabled (QActionGroup a) ((Bool)) where
setDisabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_setDisabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QActionGroup_setDisabled" qtc_QActionGroup_setDisabled :: Ptr (TQActionGroup a) -> CBool -> IO ()
instance QsetEnabled (QActionGroup a) ((Bool)) where
setEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_setEnabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QActionGroup_setEnabled" qtc_QActionGroup_setEnabled :: Ptr (TQActionGroup a) -> CBool -> IO ()
instance QsetExclusive (QActionGroup a) ((Bool)) where
setExclusive x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_setExclusive cobj_x0 (toCBool x1)
foreign import ccall "qtc_QActionGroup_setExclusive" qtc_QActionGroup_setExclusive :: Ptr (TQActionGroup a) -> CBool -> IO ()
instance QsetVisible (QActionGroup a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QActionGroup_setVisible" qtc_QActionGroup_setVisible :: Ptr (TQActionGroup a) -> CBool -> IO ()
qActionGroup_delete :: QActionGroup a -> IO ()
qActionGroup_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_delete cobj_x0
foreign import ccall "qtc_QActionGroup_delete" qtc_QActionGroup_delete :: Ptr (TQActionGroup a) -> IO ()
qActionGroup_deleteLater :: QActionGroup a -> IO ()
qActionGroup_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_deleteLater cobj_x0
foreign import ccall "qtc_QActionGroup_deleteLater" qtc_QActionGroup_deleteLater :: Ptr (TQActionGroup a) -> IO ()
instance QchildEvent (QActionGroup ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QActionGroup_childEvent" qtc_QActionGroup_childEvent :: Ptr (TQActionGroup a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QActionGroupSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QActionGroup ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QActionGroup_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QActionGroup_connectNotify" qtc_QActionGroup_connectNotify :: Ptr (TQActionGroup a) -> CWString -> IO ()
instance QconnectNotify (QActionGroupSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QActionGroup_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QActionGroup ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QActionGroup_customEvent" qtc_QActionGroup_customEvent :: Ptr (TQActionGroup a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QActionGroupSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QActionGroup ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QActionGroup_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QActionGroup_disconnectNotify" qtc_QActionGroup_disconnectNotify :: Ptr (TQActionGroup a) -> CWString -> IO ()
instance QdisconnectNotify (QActionGroupSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QActionGroup_disconnectNotify cobj_x0 cstr_x1
instance Qevent (QActionGroup ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QActionGroup_event_h" qtc_QActionGroup_event_h :: Ptr (TQActionGroup a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QActionGroupSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup_event_h cobj_x0 cobj_x1
instance QeventFilter (QActionGroup ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QActionGroup_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QActionGroup_eventFilter_h" qtc_QActionGroup_eventFilter_h :: Ptr (TQActionGroup a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QActionGroupSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QActionGroup_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QActionGroup ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QActionGroup_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QActionGroup_receivers" qtc_QActionGroup_receivers :: Ptr (TQActionGroup a) -> CWString -> IO CInt
instance Qreceivers (QActionGroupSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QActionGroup_receivers cobj_x0 cstr_x1
instance Qsender (QActionGroup ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_sender cobj_x0
foreign import ccall "qtc_QActionGroup_sender" qtc_QActionGroup_sender :: Ptr (TQActionGroup a) -> IO (Ptr (TQObject ()))
instance Qsender (QActionGroupSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QActionGroup_sender cobj_x0
instance QtimerEvent (QActionGroup ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QActionGroup_timerEvent" qtc_QActionGroup_timerEvent :: Ptr (TQActionGroup a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QActionGroupSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QActionGroup_timerEvent cobj_x0 cobj_x1
| keera-studios/hsQt | Qtc/Gui/QActionGroup.hs | bsd-2-clause | 12,769 | 0 | 14 | 2,081 | 4,018 | 2,039 | 1,979 | -1 | -1 |
-- |
-- Module: Control.Wire.Time
-- Copyright: (c) 2013 Ertugrul Soeylemez
-- License: BSD3
-- Maintainer: Ertugrul Soeylemez <[email protected]>
module Control.Wire.Time
( -- * Time wires
time,
timeF,
timeFrom
)
where
import Control.Wire.Core
import Control.Wire.Session
-- | Local time starting from zero.
time :: (HasTime t s) => Wire s e m a t
time = timeFrom 0
-- | Local time starting from zero, converted to your favorite
-- fractional type.
timeF :: (Fractional b, HasTime t s, Monad m) => Wire s e m a b
timeF = fmap realToFrac time
-- | Local time starting from the given value.
timeFrom :: (HasTime t s) => t -> Wire s e m a t
timeFrom t' =
mkSF $ \ds _ ->
let t = t' + dtime ds
in t `seq` (t, timeFrom t)
| abbradar/netwire | Control/Wire/Time.hs | bsd-3-clause | 781 | 0 | 12 | 206 | 207 | 116 | 91 | 16 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
module Main (main) where
import Control.Concurrent (ThreadId, forkIO, threadDelay)
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TVar (newTVar, readTVar, writeTVar)
import Control.Exception (throwTo, AsyncException(ThreadKilled), finally)
import Data.Binary (encode, decode)
import qualified Data.ByteString.Char8 as B8 (putStrLn)
import qualified Data.ByteString.Lazy as L (fromStrict, toStrict, hGetContents, null)
import qualified Data.Map.Strict as Map (Map, insert, empty, adjust, lookup, assocs)
import Data.Monoid ((<>))
import Data.Time.Clock (getCurrentTime, UTCTime)
import Dispatcher.Connection
import Dispatcher.Tools
import Network.Simple.TCP.TLS
import Network.TLS.Extra (fileReadPrivateKey, fileReadCertificate)
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.FilePath ((</>))
import System.IO (hSetBuffering, BufferMode(..), stdout, withFile, IOMode(..))
import Text.Printf (printf)
import Types
import Control.Monad (forever)
{- | Dispatcher executable for hpt.
The dispatcher keeps a list of connected (alive) users along with their ip address.
It also keeps a list of registered users with the hash of their passwords to ensure
unicity of identities.
-}
{- | Run the dispatcher server :
Initiate connected (alive) users list, load registered users list.
Start a thread that saves registered users list to file every 5 minutes.
Listens for incomming connections.
-}
main :: IO ()
main = getArgs >>= go
where
-- long options
go ("--version":_) = putStrLn version
go ("--help":_) = putStrLn usage
go ("--start":_) = server
-- short options
go ("-v":_) = go ["--version"]
go ("-h":_) = go ["--help"]
go ("-s":_) = go ["--start"]
go _ = putStrLn ("Wrong argument.\n" ++ usage)
{- | Load SSL certificate and private keys settings.
Load registered users list.
Fork a thread to automatically save registered users list to file.
Start the server and listen for incoming connection.
-}
server :: IO ()
server = withSocketsDo $ do
-- Construct Credential information
putStr "Loading certificate..."
certFile <- getCertificateFile
certificate <- case certFile of
Left err ->
do
failed ("failed\n" ++ err ++ "\n")
exitFailure
Right certificateFile ->
do
fileReadCertificate certificateFile
success "success\n"
putStr "Loading private key..."
keyFile <- getPrivateKeyFile
privKey <- case keyFile of
Left err ->
do
failed ("failed\n" ++ err ++ "\n")
exitFailure
Right privateKeyFile ->
do
fileReadPrivateKey privateKeyFile
success "success\n"
putStr "Creating server credential..."
let cred = Credential certificate privKey []
success "success\n"
-- Create server SSL settings
putStr "Creating server SSL settings..."
let servSettings = makeServerSettings cred Nothing
success "success\n"
-- Reading registered users database
putStr "Reading registered users database..."
regDb <- getRegisteredDb
dbFile <- case regDb of
Left err ->
do
failed ("failed\n" ++ err ++ "\n")
exitFailure
Right file ->
return file
-- De-serialize registered users list from file
raw <- withFile dbFile ReadMode $ \h ->
do !contents <- L.hGetContents h
return contents
let reg = case L.null raw of
True -> Map.empty
False -> decode raw :: Map.Map UserName HashPassword
success "success\n"
-- Create internal state
putStr "Initializing currently connected users list..."
aliveUsers <- atomically $ newTVar (Map.empty)
success "success\n"
putStr "Creating empty registered users list..."
registeredUsers <- atomically $ newTVar reg
success "success\n"
putStr "Creating internal state..."
let state = DispatcherState {
dsAlive = aliveUsers
, dsRegistered = registeredUsers
}
success "success\n"
-- Start the server
hSetBuffering stdout NoBuffering
printf "Starting dispatcher on port %s...\n\n" port
-- server_tId <- forkIO $ serve servSettings HostIPv6 port (handleClient state)
server_tId <- forkIO $ serve servSettings HostIPv4 port (handleClient state)
-- Start the thread that saves registered user list every 5 minutes
saveRegistered_tId <- forkIO $ forever $ threadDelay ((5*60 * 10^6)::Int) >> saveDb state dbFile
-- Loop and parse dispatcher administrative commands
loop state server_tId dbFile
putStrLn "Server exiting..."
where
loop state server_tId dbFile = do
putStr "Administrative dispatcher command : "
cmd <- getLine
putStr "\n"
case cmd of
"help" -> putStrLn ("Available commands : help, stop, list alive, list registered, save") >> loop state server_tId dbFile
"stop" -> putStrLn "Dispatcher exiting..." >> throwTo server_tId ThreadKilled
"list alive" -> do
clientsmap <- atomically $ readTVar (dsAlive state)
putStrLn ("Alive users : \n" ++ show clientsmap)
loop state server_tId dbFile
"list registered" -> do
regmap <- atomically $ readTVar (dsRegistered state)
putStrLn ("Registered users : \n" ++ show regmap)
loop state server_tId dbFile
"save" -> do
putStr "Saving..."
saveDb state dbFile
success "success\n"
loop state server_tId dbFile
_ -> putStrLn ("Unknown command : " ++ cmd) >> loop state server_tId dbFile
-- | Deal with a client connecting
handleClient :: DispatcherState -> (Context, SockAddr) -> IO()
handleClient state (context, sockaddr) = do
-- Displays a message on the server
putStrLn ("Incoming connection : " ++ show sockaddr)
putStrLn "Waiting for authentification..."
-- Waits for a Born request from the client
mbs <- recv context
putStr "Authentification incoming..."
case mbs of
Nothing ->
do
failed "failed\n"
putStrLn "Contact lost with client in authentification phase."
Just bs | isBornRequest decodedReq -> do
let (Born username _) = decodedReq
success "success\n"
now <- getCurrentTime
(logMsg, answer) <- atomically $ checkAuth state decodedReq now sockaddr
send context answer
case logMsg of
-- 'Left' means the authentification did not succeed
Left failMsg -> do
failed failMsg
-- 'Right' means the authentification did succeed
Right successMsg -> do
success successMsg
{- loop over the clients' requests.
Should be regular 'Alive' requests and maybe 'Change Status' or 'Suicide'
-}
finally (loop decodedReq) (atomically $ removeFromAlive state username)
| otherwise -> do
failed "failed\n"
putStrLn "Wrong request type received from client in authentification phase."
where
decodedReq = decode (L.fromStrict bs)
loop req@(Born username hashpassword) =
do mbs <- recv context
case mbs of
Nothing -> failed ("Lost contact with " ++ username ++ ".\n")
Just bs ->
-- Decode the incoming command from the client
do let cmd = decode (L.fromStrict bs) :: DispatcherRequest
case cmd of
-- Normally, not supposed to receive Born commands anymore, so just fail and close connection
Born _ _ -> send context (L.toStrict $ encode (Error (Just "Born commands should be sent on logging only")))
-- The user wants to disconnect, so remove him from the alive and tell him okay
Suicide -> send context (L.toStrict $ encode Die)
-- The regular 'ping' requests, to update timestamp and return
Alive names ->
do now <- getCurrentTime
clientsmap <- atomically $ do
-- update timestamp and return the clientsmap
clientsmap <- (readTVar (dsAlive state))
let newMap = Map.adjust (\entry -> entry{ deTime = now } ) username clientsmap
writeTVar (dsAlive state) newMap
return clientsmap
-- get contacts status
let assoc = Map.assocs clientsmap
let found = filter ((`elem` names) . fst) assoc -- ++++++++++++++++++++++++++++++++++++++
let contactList = flip map found $ \(usr, entry) -> -- ++++++++++++++++++++++++++++++++++++++
Contact {
contactUserName = usr
, contactStatus = deStatus entry
, contactIpAddr = deIpAddr entry
}
-- send results to client
send context (L.toStrict $ encode (ReportStatus contactList))
-- loop back to process other incoming requests
loop req
| nschoe/hpt | src/Dispatcher.hs | bsd-3-clause | 11,144 | 0 | 35 | 4,521 | 1,982 | 979 | 1,003 | 169 | 10 |
----------------------------------------------------------------------------
-- |
-- Module : ModuleWithExplicitExport
-- Copyright : (c) Sergey Vinokurov 2015
-- License : BSD3-style (see LICENSE)
-- Maintainer : [email protected]
----------------------------------------------------------------------------
module ModuleWithExplicitExport
( Foo2(Bar2, getBar2)
)
where
data Foo2 = Bar2 { getBar2 :: Int }
| Baz2 { getBaz2 :: Int }
deriving (Eq)
| sergv/tags-server | test-data/0002export_lists/ModuleWithExplicitExport.hs | bsd-3-clause | 482 | 0 | 8 | 84 | 55 | 38 | 17 | 7 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
-- | Mutually recursive data types.
module Ray.Types where
import Ray.Imports
import Ray.Util
import Control.Monad.Reader
import Data.Array
import Data.Vector (Vector)
import System.Random.MWC
type V3D = V3 Double
type P3D = Point V3 Double
type Dir = V3D
-- | A linear RGB space, assumed to use the BT.709 primaries
-- (equivalent to sRGB, but linear.)
type Spectrum = V3D
-- | By convention, components of RGB should be in [0,1].
type RGB = V3D
-- TODO is it easier to require normalized direction vector?
-- Certainly it doesn't change the denotation of the type.
-- | A ray is represented as a starting point and a vector. The
-- vector need not be normalized.
data Ray = Ray {
_rayOrigin :: !P3D,
_rayDir :: !V3D,
_rayt :: !(Interval Double),
_raySpectrum :: !Spectrum
} deriving Show
-- | A ray defined for t ∈ 0...∞.
mkRay :: P3D -> V3D -> Spectrum -> Ray
mkRay p u s = Ray p u nonNegative s
-- XXX Will this be true?
-- A Ray carries an arbitrary tag, typically representing the light
-- (if tracing from lamp to eye) or the accumulated absorption (if
-- tracing from eye to lamp).
-- | Solid geometry, without any description of optical behavior. In
-- the case of Mesh, shading normals are included, as quasi-geometry.
-- Mesh is the most important constructor here; Sphere and Plane are
-- provided to help in debugging other parts of the system.
data Shape = Sphere !P3D !Double
| Plane !V3D !Double
-- points, vertex indices, normals, tangents, texture parameters
| Mesh !(Vector P3D) !(Vector (V3 Int)) (Maybe (Vector V3D)) (Maybe (Vector V3D)) (Maybe (Vector (V2 Double)))
deriving Show
-- | Construct a Mesh from vertex coordinates and indices, without any
-- shading geometry.
simpleMesh :: Vector P3D -> Vector (V3 Int) -> Shape
simpleMesh ps vis = Mesh ps vis Nothing Nothing Nothing
-- TODO check definition of Reflectance, Reflectivity, &c.
type Material = V3D -- ^ diffuse Reflectance
data Object = Object !Shape !Material deriving Show
-- | Normal & material are not strict fields, since they may not be
-- used.
data Intersection a = Intersection {
_tHit :: !Double,
_tEpsilon :: !Double,
_normal :: Dir,
_material :: a
} deriving (Functor, Show)
-- The Semigroup instance picks the *closest* intersection
instance Semigroup (Intersection a) where
a <> b = if _tHit a <= _tHit b then a else b
data Lamp = PointLamp !P3D !Spectrum
| ParallelLamp !V3D !Spectrum
deriving Show
-- | follows Haines's NFF: http://tog.acm.org/resources/SPD/NFF.TXT
data Camera = Camera {
_eye :: !P3D,
_lookAtPt :: !P3D,
_upDir :: !V3D, -- ^ calculations assume this is perpendicular to eye .-. lookAt, normalized
_fov :: !Double, -- ^ y direction, in radians
_nearPlane :: !Double -- ^ distance to image plane
} deriving Show
data Scene = Scene {
_camera :: Camera,
_background :: Spectrum,
_lamps :: [Lamp],
_visibles :: [Object]
} deriving Show
r2f :: (Real a, Fractional b) => a -> b
r2f = realToFrac
data Algo = Algo {
_samplesPerPixel :: Int,
_samplesPerCameraRay :: Int,
_resolution :: V2 Int,
_imageSampler :: ImageSampler,
_discreteSampler :: DiscreteSampler,
_surfaceIntegrator :: SurfaceIntegrator,
_imageReconstructor :: ImageReconstructor,
_toneMapping :: ToneMapping
}
data MRead = MRead {
_algorithms :: Algo,
_scene :: Scene,
_gen :: GenIO
}
type M = ReaderT MRead IO
runM :: M a -> Algo -> Scene -> IO a
runM ma a s = do
gen <- create
runReaderT ma (MRead a s gen)
runMSystem :: M a -> Algo -> Scene -> IO a
runMSystem ma a s = do
gen <- createSystemRandom
runReaderT ma (MRead a s gen)
-- | Given the number of samples per pixel, and the image resolution,
-- return a set of sample coordinates, on the image plane.
type ImageSampler = Int -> V2 Int -> M [V2 Double]
-- type Sampler1D = Int -> M [Double]
-- type Sampler2D = Int -> M [V2D]
-- | sample range, number of samples. Returned values should be in
-- the range [0,r]
type DiscreteSampler = Int -> Int -> M [Int]
type DirectionSampler = Int -> M [Dir]
type SurfaceIntegrator = Int -> Ray -> Intersection Spectrum -> M Spectrum
data ImgSample a = ImgSample {
_sampleLocation :: !(V2 Double),
_sampleValue :: !a
} deriving (Functor, Foldable, Traversable, Show)
type Array2D = Array (V2 Int)
type ImageReconstructor =
Array2D [ImgSample Spectrum] -> Array2D Spectrum
-- V2 Int -> [ImageSample Spectrum] -> Spectrum
-- | A ToneMapping maps the luminance of an image from [0,∞) to [0,1].
-- It may be non-linear to compensate for the logorithmic perception
-- of the eye.
type ToneMapping =
Array2D Spectrum -> Array2D V3D
makeLenses ''Algo
makeLenses ''Camera
makeLenses ''MRead
makeLenses ''Scene
makeLenses ''ImgSample
makeLenses ''Intersection
makeLenses ''Ray
| bergey/panther | src/Ray/Types.hs | bsd-3-clause | 5,097 | 0 | 12 | 1,102 | 1,072 | 590 | 482 | 151 | 1 |
module Intel.ArBB.Literal where
import Data.Int
import Data.Word
import Intel.ArBB.Data.Int
data Literal = LitInt Int
| LitInt8 Int8
| LitInt16 Int16
| LitInt32 Int32
| LitInt64 Int64
| LitWord Word
| LitWord8 Word8
| LitWord16 Word16
| LitWord32 Word32
| LitWord64 Word64
| LitFloat Float
| LitDouble Double
| LitISize ISize
| LitUSize USize
| LitBool Bool
deriving (Eq,Show)
| svenssonjoel/EmbArBB | Intel/ArBB/Literal.hs | bsd-3-clause | 620 | 0 | 6 | 301 | 114 | 69 | 45 | 20 | 0 |
{-# LANGUAGE MultiParamTypeClasses #-}
-- Copied from http://hackage.haskell.org/package/regex-tdfa-1.2.0/docs/src/Text-Regex-TDFA-ByteString.html#compile
-- and modified to suit my needs. Many thanks to Chris Kuklewicz.
module Ebitor.Rope.Regex
( Regex
, CompOption
, ExecOption
, compile
, compileDefault
, compileFast
, execute
, matchAll
, matchOnce
, matchOnceEnd
, matchOnceBefore
, matchOnceFrom
, regexec
, replace
, replaceCount
, replaceOne
) where
import Data.Array((!),elems)
import Text.Regex.Base(MatchArray,RegexContext(..),RegexMaker(..),RegexLike(..),Extract(..))
import Text.Regex.Base.Impl(polymatch,polymatchM)
import Text.Regex.Base.RegexLike (defaultExecOpt, defaultCompOpt)
import Text.Regex.TDFA.Common(Regex(..),CompOption(lastStarGreedy),ExecOption(captureGroups))
import Text.Regex.TDFA.ReadRegex(parseRegex)
import Text.Regex.TDFA.String() -- piggyback on RegexMaker for String
import Text.Regex.TDFA.TDFA(patternToRegex)
import Data.Maybe(listToMaybe)
import Text.Regex.TDFA.NewDFA.Engine(execMatch)
import Text.Regex.TDFA.NewDFA.Tester as Tester(matchTest)
import Text.Regex.TDFA.NewDFA.Uncons as Uncons(Uncons(..))
import Data.FingerTree ((<|), ViewR((:>)))
import qualified Data.FingerTree as F
import Ebitor.Rope (Rope)
import qualified Ebitor.Rope as R
instance Extract Rope where
before = R.take
after = R.drop
empty = R.empty
instance Uncons Rope where
uncons = R.uncons
instance RegexContext Regex Rope Rope where
match = polymatch
matchM = polymatchM
instance RegexMaker Regex CompOption ExecOption Rope where
makeRegexOptsM c e source = makeRegexOptsM c e (R.unpack source)
instance RegexLike Regex Rope where
matchOnce r s = listToMaybe (matchAll r s)
matchAll r s = execMatch r 0 '\n' s
matchCount r s = length (matchAll r' s)
where
r' = r { regex_execOptions = (regex_execOptions r) {captureGroups = False} }
matchOnceText regex source =
fmap (\ma -> let (o,l) = ma!0
in ( R.take o source
, fmap (\ol@(off,len) -> (R.take len (R.drop off source),ol)) ma
, R.drop (o+l) source))
(matchOnce regex source)
matchAllText regex source =
map (fmap (\ol@(off,len) -> (R.take len (R.drop off source),ol)))
(matchAll regex source)
compile :: CompOption -- ^ Flags (summed together)
-> ExecOption -- ^ Flags (summed together)
-> Rope -- ^ The regular expression to compile
-> Either String Regex -- ^ Returns: the compiled regular expression
compile compOpt execOpt rope =
case parseRegex (R.unpack rope) of
Left err -> Left ("parseRegex for Ebitor.Rope.Regex failed:"++show err)
Right pattern -> Right (patternToRegex pattern compOpt execOpt)
fastCompOpt = defaultCompOpt { lastStarGreedy = True }
fastExecOpt = defaultExecOpt { captureGroups = False }
compileDefault :: Rope -> Either String Regex
compileDefault = compile defaultCompOpt defaultExecOpt
compileFast :: Rope -> Either String Regex
compileFast = compile fastCompOpt fastExecOpt
execute :: Regex -- ^ Compiled regular expression
-> Rope -- ^ Rope to match against
-> Either String (Maybe MatchArray)
execute r rope = Right (matchOnce r rope)
regexec :: Regex -- ^ Compiled regular expression
-> Rope -- ^ Rope to match against
-> Either String (Maybe (Rope, Rope, Rope, [Rope]))
regexec r rope =
case matchOnceText r rope of
Nothing -> Right (Nothing)
Just (pre,mt,post) ->
let main = fst (mt!0)
rest = map fst (tail (elems mt)) -- will be []
in Right (Just (pre,main,post,rest))
replaceCount :: Int
-> Regex
-> Rope
-> Rope
-> Rope
replaceCount n r replacement haystack = replaceCount' n ("", haystack)
where
replaceCount' 0 (h1, h2) = R.append h1 h2
replaceCount' n haystack@(h1, h2) =
case matchOnce r h2 of
Just match ->
let (offset, len) = match ! 0
(prefix, result) = R.splitAt offset h2
h1' = R.concat [h1, prefix, replacement]
result' = R.drop len result
in replaceCount' (n - 1) (h1', result')
Nothing -> replaceCount' 0 haystack
replaceOne :: Regex
-> Rope
-> Rope
-> Rope
replaceOne = replaceCount 1
replace :: Regex
-> Rope
-> Rope
-> Rope
replace = replaceCount (-1)
matchOnceFrom :: Regex -> Int -> Rope -> Maybe (Int, Int)
matchOnceFrom regex i rope =
let r = snd $ R.splitAt i rope
in setOffset `fmap` (!0) `fmap` (matchOnce regex r)
where
setOffset (offset, len) = (i + offset, len)
matchOnceEnd :: Regex -> Rope -> Maybe (Int, Int)
matchOnceEnd regex (R.Rope rope) = matchOnceEnd' [] rope F.empty
where
matchOnceEnd' matches rest rope
| length matches > 1 || F.null rest =
setOffset `fmap` (!0) `fmap` listToMaybe (reverse matches)
| otherwise =
let rest' :> chunk = F.viewr rest
rope' = chunk <| rope
in matchOnceEnd' (matchAll regex $ R.Rope rope') rest' rope'
where
restLen = R.length (R.Rope rest)
setOffset (offset, len) = (restLen + offset, len)
matchOnceBefore :: Regex -> Int -> Rope -> Maybe (Int, Int)
matchOnceBefore regex i rope =
let r = fst $ R.splitAt i rope
in matchOnceEnd regex r
| benekastah/ebitor | src/Ebitor/Rope/Regex.hs | bsd-3-clause | 5,623 | 0 | 21 | 1,503 | 1,746 | 962 | 784 | 133 | 3 |
{-# LANGUAGE RecordWildCards, ScopedTypeVariables #-}
module Codex.Lib.Network.TCP.Server (
TCPServer,
TCPConnection,
runTCPServer,
destroyTCPServer,
buildTCPServer
) where
import Prelude hiding (catch)
import Network
import System.IO
import Control.Monad
import Control.Exception as E
import Control.Concurrent
import Data.IORef
data TCPServer = TCPServer {
_port :: PortNumber,
_sock :: Socket,
_cb :: Handle -> Int -> IO (),
_connections :: [Handle],
_maxConnections :: Int,
_connected :: IORef Int,
_counter :: Int
}
data TCPConnection = TCPConnection {
_id :: Int,
_conn :: Handle
}
buildTCPServer :: PortNumber -> Int -> (Handle -> Int -> IO ()) -> TCPServer
buildTCPServer port maxConnections cb = TCPServer { _port = port, _maxConnections = maxConnections, _cb = cb }
runTCPServer :: TCPServer -> IO TCPServer
runTCPServer serv@TCPServer{..} =
withSocketsDo $ do
sock <- listenOn $ PortNumber _port
ioref <- newIORef 0
let serv' = serv { _sock = sock, _connections = [], _connected = ioref, _counter = 0 }
forkIO $ accept' serv'
return serv'
destroyTCPServer :: TCPServer -> IO ()
destroyTCPServer serv@TCPServer{..} = do
sClose _sock
return ()
accept' :: TCPServer -> IO ()
accept' serv@TCPServer{..} = do
let counter = _counter + 1
(conn,_,_) <- accept _sock
connected <- incr _connected
-- putStrLn $ "connection count: " ++ show connected
case (connected > _maxConnections && _maxConnections >= 0) of
True -> do
disconnect serv conn
accept' serv
False -> do
let client = TCPConnection { _id = 0, _conn = conn }
hSetBuffering conn NoBuffering
forkIO $ _cb conn counter `catch` disconnected `finally` disconnect serv conn
accept' $ serv { _counter = counter }
where
disconnected (ex :: IOException) = do
-- hPutStrLn stderr $ "Disconnected"
return ()
disconnect :: TCPServer -> Handle -> IO ()
disconnect serv@TCPServer{..} h = do
_ <- decr _connected
hClose h
incr :: IORef Int -> IO Int
incr ioref = do
atomicModifyIORef' ioref (\a -> (a+1,a+1))
decr :: IORef Int -> IO Int
decr ioref = do
atomicModifyIORef' ioref (\a -> (a-1,a-1))
get :: IORef Int -> IO Int
get ioref = do
atomicModifyIORef' ioref (\a -> (a,a))
| adarqui/Codex | src/Codex/Lib/Network/TCP/Server.hs | bsd-3-clause | 2,212 | 0 | 16 | 423 | 804 | 424 | 380 | 68 | 2 |
-- | Read templates in Hakyll's native format
--
module Hakyll.Web.Template.Read.Hakyll
( readTemplate
) where
import Data.List (isPrefixOf)
import Data.Char (isAlphaNum)
import Hakyll.Web.Template.Internal
-- | Construct a @Template@ from a string.
--
readTemplate :: String -> Template
readTemplate = Template . readTemplate'
where
readTemplate' [] = []
readTemplate' string
| "$$" `isPrefixOf` string =
Escaped : readTemplate' (drop 2 string)
| "$" `isPrefixOf` string =
case readKey (drop 1 string) of
Just (key, rest) -> Key key : readTemplate' rest
Nothing -> Chunk "$" : readTemplate' (drop 1 string)
| otherwise =
let (chunk, rest) = break (== '$') string
in Chunk chunk : readTemplate' rest
-- Parse an key into (key, rest) if it's valid, and return
-- Nothing otherwise
readKey string =
let (key, rest) = span isAlphaNum string
in if not (null key) && "$" `isPrefixOf` rest
then Just (key, drop 1 rest)
else Nothing
| sol/hakyll | src/Hakyll/Web/Template/Read/Hakyll.hs | bsd-3-clause | 1,113 | 0 | 14 | 335 | 311 | 164 | 147 | 23 | 4 |
module Lasca.JIT (
runJIT,
withOptimizedModule
) where
import Data.Int
import Data.Word
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as LT
import qualified Data.Text.IO as TIO
import System.IO
import Foreign.Ptr
import Foreign.C.String
import Foreign.C.Types
import Foreign.Marshal.Array
import Lasca.Syntax
import Lasca.Options
import Control.Monad.Except
import qualified LLVM.AST as AST
import LLVM.CodeModel
import LLVM.Context
import LLVM.Module as Mod
import LLVM.Target hiding (withHostTargetMachine)
import LLVM.Analysis
import LLVM.PassManager
import LLVM.Transforms
import LLVM.OrcJIT
import LLVM.OrcJIT.CompileLayer
import LLVM.Linking (loadLibraryPermanently, getSymbolAddressInProcess)
import qualified LLVM.CodeGenOpt as CodeGenOpt
import qualified LLVM.CodeModel as CodeModel
import qualified LLVM.Relocation as Reloc
--import LLVM.Pretty (ppllvm)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as Char8
foreign import ccall "dynamic" mainFun :: FunPtr (Int -> Ptr CString -> IO ()) -> Int -> Ptr CString -> IO ()
passes :: Int -> PassSetSpec
passes level = defaultCuratedPassSetSpec { optLevel = Just (fromIntegral level) }
withHostTargetMachine :: (TargetMachine -> IO a) -> IO a
withHostTargetMachine f = do
initializeAllTargets
triple <- getProcessTargetTriple
cpu <- getHostCPUName
features <- getHostCPUFeatures
(target, _) <- lookupTarget Nothing triple
withTargetOptions $ \options ->
-- Make it PIC, otherwise it won't work with shared libraries
withTargetMachine target triple cpu features options Reloc.PIC CodeModel.Default CodeGenOpt.Default f
resolver :: IRCompileLayer l -> SymbolResolver
resolver compileLayer =
SymbolResolver
(\s -> findSymbol compileLayer s True)
(\s ->
fmap (\a -> Right $ JITSymbol a (JITSymbolFlags False True False True)) (getSymbolAddressInProcess s)
)
{-
Read https://purelyfunctional.org/posts/2018-04-02-llvm-hs-jit-external-function.html
for explanation.
-}
runJIT :: LascaOpts -> AST.Module -> IO ()
runJIT opts mod = do
-- putStrLn $ LT.unpack $ ppllvm mod
b <- loadLibraryPermanently Nothing
unless (not b) (error "Couldn’t load library")
withOptimizedModule opts mod $ \context m ->
withHostTargetMachine $ \tm ->
withObjectLinkingLayer $ \linkingLayer ->
withIRCompileLayer linkingLayer tm $ \compileLayer ->
withModule compileLayer m
(resolver compileLayer) $ \moduleHandle -> do
mainSymbol <- mangleSymbol compileLayer "main"
(Right (JITSymbol mainFn _)) <- findSymbol compileLayer mainSymbol True
let args = lascaFiles opts
let len = length args
cargs <- mapM newCString args
array <- mallocArray len
pokeArray array cargs
result <- mainFun (castPtrToFunPtr (wordPtrToPtr mainFn)) len array
return ()
withOptimizedModule opts mod f = withContext $ \context ->
withModuleFromAST context mod $ \m ->
withPassManager (passes (optimization opts)) $ \pm -> do
-- Optimization Pass
-- linkModules m stdModule
runPassManager pm m
optmod <- moduleAST m
when (printLLVMAsm opts) $ do
s <- moduleLLVMAssembly m
Char8.putStrLn s
f context m
| nau/lasca-compiler | src/lib/Lasca/JIT.hs | bsd-3-clause | 3,764 | 0 | 24 | 1,102 | 882 | 464 | 418 | 78 | 1 |
{-
Copyright (c) 2013, Genome Research Limited
Author: Nicholas Clarke <[email protected]>
-- Creates a new version of a template.
hg-version <oldname> [<newname>]
- If <newname> not set, increment a version number
- Get repo
- cvmfs_server transaction repo
- Copy newname to oldname
- Copy config file to temporary location
- Modify temporary config file to adjust location of rootfs and fstab
- lxc-start and lxc-console
- Clean (remove cache dirs)
- Publish (possibly - maybe prompt?)
-}
module Main where
import Prelude hiding (mapM)
import Control.Monad (when, unless, filterM, liftM, join)
import Data.Maybe (maybeToList)
import Data.List (intercalate)
import Data.List.Split (splitOneOf)
import Data.Traversable (mapM)
import System.Console.GetOpt
import System.Environment (getArgs)
import System.Exit (ExitCode(..))
import System.FilePath
import System.Random (randomIO)
import System.Directory (canonicalizePath
, doesDirectoryExist
, removeDirectoryRecursive)
import System.Log.Logger
import qualified Hgc.Cvmfs as Cvmfs
import qualified Hgc.Lxc as Lxc
import Hgc.Shell
import Hgc.Mount
data Options = Options {
optPublish :: Bool -- ^ Automatically publish the CVMFS repo
, optMajorRevision :: Bool -- ^ Create a new major revision
, optNewCapsule :: Maybe String -- ^ Name for new capsule
, optRepository :: String
, optCloneOnly :: Bool -- ^ Only clone the template, don't start as a capsule.
, optMount :: [FilePath] -- ^ Resources to mount in the capsule.
, optPkgSrcDir :: Maybe FilePath -- ^ Location to use for package source cache.
, optVerbose :: Bool
, optAmend :: Bool
}
defaultOptions :: Options
defaultOptions = Options {
optPublish = False
, optMajorRevision = False
, optNewCapsule = Nothing
, optRepository = "mercury.repo"
, optCloneOnly = False
, optMount = []
, optPkgSrcDir = Nothing
, optVerbose = False
, optAmend = False
}
options :: [OptDescr (Options -> Options)]
options =
[
Option [] ["amend"] (NoArg (\o -> o { optAmend = True }))
"Amend the current capsule rather than creating a new one."
, Option [] ["clone-only"] (NoArg (\o -> o { optCloneOnly = True }))
"Only clone the template, don't start the capsule."
, Option ['m'] ["mount"] (ReqArg (\n o -> o { optMount = n : optMount o }) "MOUNT_POINT")
"Mount the specified resource into the capsule."
, Option ['M'] ["major"] (NoArg (\o -> o { optMajorRevision = True }))
"Create a major revision."
, Option ['n'] ["new-capsule"] (ReqArg (\n o -> o { optNewCapsule = Just n }) "NAME")
"Create a capsule under a new name."
, Option ['p'] ["pkgdir"] (ReqArg (\n o -> o { optPkgSrcDir = Just n}) "PKGDIR")
"Use specified directory in place of the aura source package cache."
, Option ['r'] ["repository"] (ReqArg (\n o -> o { optRepository = n }) "REPOSITORY")
"Use the specified repository name (defaults to mercury.repo)."
, Option ['v'] ["verbose"] (NoArg (\o -> o { optVerbose = True }))
"Enable verbose output."
, Option ['y'] ["publish"] (NoArg (\o -> o { optPublish = True }))
"Automatically publish new capsule."
]
usage :: String
usage = usageInfo header options
where header = "Create a new version of a Mercury capsule based on the specified template.\n" ++
"Usage: hgc-version [Option...] template"
main :: IO ()
main = do
args <- getArgs
case (getOpt Permute options args) of
(o,[f],[]) -> doStuff f (foldl (flip id) defaultOptions o)
(_,_,errs) -> putStrLn (concat errs ++ "\n" ++ usage)
doStuff :: String
-> Options
-> IO ()
doStuff oldname opts = do
when (optVerbose opts) $ updateGlobalLogger "hgc" (setLevel DEBUG)
Cvmfs.inTransaction repository publish $ do
capsuleLoc <- if (amend) then
return $ repositoryLoc </> oldname
else
copyCapsule oldname newname repositoryLoc
debugM "hgc" $ "Capsule location: " ++ capsuleLoc
tmpConfig <- updateConfig newname capsuleLoc opts
debugM "hgc" $ "Config location: " ++ tmpConfig
unless (optCloneOnly opts) $ Lxc.startConsole newname tmpConfig
cleanCapsule capsuleLoc
where
repository = optRepository opts
publish = optPublish opts
amend = optAmend opts
repositoryLoc = Cvmfs.base </> repository
newname = if amend then oldname else capsuleName oldname opts
-- TODO: replace with regex?
capsuleName :: String -- ^ Old name
-> Options -- ^ options
-> String -- ^ New name
capsuleName old opts = newname ++ "-" ++ show major ++ "." ++ show minor
where (oldname, oldmaj, oldmin) = case reverse (splitOneOf "-." old) of
[name] -> (name, 0, 0)
(minor : major : name) ->
(intercalate "-" . reverse $ name, read major :: Int, read minor :: Int)
(newname, major, minor) = case optNewCapsule opts of
Just n -> (n, oldmaj, oldmin)
Nothing -> if optMajorRevision opts
then (oldname, oldmaj + 1, 0)
else (oldname, oldmaj, oldmin + 1)
-- Copy the old capsule to a new version location
copyCapsule :: String -- ^ Old name
-> String -- ^ New name
-> FilePath -- ^ Repository location
-> IO FilePath
copyCapsule oldname newname repobase =
debugM "hgc" ("Copying " ++ oldname ++ " to " ++ newname ++ " in repository " ++ repobase) >>
cp oldloc newloc >>= \cpStatus ->
case cpStatus of
ExitSuccess -> return newloc
ExitFailure r -> ioError . userError $ "Failed to copy capsule (exit code " ++ show r ++ ")."
where
oldloc = repobase </> oldname
newloc = repobase </> newname
-- Update the config to a temporary location.
updateConfig :: String -- Capsule name
-> FilePath -- Capsule location
-> Options -- Options
-> IO FilePath -- Temporary config file location
updateConfig capsule capsuleLoc opts = do
rand <- (randomIO :: IO Int)
let tmpConfig = "/tmp/config-" ++ capsule ++ show rand
let tmpFstab = "/tmp/fstab-" ++ capsule ++ show rand
let update c = Lxc.setConfig "lxc.rootfs" [(capsuleLoc </> "rootfs")] .
Lxc.setConfig "lxc.mount" [tmpFstab] .
Lxc.setConfig "lxc.utsname" [capsule] $ c
writeFstab capsuleLoc tmpFstab opts
Lxc.readConfig configloc >>= Lxc.writeConfig tmpConfig . update
return tmpConfig
where
configloc = (capsuleLoc </> "config")
-- Write the FSTAB for the capsule.
writeFstab :: FilePath -- ^ Capsule location.
-> FilePath -- ^ New fstab location
-> Options
-> IO ()
writeFstab capsuleLoc tmpFstab opts = do
pkgSrcMnt <- fmap (\a -> fmap (mkBindMount internalPkgSrcDir) a)
. mapM canonicalizePath $ optPkgSrcDir opts
otherMounts <- fmap (\a -> fmap mkMount a)
. mapM (\a -> mkMountPoint internalMntDir a)
$ optMount opts
let mounts = (maybeToList pkgSrcMnt) ++ otherMounts
mapM_ (debugM "hgc" . (\a -> "Mount point: " ++ a)) mounts
let writeMounts str = str ++ "\n" ++ unlines mounts
readFile fstabloc >>= writeFile tmpFstab . writeMounts
where
fstabloc = (capsuleLoc </> "fstab")
internalPkgSrcDir = capsuleLoc </> "rootfs/var/cache/aura/src"
internalMntDir = capsuleLoc </> "rootfs/mnt"
mkBindMount int ext = intercalate " " [ext, int, "none", "bind", "0", "0"]
mkMount (a,b) = mkBindMount (internalMntDir </> b) a
-- Clean the template, removing specified cache directories (/var/cache/pacman etc)
cleanCapsule :: FilePath -- Capsule location
-> IO ()
cleanCapsule capsule =
let cacheDirs = [
"var/cache/pacman/pkg"
, "var/log"
]
rmdir dir = do
debugM "hgc" $ "Removing directory " ++ dir
removeDirectoryRecursive dir
mkdir dir
isDir dir = do
exists <- doesDirectoryExist dir
unless (exists) $ debugM "hgc" $ "Directory " ++ dir ++ " does not exist."
return exists
in do
debugM "hgc" ("Cleaning capsule " ++ capsule)
join . (liftM $ mapM_ rmdir) . filterM isDir $
map (\a -> capsule </> "rootfs" </> a) cacheDirs | wtsi-hgi/hgc-tools | hgc-version.hs | bsd-3-clause | 8,537 | 0 | 16 | 2,335 | 2,172 | 1,161 | 1,011 | 168 | 4 |
module Angular.Ng.Compile where
import FFI
import JQuery
import Angular.Ng.RootScope
import Angular.Ng.Controller
import Angular.Module
type DirectiveName = String
type Directive = [DirectiveDefinitionConf] -> Fay DirectiveDefinition
type Linking = (NgScope -> JQuery -> Attrs -> Fay())
type Compiling = (NgScope -> JQuery -> Attrs -> Fay Linking)
data Attrs
data DirectiveDefinitionConf = Priority Int
| Template String
| TemplateUrl String
| Transclude Bool
| Restrict String
| Scope Bool -- not done
| Controller NgController
| ControllerAs String
| Require String
| Link Linking
| Compile Compiling
data DirectiveDefinition
-- DirectiveName
ngDirective :: NgModule -> String -> DirectiveDefinition -> Fay()
ngDirective = ffi "%1.directive(%2, function(){ return %3 })"
newNgDirectiveDefinition :: Fay DirectiveDefinition
newNgDirectiveDefinition = ffi "new Object()"
ngDirectiveDefinitionFunc2 :: DirectiveDefinition -> String -> (a -> b -> Fay()) -> Fay()
ngDirectiveDefinitionFunc2 = ffi "%1[%2] = %3"
ngDirectiveDefinitionFunc3 :: DirectiveDefinition -> String -> (a -> b -> c -> Fay()) -> Fay()
ngDirectiveDefinitionFunc3 = ffi "%1[%2] = %3"
ngDirectiveDefinitionFunc3' :: DirectiveDefinition -> String -> (a -> b -> c -> Fay Linking) -> Fay()
ngDirectiveDefinitionFunc3' = ffi "%1[%2] = %3"
ngDirectiveDefinitionStr :: DirectiveDefinition -> String -> String -> Fay()
ngDirectiveDefinitionStr = ffi "%1[%2] = %3"
ngDirectiveDefinitionBool :: DirectiveDefinition -> String -> Bool -> Fay()
ngDirectiveDefinitionBool = ffi "%1[%2] = %3"
ngDirectiveDefinitionInt :: DirectiveDefinition -> String -> Int -> Fay()
ngDirectiveDefinitionInt = ffi "%1[%2] = %3"
ngDirectiveDefinition' ::[DirectiveDefinitionConf] -> DirectiveDefinition -> Fay DirectiveDefinition
ngDirectiveDefinition' [] d = return d
ngDirectiveDefinition' [(Priority x)] d = ngDirectiveDefinitionInt d "priority" x >>= \_ -> return d
ngDirectiveDefinition' [(Template x)] d = ngDirectiveDefinitionStr d "template" x >>= \_ -> return d
ngDirectiveDefinition' [(TemplateUrl x)] d = ngDirectiveDefinitionStr d "templateUrl" x >>= \_ -> return d
ngDirectiveDefinition' [(Transclude x)] d = ngDirectiveDefinitionBool d "transclude" x >>= \_ -> return d
ngDirectiveDefinition' [(Restrict x)] d = ngDirectiveDefinitionStr d "restrict" x >>= \_ -> return d
ngDirectiveDefinition' [(Scope x)] d = ngDirectiveDefinitionBool d "scope" x >>= \_ -> return d
ngDirectiveDefinition' [(Controller x)] d = ngDirectiveDefinitionFunc2 d "controller" x >>= \_ -> return d
ngDirectiveDefinition' [(ControllerAs x)] d = ngDirectiveDefinitionStr d "controllerAs" x >>= \_ -> return d
ngDirectiveDefinition' [(Require x)] d = ngDirectiveDefinitionStr d "require" x >>= \_ -> return d
ngDirectiveDefinition' [(Link x)] d = ngDirectiveDefinitionFunc3 d "link" x >>= \_ -> return d
ngDirectiveDefinition' [(Compile x)] d = ngDirectiveDefinitionFunc3' d "compile" x >>= \_ -> return d
ngDirectiveDefinition' (x:xs) d = do ngDirectiveDefinition' [x] d
ngDirectiveDefinition' xs d
return d
ngDirectiveDefinition :: [DirectiveDefinitionConf] -> Fay DirectiveDefinition
ngDirectiveDefinition confs = newNgDirectiveDefinition >>= ngDirectiveDefinition' confs >>= return
| faylang/fay-angular | src/Angular/Ng/Compile.hs | bsd-3-clause | 3,811 | 0 | 13 | 1,021 | 977 | 503 | 474 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import System.Environment (getArgs)
import PCD.Conversion (asciiToBinary)
import PCD.Data (projectBinaryFields)
data Args = Args { _inputFile :: FilePath
, _outputFile :: FilePath
, _justXyz :: Bool }
parseArgs :: [String] -> Maybe Args
parseArgs ["-xyz", a, b] = Just $ Args a b True
parseArgs [a,b] = Just $ Args a b False
parseArgs _ = Nothing
usage :: IO ()
usage = do putStrLn "Usage: pcd2bin [-xyz] asciiPcd outputBinaryFile"
putStrLn "- The '-xyz' option restricts output to those fields."
main :: IO ()
main = getArgs >>= maybe usage aux . parseArgs
where aux (Args a b False) = asciiToBinary a b
aux (Args a b True) = projectBinaryFields ["x","y","z"] a b
| acowley/pcd-loader | src/executable/Main.hs | bsd-3-clause | 788 | 0 | 9 | 183 | 257 | 138 | 119 | 19 | 2 |
-- | Complex Type: @boundsType@ <http://www.topografix.com/GPX/1/1/#type_boundsType>
module Data.Geo.GPX.Type.Bounds(
Bounds
, bounds
) where
import Data.Geo.GPX.Type.Latitude
import Data.Geo.GPX.Type.Longitude
import Data.Geo.GPX.Lens.MinlatL
import Data.Geo.GPX.Lens.MaxlatL
import Data.Geo.GPX.Lens.MinlonL
import Data.Geo.GPX.Lens.MaxlonL
import Data.Lens.Common
import Control.Comonad.Trans.Store
import Text.XML.HXT.Arrow.Pickle
data Bounds = Bounds (Latitude, Longitude) (Latitude, Longitude)
deriving (Eq, Ord)
bounds ::
(Latitude, Longitude) -- ^ The minimum latitude and longitude.
-> (Latitude, Longitude) -- ^ The maximum latitude and longitude.
-> Bounds
bounds =
Bounds
instance MinlatL Bounds where
minlatL =
Lens $ \(Bounds (minlat, minlon) (maxlat, maxlon)) -> store (\minlat -> Bounds (minlat, minlon) (maxlat, maxlon)) minlat
instance MinlonL Bounds where
minlonL =
Lens $ \(Bounds (minlat, minlon) (maxlat, maxlon)) -> store (\minlon -> Bounds (minlat, minlon) (maxlat, maxlon)) minlon
instance MaxlatL Bounds where
maxlatL =
Lens $ \(Bounds (minlat, minlon) (maxlat, maxlon)) -> store (\maxlat -> Bounds (minlat, minlon) (maxlat, maxlon)) maxlat
instance MaxlonL Bounds where
maxlonL =
Lens $ \(Bounds (minlat, minlon) (maxlat, maxlon)) -> store (\maxlon -> Bounds (minlat, minlon) (maxlat, maxlon)) maxlon
instance XmlPickler Bounds where
xpickle =
xpWrap (\(minlat', minlon', maxlat', maxlon') -> bounds (minlat', minlon') (maxlat', maxlon'),
\(Bounds (minlat', minlon') (maxlat', maxlon')) -> (minlat', minlon', maxlat', maxlon')) (xp4Tuple
(xpAttr "minlat" xpickle)
(xpAttr "minlon" xpickle)
(xpAttr "maxlat" xpickle)
(xpAttr "maxlon" xpickle))
| tonymorris/geo-gpx | src/Data/Geo/GPX/Type/Bounds.hs | bsd-3-clause | 1,790 | 0 | 12 | 320 | 580 | 347 | 233 | 40 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Snap.Snaplet.Sass (
Sass
, initSass
, sassServe
) where
------------------------------------------------------------------------------
import Control.Monad
import Control.Monad.Reader
import Control.Monad.State.Class
import Control.Monad.Trans.Writer
import Data.Char (toLower)
import qualified Data.Configurator as C
import Data.List (intercalate)
import Data.Maybe (isNothing)
import Snap.Core (modifyResponse, setContentType)
import Snap.Snaplet
import Snap.Util.FileServe
import System.Process (rawSystem)
import Paths_snaplet_sass
import Snap.Snaplet.Sass.Internal
-- | Snaplet initialization
initSass :: SnapletInit b Sass
initSass = makeSnaplet "sass" description datadir $ do
config <- getSnapletUserConfig
fp <- getSnapletFilePath
(opts, errs) <- runWriterT $ do
cmStr <- logErr "Must specify compileMode" $ C.lookup config "compileMode"
cm <- case cmStr of
Just x -> logErr "Invalid compileMode" . return $ compileModeFromString x
Nothing -> return Nothing
stStr <- logErr "Must specify style" $ C.lookup config "style"
st <- case stStr of
Just x -> logErr "Invalid style" . return $ styleFromString x
Nothing -> return Nothing
sm <- logErr "Must specify sourcemap" $ C.lookup config "sourcemap"
v <- logErr "Must specify verbose" $ C.lookup config "verbose"
return (cm, st, sm, v)
let sass = case opts of
(Just cm, Just st, Just sm, Just v) ->
Sass
{ snapletFilePath = fp
, compileMode = cm
, style = st
, sourcemap = sm
, verbose = v
}
_ -> error $ intercalate "\n" errs
-- Make sure snaplet/sass, snaplet/sass/src, snaplet/sass/css are present.
liftIO $ mapM_ createDirUnlessExists [fp, srcDir sass, destDir sass]
when (Production == compileMode sass) (liftIO $ compileAll sass)
return sass
where
datadir = Just $ liftM (++ "/resources") getDataDir
description = "Automatic (re)compilation and serving of Sass files"
logErr :: MonadIO m => t -> IO (Maybe a) -> WriterT [t] m (Maybe a)
logErr err m = do
res <- liftIO m
when (isNothing res) (tell [err])
return res
-- | Serves the compiled Fay scripts using the chosen compile mode.
sassServe :: Handler b Sass ()
sassServe = do
modifyResponse . setContentType $ "text/css;charset=utf-8"
get >>= compileWithMode . compileMode
-- | Compiles according to the specified mode.
compileWithMode :: CompileMode -> Handler b Sass ()
compileWithMode Development = do
config <- get
compileAll config
compileWithMode Production
-- Production compilation has already been done.
compileWithMode Production = get >>= serveDirectory . destDir
compileAll :: MonadIO m => Sass -> m ()
compileAll cfg = liftIO $ compile >> return ()
where
compile = verboseLog >> rawSystem "sass" args
verboseLog = verbosePut cfg $ "compiling " ++ srcDir cfg
args = ["--update", ioDirs, "--style", st] ++ sm
ioDirs = srcDir cfg ++ ":" ++ destDir cfg
sm = if sourcemap cfg then ["--sourcemap"] else []
st = map toLower . show $ style cfg
| lukerandall/snaplet-sass | src/Snap/Snaplet/Sass.hs | bsd-3-clause | 3,525 | 0 | 18 | 1,018 | 907 | 464 | 443 | 73 | 4 |
module Data.OBO.Document where
-- OBO data type definitions.
type Header = String
type Name = String
type Tag = String
type Value = String
type TagValues = [(Tag, Value)]
data Document =
Document {
docHeader :: TagValues
, docStanzas :: [Stanza]
} deriving (Eq, Ord, Show)
data Stanza =
Stanza {
stName :: Name
, stMap :: TagValues
} deriving (Eq, Ord, Show)
| sebastiaanvisser/islay | src/Data/OBO/Document.hs | bsd-3-clause | 404 | 0 | 9 | 108 | 122 | 76 | 46 | 16 | 0 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples, RankNTypes #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.ST
-- Copyright : (c) The University of Glasgow, 1992-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The 'ST' Monad.
--
-----------------------------------------------------------------------------
module GHC.ST (
ST(..), STret(..), STRep,
fixST, runST, runSTRep,
-- * Unsafe functions
liftST, unsafeInterleaveST
) where
import GHC.Base
import GHC.Show
default ()
-- The state-transformer monad proper. By default the monad is strict;
-- too many people got bitten by space leaks when it was lazy.
-- | The strict state-transformer monad.
-- A computation of type @'ST' s a@ transforms an internal state indexed
-- by @s@, and returns a value of type @a@.
-- The @s@ parameter is either
--
-- * an uninstantiated type variable (inside invocations of 'runST'), or
--
-- * 'RealWorld' (inside invocations of 'Control.Monad.ST.stToIO').
--
-- It serves to keep the internal states of different invocations
-- of 'runST' separate from each other and from invocations of
-- 'Control.Monad.ST.stToIO'.
--
-- The '>>=' and '>>' operations are strict in the state (though not in
-- values stored in the state). For example,
--
-- @'runST' (writeSTRef _|_ v >>= f) = _|_@
newtype ST s a = ST (STRep s a)
type STRep s a = State# s -> (# State# s, a #)
instance Functor (ST s) where
fmap f (ST m) = ST $ \ s ->
case (m s) of { (# new_s, r #) ->
(# new_s, f r #) }
instance Applicative (ST s) where
pure = return
(<*>) = ap
instance Monad (ST s) where
{-# INLINE return #-}
{-# INLINE (>>) #-}
{-# INLINE (>>=) #-}
return x = ST (\ s -> (# s, x #))
m >> k = m >>= \ _ -> k
(ST m) >>= k
= ST (\ s ->
case (m s) of { (# new_s, r #) ->
case (k r) of { ST k2 ->
(k2 new_s) }})
data STret s a = STret (State# s) a
-- liftST is useful when we want a lifted result from an ST computation. See
-- fixST below.
liftST :: ST s a -> State# s -> STret s a
liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r
{-# NOINLINE unsafeInterleaveST #-}
unsafeInterleaveST :: ST s a -> ST s a
unsafeInterleaveST (ST m) = ST ( \ s ->
let
r = case m s of (# _, res #) -> res
in
(# s, r #)
)
-- | Allow the result of a state transformer computation to be used (lazily)
-- inside the computation.
-- Note that if @f@ is strict, @'fixST' f = _|_@.
fixST :: (a -> ST s a) -> ST s a
fixST k = ST $ \ s ->
let ans = liftST (k r) s
STret _ r = ans
in
case ans of STret s' x -> (# s', x #)
instance Show (ST s a) where
showsPrec _ _ = showString "<<ST action>>"
showList = showList__ (showsPrec 0)
{-
Definition of runST
~~~~~~~~~~~~~~~~~~~
SLPJ 95/04: Why @runST@ must not have an unfolding; consider:
\begin{verbatim}
f x =
runST ( \ s -> let
(a, s') = newArray# 100 [] s
(_, s'') = fill_in_array_or_something a x s'
in
freezeArray# a s'' )
\end{verbatim}
If we inline @runST@, we'll get:
\begin{verbatim}
f x = let
(a, s') = newArray# 100 [] realWorld#{-NB-}
(_, s'') = fill_in_array_or_something a x s'
in
freezeArray# a s''
\end{verbatim}
And now the @newArray#@ binding can be floated to become a CAF, which
is totally and utterly wrong:
\begin{verbatim}
f = let
(a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
in
\ x ->
let (_, s'') = fill_in_array_or_something a x s' in
freezeArray# a s''
\end{verbatim}
All calls to @f@ will share a {\em single} array! End SLPJ 95/04.
-}
{-# INLINE runST #-}
-- The INLINE prevents runSTRep getting inlined in *this* module
-- so that it is still visible when runST is inlined in an importing
-- module. Regrettably delicate. runST is behaving like a wrapper.
-- | Return the value computed by a state transformer computation.
-- The @forall@ ensures that the internal state used by the 'ST'
-- computation is inaccessible to the rest of the program.
runST :: (forall s. ST s a) -> a
runST st = runSTRep (case st of { ST st_rep -> st_rep })
-- I'm only letting runSTRep be inlined right at the end, in particular *after* full laziness
-- That's what the "INLINE [0]" says.
-- SLPJ Apr 99
-- {-# INLINE [0] runSTRep #-}
-- SDM: further to the above, inline phase 0 is run *before*
-- full-laziness at the moment, which means that the above comment is
-- invalid. Inlining runSTRep doesn't make a huge amount of
-- difference, anyway. Hence:
{-# NOINLINE runSTRep #-}
runSTRep :: (forall s. STRep s a) -> a
runSTRep st_rep = case st_rep realWorld# of
(# _, r #) -> r
| jstolarek/ghc | libraries/base/GHC/ST.hs | bsd-3-clause | 5,028 | 0 | 16 | 1,273 | 792 | 448 | 344 | 54 | 1 |
{-# LANGUAGE PackageImports #-}
module GHC.IO.Encoding (module M) where
import "base" GHC.IO.Encoding as M
| silkapp/base-noprelude | src/GHC/IO/Encoding.hs | bsd-3-clause | 112 | 0 | 4 | 18 | 23 | 17 | 6 | 3 | 0 |
--------------------------------------------------------------------------------
-- |
-- Module : Generics.EMGM.Functions.Everywhere
-- Copyright : (c) 2008, 2009 Universiteit Utrecht
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable
--
-- Summary: Generic functions that apply a transformation at every location of
-- one type in a value of a possibly different type.
--
-- The functions 'everywhere' and 'everywhere'' have exactly the same type, but
-- they apply the transformation in different fashions. 'everywhere' uses
-- bottom-up application while 'everywhere'' uses a top-down approach. This may
-- make a difference if you have recursive datatypes or use nested pattern
-- matching in the higher-order function.
--
-- These functions are very similar to others with the same names in the \"Scrap
-- Your Boilerplate\" library (@syb@ package). The SYB functions use rank-2
-- types, while the EMGM functions use a single class constraint. Compare the
-- types of the following:
--
-- @
-- -- SYB
-- everywhere :: (forall a. Data a => a -> a) -> forall a. Data a => a -> a
-- @
--
-- @
-- -- EMGM
-- everywhere :: (Rep (Everywhere a) b) => (a -> a) -> b -> b
-- @
--------------------------------------------------------------------------------
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverlappingInstances #-}
module Generics.EMGM.Functions.Everywhere (
Everywhere(..),
everywhere,
Everywhere'(..),
everywhere',
) where
import Generics.EMGM.Base
--------------------------------------------------------------------------------
-- Types
--------------------------------------------------------------------------------
-- | The type of a generic function that takes a function of one type, a value
-- of another type, and returns a value of the value type.
--
-- For datatypes to work with Everywhere, a special instance must be given. This
-- instance is trivial to write. For a non-recursive type, the instance is the
-- same as described for 'Everywhere''. For a recursive type @T@, the 'Rep'
-- instance looks like this:
--
-- > {-# LANGUAGE OverlappingInstances #-}
--
-- @
-- data T a = Val a | Rec (T a)
-- @
--
-- @
-- instance ('Rep' (Everywhere (T a)) (T a), 'Rep' (Everywhere (T a)) a) => 'Rep' (Everywhere (T a)) (T a) where
-- 'rep' = Everywhere app
-- where
-- app f x =
-- case x of
-- Val v1 -> f (Val (selEverywhere 'rep' f v1))
-- Rec v1 -> f (Rec (selEverywhere 'rep' f v1))
-- @
--
-- Note the requirement of overlapping instances.
--
-- This instance is triggered when the function type (the first @T a@ in @'Rep'
-- (Everywhere (T a)) (T a)@) matches some value type (the second @T a@)
-- contained within the argument to 'everywhere'.
newtype Everywhere a b = Everywhere { selEverywhere :: (a -> a) -> b -> b }
--------------------------------------------------------------------------------
-- Generic instance declaration
--------------------------------------------------------------------------------
rsumEverywhere :: Everywhere a b1 -> Everywhere a b2 -> (a -> a) -> (b1 :+: b2) -> b1 :+: b2
rsumEverywhere ra _ f (L a) = L (selEverywhere ra f a)
rsumEverywhere _ rb f (R b) = R (selEverywhere rb f b)
rprodEverywhere :: Everywhere a b1 -> Everywhere a b2 -> (a -> a) -> (b1 :*: b2) -> b1 :*: b2
rprodEverywhere ra rb f (a :*: b) = selEverywhere ra f a :*: selEverywhere rb f b
rtypeEverywhere :: EP d b -> Everywhere a b -> (a -> a) -> d -> d
rtypeEverywhere ep ra f = to ep . selEverywhere ra f . from ep
instance Generic (Everywhere a) where
rint = Everywhere $ const id
rinteger = Everywhere $ const id
rfloat = Everywhere $ const id
rdouble = Everywhere $ const id
rchar = Everywhere $ const id
runit = Everywhere $ const id
rsum ra rb = Everywhere $ rsumEverywhere ra rb
rprod ra rb = Everywhere $ rprodEverywhere ra rb
rtype ep ra = Everywhere $ rtypeEverywhere ep ra
--------------------------------------------------------------------------------
-- Rep instance declarations
--------------------------------------------------------------------------------
instance Rep (Everywhere Int) Int where
rep = Everywhere ($)
instance Rep (Everywhere Integer) Integer where
rep = Everywhere ($)
instance Rep (Everywhere Double) Double where
rep = Everywhere ($)
instance Rep (Everywhere Float) Float where
rep = Everywhere ($)
instance Rep (Everywhere Char) Char where
rep = Everywhere ($)
--------------------------------------------------------------------------------
-- Exported functions
--------------------------------------------------------------------------------
-- | Apply a transformation @a -> a@ to values of type @a@ within the argument
-- of type @b@ in a bottom-up manner. Values that do not have type @a@ are
-- passed through 'id'.
--
-- @everywhere@ works by searching the datatype @b@ for values that are the same
-- type as the function argument type @a@. Here are some examples using the
-- datatype declared in the documentation for 'Everywhere'.
--
-- @
-- ghci> let f t = case t of { Val i -> Val (i+(1::'Int')); other -> other }
-- ghci> everywhere f (Val (1::'Int'))
-- Val 2
-- ghci> everywhere f (Rec (Rec (Val (1::'Int'))))
-- Rec (Rec (Val 2))
-- @
--
-- @
-- ghci> let x = ['Left' 1, 'Right' \'a\', 'Left' 2] :: ['Either' 'Int' 'Char']
-- ghci> everywhere (*(3::'Int')) x
-- ['Left' 3,'Right' \'a\','Left' 6]
-- ghci> everywhere (\\x -> x :: 'Float') x == x
-- 'True'
-- @
--
-- Note the type annotations. Since numerical constants have the type @'Num' a
-- => a@, you may need to give explicit types. Also, the function @\\x -> x@ has
-- type @a -> a@, but we need to give it some non-polymorphic type here. By
-- design, there is no connection that can be inferred between the value type
-- and the function type.
--
-- @everywhere@ only works if there is an instance for the return type as
-- described in the @newtype 'Everywhere'@.
everywhere :: (Rep (Everywhere a) b) => (a -> a) -> b -> b
everywhere f = selEverywhere rep f
--------------------------------------------------------------------------------
-- Types
--------------------------------------------------------------------------------
-- | This type servers the same purpose as 'Everywhere', except that 'Rep'
-- instances are designed to be top-down instead of bottom-up. That means, given
-- any type @U@ (recursive or not), the 'Rep' instance looks like this:
--
-- > {-# LANGUAGE OverlappingInstances #-}
--
-- @
-- data U = ...
-- @
--
-- @
-- instance 'Rep' (Everywhere' U) U where
-- 'rep' = Everywhere' ($)
-- @
--
-- Note the requirement of overlapping instances.
--
-- This instance is triggered when the function type (the first @U@ in @'Rep'
-- (Everywhere U) U@) matches some value type (the second @U@) contained within
-- the argument to 'everywhere''.
newtype Everywhere' a b = Everywhere' { selEverywhere' :: (a -> a) -> b -> b }
--------------------------------------------------------------------------------
-- Generic instance declaration
--------------------------------------------------------------------------------
rsumEverywhere' :: Everywhere' a b1 -> Everywhere' a b2 -> (a -> a) -> (b1 :+: b2) -> b1 :+: b2
rsumEverywhere' ra _ f (L a) = L (selEverywhere' ra f a)
rsumEverywhere' _ rb f (R b) = R (selEverywhere' rb f b)
rprodEverywhere' :: Everywhere' a b1 -> Everywhere' a b2 -> (a -> a) -> (b1 :*: b2) -> b1 :*: b2
rprodEverywhere' ra rb f (a :*: b) = selEverywhere' ra f a :*: selEverywhere' rb f b
rtypeEverywhere' :: EP d b -> Everywhere' a b -> (a -> a) -> d -> d
rtypeEverywhere' ep ra f = to ep . selEverywhere' ra f . from ep
instance Generic (Everywhere' a) where
rint = Everywhere' $ const id
rinteger = Everywhere' $ const id
rfloat = Everywhere' $ const id
rdouble = Everywhere' $ const id
rchar = Everywhere' $ const id
runit = Everywhere' $ const id
rsum ra rb = Everywhere' $ rsumEverywhere' ra rb
rprod ra rb = Everywhere' $ rprodEverywhere' ra rb
rtype ep ra = Everywhere' $ rtypeEverywhere' ep ra
--------------------------------------------------------------------------------
-- Rep instance declarations
--------------------------------------------------------------------------------
instance Rep (Everywhere' Int) Int where
rep = Everywhere' ($)
instance Rep (Everywhere' Integer) Integer where
rep = Everywhere' ($)
instance Rep (Everywhere' Double) Double where
rep = Everywhere' ($)
instance Rep (Everywhere' Float) Float where
rep = Everywhere' ($)
instance Rep (Everywhere' Char) Char where
rep = Everywhere' ($)
--------------------------------------------------------------------------------
-- Exported functions
--------------------------------------------------------------------------------
-- | Apply a transformation @a -> a@ to values of type @a@ within the argument
-- of type @b@ in a top-down manner. Values that do not have type @a@ are passed
-- through 'id'.
--
-- @everywhere'@ is the same as 'everywhere' with the exception of recursive
-- datatypes. For example, compare the example used in the documentation for
-- 'everywhere' with the following.
--
-- @
-- ghci> let f t = case t of { Val i -> Val (i+(1::'Int')); other -> other }
-- ghci> everywhere' f (Val (1::'Int'))
-- Val 2
-- ghci> everywhere' f (Rec (Rec (Val (1::'Int'))))
-- Rec (Rec (Val 1))
-- @
--
-- @everywhere'@ only works if there is an instance for the return type as
-- described in the @newtype 'Everywhere''@.
everywhere' :: (Rep (Everywhere' a) b) => (a -> a) -> b -> b
everywhere' f = selEverywhere' rep f
| spl/emgm | src/Generics/EMGM/Functions/Everywhere.hs | bsd-3-clause | 9,994 | 0 | 10 | 1,915 | 1,450 | 827 | 623 | 72 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-|
This module implements the Heist snaplet without using type classes. It is
provided mainly as an example of how snaplets can be written with and without
a type class for convenience.
-}
module Snap.Snaplet.HeistNoClass
( Heist
, DefaultMode(..)
, heistInit
, heistInit'
, heistReloader
, setInterpreted
, getCurHeistConfig
, clearHeistCache
, addTemplates
, addTemplatesAt
, getHeistState
, modifyHeistState
, modifyHeistState'
, withHeistState
, withHeistState'
, gRender
, gRenderAs
, gHeistServe
, gHeistServeSingle
, chooseMode
, addConfig
, cRender
, cRenderAs
, cHeistServe
, cHeistServeSingle
, render
, renderAs
, heistServe
, heistServeSingle
, heistLocal
, withSplices
, renderWithSplices
, heistLocal'
, withSplices'
, renderWithSplices'
, SnapletHeist
, SnapletISplice
, SnapletCSplice
) where
import Prelude hiding ((.), id)
import Control.Applicative
import Control.Category
import Control.Lens
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Trans.Either
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.DList (DList)
import qualified Data.HashMap.Strict as Map
import Data.IORef
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import Data.Text.Encoding
import System.FilePath.Posix
import Heist
import qualified Heist.Compiled as C
import qualified Heist.Interpreted as I
import Heist.Splices.Cache
import Snap.Snaplet
import Snap.Snaplet.Heist.Internal
import Snap.Core
import Snap.Util.FileServe
------------------------------------------------------------------------------
changeState :: (HeistState (Handler a a) -> HeistState (Handler a a))
-> Heist a
-> Heist a
changeState _ (Configuring _) =
error "changeState: HeistState has not been initialized"
changeState f (Running hc hs cts dm) = Running hc (f hs) cts dm
------------------------------------------------------------------------------
-- | Clears data stored by the cache tag. The cache tag automatically reloads
-- its data when the specified TTL expires, but sometimes you may want to
-- trigger a manual reload. This function lets you do that.
clearHeistCache :: Heist b -> IO ()
clearHeistCache = clearCacheTagState . _heistCTS
-----------------------------
-- SnapletSplice functions --
-----------------------------
------------------------------------------------------------------------------
-- | This instance is here because we don't want the heist package to depend
-- on anything from snap packages.
instance MonadSnap m => MonadSnap (HeistT n m) where
liftSnap = lift . liftSnap
type SnapletHeist b m a = HeistT (Handler b b) m a
type SnapletCSplice b = SnapletHeist b IO (DList (Chunk (Handler b b)))
type SnapletISplice b = SnapletHeist b (Handler b b) Template
---------------------------
-- Initializer functions --
---------------------------
------------------------------------------------------------------------------
-- | The 'Initializer' for 'Heist'. This function is a convenience wrapper
-- around `heistInit'` that uses defaultHeistState and sets up routes for all
-- the templates. It sets up a \"heistReload\" route that reloads the heist
-- templates when you request it from localhost.
heistInit :: FilePath
-- ^ Path to templates
-> SnapletInit b (Heist b)
heistInit = gHeistInit heistServe
------------------------------------------------------------------------------
-- | A lower level 'Initializer' for 'Heist'. This initializer requires you
-- to specify the initial HeistConfig. It also does not add any routes for
-- templates, allowing you complete control over which templates get routed.
heistInit' :: FilePath
-- ^ Path to templates
-> HeistConfig (Handler b b)
-- ^ Initial HeistConfig
-> SnapletInit b (Heist b)
heistInit' templateDir initialConfig =
makeSnaplet "heist" "" Nothing $ heistInitWorker templateDir initialConfig
------------------------------------------------------------------------------
-- | Sets the snaplet to default to interpreted mode. Initially, the
-- initializer sets the value to compiled mode. This function allows you to
-- override that setting. Note that this is just a default. It only has an
-- effect if you use one of the generic functions: 'gRender', 'gRenderAs',
-- 'gHeistServe', or 'gHeistServeSingle'. If you call the non-generic
-- versions directly, then this value will not be checked and you will get the
-- mode implemented by the function you called.
setInterpreted :: Snaplet (Heist b) -> Initializer b v ()
setInterpreted h =
liftIO $ atomicModifyIORef (_heistConfig $ view snapletValue h)
(\(hc,_) -> ((hc,Interpreted),()))
------------------------------------------------------------------------------
-- | Adds templates to the Heist HeistConfig. Other snaplets should use
-- this function to add their own templates. The templates are automatically
-- read from the templates directory in the current snaplet's filesystem root.
addTemplates :: Snaplet (Heist b)
-> ByteString
-- ^ The url prefix for the template routes
-> Initializer b (Heist b) ()
addTemplates h urlPrefix = do
snapletPath <- getSnapletFilePath
addTemplatesAt h urlPrefix (snapletPath </> "templates")
------------------------------------------------------------------------------
-- | Adds templates to the Heist HeistConfig, and lets you specify where
-- they are found in the filesystem. Note that the path to the template
-- directory is an absolute path. This allows you more flexibility in where
-- your templates are located, but means that you have to explicitly call
-- getSnapletFilePath if you want your snaplet to use templates within its
-- normal directory structure.
addTemplatesAt :: Snaplet (Heist b)
-> ByteString
-- ^ URL prefix for template routes
-> FilePath
-- ^ Path to templates
-> Initializer b (Heist b) ()
addTemplatesAt h urlPrefix templateDir = do
rootUrl <- getSnapletRootURL
let fullPrefix = (T.unpack $ decodeUtf8 rootUrl) </>
(T.unpack $ decodeUtf8 urlPrefix)
addPrefix = addTemplatePathPrefix
(encodeUtf8 $ T.pack fullPrefix)
ts <- liftIO $ runEitherT (loadTemplates templateDir) >>=
either (error . concat) return
printInfo $ T.pack $ unwords
[ "...adding"
, (show $ Map.size ts)
, "templates from"
, templateDir
, "with route prefix"
, fullPrefix ++ "/"
]
let locations = [liftM addPrefix $ loadTemplates templateDir]
add (hc, dm) =
((over hcTemplateLocations (mappend locations) hc, dm), ())
liftIO $ atomicModifyIORef (_heistConfig $ view snapletValue h) add
getCurHeistConfig :: Snaplet (Heist b)
-> Initializer b v (HeistConfig (Handler b b))
getCurHeistConfig h = case view snapletValue h of
Configuring ref -> do
(hc, _) <- liftIO $ readIORef ref
return hc
Running _ _ _ _ ->
error "Can't get HeistConfig after heist is initialized."
------------------------------------------------------------------------------
getHeistState :: SnapletLens (Snaplet b) (Heist b)
-> Handler b v (HeistState (Handler b b))
getHeistState heist = withTop' heist $ gets _heistState
------------------------------------------------------------------------------
modifyHeistState' :: SnapletLens (Snaplet b) (Heist b)
-> (HeistState (Handler b b) -> HeistState (Handler b b))
-> Initializer b v ()
modifyHeistState' heist f = do
withTop' heist $ addPostInitHook $ return . changeState f
------------------------------------------------------------------------------
modifyHeistState :: SnapletLens b (Heist b)
-> (HeistState (Handler b b) -> HeistState (Handler b b))
-> Initializer b v ()
modifyHeistState heist f = modifyHeistState' (subSnaplet heist) f
------------------------------------------------------------------------------
withHeistState' :: SnapletLens (Snaplet b) (Heist b)
-> (HeistState (Handler b b) -> a)
-> Handler b v a
withHeistState' heist f = do
hs <- withTop' heist $ gets _heistState
return $ f hs
------------------------------------------------------------------------------
withHeistState :: SnapletLens b (Heist b)
-> (HeistState (Handler b b) -> a)
-> Handler b v a
withHeistState heist f = withHeistState' (subSnaplet heist) f
------------------------------------------------------------------------------
-- | Adds more HeistConfig data using mappend with whatever is currently
-- there. This is the preferred method for adding all four kinds of splices
-- as well as new templates.
addConfig :: Snaplet (Heist b)
-> SpliceConfig (Handler b b)
-> Initializer b v ()
addConfig h sc = case view snapletValue h of
Configuring ref ->
liftIO $ atomicModifyIORef ref add
Running _ _ _ _ -> do
printInfo "finalLoadHook called while running"
error "this shouldn't happen"
where
add (hc, dm) =
((over hcSpliceConfig (`mappend` sc) hc, dm), ())
-----------------------
-- Handler functions --
-----------------------
------------------------------------------------------------------------------
-- | Internal helper function for rendering.
iRenderHelper :: Maybe MIMEType
-> ByteString
-> Handler b (Heist b) ()
iRenderHelper c t = do
(Running _ hs _ _) <- get
withTop' id $ I.renderTemplate hs t >>= maybe pass serve
where
serve (b, mime) = do
modifyResponse $ setContentType $ fromMaybe mime c
writeBuilder b
------------------------------------------------------------------------------
-- | Internal helper function for rendering.
cRenderHelper :: Maybe MIMEType
-> ByteString
-> Handler b (Heist b) ()
cRenderHelper c t = do
(Running _ hs _ _) <- get
withTop' id $ maybe pass serve $ C.renderTemplate hs t
where
serve (b, mime) = do
modifyResponse $ setContentType $ fromMaybe mime c
writeBuilder =<< b
------------------------------------------------------------------------------
serveURI :: Handler b (Heist b) ByteString
serveURI = do
p <- getSafePath
-- Allows users to prefix template filenames with an underscore to prevent
-- the template from being served.
if take 1 p == "_" then pass else return $ B.pack p
------------------------------------------------------------------------------
render :: ByteString
-- ^ Name of the template
-> Handler b (Heist b) ()
render t = iRenderHelper Nothing t
------------------------------------------------------------------------------
renderAs :: ByteString
-- ^ Content type
-> ByteString
-- ^ Name of the template
-> Handler b (Heist b) ()
renderAs ct t = iRenderHelper (Just ct) t
------------------------------------------------------------------------------
heistServe :: Handler b (Heist b) ()
heistServe =
ifTop (render "index") <|> (render =<< serveURI)
------------------------------------------------------------------------------
heistServeSingle :: ByteString -> Handler b (Heist b) ()
heistServeSingle t =
render t <|> error ("Template " ++ show t ++ " not found.")
------------------------------------------------------------------------------
cRender :: ByteString
-- ^ Name of the template
-> Handler b (Heist b) ()
cRender t = cRenderHelper Nothing t
------------------------------------------------------------------------------
cRenderAs :: ByteString
-- ^ Content type
-> ByteString
-- ^ Name of the template
-> Handler b (Heist b) ()
cRenderAs ct t = cRenderHelper (Just ct) t
------------------------------------------------------------------------------
cHeistServe :: Handler b (Heist b) ()
cHeistServe =
ifTop (cRender "index") <|> (cRender =<< serveURI)
------------------------------------------------------------------------------
cHeistServeSingle :: ByteString -> Handler b (Heist b) ()
cHeistServeSingle t =
cRender t <|> error ("Template " ++ show t ++ " not found.")
------------------------------------------------------------------------------
-- | Chooses between a compiled action and an interpreted action based on the
-- configured default.
chooseMode :: MonadState (Heist b1) m
=> m b
-- ^ A compiled action
-> m b
-- ^ An interpreted action
-> m b
chooseMode cAction iAction = do
mode <- gets _defMode
case mode of
Compiled -> cAction
Interpreted -> iAction
------------------------------------------------------------------------------
-- | Like render/cRender, but chooses between the two appropriately based on
-- the default mode.
gRender :: ByteString
-- ^ Name of the template
-> Handler b (Heist b) ()
gRender t = chooseMode (cRender t) (render t)
------------------------------------------------------------------------------
-- | Like renderAs/cRenderAs, but chooses between the two appropriately based
-- on the default mode.
gRenderAs :: ByteString
-- ^ Content type
-> ByteString
-- ^ Name of the template
-> Handler b (Heist b) ()
gRenderAs ct t = chooseMode (cRenderAs ct t) (renderAs ct t)
------------------------------------------------------------------------------
-- | Like heistServe/cHeistServe, but chooses between the two appropriately
-- based on the default mode.
gHeistServe :: Handler b (Heist b) ()
gHeistServe = chooseMode cHeistServe heistServe
------------------------------------------------------------------------------
-- | Like heistServeSingle/cHeistServeSingle, but chooses between the two
-- appropriately based on the default mode.
gHeistServeSingle :: ByteString -> Handler b (Heist b) ()
gHeistServeSingle t = chooseMode (cHeistServeSingle t) (heistServeSingle t)
------------------------------------------------------------------------------
heistLocal' :: SnapletLens (Snaplet b) (Heist b)
-> (HeistState (Handler b b) -> HeistState (Handler b b))
-> Handler b v a
-> Handler b v a
heistLocal' heist f m = do
hs <- withTop' heist get
withTop' heist $ modify $ changeState f
res <- m
withTop' heist $ put hs
return res
------------------------------------------------------------------------------
heistLocal :: SnapletLens b (Heist b)
-> (HeistState (Handler b b) -> HeistState (Handler b b))
-> Handler b v a
-> Handler b v a
heistLocal heist f m = heistLocal' (subSnaplet heist) f m
------------------------------------------------------------------------------
withSplices' :: SnapletLens (Snaplet b) (Heist b)
-> Splices (SnapletISplice b)
-> Handler b v a
-> Handler b v a
withSplices' heist splices m = do
heistLocal' heist (I.bindSplices splices) m
------------------------------------------------------------------------------
withSplices :: SnapletLens b (Heist b)
-> Splices (SnapletISplice b)
-> Handler b v a
-> Handler b v a
withSplices heist splices m = withSplices' (subSnaplet heist) splices m
------------------------------------------------------------------------------
renderWithSplices' :: SnapletLens (Snaplet b) (Heist b)
-> ByteString
-> Splices (SnapletISplice b)
-> Handler b v ()
renderWithSplices' heist t splices =
withSplices' heist splices $ withTop' heist $ render t
------------------------------------------------------------------------------
renderWithSplices :: SnapletLens b (Heist b)
-> ByteString
-> Splices (SnapletISplice b)
-> Handler b v ()
renderWithSplices heist t splices =
renderWithSplices' (subSnaplet heist) t splices
| 23Skidoo/snap | src/Snap/Snaplet/HeistNoClass.hs | bsd-3-clause | 17,187 | 0 | 14 | 4,065 | 3,357 | 1,743 | 1,614 | 273 | 2 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{- BlockId module should probably go away completely, being superseded by Label -}
module GHC.Cmm.BlockId
( BlockId, mkBlockId -- ToDo: BlockId should be abstract, but it isn't yet
, newBlockId
, blockLbl, infoTblLbl
) where
import GhcPrelude
import GHC.Cmm.CLabel
import IdInfo
import Name
import Unique
import UniqSupply
import GHC.Cmm.Dataflow.Label (Label, mkHooplLabel)
----------------------------------------------------------------
--- Block Ids, their environments, and their sets
{- Note [Unique BlockId]
~~~~~~~~~~~~~~~~~~~~~~~~
Although a 'BlockId' is a local label, for reasons of implementation,
'BlockId's must be unique within an entire compilation unit. The reason
is that each local label is mapped to an assembly-language label, and in
most assembly languages allow, a label is visible throughout the entire
compilation unit in which it appears.
-}
type BlockId = Label
mkBlockId :: Unique -> BlockId
mkBlockId unique = mkHooplLabel $ getKey unique
newBlockId :: MonadUnique m => m BlockId
newBlockId = mkBlockId <$> getUniqueM
blockLbl :: BlockId -> CLabel
blockLbl label = mkLocalBlockLabel (getUnique label)
infoTblLbl :: BlockId -> CLabel
infoTblLbl label
= mkBlockInfoTableLabel (mkFCallName (getUnique label) "block") NoCafRefs
| sdiehl/ghc | compiler/GHC/Cmm/BlockId.hs | bsd-3-clause | 1,351 | 0 | 9 | 201 | 183 | 106 | 77 | 23 | 1 |
module Spring13.Week1.CreditCard
(toDigits
,toDigitsRev
,doubleEveryOther
,sumDigits
,validate)
where
main :: IO ()
main = do
print $ toDigits 1234
print $ toDigitsRev 1234
print $ toDigits 0
print $ toDigits (-17)
toDigits :: Integer -> [Integer]
toDigits n
| n > 0 = toDigits (n `div` 10) ++ [n `mod` 10]
| otherwise = []
toDigitsRev :: Integer -> [Integer]
toDigitsRev n
| n > 0 = (n `mod` 10) : toDigitsRev (n `div` 10)
| otherwise = []
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther = reverse . zipWith (*) oneTwo . reverse
where
oneTwo = 1 : 2 : oneTwo
sumDigits :: [Integer] -> Integer
sumDigits = sum . map (sum . toDigits)
validate :: Integer -> Bool
validate n
| n > 0 = mod (sumDigits . doubleEveryOther . toDigits $ n) 10 == 0
| otherwise = False
| bibaijin/cis194 | src/Spring13/Week1/CreditCard.hs | bsd-3-clause | 816 | 0 | 11 | 185 | 357 | 187 | 170 | 29 | 1 |
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module Mud.RollbackSpec where
import System.Exit
import System.Posix.Process
import Mud.Config (defaultConfig)
import Mud.History
import Mud.Rollback
import SpecHelpers
spec :: Spec
spec = do
let parseConfigFiles = \case
"project" -> [defaultConfig "/etc/mud/project"]
name -> error $ "no mock found for parseConfigFiles " ++ show name
describe "rollbackCommand" $ do
it "runs both undeploy and deploy scripts" $ do
let runProcess Nothing Nothing "/etc/mud/project.undeploy"
["project", "version2", "/tmp"] [] = Exited ExitSuccess
runProcess Nothing Nothing "/etc/mud/project.deploy"
["project", "version1", "/tmp"] [] = Exited ExitSuccess
entry1 = HistDeploy "project" someTime True "version1" []
entry2 = HistDeploy "project" someTime True "version2" []
history = defaultHistory { histEntries = [entry1, entry2] }
history' = history
{ histEntries = histEntries history
++ [HistRollback "project" someTime True] }
histories = [("/tmp", history)]
runFakeMudHist mempty parseConfigFiles runProcess histories
(rollbackCommand "project")
`shouldBe` Right ((), [("/tmp", history')])
| thoferon/mud | tests/Mud/RollbackSpec.hs | bsd-3-clause | 1,353 | 0 | 20 | 362 | 320 | 172 | 148 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-|
Internal types and accessors. There are no guarantees that heist will
preserve backwards compatibility for symbols in this module. If you use them,
no complaining when your code breaks.
-}
module Heist.Internal.Types
( module Heist.Internal.Types.HeistState
, module Heist.Internal.Types
) where
------------------------------------------------------------------------------
import Control.Applicative
import Data.HashMap.Strict (HashMap)
import Data.Monoid
import Data.Text (Text)
------------------------------------------------------------------------------
import qualified Heist.Compiled.Internal as C
import qualified Heist.Interpreted.Internal as I
import Heist.Internal.Types.HeistState
------------------------------------------------------------------------------
------------------------------------------------------------------------------
type TemplateRepo = HashMap TPath DocumentFile
------------------------------------------------------------------------------
-- | An IO action for getting a template repo from this location. By not just
-- using a directory path here, we support templates loaded from a database,
-- retrieved from the network, or anything else you can think of.
type TemplateLocation = IO (Either [String] TemplateRepo)
------------------------------------------------------------------------------
-- | My lens creation function to avoid a dependency on lens.
lens :: Functor f => (t1 -> t) -> (t1 -> a -> b) -> (t -> f a) -> t1 -> f b
lens sa sbt afb s = sbt s <$> afb (sa s)
------------------------------------------------------------------------------
-- | The splices and templates Heist will use. To bind a splice simply
-- include it in the appropriate place here.
data SpliceConfig m = SpliceConfig
{ _scInterpretedSplices :: Splices (I.Splice m)
-- ^ Interpreted splices are the splices that Heist has always had.
-- They return a list of nodes and are processed at runtime.
, _scLoadTimeSplices :: Splices (I.Splice IO)
-- ^ Load time splices are like interpreted splices because they
-- return a list of nodes. But they are like compiled splices because
-- they are processed once at load time. All of Heist's built-in
-- splices should be used as load time splices.
, _scCompiledSplices :: Splices (C.Splice m)
-- ^ Compiled splices return a DList of Chunks and are processed at
-- load time to generate a runtime monad action that will be used to
-- render the template.
, _scAttributeSplices :: Splices (AttrSplice m)
-- ^ Attribute splices are bound to attribute names and return a list
-- of attributes.
, _scTemplateLocations :: [TemplateLocation]
-- ^ A list of all the locations that Heist should get its templates
-- from.
}
------------------------------------------------------------------------------
-- | Lens for interpreted splices
-- :: Simple Lens (SpliceConfig m) (Splices (I.Splice m))
scInterpretedSplices
:: Functor f
=> (Splices (I.Splice m) -> f (Splices (I.Splice m)))
-> SpliceConfig m -> f (SpliceConfig m)
scInterpretedSplices = lens _scInterpretedSplices setter
where
setter sc v = sc { _scInterpretedSplices = v }
------------------------------------------------------------------------------
-- | Lens for load time splices
-- :: Simple Lens (SpliceConfig m) (Splices (I.Splice IO))
scLoadTimeSplices
:: Functor f
=> (Splices (I.Splice IO) -> f (Splices (I.Splice IO)))
-> SpliceConfig m -> f (SpliceConfig m)
scLoadTimeSplices = lens _scLoadTimeSplices setter
where
setter sc v = sc { _scLoadTimeSplices = v }
------------------------------------------------------------------------------
-- | Lens for complied splices
-- :: Simple Lens (SpliceConfig m) (Splices (C.Splice m))
scCompiledSplices
:: Functor f
=> (Splices (C.Splice m) -> f (Splices (C.Splice m)))
-> SpliceConfig m -> f (SpliceConfig m)
scCompiledSplices = lens _scCompiledSplices setter
where
setter sc v = sc { _scCompiledSplices = v }
------------------------------------------------------------------------------
-- | Lens for attribute splices
-- :: Simple Lens (SpliceConfig m) (Splices (AttrSplice m))
scAttributeSplices
:: Functor f
=> (Splices (AttrSplice m) -> f (Splices (AttrSplice m)))
-> SpliceConfig m -> f (SpliceConfig m)
scAttributeSplices = lens _scAttributeSplices setter
where
setter sc v = sc { _scAttributeSplices = v }
------------------------------------------------------------------------------
-- | Lens for template locations
-- :: Simple Lens (SpliceConfig m) [TemplateLocation]
scTemplateLocations
:: Functor f
=> ([TemplateLocation] -> f [TemplateLocation])
-> SpliceConfig m -> f (SpliceConfig m)
scTemplateLocations = lens _scTemplateLocations setter
where
setter sc v = sc { _scTemplateLocations = v }
instance Monoid (SpliceConfig m) where
mempty = SpliceConfig mempty mempty mempty mempty mempty
mappend (SpliceConfig a1 b1 c1 d1 e1) (SpliceConfig a2 b2 c2 d2 e2) =
SpliceConfig (mappend a1 a2) (mappend b1 b2) (mappend c1 c2)
(mappend d1 d2) (mappend e1 e2)
data HeistConfig m = HeistConfig
{ _hcSpliceConfig :: SpliceConfig m
-- ^ Splices and templates
, _hcNamespace :: Text
-- ^ A namespace to use for all tags that are bound to splices. Use
-- empty string for no namespace.
, _hcErrorNotBound :: Bool
-- ^ Whether to throw an error when a tag wih the heist namespace does
-- not correspond to a bound splice. When not using a namespace, this
-- flag is ignored.
}
------------------------------------------------------------------------------
-- | Lens for the SpliceConfig
-- :: Simple Lens (HeistConfig m) (SpliceConfig m)
hcSpliceConfig
:: Functor f
=> ((SpliceConfig m) -> f (SpliceConfig m))
-> HeistConfig m -> f (HeistConfig m)
hcSpliceConfig = lens _hcSpliceConfig setter
where
setter hc v = hc { _hcSpliceConfig = v }
------------------------------------------------------------------------------
-- | Lens for the namespace
-- :: Simple Lens (HeistConfig m) Text
hcNamespace
:: Functor f
=> (Text -> f Text)
-> HeistConfig m -> f (HeistConfig m)
hcNamespace = lens _hcNamespace setter
where
setter hc v = hc { _hcNamespace = v }
------------------------------------------------------------------------------
-- | Lens for the namespace error flag
-- :: Simple Lens (HeistConfig m) Bool
hcErrorNotBound
:: Functor f
=> (Bool -> f Bool)
-> HeistConfig m -> f (HeistConfig m)
hcErrorNotBound = lens _hcErrorNotBound setter
where
setter hc v = hc { _hcErrorNotBound = v }
------------------------------------------------------------------------------
-- | Lens for interpreted splices
-- :: Simple Lens (HeistConfig m) (Splices (I.Splice m))
hcInterpretedSplices
:: Functor f
=> (Splices (I.Splice m) -> f (Splices (I.Splice m)))
-> HeistConfig m -> f (HeistConfig m)
hcInterpretedSplices = hcSpliceConfig . scInterpretedSplices
------------------------------------------------------------------------------
-- | Lens for load time splices
-- :: Simple Lens (HeistConfig m) (Splices (I.Splice IO))
hcLoadTimeSplices
:: Functor f
=> (Splices (I.Splice IO) -> f (Splices (I.Splice IO)))
-> HeistConfig m -> f (HeistConfig m)
hcLoadTimeSplices = hcSpliceConfig . scLoadTimeSplices
------------------------------------------------------------------------------
-- | Lens for compiled splices
-- :: Simple Lens (HeistConfig m) (Splices (C.Splice m))
hcCompiledSplices
:: Functor f
=> (Splices (C.Splice m) -> f (Splices (C.Splice m)))
-> HeistConfig m -> f (HeistConfig m)
hcCompiledSplices = hcSpliceConfig . scCompiledSplices
------------------------------------------------------------------------------
-- | Lens for attribute splices
-- :: Simple Lens (HeistConfig m) (Splices (AttrSplice m))
hcAttributeSplices
:: Functor f
=> (Splices (AttrSplice m) -> f (Splices (AttrSplice m)))
-> HeistConfig m -> f (HeistConfig m)
hcAttributeSplices = hcSpliceConfig . scAttributeSplices
------------------------------------------------------------------------------
-- | Lens for template locations
-- :: Simple Lens (HeistConfig m) [TemplateLocation]
hcTemplateLocations
:: Functor f
=> ([TemplateLocation] -> f [TemplateLocation])
-> HeistConfig m -> f (HeistConfig m)
hcTemplateLocations = hcSpliceConfig . scTemplateLocations
| 23Skidoo/heist | src/Heist/Internal/Types.hs | bsd-3-clause | 9,038 | 0 | 14 | 1,747 | 1,562 | 840 | 722 | 110 | 1 |
module Main where
import ABS
(n_div:x:main_ret:i:f:n:obj:reminder:res:the_end) = [0..]
main_ :: Method
main_ [] this wb k =
Assign n (Val (I 2000)) $
Assign x (Sync primality_test [n]) $
k
primality_test :: Method
primality_test [pn] this wb k =
Assign i (Val (I 1)) $
Assign n (Val (I pn)) $
While (ILTE (Attr i) (Attr n)) (\k' ->
Assign obj New $
Assign f (Async obj divides [i,n]) $
Assign i (Val (Add (Attr i) (I 1))) $
k'
) $
Return i wb k
divides :: Method
divides [pd, pn] this wb k =
Assign reminder (Val (Mod (I pn) (I pd)) ) $
If (IEq (Attr reminder) (I 0))
(\k' -> Assign res (Val (I 1)) k')
(\k' -> Assign res (Val (I 0)) k' ) $
Return res wb k
main' :: IO ()
main' = run' 1000000 main_ (head the_end)
main :: IO ()
main = printHeap =<< run 1000000 main_ (head the_end)
| abstools/abs-haskell-formal | benchmarks/3_primality_test_parallel/progs/2000.hs | bsd-3-clause | 846 | 0 | 18 | 222 | 506 | 256 | 250 | 30 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
module Main where
import Control.Comonad ( extract )
import qualified Control.DeepSeq as Deep
import qualified Control.Exception as Exc
import Control.Monad
import Control.Monad.Catch
import Control.Monad.Free
import Control.Monad.IO.Class
-- import Control.Monad.ST
import qualified Data.Aeson.Text as A
import qualified Data.HashMap.Lazy as M
import qualified Data.Map as Map
import Data.List ( sortOn )
import Data.Maybe ( fromJust )
import Data.Time
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import qualified Data.Text.Lazy.IO as TL
import Data.Text.Prettyprint.Doc
import Data.Text.Prettyprint.Doc.Render.Text
import Nix
import Nix.Convert
import qualified Nix.Eval as Eval
import Nix.Fresh.Basic
import Nix.Json
-- import Nix.Lint
import Nix.Options.Parser
import Nix.Standard
import Nix.Thunk.Basic
import qualified Nix.Type.Env as Env
import qualified Nix.Type.Infer as HM
import Nix.Utils
import Nix.Var
import Nix.Value.Monad
import Options.Applicative hiding ( ParserResult(..) )
import qualified Repl
import System.FilePath
import System.IO
import qualified Text.Show.Pretty as PS
main :: IO ()
main = do
time <- getCurrentTime
opts <- execParser (nixOptionsInfo time)
runWithBasicEffectsIO opts $ case readFrom opts of
Just path -> do
let file = addExtension (dropExtension path) "nixc"
process opts (Just file) =<< liftIO (readCache path)
Nothing -> case expression opts of
Just s -> handleResult opts Nothing (parseNixTextLoc s)
Nothing -> case fromFile opts of
Just "-" -> mapM_ (processFile opts) =<< (lines <$> liftIO getContents)
Just path ->
mapM_ (processFile opts) =<< (lines <$> liftIO (readFile path))
Nothing -> case filePaths opts of
[] -> withNixContext Nothing $ Repl.main
["-"] ->
handleResult opts Nothing
. parseNixTextLoc
=<< liftIO Text.getContents
paths -> mapM_ (processFile opts) paths
where
processFile opts path = do
eres <- parseNixFileLoc path
handleResult opts (Just path) eres
handleResult opts mpath = \case
Failure err ->
(if ignoreErrors opts
then liftIO . hPutStrLn stderr
else errorWithoutStackTrace
)
$ "Parse failed: "
++ show err
Success expr -> do
when (check opts) $ do
expr' <- liftIO (reduceExpr mpath expr)
case HM.inferTop Env.empty [("it", stripAnnotation expr')] of
Left err -> errorWithoutStackTrace $ "Type error: " ++ PS.ppShow err
Right ty -> liftIO $ putStrLn $ "Type of expression: " ++ PS.ppShow
(fromJust (Map.lookup "it" (Env.types ty)))
-- liftIO $ putStrLn $ runST $
-- runLintM opts . renderSymbolic =<< lint opts expr
catch (process opts mpath expr) $ \case
NixException frames ->
errorWithoutStackTrace
. show
=<< renderFrames @(StdValue (StandardT (StdIdT IO)))
@(StdThunk (StandardT (StdIdT IO)))
frames
when (repl opts) $ withNixContext Nothing Repl.main
process opts mpath expr
| evaluate opts
, tracing opts
= evaluateExpression mpath Nix.nixTracingEvalExprLoc printer expr
| evaluate opts
, Just path <- reduce opts
= evaluateExpression mpath (reduction path) printer expr
| evaluate opts
, not (null (arg opts) && null (argstr opts))
= evaluateExpression mpath Nix.nixEvalExprLoc printer expr
| evaluate opts
= processResult printer =<< Nix.nixEvalExprLoc mpath expr
| xml opts
= error "Rendering expression trees to XML is not yet implemented"
| json opts
= liftIO $ TL.putStrLn $ A.encodeToLazyText (stripAnnotation expr)
| verbose opts >= DebugInfo
= liftIO $ putStr $ PS.ppShow $ stripAnnotation expr
| cache opts
, Just path <- mpath
= liftIO $ writeCache (addExtension (dropExtension path) "nixc") expr
| parseOnly opts
= void $ liftIO $ Exc.evaluate $ Deep.force expr
| otherwise
= liftIO
$ renderIO stdout
. layoutPretty (LayoutOptions $ AvailablePerLine 80 0.4)
. prettyNix
. stripAnnotation
$ expr
where
printer
| finder opts
= fromValue @(AttrSet (StdValue (StandardT (StdIdT IO)))) >=> findAttrs
| xml opts
= liftIO
. putStrLn
. Text.unpack
. principledStringIgnoreContext
. toXML
<=< normalForm
| json opts
= liftIO
. Text.putStrLn
. principledStringIgnoreContext
<=< nvalueToJSONNixString
| strict opts
= liftIO . print . prettyNValue <=< normalForm
| values opts
= liftIO . print . prettyNValueProv <=< removeEffects
| otherwise
= liftIO . print . prettyNValue <=< removeEffects
where
findAttrs
:: AttrSet (StdValue (StandardT (StdIdT IO)))
-> StandardT (StdIdT IO) ()
findAttrs = go ""
where
go prefix s = do
xs <- forM (sortOn fst (M.toList s)) $ \(k, nv) -> case nv of
Free v -> pure (k, Just (Free v))
Pure (StdThunk (extract -> Thunk _ _ ref)) -> do
let path = prefix ++ Text.unpack k
(_, descend) = filterEntry path k
val <- readVar @(StandardT (StdIdT IO)) ref
case val of
Computed _ -> pure (k, Nothing)
_ | descend -> (k, ) <$> forceEntry path nv
| otherwise -> pure (k, Nothing)
forM_ xs $ \(k, mv) -> do
let path = prefix ++ Text.unpack k
(report, descend) = filterEntry path k
when report $ do
liftIO $ putStrLn path
when descend $ case mv of
Nothing -> return ()
Just v -> case v of
NVSet s' _ -> go (path ++ ".") s'
_ -> return ()
where
filterEntry path k = case (path, k) of
("stdenv", "stdenv" ) -> (True, True)
(_ , "stdenv" ) -> (False, False)
(_ , "out" ) -> (True, False)
(_ , "src" ) -> (True, False)
(_ , "mirrorsFile" ) -> (True, False)
(_ , "buildPhase" ) -> (True, False)
(_ , "builder" ) -> (False, False)
(_ , "drvPath" ) -> (False, False)
(_ , "outPath" ) -> (False, False)
(_ , "__impureHostDeps") -> (False, False)
(_ , "__sandboxProfile") -> (False, False)
("pkgs" , "pkgs" ) -> (True, True)
(_ , "pkgs" ) -> (False, False)
(_ , "drvAttrs" ) -> (False, False)
_ -> (True, True)
forceEntry k v =
catch (Just <$> demand v pure) $ \(NixException frames) -> do
liftIO
. putStrLn
. ("Exception forcing " ++)
. (k ++)
. (": " ++)
. show
=<< renderFrames @(StdValue (StandardT (StdIdT IO)))
@(StdThunk (StandardT (StdIdT IO)))
frames
return Nothing
reduction path mp x = do
eres <- Nix.withNixContext mp
$ Nix.reducingEvalExpr (Eval.eval . annotated . getCompose) mp x
handleReduced path eres
handleReduced
:: (MonadThrow m, MonadIO m)
=> FilePath
-> (NExprLoc, Either SomeException (NValue t f m))
-> m (NValue t f m)
handleReduced path (expr', eres) = do
liftIO $ do
putStrLn $ "Wrote winnowed expression tree to " ++ path
writeFile path $ show $ prettyNix (stripAnnotation expr')
case eres of
Left err -> throwM err
Right v -> return v
| jwiegley/hnix | main/Main.hs | bsd-3-clause | 8,777 | 0 | 31 | 3,258 | 2,535 | 1,296 | 1,239 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Database.PostgreSQL.Simple
import DataTypes
import JsonInstances ()
import TenantApi
import Validations
import Web.Spock
import Web.Spock.Config
import qualified Data.Text as T
data MySession =
EmptySession
data MyAppState = DummyAppState
connectDb :: IO Connection
connectDb = connect defaultConnectInfo { connectDatabase = "haskell-webapps" }
main :: IO ()
main = do
spockCfg <-
defaultSpockCfg
EmptySession
(PCConn $ ConnBuilder connectDb close (PoolCfg 10 10 10))
DummyAppState
runSpock 8080 (spock spockCfg app)
app :: SpockM Connection MySession MyAppState ()
app = do
post ("tenants/new") $
do maybe_tenant_incoming <- jsonBody
maybe_newtenant <-
case maybe_tenant_incoming of
Just incoming_tenant -> do
result <-
runQuery (\conn -> validateIncomingTenant conn incoming_tenant)
case result of
Valid -> runQuery (\conn -> create_tenant conn incoming_tenant)
_ -> return Nothing
Nothing -> return Nothing
case maybe_newtenant of
Just tenant -> json tenant
_ -> json $ T.pack "Tenant not created"
| vacationlabs/haskell-webapps | SpockOpaleye/app/Main.hs | mit | 1,348 | 0 | 22 | 430 | 317 | 162 | 155 | 39 | 4 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Pos.Explorer.Socket.Util
( EventName (..)
, emit
, emitJSON
, emitTo
, emitJSONTo
, on_
, on
, runPeriodically
, regroupBySnd
) where
import Universum hiding (on)
import Control.Concurrent (threadDelay)
import Control.Monad.Reader (MonadReader)
import Control.Monad.State (MonadState)
import Control.Monad.Trans (MonadIO)
import Data.Aeson.Types (Array, FromJSON, ToJSON)
import qualified Data.Map as M
import Data.Text (Text)
import Data.Time.Units (TimeUnit (..))
import Formatting (sformat, shown, (%))
import Network.EngineIO.Wai (WaiMonad)
import qualified Network.SocketIO as S
import Pos.Util.Wlog (CanLog (..), WithLogger, logWarning)
-- * Provides type-safety for event names in some socket-io functions.
class EventName a where
toName :: a -> Text
-- ** Socket-io functions which works with `EventName name` rather than
-- with plain `Text`.
emit
:: (ToJSON event, EventName name, MonadReader S.Socket m, MonadIO m)
=> name -> event -> m ()
emit eventName =
S.emit $ toName eventName
-- logDebug . sformat ("emit "%stext) $ toName eventName
emitTo
:: (ToJSON event, EventName name, MonadIO m)
=> S.Socket -> name -> event -> m ()
emitTo sock eventName = S.emitTo sock (toName eventName)
emitJSON
:: (EventName name, MonadReader S.Socket m, MonadIO m)
=> name -> Array -> m ()
emitJSON eventName = S.emitJSON (toName eventName)
emitJSONTo
:: (EventName name, MonadIO m)
=> S.Socket -> name -> Array -> m ()
emitJSONTo sock eventName = S.emitJSONTo sock (toName eventName)
on_ :: (MonadState S.RoutingTable m, EventName name)
=> name -> S.EventHandler a -> m ()
on_ eventName = S.on (toName eventName)
on :: (MonadState S.RoutingTable m, FromJSON event, EventName name)
=> name -> (event -> S.EventHandler a) -> m ()
on eventName = S.on (toName eventName)
-- * Instances
instance CanLog WaiMonad where
dispatchMessage logName sev msg = liftIO $ dispatchMessage logName sev msg
-- * Misc
-- | Runs an action periodically.
-- Action is launched with state. If action fails, state remains unmodified.
runPeriodically
:: (MonadIO m, MonadCatch m, WithLogger m, TimeUnit t)
=> t -> s -> StateT s m () -> m ()
runPeriodically delay initState action =
let loop st = do
st' <- execStateT action st
`catchAny` \e -> handler e $> st
-- toMicroseconds makes an 'Integer'
liftIO $ threadDelay (fromIntegral (toMicroseconds delay))
loop st'
in loop initState
where
handler = logWarning . sformat ("Periodic action failed: "%shown)
regroupBySnd
:: forall a b l. (Ord b, Container l, Element l ~ b)
=> [(a, l)] -> M.Map b [a]
regroupBySnd info =
let entries :: [(b, a)]
entries = fmap swap $ concatMap sequence $ toList <<$>> info
in fmap ($ []) $ M.fromListWith (.) $ fmap (second $ (++) . pure) entries
| input-output-hk/pos-haskell-prototype | explorer/src/Pos/Explorer/Socket/Util.hs | mit | 3,191 | 0 | 16 | 800 | 974 | 528 | 446 | -1 | -1 |
--
--
--
------------------
-- Exercise 10.10.
------------------
--
--
--
module E'10'10 where
import E'10''9 ( iter )
import Test.QuickCheck.Modifiers ( Positive(..) )
import Test.QuickCheck ( quickCheck )
power2 :: Integer -> Integer
power2 exponent
| exponent < 0 = error "Negative exponent."
| otherwise = iter exponent double 1
where
double :: Integer -> Integer
double integer = integer * 2
prop_power2 :: ( Positive Integer ) -> Bool
prop_power2 ( Positive integer )
= power2 integer == 2 ^ integer
-- GHCi> quickCheck prop_power2
| pascal-knodel/haskell-craft | _/links/E'10'10.hs | mit | 571 | 0 | 8 | 119 | 156 | 87 | 69 | 13 | 1 |
{-# LANGUAGE NoImplicitPrelude, DeriveFunctor, RankNTypes #-}
module Lamdu.Sugar.Names.CPS
( CPS(..)
) where
import Prelude.Compat
data CPS m a = CPS { runCPS :: forall r. m r -> m (a, r) }
deriving (Functor)
instance Functor m => Applicative (CPS m) where
pure x = CPS $ fmap ((,) x)
CPS cpsf <*> CPS cpsx =
CPS (fmap foo . cpsf . cpsx)
where
foo (f, (x, r)) = (f x, r)
| da-x/lamdu | Lamdu/Sugar/Names/CPS.hs | gpl-3.0 | 422 | 0 | 12 | 123 | 178 | 97 | 81 | 11 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-- Module : Test.AWS.DynamoDBStreams
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Test.AWS.DynamoDBStreams
( tests
, fixtures
) where
import Network.AWS.DynamoDBStreams
import Test.AWS.Gen.DynamoDBStreams
import Test.Tasty
tests :: [TestTree]
tests = []
fixtures :: [TestTree]
fixtures = []
| fmapfmapfmap/amazonka | amazonka-dynamodb-streams/test/Test/AWS/DynamoDBStreams.hs | mpl-2.0 | 772 | 0 | 5 | 201 | 73 | 50 | 23 | 11 | 1 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
module Handler.Labels
( getLabelsR
, postLabelsR
, postNewLabelR
, LTree (..)
, getLTree
) where
import Wiki
import Control.Monad (unless)
import Data.Aeson (json, Value (..))
import Data.Text.Encoding (encodeUtf8)
import Data.Attoparsec (parse, maybeResult)
import qualified Data.Map as Map
import qualified Data.Vector as V
newLabelForm :: Handler ((FormResult Text, Widget), Enctype)
newLabelForm = runFormPost $ renderTable $ id
<$> areq textField (FieldSettings MsgLabelName Nothing Nothing Nothing) Nothing
data LTree = LTree
{ lid :: LabelId
, lname :: Text
, lchildren :: [LTree]
}
showLTree :: [LTree] -> Widget
showLTree ls = [whamlet|
<ul>
$forall l <- ls
<li #label#{toSinglePiece $ lid l}>
<span>#{lname l}
^{showLTree $ lchildren l}
|]
getLTree :: Handler [LTree]
getLTree = do
allLabels <- runDB $ selectList [] []
return $ map (go allLabels) $ filter (filt Nothing) (allLabels :: [(LabelId, Label)])
where
filt :: Maybe LabelId -> (LabelId, Label) -> Bool
filt x (_, y) = labelParent y == x
go :: [(LabelId, Label)] -> (LabelId, Label) -> LTree
go m (lid', l) = LTree lid' (labelName l) $ map (go m) $ filter (filt $ Just lid') m
getLabelsR :: Handler RepHtml
getLabelsR = do
(_, user) <- requireAuth
unless (userAdmin user) $ permissionDenied ""
((_, newform), _) <- newLabelForm
ltree <- getLTree
defaultLayout $ do
addScript $ StaticR jquery_js
addLucius $(luciusFile "edit-map")
$(widgetFile "labels")
postLabelsR :: Handler ()
postLabelsR = do
text <- runInputPost $ ireq textField "tree"
case maybeResult (parse json $ encodeUtf8 text) >>= go of
Nothing -> invalidArgsI [MsgInvalidJsonInput text]
Just x -> do
runDB $ mapM_ (fix Nothing) x
setMessageI MsgLabelsUpdated
redirect RedirectTemporary LabelsR
where
fix parent lt = do
update (lid lt) [LabelParent =. parent]
mapM_ (fix $ Just $ lid lt) $ lchildren lt
go (Array x) = mapM go' $ V.toList x
go _ = Nothing
go' (Object o) = do
t <- Map.lookup "id" o
t' <- go'' t
c <- Map.lookup "children" o
c' <- go c
return $ LTree t' "ignored" c'
go' _ = Nothing
go'' (String t) = fromSinglePiece t
go'' _ = Nothing
postNewLabelR :: Handler ()
postNewLabelR = do
((res, _), _) <- newLabelForm
case res of
FormSuccess name -> runDB (insert $ Label Nothing name) >> return ()
_ -> return ()
redirect RedirectTemporary LabelsR
| snoyberg/yesodwiki | Handler/Labels.hs | bsd-2-clause | 2,687 | 0 | 15 | 714 | 948 | 484 | 464 | 71 | 5 |
module Settings.Flavours.GhcInGhci (ghcInGhciFlavour) where
import Expression
import Flavour
import {-# SOURCE #-} Settings.Default
import Settings.Flavours.Common
-- Please update doc/flavours.md when changing this file.
ghcInGhciFlavour :: Flavour
ghcInGhciFlavour = defaultFlavour
{ name = "ghc-in-ghci"
, args = defaultBuilderArgs <> ghciArgs <> defaultPackageArgs
-- We can't build DLLs on Windows (yet). Actually we should only
-- include the dynamic way when we have a dynamic host GHC, but just
-- checking for Windows seems simpler for now.
, libraryWays = pure [vanilla] <> pure [ dynamic | not windowsHost ]
, rtsWays = pure [vanilla, threaded] <> pure [ dynamic | not windowsHost ]
, dynamicGhcPrograms = return False }
ghciArgs :: Args
ghciArgs = sourceArgs SourceArgs
{ hsDefault = mconcat $
[ pure ["-O0", "-H64m"]
, naturalInBaseFixArgs
]
, hsLibrary = mempty
, hsCompiler = mempty
, hsGhc = mempty }
| sdiehl/ghc | hadrian/src/Settings/Flavours/GhcInGhci.hs | bsd-3-clause | 1,012 | 0 | 11 | 235 | 194 | 115 | 79 | 20 | 1 |
-- |
-- Module : Crypto.Hash.MD5
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
-- Module containing the binding functions to work with the
-- MD5 cryptographic hash.
--
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
module Crypto.Hash.MD5 ( MD5 (..) ) where
import Crypto.Hash.Types
import Foreign.Ptr (Ptr)
import Data.Data
import Data.Word (Word8, Word32)
-- | MD5 cryptographic hash algorithm
data MD5 = MD5
deriving (Show,Data)
instance HashAlgorithm MD5 where
type HashBlockSize MD5 = 64
type HashDigestSize MD5 = 16
type HashInternalContextSize MD5 = 96
hashBlockSize _ = 64
hashDigestSize _ = 16
hashInternalContextSize _ = 96
hashInternalInit = c_md5_init
hashInternalUpdate = c_md5_update
hashInternalFinalize = c_md5_finalize
instance HashAlgorithmPrefix MD5 where
hashInternalFinalizePrefix = c_md5_finalize_prefix
foreign import ccall unsafe "cryptonite_md5_init"
c_md5_init :: Ptr (Context a)-> IO ()
foreign import ccall "cryptonite_md5_update"
c_md5_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO ()
foreign import ccall unsafe "cryptonite_md5_finalize"
c_md5_finalize :: Ptr (Context a) -> Ptr (Digest a) -> IO ()
foreign import ccall "cryptonite_md5_finalize_prefix"
c_md5_finalize_prefix :: Ptr (Context a) -> Ptr Word8 -> Word32 -> Word32 -> Ptr (Digest a) -> IO ()
| vincenthz/cryptonite | Crypto/Hash/MD5.hs | bsd-3-clause | 1,645 | 0 | 13 | 381 | 346 | 190 | 156 | 31 | 0 |
{-# LANGUAGE CPP, MagicHash, NondecreasingIndentation, UnboxedTuples #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2007
--
-- Running statements interactively
--
-- -----------------------------------------------------------------------------
module InteractiveEval (
#ifdef GHCI
RunResult(..), Status(..), Resume(..), History(..),
runStmt, runStmtWithLocation, runDecls, runDeclsWithLocation,
parseImportDecl, SingleStep(..),
resume,
abandon, abandonAll,
getResumeContext,
getHistorySpan,
getModBreaks,
getHistoryModule,
back, forward,
setContext, getContext,
availsToGlobalRdrEnv,
getNamesInScope,
getRdrNamesInScope,
moduleIsInterpreted,
getInfo,
exprType,
typeKind,
parseName,
showModule,
isModuleInterpreted,
compileExpr, dynCompileExpr,
Term(..), obtainTermFromId, obtainTermFromVal, reconstructType
#endif
) where
#ifdef GHCI
#include "HsVersions.h"
import InteractiveEvalTypes
import GhcMonad
import HscMain
import HsSyn
import HscTypes
import BasicTypes ( HValue )
import InstEnv
import FamInstEnv ( FamInst, orphNamesOfFamInst )
import TyCon
import Type hiding( typeKind )
import TcType hiding( typeKind )
import Var
import Id
import Name hiding ( varName )
import NameSet
import Avail
import RdrName
import VarSet
import VarEnv
import ByteCodeInstr
import Linker
import DynFlags
import Unique
import UniqSupply
import Module
import Panic
import UniqFM
import Maybes
import ErrUtils
import SrcLoc
import BreakArray
import RtClosureInspect
import Outputable
import FastString
import MonadUtils
import System.Mem.Weak
import System.Directory
import Data.Dynamic
import Data.Either
import Data.List (find)
import Control.Monad
import Foreign.Safe
import Foreign.C
import GHC.Exts
import Data.Array
import Exception
import Control.Concurrent
import System.IO.Unsafe
-- -----------------------------------------------------------------------------
-- running a statement interactively
getResumeContext :: GhcMonad m => m [Resume]
getResumeContext = withSession (return . ic_resume . hsc_IC)
data SingleStep
= RunToCompletion
| SingleStep
| RunAndLogSteps
isStep :: SingleStep -> Bool
isStep RunToCompletion = False
isStep _ = True
mkHistory :: HscEnv -> HValue -> BreakInfo -> History
mkHistory hsc_env hval bi = let
decls = findEnclosingDecls hsc_env bi
in History hval bi decls
getHistoryModule :: History -> Module
getHistoryModule = breakInfo_module . historyBreakInfo
getHistorySpan :: HscEnv -> History -> SrcSpan
getHistorySpan hsc_env hist =
let inf = historyBreakInfo hist
num = breakInfo_number inf
in case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
Just hmi -> modBreaks_locs (getModBreaks hmi) ! num
_ -> panic "getHistorySpan"
getModBreaks :: HomeModInfo -> ModBreaks
getModBreaks hmi
| Just linkable <- hm_linkable hmi,
[BCOs _ modBreaks] <- linkableUnlinked linkable
= modBreaks
| otherwise
= emptyModBreaks -- probably object code
{- | Finds the enclosing top level function name -}
-- ToDo: a better way to do this would be to keep hold of the decl_path computed
-- by the coverage pass, which gives the list of lexically-enclosing bindings
-- for each tick.
findEnclosingDecls :: HscEnv -> BreakInfo -> [String]
findEnclosingDecls hsc_env inf =
let hmi = expectJust "findEnclosingDecls" $
lookupUFM (hsc_HPT hsc_env) (moduleName $ breakInfo_module inf)
mb = getModBreaks hmi
in modBreaks_decls mb ! breakInfo_number inf
-- | Update fixity environment in the current interactive context.
updateFixityEnv :: GhcMonad m => FixityEnv -> m ()
updateFixityEnv fix_env = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
setSession $ hsc_env { hsc_IC = ic { ic_fix_env = fix_env } }
-- | Run a statement in the current interactive context. Statement
-- may bind multple values.
runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
runStmt = runStmtWithLocation "<interactive>" 1
-- | Run a statement in the current interactive context. Passing debug information
-- Statement may bind multple values.
runStmtWithLocation :: GhcMonad m => String -> Int ->
String -> SingleStep -> m RunResult
runStmtWithLocation source linenumber expr step =
do
hsc_env <- getSession
breakMVar <- liftIO $ newEmptyMVar -- wait on this when we hit a breakpoint
statusMVar <- liftIO $ newEmptyMVar -- wait on this when a computation is running
-- Turn off -fwarn-unused-bindings when running a statement, to hide
-- warnings about the implicit bindings we introduce.
let ic = hsc_IC hsc_env -- use the interactive dflags
idflags' = ic_dflags ic `wopt_unset` Opt_WarnUnusedBinds
hsc_env' = hsc_env{ hsc_IC = ic{ ic_dflags = idflags' } }
-- compile to value (IO [HValue]), don't run
r <- liftIO $ hscStmtWithLocation hsc_env' expr source linenumber
case r of
-- empty statement / comment
Nothing -> return (RunOk [])
Just (tyThings, hval, fix_env) -> do
updateFixityEnv fix_env
status <-
withVirtualCWD $
withBreakAction (isStep step) idflags' breakMVar statusMVar $ do
liftIO $ sandboxIO idflags' statusMVar hval
let ic = hsc_IC hsc_env
bindings = (ic_tythings ic, ic_rn_gbl_env ic)
size = ghciHistSize idflags'
handleRunStatus step expr bindings tyThings
breakMVar statusMVar status (emptyHistory size)
runDecls :: GhcMonad m => String -> m [Name]
runDecls = runDeclsWithLocation "<interactive>" 1
runDeclsWithLocation :: GhcMonad m => String -> Int -> String -> m [Name]
runDeclsWithLocation source linenumber expr =
do
hsc_env <- getSession
(tyThings, ic) <- liftIO $ hscDeclsWithLocation hsc_env expr source linenumber
setSession $ hsc_env { hsc_IC = ic }
hsc_env <- getSession
hsc_env' <- liftIO $ rttiEnvironment hsc_env
modifySession (\_ -> hsc_env')
return (map getName tyThings)
withVirtualCWD :: GhcMonad m => m a -> m a
withVirtualCWD m = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
let set_cwd = do
dir <- liftIO $ getCurrentDirectory
case ic_cwd ic of
Just dir -> liftIO $ setCurrentDirectory dir
Nothing -> return ()
return dir
reset_cwd orig_dir = do
virt_dir <- liftIO $ getCurrentDirectory
hsc_env <- getSession
let old_IC = hsc_IC hsc_env
setSession hsc_env{ hsc_IC = old_IC{ ic_cwd = Just virt_dir } }
liftIO $ setCurrentDirectory orig_dir
gbracket set_cwd reset_cwd $ \_ -> m
parseImportDecl :: GhcMonad m => String -> m (ImportDecl RdrName)
parseImportDecl expr = withSession $ \hsc_env -> liftIO $ hscImport hsc_env expr
emptyHistory :: Int -> BoundedList History
emptyHistory size = nilBL size
handleRunStatus :: GhcMonad m
=> SingleStep -> String-> ([TyThing],GlobalRdrEnv) -> [Id]
-> MVar () -> MVar Status -> Status -> BoundedList History
-> m RunResult
handleRunStatus step expr bindings final_ids
breakMVar statusMVar status history
| RunAndLogSteps <- step = tracing
| otherwise = not_tracing
where
tracing
| Break is_exception apStack info tid <- status
, not is_exception
= do
hsc_env <- getSession
b <- liftIO $ isBreakEnabled hsc_env info
if b
then not_tracing
-- This breakpoint is explicitly enabled; we want to stop
-- instead of just logging it.
else do
let history' = mkHistory hsc_env apStack info `consBL` history
-- probably better make history strict here, otherwise
-- our BoundedList will be pointless.
_ <- liftIO $ evaluate history'
status <- withBreakAction True (hsc_dflags hsc_env)
breakMVar statusMVar $ do
liftIO $ mask_ $ do
putMVar breakMVar () -- awaken the stopped thread
redirectInterrupts tid $
takeMVar statusMVar -- and wait for the result
handleRunStatus RunAndLogSteps expr bindings final_ids
breakMVar statusMVar status history'
| otherwise
= not_tracing
not_tracing
-- Hit a breakpoint
| Break is_exception apStack info tid <- status
= do
hsc_env <- getSession
let mb_info | is_exception = Nothing
| otherwise = Just info
(hsc_env1, names, span) <- liftIO $
bindLocalsAtBreakpoint hsc_env apStack mb_info
let
resume = Resume
{ resumeStmt = expr, resumeThreadId = tid
, resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
, resumeBindings = bindings, resumeFinalIds = final_ids
, resumeApStack = apStack, resumeBreakInfo = mb_info
, resumeSpan = span, resumeHistory = toListBL history
, resumeHistoryIx = 0 }
hsc_env2 = pushResume hsc_env1 resume
modifySession (\_ -> hsc_env2)
return (RunBreak tid names mb_info)
-- Completed with an exception
| Complete (Left e) <- status
= return (RunException e)
-- Completed successfully
| Complete (Right hvals) <- status
= do hsc_env <- getSession
let final_ic = extendInteractiveContext (hsc_IC hsc_env)
(map AnId final_ids)
final_names = map getName final_ids
liftIO $ Linker.extendLinkEnv (zip final_names hvals)
hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
modifySession (\_ -> hsc_env')
return (RunOk final_names)
| otherwise
= panic "handleRunStatus" -- The above cases are in fact exhaustive
isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
isBreakEnabled hsc_env inf =
case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
Just hmi -> do
w <- getBreak (hsc_dflags hsc_env)
(modBreaks_flags (getModBreaks hmi))
(breakInfo_number inf)
case w of Just n -> return (n /= 0); _other -> return False
_ ->
return False
foreign import ccall "&rts_stop_next_breakpoint" stepFlag :: Ptr CInt
foreign import ccall "&rts_stop_on_exception" exceptionFlag :: Ptr CInt
setStepFlag :: IO ()
setStepFlag = poke stepFlag 1
resetStepFlag :: IO ()
resetStepFlag = poke stepFlag 0
-- this points to the IO action that is executed when a breakpoint is hit
foreign import ccall "&rts_breakpoint_io_action"
breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ()))
-- When running a computation, we redirect ^C exceptions to the running
-- thread. ToDo: we might want a way to continue even if the target
-- thread doesn't die when it receives the exception... "this thread
-- is not responding".
--
-- Careful here: there may be ^C exceptions flying around, so we start the new
-- thread blocked (forkIO inherits mask from the parent, #1048), and unblock
-- only while we execute the user's code. We can't afford to lose the final
-- putMVar, otherwise deadlock ensues. (#1583, #1922, #1946)
sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
sandboxIO dflags statusMVar thing =
mask $ \restore -> -- fork starts blocked
let runIt = liftM Complete $ try (restore $ rethrow dflags thing)
in if gopt Opt_GhciSandbox dflags
then do tid <- forkIO $ do res <- runIt
putMVar statusMVar res -- empty: can't block
redirectInterrupts tid $
takeMVar statusMVar
else -- GLUT on OS X needs to run on the main thread. If you
-- try to use it from another thread then you just get a
-- white rectangle rendered. For this, or anything else
-- with such restrictions, you can turn the GHCi sandbox off
-- and things will be run in the main thread.
--
-- BUT, note that the debugging features (breakpoints,
-- tracing, etc.) need the expression to be running in a
-- separate thread, so debugging is only enabled when
-- using the sandbox.
runIt
--
-- While we're waiting for the sandbox thread to return a result, if
-- the current thread receives an asynchronous exception we re-throw
-- it at the sandbox thread and continue to wait.
--
-- This is for two reasons:
--
-- * So that ^C interrupts runStmt (e.g. in GHCi), allowing the
-- computation to run its exception handlers before returning the
-- exception result to the caller of runStmt.
--
-- * clients of the GHC API can terminate a runStmt in progress
-- without knowing the ThreadId of the sandbox thread (#1381)
--
-- NB. use a weak pointer to the thread, so that the thread can still
-- be considered deadlocked by the RTS and sent a BlockedIndefinitely
-- exception. A symptom of getting this wrong is that conc033(ghci)
-- will hang.
--
redirectInterrupts :: ThreadId -> IO a -> IO a
redirectInterrupts target wait
= do wtid <- mkWeakThreadId target
wait `catch` \e -> do
m <- deRefWeak wtid
case m of
Nothing -> wait
Just target -> do throwTo target (e :: SomeException); wait
-- We want to turn ^C into a break when -fbreak-on-exception is on,
-- but it's an async exception and we only break for sync exceptions.
-- Idea: if we catch and re-throw it, then the re-throw will trigger
-- a break. Great - but we don't want to re-throw all exceptions, because
-- then we'll get a double break for ordinary sync exceptions (you'd have
-- to :continue twice, which looks strange). So if the exception is
-- not "Interrupted", we unset the exception flag before throwing.
--
rethrow :: DynFlags -> IO a -> IO a
rethrow dflags io = Exception.catch io $ \se -> do
-- If -fbreak-on-error, we break unconditionally,
-- but with care of not breaking twice
if gopt Opt_BreakOnError dflags &&
not (gopt Opt_BreakOnException dflags)
then poke exceptionFlag 1
else case fromException se of
-- If it is a "UserInterrupt" exception, we allow
-- a possible break by way of -fbreak-on-exception
Just UserInterrupt -> return ()
-- In any other case, we don't want to break
_ -> poke exceptionFlag 0
Exception.throwIO se
-- This function sets up the interpreter for catching breakpoints, and
-- resets everything when the computation has stopped running. This
-- is a not-very-good way to ensure that only the interactive
-- evaluation should generate breakpoints.
withBreakAction :: (ExceptionMonad m, MonadIO m) =>
Bool -> DynFlags -> MVar () -> MVar Status -> m a -> m a
withBreakAction step dflags breakMVar statusMVar act
= gbracket (liftIO setBreakAction) (liftIO . resetBreakAction) (\_ -> act)
where
setBreakAction = do
stablePtr <- newStablePtr onBreak
poke breakPointIOAction stablePtr
when (gopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
when step $ setStepFlag
return stablePtr
-- Breaking on exceptions is not enabled by default, since it
-- might be a bit surprising. The exception flag is turned off
-- as soon as it is hit, or in resetBreakAction below.
onBreak is_exception info apStack = do
tid <- myThreadId
putMVar statusMVar (Break is_exception apStack info tid)
takeMVar breakMVar
resetBreakAction stablePtr = do
poke breakPointIOAction noBreakStablePtr
poke exceptionFlag 0
resetStepFlag
freeStablePtr stablePtr
noBreakStablePtr :: StablePtr (Bool -> BreakInfo -> HValue -> IO ())
noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
noBreakAction :: Bool -> BreakInfo -> HValue -> IO ()
noBreakAction False _ _ = putStrLn "*** Ignoring breakpoint"
noBreakAction True _ _ = return () -- exception: just continue
resume :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m RunResult
resume canLogSpan step
= do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> liftIO $
throwGhcExceptionIO (ProgramError "not stopped at a breakpoint")
(r:rs) -> do
-- unbind the temporary locals by restoring the TypeEnv from
-- before the breakpoint, and drop this Resume from the
-- InteractiveContext.
let (resume_tmp_te,resume_rdr_env) = resumeBindings r
ic' = ic { ic_tythings = resume_tmp_te,
ic_rn_gbl_env = resume_rdr_env,
ic_resume = rs }
modifySession (\_ -> hsc_env{ hsc_IC = ic' })
-- remove any bindings created since the breakpoint from the
-- linker's environment
let new_names = map getName (filter (`notElem` resume_tmp_te)
(ic_tythings ic))
liftIO $ Linker.deleteFromLinkEnv new_names
when (isStep step) $ liftIO setStepFlag
case r of
Resume { resumeStmt = expr, resumeThreadId = tid
, resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
, resumeBindings = bindings, resumeFinalIds = final_ids
, resumeApStack = apStack, resumeBreakInfo = info, resumeSpan = span
, resumeHistory = hist } -> do
withVirtualCWD $ do
withBreakAction (isStep step) (hsc_dflags hsc_env)
breakMVar statusMVar $ do
status <- liftIO $ mask_ $ do
putMVar breakMVar ()
-- this awakens the stopped thread...
redirectInterrupts tid $
takeMVar statusMVar
-- and wait for the result
let prevHistoryLst = fromListBL 50 hist
hist' = case info of
Nothing -> prevHistoryLst
Just i
| not $canLogSpan span -> prevHistoryLst
| otherwise -> mkHistory hsc_env apStack i `consBL`
fromListBL 50 hist
handleRunStatus step expr bindings final_ids
breakMVar statusMVar status hist'
back :: GhcMonad m => m ([Name], Int, SrcSpan)
back = moveHist (+1)
forward :: GhcMonad m => m ([Name], Int, SrcSpan)
forward = moveHist (subtract 1)
moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan)
moveHist fn = do
hsc_env <- getSession
case ic_resume (hsc_IC hsc_env) of
[] -> liftIO $
throwGhcExceptionIO (ProgramError "not stopped at a breakpoint")
(r:rs) -> do
let ix = resumeHistoryIx r
history = resumeHistory r
new_ix = fn ix
--
when (new_ix > length history) $ liftIO $
throwGhcExceptionIO (ProgramError "no more logged breakpoints")
when (new_ix < 0) $ liftIO $
throwGhcExceptionIO (ProgramError "already at the beginning of the history")
let
update_ic apStack mb_info = do
(hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env
apStack mb_info
let ic = hsc_IC hsc_env1
r' = r { resumeHistoryIx = new_ix }
ic' = ic { ic_resume = r':rs }
modifySession (\_ -> hsc_env1{ hsc_IC = ic' })
return (names, new_ix, span)
-- careful: we want apStack to be the AP_STACK itself, not a thunk
-- around it, hence the cases are carefully constructed below to
-- make this the case. ToDo: this is v. fragile, do something better.
if new_ix == 0
then case r of
Resume { resumeApStack = apStack,
resumeBreakInfo = mb_info } ->
update_ic apStack mb_info
else case history !! (new_ix - 1) of
History apStack info _ ->
update_ic apStack (Just info)
-- -----------------------------------------------------------------------------
-- After stopping at a breakpoint, add free variables to the environment
result_fs :: FastString
result_fs = fsLit "_result"
bindLocalsAtBreakpoint
:: HscEnv
-> HValue
-> Maybe BreakInfo
-> IO (HscEnv, [Name], SrcSpan)
-- Nothing case: we stopped when an exception was raised, not at a
-- breakpoint. We have no location information or local variables to
-- bind, all we can do is bind a local variable to the exception
-- value.
bindLocalsAtBreakpoint hsc_env apStack Nothing = do
let exn_fs = fsLit "_exception"
exn_name = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
e_fs = fsLit "e"
e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
e_tyvar = mkRuntimeUnkTyVar e_name liftedTypeKind
exn_id = AnId $ Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar)
ictxt0 = hsc_IC hsc_env
ictxt1 = extendInteractiveContext ictxt0 [exn_id]
span = mkGeneralSrcSpan (fsLit "<exception thrown>")
--
Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
-- Just case: we stopped at a breakpoint, we have information about the location
-- of the breakpoint and the free variables of the expression.
bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
let
mod_name = moduleName (breakInfo_module info)
hmi = expectJust "bindLocalsAtBreakpoint" $
lookupUFM (hsc_HPT hsc_env) mod_name
breaks = getModBreaks hmi
index = breakInfo_number info
vars = breakInfo_vars info
result_ty = breakInfo_resty info
occs = modBreaks_vars breaks ! index
span = modBreaks_locs breaks ! index
-- Filter out any unboxed ids;
-- we can't bind these at the prompt
pointers = filter (\(id,_) -> isPointer id) vars
isPointer id | UnaryRep ty <- repType (idType id)
, PtrRep <- typePrimRep ty = True
| otherwise = False
(ids, offsets) = unzip pointers
free_tvs = mapUnionVarSet (tyVarsOfType . idType) ids
`unionVarSet` tyVarsOfType result_ty
-- It might be that getIdValFromApStack fails, because the AP_STACK
-- has been accidentally evaluated, or something else has gone wrong.
-- So that we don't fall over in a heap when this happens, just don't
-- bind any free variables instead, and we emit a warning.
mb_hValues <- mapM (getIdValFromApStack apStack) (map fromIntegral offsets)
let filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
when (any isNothing mb_hValues) $
debugTraceMsg (hsc_dflags hsc_env) 1 $
text "Warning: _result has been evaluated, some bindings have been lost"
us <- mkSplitUniqSupply 'I'
let (us1, us2) = splitUniqSupply us
tv_subst = newTyVars us1 free_tvs
new_ids = zipWith3 (mkNewId tv_subst) occs filtered_ids (uniqsFromSupply us2)
names = map idName new_ids
-- make an Id for _result. We use the Unique of the FastString "_result";
-- we don't care about uniqueness here, because there will only be one
-- _result in scope at any time.
let result_name = mkInternalName (getUnique result_fs)
(mkVarOccFS result_fs) span
result_id = Id.mkVanillaGlobal result_name (substTy tv_subst result_ty)
-- for each Id we're about to bind in the local envt:
-- - tidy the type variables
-- - globalise the Id (Ids are supposed to be Global, apparently).
--
let result_ok = isPointer result_id
all_ids | result_ok = result_id : new_ids
| otherwise = new_ids
id_tys = map idType all_ids
(_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
final_ids = zipWith setIdType all_ids tidy_tys
ictxt0 = hsc_IC hsc_env
ictxt1 = extendInteractiveContext ictxt0 (map AnId final_ids)
Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
when result_ok $ Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
return (hsc_env1, if result_ok then result_name:names else names, span)
where
-- We need a fresh Unique for each Id we bind, because the linker
-- state is single-threaded and otherwise we'd spam old bindings
-- whenever we stop at a breakpoint. The InteractveContext is properly
-- saved/restored, but not the linker state. See #1743, test break026.
mkNewId :: TvSubst -> OccName -> Id -> Unique -> Id
mkNewId tv_subst occ id uniq
= Id.mkVanillaGlobalWithInfo name ty (idInfo id)
where
loc = nameSrcSpan (idName id)
name = mkInternalName uniq occ loc
ty = substTy tv_subst (idType id)
newTyVars :: UniqSupply -> TcTyVarSet -> TvSubst
-- Similarly, clone the type variables mentioned in the types
-- we have here, *and* make them all RuntimeUnk tyars
newTyVars us tvs
= mkTopTvSubst [ (tv, mkTyVarTy (mkRuntimeUnkTyVar name (tyVarKind tv)))
| (tv, uniq) <- varSetElems tvs `zip` uniqsFromSupply us
, let name = setNameUnique (tyVarName tv) uniq ]
rttiEnvironment :: HscEnv -> IO HscEnv
rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
let tmp_ids = [id | AnId id <- ic_tythings ic]
incompletelyTypedIds =
[id | id <- tmp_ids
, not $ noSkolems id
, (occNameFS.nameOccName.idName) id /= result_fs]
hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
return hsc_env'
where
noSkolems = isEmptyVarSet . tyVarsOfType . idType
improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
let tmp_ids = [id | AnId id <- ic_tythings ic]
Just id = find (\i -> idName i == name) tmp_ids
if noSkolems id
then return hsc_env
else do
mb_new_ty <- reconstructType hsc_env 10 id
let old_ty = idType id
case mb_new_ty of
Nothing -> return hsc_env
Just new_ty -> do
case improveRTTIType hsc_env old_ty new_ty of
Nothing -> return $
WARN(True, text (":print failed to calculate the "
++ "improvement for a type")) hsc_env
Just subst -> do
let dflags = hsc_dflags hsc_env
when (dopt Opt_D_dump_rtti dflags) $
printInfoForUser dflags alwaysQualify $
fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
let ic' = extendInteractiveContext
(substInteractiveContext ic subst) []
return hsc_env{hsc_IC=ic'}
getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
getIdValFromApStack apStack (I# stackDepth) = do
case getApStackVal# apStack (stackDepth +# 1#) of
-- The +1 is magic! I don't know where it comes
-- from, but this makes things line up. --SDM
(# ok, result #) ->
case ok of
0# -> return Nothing -- AP_STACK not found
_ -> return (Just (unsafeCoerce# result))
pushResume :: HscEnv -> Resume -> HscEnv
pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
where
ictxt0 = hsc_IC hsc_env
ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
-- -----------------------------------------------------------------------------
-- Abandoning a resume context
abandon :: GhcMonad m => m Bool
abandon = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> return False
r:rs -> do
modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = rs } }
liftIO $ abandon_ r
return True
abandonAll :: GhcMonad m => m Bool
abandonAll = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> return False
rs -> do
modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = [] } }
liftIO $ mapM_ abandon_ rs
return True
-- when abandoning a computation we have to
-- (a) kill the thread with an async exception, so that the
-- computation itself is stopped, and
-- (b) fill in the MVar. This step is necessary because any
-- thunks that were under evaluation will now be updated
-- with the partial computation, which still ends in takeMVar,
-- so any attempt to evaluate one of these thunks will block
-- unless we fill in the MVar.
-- (c) wait for the thread to terminate by taking its status MVar. This
-- step is necessary to prevent race conditions with
-- -fbreak-on-exception (see #5975).
-- See test break010.
abandon_ :: Resume -> IO ()
abandon_ r = do
killThread (resumeThreadId r)
putMVar (resumeBreakMVar r) ()
_ <- takeMVar (resumeStatMVar r)
return ()
-- -----------------------------------------------------------------------------
-- Bounded list, optimised for repeated cons
data BoundedList a = BL
{-# UNPACK #-} !Int -- length
{-# UNPACK #-} !Int -- bound
[a] -- left
[a] -- right, list is (left ++ reverse right)
nilBL :: Int -> BoundedList a
nilBL bound = BL 0 bound [] []
consBL :: a -> BoundedList a -> BoundedList a
consBL a (BL len bound left right)
| len < bound = BL (len+1) bound (a:left) right
| null right = BL len bound [a] $! tail (reverse left)
| otherwise = BL len bound (a:left) $! tail right
toListBL :: BoundedList a -> [a]
toListBL (BL _ _ left right) = left ++ reverse right
fromListBL :: Int -> [a] -> BoundedList a
fromListBL bound l = BL (length l) bound l []
-- lenBL (BL len _ _ _) = len
-- -----------------------------------------------------------------------------
-- | Set the interactive evaluation context.
--
-- (setContext imports) sets the ic_imports field (which in turn
-- determines what is in scope at the prompt) to 'imports', and
-- constructs the ic_rn_glb_env environment to reflect it.
--
-- We retain in scope all the things defined at the prompt, and kept
-- in ic_tythings. (Indeed, they shadow stuff from ic_imports.)
setContext :: GhcMonad m => [InteractiveImport] -> m ()
setContext imports
= do { hsc_env <- getSession
; let dflags = hsc_dflags hsc_env
; all_env_err <- liftIO $ findGlobalRdrEnv hsc_env imports
; case all_env_err of
Left (mod, err) ->
liftIO $ throwGhcExceptionIO (formatError dflags mod err)
Right all_env -> do {
; let old_ic = hsc_IC hsc_env
final_rdr_env = all_env `icExtendGblRdrEnv` ic_tythings old_ic
; modifySession $ \_ ->
hsc_env{ hsc_IC = old_ic { ic_imports = imports
, ic_rn_gbl_env = final_rdr_env }}}}
where
formatError dflags mod err = ProgramError . showSDoc dflags $
text "Cannot add module" <+> ppr mod <+>
text "to context:" <+> text err
findGlobalRdrEnv :: HscEnv -> [InteractiveImport]
-> IO (Either (ModuleName, String) GlobalRdrEnv)
-- Compute the GlobalRdrEnv for the interactive context
findGlobalRdrEnv hsc_env imports
= do { idecls_env <- hscRnImportDecls hsc_env idecls
-- This call also loads any orphan modules
; return $ case partitionEithers (map mkEnv imods) of
([], imods_env) -> Right (foldr plusGlobalRdrEnv idecls_env imods_env)
(err : _, _) -> Left err }
where
idecls :: [LImportDecl RdrName]
idecls = [noLoc d | IIDecl d <- imports]
imods :: [ModuleName]
imods = [m | IIModule m <- imports]
mkEnv mod = case mkTopLevEnv (hsc_HPT hsc_env) mod of
Left err -> Left (mod, err)
Right env -> Right env
availsToGlobalRdrEnv :: ModuleName -> [AvailInfo] -> GlobalRdrEnv
availsToGlobalRdrEnv mod_name avails
= mkGlobalRdrEnv (gresFromAvails imp_prov avails)
where
-- We're building a GlobalRdrEnv as if the user imported
-- all the specified modules into the global interactive module
imp_prov = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
is_qual = False,
is_dloc = srcLocSpan interactiveSrcLoc }
mkTopLevEnv :: HomePackageTable -> ModuleName -> Either String GlobalRdrEnv
mkTopLevEnv hpt modl
= case lookupUFM hpt modl of
Nothing -> Left "not a home module"
Just details ->
case mi_globals (hm_iface details) of
Nothing -> Left "not interpreted"
Just env -> Right env
-- | Get the interactive evaluation context, consisting of a pair of the
-- set of modules from which we take the full top-level scope, and the set
-- of modules from which we take just the exports respectively.
getContext :: GhcMonad m => m [InteractiveImport]
getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
return (ic_imports ic)
-- | Returns @True@ if the specified module is interpreted, and hence has
-- its full top-level scope available.
moduleIsInterpreted :: GhcMonad m => Module -> m Bool
moduleIsInterpreted modl = withSession $ \h ->
if modulePackageKey modl /= thisPackage (hsc_dflags h)
then return False
else case lookupUFM (hsc_HPT h) (moduleName modl) of
Just details -> return (isJust (mi_globals (hm_iface details)))
_not_a_home_module -> return False
-- | Looks up an identifier in the current interactive context (for :info)
-- Filter the instances by the ones whose tycons (or clases resp)
-- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
-- The exact choice of which ones to show, and which to hide, is a judgement call.
-- (see Trac #1581)
getInfo :: GhcMonad m => Bool -> Name -> m (Maybe (TyThing,Fixity,[ClsInst],[FamInst]))
getInfo allInfo name
= withSession $ \hsc_env ->
do mb_stuff <- liftIO $ hscTcRnGetInfo hsc_env name
case mb_stuff of
Nothing -> return Nothing
Just (thing, fixity, cls_insts, fam_insts) -> do
let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
-- Filter the instances based on whether the constituent names of their
-- instance heads are all in scope.
let cls_insts' = filter (plausible rdr_env . orphNamesOfClsInst) cls_insts
fam_insts' = filter (plausible rdr_env . orphNamesOfFamInst) fam_insts
return (Just (thing, fixity, cls_insts', fam_insts'))
where
plausible rdr_env names
-- Dfun involving only names that are in ic_rn_glb_env
= allInfo
|| all ok (nameSetToList names)
where -- A name is ok if it's in the rdr_env,
-- whether qualified or not
ok n | n == name = True -- The one we looked for in the first place!
| isBuiltInSyntax n = True
| isExternalName n = any ((== n) . gre_name)
(lookupGRE_Name rdr_env n)
| otherwise = True
-- | Returns all names in scope in the current interactive context
getNamesInScope :: GhcMonad m => m [Name]
getNamesInScope = withSession $ \hsc_env -> do
return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
getRdrNamesInScope :: GhcMonad m => m [RdrName]
getRdrNamesInScope = withSession $ \hsc_env -> do
let
ic = hsc_IC hsc_env
gbl_rdrenv = ic_rn_gbl_env ic
gbl_names = concatMap greToRdrNames $ globalRdrEnvElts gbl_rdrenv
return gbl_names
-- ToDo: move to RdrName
greToRdrNames :: GlobalRdrElt -> [RdrName]
greToRdrNames GRE{ gre_name = name, gre_prov = prov }
= case prov of
LocalDef -> [unqual]
Imported specs -> concat (map do_spec (map is_decl specs))
where
occ = nameOccName name
unqual = Unqual occ
do_spec decl_spec
| is_qual decl_spec = [qual]
| otherwise = [unqual,qual]
where qual = Qual (is_as decl_spec) occ
-- | Parses a string as an identifier, and returns the list of 'Name's that
-- the identifier can refer to in the current interactive context.
parseName :: GhcMonad m => String -> m [Name]
parseName str = withSession $ \hsc_env -> do
(L _ rdr_name) <- liftIO $ hscParseIdentifier hsc_env str
liftIO $ hscTcRnLookupRdrName hsc_env rdr_name
-- -----------------------------------------------------------------------------
-- Getting the type of an expression
-- | Get the type of an expression
-- Returns its most general type
exprType :: GhcMonad m => String -> m Type
exprType expr = withSession $ \hsc_env -> do
ty <- liftIO $ hscTcExpr hsc_env expr
return $ tidyType emptyTidyEnv ty
-- -----------------------------------------------------------------------------
-- Getting the kind of a type
-- | Get the kind of a type
typeKind :: GhcMonad m => Bool -> String -> m (Type, Kind)
typeKind normalise str = withSession $ \hsc_env -> do
liftIO $ hscKcType hsc_env normalise str
-----------------------------------------------------------------------------
-- Compile an expression, run it and deliver the resulting HValue
compileExpr :: GhcMonad m => String -> m HValue
compileExpr expr = withSession $ \hsc_env -> do
Just (ids, hval, fix_env) <- liftIO $ hscStmt hsc_env ("let __cmCompileExpr = "++expr)
updateFixityEnv fix_env
hvals <- liftIO hval
case (ids,hvals) of
([_],[hv]) -> return hv
_ -> panic "compileExpr"
-- -----------------------------------------------------------------------------
-- Compile an expression, run it and return the result as a dynamic
dynCompileExpr :: GhcMonad m => String -> m Dynamic
dynCompileExpr expr = do
iis <- getContext
let importDecl = ImportDecl {
ideclName = noLoc (mkModuleName "Data.Dynamic"),
ideclPkgQual = Nothing,
ideclSource = False,
ideclSafe = False,
ideclQualified = True,
ideclImplicit = False,
ideclAs = Nothing,
ideclHiding = Nothing
}
setContext (IIDecl importDecl : iis)
let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
Just (ids, hvals, fix_env) <- withSession $ \hsc_env ->
liftIO $ hscStmt hsc_env stmt
setContext iis
updateFixityEnv fix_env
vals <- liftIO (unsafeCoerce# hvals :: IO [Dynamic])
case (ids,vals) of
(_:[], v:[]) -> return v
_ -> panic "dynCompileExpr"
-----------------------------------------------------------------------------
-- show a module and it's source/object filenames
showModule :: GhcMonad m => ModSummary -> m String
showModule mod_summary =
withSession $ \hsc_env -> do
interpreted <- isModuleInterpreted mod_summary
let dflags = hsc_dflags hsc_env
return (showModMsg dflags (hscTarget dflags) interpreted mod_summary)
isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
isModuleInterpreted mod_summary = withSession $ \hsc_env ->
case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
Nothing -> panic "missing linkable"
Just mod_info -> return (not obj_linkable)
where
obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
----------------------------------------------------------------------------
-- RTTI primitives
obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
obtainTermFromVal hsc_env bound force ty x =
cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
obtainTermFromId hsc_env bound force id = do
hv <- Linker.getHValue hsc_env (varName id)
cvObtainTerm hsc_env bound force (idType id) hv
-- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
reconstructType hsc_env bound id = do
hv <- Linker.getHValue hsc_env (varName id)
cvReconstructType hsc_env bound (idType id) hv
mkRuntimeUnkTyVar :: Name -> Kind -> TyVar
mkRuntimeUnkTyVar name kind = mkTcTyVar name kind RuntimeUnk
#endif /* GHCI */
| spacekitteh/smcghc | compiler/main/InteractiveEval.hs | bsd-3-clause | 41,737 | 13 | 34 | 11,896 | 8,995 | 4,601 | 4,394 | 2 | 0 |
{-# LANGUAGE OverlappingInstances, TypeSynonymInstances #-}
-- |
-- Module : Data.BERT.Parser
-- Copyright : (c) marius a. eriksen 2009
--
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- Parse (simple) BERTs.
module Data.BERT.Parser
( parseTerm
) where
import Data.Char (ord)
import Control.Applicative
import Control.Monad (MonadPlus(..), ap)
import Numeric (readSigned, readFloat, readDec)
import Control.Monad (liftM)
import Text.ParserCombinators.Parsec hiding (many, optional, (<|>))
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as C
import Data.BERT.Types (Term(..))
--instance Applicative (GenParser s a) where
-- pure = return
-- (<*>) = ap
--instance Alternative (GenParser s a) where
-- empty = mzero
-- (<|>) = mplus
-- | Parse a simple BERT (erlang) term from a string in the erlang
-- grammar. Does not attempt to decompose complex terms.
parseTerm :: String -> Either ParseError Term
parseTerm = parse p_term "term"
p_term :: Parser Term
p_term = t <* spaces
where
t = IntTerm <$> p_num (readSigned readDec)
<|> FloatTerm <$> p_num (readSigned readFloat)
<|> AtomTerm <$> p_atom
<|> TupleTerm <$> p_tuple
<|> BytelistTerm . C.pack <$> p_string
<|> ListTerm <$> p_list
<|> BinaryTerm . B.pack <$> p_binary
p_num which = do
s <- getInput
case which s of
[(n, s')] -> n <$ setInput s'
_ -> empty
p_atom = unquoted <|> quoted
where
unquoted = many1 $ lower <|> oneOf ['_', '@']
quoted = quote >> many1 letter <* quote
quote = char '\''
p_seq open close elem =
between (open >> spaces) (spaces >> close) $
elem `sepBy` (spaces >> char ',' >> spaces)
p_tuple = p_seq (char '{') (char '}') p_term
p_list = p_seq (char '[') (char ']') p_term
p_string = char '"' >> many strchar <* char '"'
where
strchar = noneOf ['\\', '"'] <|> (char '\\' >> anyChar)
p_binary = string "<<" >> (bstr <|> bseq) <* string ">>"
where
bseq = (p_num readDec) `sepBy` (spaces >> char ',' >> spaces)
bstr = map (fromIntegral . ord) <$> p_string
| mariusae/bert | Data/BERT/Parser.hs | bsd-3-clause | 2,257 | 0 | 24 | 558 | 614 | 342 | 272 | -1 | -1 |
module Distribution.Server.Features.PackageContents (
PackageContentsFeature,
PackageContentsResource(..),
initPackageContentsFeature
) where
import Distribution.Server.Framework
import Distribution.Server.Features.Check
import Distribution.Server.Features.Core
import Distribution.Server.Packages.Types
import Distribution.Server.Framework.BlobStorage (BlobStorage)
import Distribution.Server.Util.ChangeLog (lookupTarball, lookupChangeLog)
import qualified Distribution.Server.Util.ServeTarball as TarIndex
import Data.TarIndex (TarIndex)
import Distribution.Text
import Distribution.Package
import Control.Monad.Trans
-- FIXME: cache TarIndexes?
data PackageContentsFeature = PackageContentsFeature {
featureInterface :: HackageFeature,
packageContentsResource :: PackageContentsResource
}
data PackageContentsResource = PackageContentsResource {
packageContents :: Resource,
packageContentsCandidate :: Resource,
packageContentsChangeLog :: Resource,
packageContentsCandidateChangeLog :: Resource,
packageContentsChangeLogUri :: PackageId -> String,
packageContentsCandidateChangeLogUri :: PackageId -> String
}
instance IsHackageFeature PackageContentsFeature where
getFeatureInterface = featureInterface
initPackageContentsFeature :: ServerEnv -> CoreFeature -> CheckFeature -> IO PackageContentsFeature
initPackageContentsFeature env _ _ = do
let store = serverBlobStore env
resources = PackageContentsResource {
packageContents = (resourceAt "/package/:package/src/..") { resourceGet = [("", serveContents store)] }
, packageContentsCandidate = (resourceAt "/package/:package/candidate/src/..") { resourceGet = [("", serveCandidateContents store)] }
, packageContentsChangeLog = (resourceAt "/package/:package/changelog") { resourceGet = [("changelog", serveChangeLog store)] }
, packageContentsCandidateChangeLog = (resourceAt "/package/:package/candidate/changelog") { resourceGet = [("changelog", serveCandidateChangeLog store)] }
, packageContentsChangeLogUri = \pkgid -> renderResource (packageContentsChangeLog resources) [display pkgid, display (packageName pkgid)]
, packageContentsCandidateChangeLogUri = \pkgid -> renderResource (packageContentsCandidateChangeLog resources) [display pkgid, display (packageName pkgid)]
}
return PackageContentsFeature {
featureInterface = (emptyHackageFeature "package-contents") {
featureResources = map ($ resources) [packageContents, packageContentsCandidate, packageContentsChangeLog, packageContentsCandidateChangeLog]
}
, packageContentsResource = resources
}
--TODO: use something other than runServerPartE for nice html error pages
withPackagePath', withCandidatePath' :: DynamicPath -> (PkgInfo -> ServerPartE a) -> ServerPartE a
withPackagePath' dpath k = withPackagePath dpath $ \pkg _ -> k pkg
withCandidatePath' dpath k = withCandidatePath dpath $ \_ pkg -> k (candPkgInfo pkg)
-- result: changelog or not-found error
serveChangeLog, serveCandidateChangeLog :: BlobStorage -> DynamicPath -> ServerPart Response
serveChangeLog = serveChangeLog' withPackagePath'
serveCandidateChangeLog = serveChangeLog' withCandidatePath'
serveChangeLog' :: (DynamicPath -> ((PkgInfo -> ServerPartE Response) -> ServerPartE Response))
-> BlobStorage -> DynamicPath -> ServerPart Response
serveChangeLog' with_pkg_path store dpath = runServerPartE $ with_pkg_path dpath $ \pkg -> do
res <- liftIO $ lookupChangeLog store pkg
case res of
Left err -> errNotFound "Changelog not found" [MText err]
Right (fp, offset, name) -> liftIO $ TarIndex.serveTarEntry fp offset name
-- return: not-found error or tarball
serveContents, serveCandidateContents :: BlobStorage -> DynamicPath -> ServerPart Response
serveContents = serveContents' withPackagePath'
serveCandidateContents = serveContents' withCandidatePath'
serveContents' :: (DynamicPath -> ((PkgInfo -> ServerPartE Response) -> ServerPartE Response))
-> BlobStorage -> DynamicPath -> ServerPart Response
serveContents' with_pkg_path store dpath = runServerPartE $ withContents $ \pkgid tarball index -> do
-- if given a directory, the default page is index.html
-- the default directory prefix is the package name itself (including the version)
TarIndex.serveTarball ["index.html"] (display pkgid) tarball index
where
withContents :: (PackageId -> FilePath -> TarIndex -> ServerPartE Response) -> ServerPartE Response
withContents func = with_pkg_path dpath $ \pkg ->
case lookupTarball store pkg of
Nothing -> fail "Could not serve package contents: no tarball exists."
Just io -> liftIO io >>= \(fp, index) -> func (packageId pkg) fp index
| isomorphism/hackage2 | Distribution/Server/Features/PackageContents.hs | bsd-3-clause | 4,954 | 0 | 17 | 893 | 1,034 | 568 | 466 | 66 | 2 |
module Code.Check where
-- $Id$
import Code.Type
import Autolib.ToDoc
import Autolib.Set
import Autolib.FiniteMap
import qualified Autolib.Reporter.Checker as C
import qualified Autolib.Reporter.Set
import Autolib.Reporter
import Data.List
import Control.Monad
istotal :: ( ToDoc b, ToDoc a, Ord a )
=> Set a
-> Code a b
-> Reporter ()
istotal xs c @ ( Code code ) = do
inform $ fsep
[ text "ist", toDoc c, text "vollständig"
, text "für", toDoc xs, text "?"
]
nested 4 $ Autolib.Reporter.Set.subeq
( text "zu codierende Buchstaben" , xs )
( text "tatsächlich codierte Buchstaben", mkSet $ keysFM code )
isprefix :: ( ToDoc a, ToDoc b, Ord a, Eq b )
=> Code a b
-> Reporter ()
isprefix c @ ( Code code ) = do
inform $ fsep [ text "ist", toDoc c, text "ein Präfix-Code?"]
sequence_ $ do
(x, cs) <- fmToList code
(y, ds) <- fmToList code
let msg (x, cs) = text "code" <+> parens ( toDoc x)
<+> equals <+> toDoc cs
guard $ x /= y
return $ do
when ( isPrefixOf cs ds ) $ reject $ fsep
[ text "Nein:"
, msg (x, cs) , text "ist Präfix von", msg (y, ds)
]
inform $ text "Ja."
| florianpilz/autotool | src/Code/Check.hs | gpl-2.0 | 1,261 | 10 | 23 | 391 | 490 | 247 | 243 | 37 | 1 |
import System.Environment
import System.IO
import Data.List.Split hiding (oneOf)
import Text.ParserCombinators.Parsec
import Control.Monad
import Data.ByteString.Lazy.Char8 as BS hiding (filter,last,zip,head,drop,reverse,concat)
import Control.Applicative hiding ((<|>), many)
import Text.Printf
{--
divsen(Open usp Tukubai)
designed by Nobuaki Tounaka
written by Ryuichi Ueda
The MIT License
Copyright (C) 2012 Universal Shell Programming Laboratory
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--}
showUsage :: IO ()
showUsage = do System.IO.hPutStr stderr ("Usage : divsen <f1> <f2> ... <file>\n" ++
"Tue Jul 30 14:54:45 JST 2013\n" ++
"Open usp Tukubai (LINUX+FREEBSD), Haskell ver.\n")
main :: IO ()
main = do args <- getArgs
case args of
["-h"] -> showUsage
["--help"] -> showUsage
_ -> mainProc (setOpts args)
readF :: String -> IO BS.ByteString
readF "-" = BS.getContents
readF f = BS.readFile f
mainProc :: Opts -> IO ()
mainProc (Opts s fs file) = readF file >>= mainProc' s fs
mainProc' :: Char -> [Int] -> BS.ByteString -> IO ()
mainProc' s fs str = BS.putStr $ BS.unlines [ mainProc'' s fs ln | ln <- BS.lines str]
mainProc'' :: Char -> [Int] -> BS.ByteString -> BS.ByteString
mainProc'' s fs ln = BS.unwords [ fnc fs w | w <- zip [1..] (myWords ln)]
where fnc fs (n,w) = if filter ( == n) fs == []
then w
else BS.pack $ divsen s $ BS.unpack w
divsen :: Char -> String -> String
divsen 's' cs = printf "%f" $ (read cs::Double) / 1000
divsen s ('-':cs) = '-' : divsen s cs
divsen '0' cs = show m'
where n = read (head $ splitOn "." cs)::Int
m = n `div` 1000
m' = if n - (m*1000) < 500 then m else m + 1
myWords :: BS.ByteString -> [BS.ByteString]
myWords line = filter (/= (BS.pack "")) $ BS.split ' ' line
data Opts = Opts Char [Int] String | Error String deriving Show
setOpts :: [String] -> Opts
setOpts as = case parse args "" ((Prelude.unwords as) ++ " ") of
Right opt -> opt
Left err -> Error ( show err )
args = do Opts <$> sflg <*> (many1 $ try field) <*> (try(filename) <|> return "-")
sflg = try(string "-s " >> return 's') <|> return '0'
field = do a <- many1 digit
char ' '
return (read a::Int)
filename = many1 ( try(letter) <|> try(digit) <|> symbol ) >>= return
symbol = oneOf "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
| ShellShoccar-jpn/Open-usp-Tukubai | COMMANDS.HS/divsen.hs | mit | 3,554 | 0 | 12 | 883 | 922 | 480 | 442 | 51 | 3 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>Список каталогов v1.0 </title>
<maps>
<homeID>directorylistv1</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/directorylistv1/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 1,026 | 78 | 66 | 158 | 494 | 248 | 246 | -1 | -1 |
module HAD.Y2014.M03.D14.Exercise where
-- $setup
-- >>> import Control.Applicative
-- >>> let s2 = ([id,(+1)] <*>) . pure
-- | groupByStraights Group elements in a list by "straights"
-- i.e: consecutive elements are grouped together.
--
-- Examples:
--
-- >>> groupByStraights [1,2,5,6,8]
-- [[1,2],[5,6],[8]]
--
-- >>> take 3 . groupByStraights $ [0..] >>= s2
-- [[0,1],[1,2],[2,3]]
--
-- >>> take 4 . groupByStraights $ "abbccddeeeeeeeeeee"
-- ["ab","bc","cd","de"]
--
-- groupByStraights :: START HERE
groupByStraights = undefined
| 1HaskellADay/1HAD | exercises/HAD/Y2014/M03/D14/Exercise.hs | mit | 539 | 0 | 4 | 81 | 32 | 28 | 4 | 2 | 1 |
{-# LANGUAGE ExistentialQuantification, MultiParamTypeClasses #-}
module ExTy where
class Show (layout a) => LayoutClass layout a where
data Layout a = forall l. Layout (l a)
readsLayout :: Layout a -> String -> Layout a
readsLayout (Layout l) s = Layout (asTypeOf undefined l)
type Size = Int
data Step s a = S s a
data Stream a =
forall s. Stream
(s -> Step s a) -- stepper function
!s -- current state
!Size -- size hint
foo :: Stream a -> Size
foo (Stream _ _ s) = s
stream = Stream (\_ -> S 1 True) 0 0
| mightymoose/liquidhaskell | tests/pos/extype.hs | bsd-3-clause | 593 | 0 | 9 | 187 | 206 | 109 | 97 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, Rank2Types, ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Data
-- Copyright : (c) The University of Glasgow, CWI 2001--2004
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (local universal quantification)
--
-- \"Scrap your boilerplate\" --- Generic programming in Haskell.
-- See <http://www.cs.vu.nl/boilerplate/>. This module provides
-- the 'Data' class with its primitives for generic programming, along
-- with instances for many datatypes. It corresponds to a merge between
-- the previous "Data.Generics.Basics" and almost all of
-- "Data.Generics.Instances". The instances that are not present
-- in this module were moved to the @Data.Generics.Instances@ module
-- in the @syb@ package.
--
-- For more information, please visit the new
-- SYB wiki: <http://www.cs.uu.nl/wiki/bin/view/GenericProgramming/SYB>.
--
-----------------------------------------------------------------------------
module Data.Data (
-- * Module Data.Typeable re-exported for convenience
module Data.Typeable,
-- * The Data class for processing constructor applications
Data(
gfoldl, -- :: ... -> a -> c a
gunfold, -- :: ... -> Constr -> c a
toConstr, -- :: a -> Constr
dataTypeOf, -- :: a -> DataType
dataCast1, -- mediate types and unary type constructors
dataCast2, -- mediate types and binary type constructors
-- Generic maps defined in terms of gfoldl
gmapT,
gmapQ,
gmapQl,
gmapQr,
gmapQi,
gmapM,
gmapMp,
gmapMo
),
-- * Datatype representations
DataType, -- abstract, instance of: Show
-- ** Constructors
mkDataType, -- :: String -> [Constr] -> DataType
mkIntType, -- :: String -> DataType
mkFloatType, -- :: String -> DataType
mkStringType, -- :: String -> DataType
mkCharType, -- :: String -> DataType
mkNoRepType, -- :: String -> DataType
mkNorepType, -- :: String -> DataType
-- ** Observers
dataTypeName, -- :: DataType -> String
DataRep(..), -- instance of: Eq, Show
dataTypeRep, -- :: DataType -> DataRep
-- ** Convenience functions
repConstr, -- :: DataType -> ConstrRep -> Constr
isAlgType, -- :: DataType -> Bool
dataTypeConstrs,-- :: DataType -> [Constr]
indexConstr, -- :: DataType -> ConIndex -> Constr
maxConstrIndex, -- :: DataType -> ConIndex
isNorepType, -- :: DataType -> Bool
-- * Data constructor representations
Constr, -- abstract, instance of: Eq, Show
ConIndex, -- alias for Int, start at 1
Fixity(..), -- instance of: Eq, Show
-- ** Constructors
mkConstr, -- :: DataType -> String -> Fixity -> Constr
mkIntConstr, -- :: DataType -> Integer -> Constr
mkFloatConstr, -- :: DataType -> Double -> Constr
mkIntegralConstr,-- :: (Integral a) => DataType -> a -> Constr
mkRealConstr, -- :: (Real a) => DataType -> a -> Constr
mkStringConstr, -- :: DataType -> String -> Constr
mkCharConstr, -- :: DataType -> Char -> Constr
-- ** Observers
constrType, -- :: Constr -> DataType
ConstrRep(..), -- instance of: Eq, Show
constrRep, -- :: Constr -> ConstrRep
constrFields, -- :: Constr -> [String]
constrFixity, -- :: Constr -> Fixity
-- ** Convenience function: algebraic data types
constrIndex, -- :: Constr -> ConIndex
-- ** From strings to constructors and vice versa: all data types
showConstr, -- :: Constr -> String
readConstr, -- :: DataType -> String -> Maybe Constr
-- * Convenience functions: take type constructors apart
tyconUQname, -- :: String -> String
tyconModule, -- :: String -> String
-- * Generic operations defined in terms of 'gunfold'
fromConstr, -- :: Constr -> a
fromConstrB, -- :: ... -> Constr -> a
fromConstrM -- :: Monad m => ... -> Constr -> m a
) where
------------------------------------------------------------------------------
import Prelude -- necessary to get dependencies right
import Data.Typeable
import Data.Maybe
import Control.Monad
-- Imports for the instances
import Data.Int -- So we can give Data instance for Int8, ...
import Data.Word -- So we can give Data instance for Word8, ...
#ifdef __GLASGOW_HASKELL__
import GHC.Real( Ratio(..) ) -- So we can give Data instance for Ratio
--import GHC.IOBase -- So we can give Data instance for IO, Handle
import GHC.Ptr -- So we can give Data instance for Ptr
import GHC.ForeignPtr -- So we can give Data instance for ForeignPtr
--import GHC.Stable -- So we can give Data instance for StablePtr
--import GHC.ST -- So we can give Data instance for ST
--import GHC.Conc -- So we can give Data instance for MVar & Co.
import GHC.Arr -- So we can give Data instance for Array
#else
# ifdef __HUGS__
import Hugs.Prelude( Ratio(..) )
# endif
import Foreign.Ptr
import Foreign.ForeignPtr
import Data.Array
#endif
#include "Typeable.h"
------------------------------------------------------------------------------
--
-- The Data class
--
------------------------------------------------------------------------------
{- |
The 'Data' class comprehends a fundamental primitive 'gfoldl' for
folding over constructor applications, say terms. This primitive can
be instantiated in several ways to map over the immediate subterms
of a term; see the @gmap@ combinators later in this class. Indeed, a
generic programmer does not necessarily need to use the ingenious gfoldl
primitive but rather the intuitive @gmap@ combinators. The 'gfoldl'
primitive is completed by means to query top-level constructors, to
turn constructor representations into proper terms, and to list all
possible datatype constructors. This completion allows us to serve
generic programming scenarios like read, show, equality, term generation.
The combinators 'gmapT', 'gmapQ', 'gmapM', etc are all provided with
default definitions in terms of 'gfoldl', leaving open the opportunity
to provide datatype-specific definitions.
(The inclusion of the @gmap@ combinators as members of class 'Data'
allows the programmer or the compiler to derive specialised, and maybe
more efficient code per datatype. /Note/: 'gfoldl' is more higher-order
than the @gmap@ combinators. This is subject to ongoing benchmarking
experiments. It might turn out that the @gmap@ combinators will be
moved out of the class 'Data'.)
Conceptually, the definition of the @gmap@ combinators in terms of the
primitive 'gfoldl' requires the identification of the 'gfoldl' function
arguments. Technically, we also need to identify the type constructor
@c@ for the construction of the result type from the folded term type.
In the definition of @gmapQ@/x/ combinators, we use phantom type
constructors for the @c@ in the type of 'gfoldl' because the result type
of a query does not involve the (polymorphic) type of the term argument.
In the definition of 'gmapQl' we simply use the plain constant type
constructor because 'gfoldl' is left-associative anyway and so it is
readily suited to fold a left-associative binary operation over the
immediate subterms. In the definition of gmapQr, extra effort is
needed. We use a higher-order accumulation trick to mediate between
left-associative constructor application vs. right-associative binary
operation (e.g., @(:)@). When the query is meant to compute a value
of type @r@, then the result type withing generic folding is @r -> r@.
So the result of folding is a function to which we finally pass the
right unit.
With the @-XDeriveDataTypeable@ option, GHC can generate instances of the
'Data' class automatically. For example, given the declaration
> data T a b = C1 a b | C2 deriving (Typeable, Data)
GHC will generate an instance that is equivalent to
> instance (Data a, Data b) => Data (T a b) where
> gfoldl k z (C1 a b) = z C1 `k` a `k` b
> gfoldl k z C2 = z C2
>
> gunfold k z c = case constrIndex c of
> 1 -> k (k (z C1))
> 2 -> z C2
>
> toConstr (C1 _ _) = con_C1
> toConstr C2 = con_C2
>
> dataTypeOf _ = ty_T
>
> con_C1 = mkConstr ty_T "C1" [] Prefix
> con_C2 = mkConstr ty_T "C2" [] Prefix
> ty_T = mkDataType "Module.T" [con_C1, con_C2]
This is suitable for datatypes that are exported transparently.
-}
class Typeable a => Data a where
-- | Left-associative fold operation for constructor applications.
--
-- The type of 'gfoldl' is a headache, but operationally it is a simple
-- generalisation of a list fold.
--
-- The default definition for 'gfoldl' is @'const' 'id'@, which is
-- suitable for abstract datatypes with no substructures.
gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b)
-- ^ defines how nonempty constructor applications are
-- folded. It takes the folded tail of the constructor
-- application and its head, i.e., an immediate subterm,
-- and combines them in some way.
-> (forall g. g -> c g)
-- ^ defines how the empty constructor application is
-- folded, like the neutral \/ start element for list
-- folding.
-> a
-- ^ structure to be folded.
-> c a
-- ^ result, with a type defined in terms of @a@, but
-- variability is achieved by means of type constructor
-- @c@ for the construction of the actual result type.
-- See the 'Data' instances in this file for an illustration of 'gfoldl'.
gfoldl _ z = z
-- | Unfolding constructor applications
gunfold :: (forall b r. Data b => c (b -> r) -> c r)
-> (forall r. r -> c r)
-> Constr
-> c a
-- | Obtaining the constructor from a given datum.
-- For proper terms, this is meant to be the top-level constructor.
-- Primitive datatypes are here viewed as potentially infinite sets of
-- values (i.e., constructors).
toConstr :: a -> Constr
-- | The outer type constructor of the type
dataTypeOf :: a -> DataType
------------------------------------------------------------------------------
--
-- Mediate types and type constructors
--
------------------------------------------------------------------------------
-- | Mediate types and unary type constructors.
-- In 'Data' instances of the form @T a@, 'dataCast1' should be defined
-- as 'gcast1'.
--
-- The default definition is @'const' 'Nothing'@, which is appropriate
-- for non-unary type constructors.
dataCast1 :: Typeable1 t
=> (forall d. Data d => c (t d))
-> Maybe (c a)
dataCast1 _ = Nothing
-- | Mediate types and binary type constructors.
-- In 'Data' instances of the form @T a b@, 'dataCast2' should be
-- defined as 'gcast2'.
--
-- The default definition is @'const' 'Nothing'@, which is appropriate
-- for non-binary type constructors.
dataCast2 :: Typeable2 t
=> (forall d e. (Data d, Data e) => c (t d e))
-> Maybe (c a)
dataCast2 _ = Nothing
------------------------------------------------------------------------------
--
-- Typical generic maps defined in terms of gfoldl
--
------------------------------------------------------------------------------
-- | A generic transformation that maps over the immediate subterms
--
-- The default definition instantiates the type constructor @c@ in the
-- type of 'gfoldl' to an identity datatype constructor, using the
-- isomorphism pair as injection and projection.
gmapT :: (forall b. Data b => b -> b) -> a -> a
-- Use an identity datatype constructor ID (see below)
-- to instantiate the type constructor c in the type of gfoldl,
-- and perform injections ID and projections unID accordingly.
--
gmapT f x0 = unID (gfoldl k ID x0)
where
k :: Data d => ID (d->b) -> d -> ID b
k (ID c) x = ID (c (f x))
-- | A generic query with a left-associative binary operator
gmapQl :: forall r r'. (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> a -> r
gmapQl o r f = unCONST . gfoldl k z
where
k :: Data d => CONST r (d->b) -> d -> CONST r b
k c x = CONST $ (unCONST c) `o` f x
z :: g -> CONST r g
z _ = CONST r
-- | A generic query with a right-associative binary operator
gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> a -> r
gmapQr o r0 f x0 = unQr (gfoldl k (const (Qr id)) x0) r0
where
k :: Data d => Qr r (d->b) -> d -> Qr r b
k (Qr c) x = Qr (\r -> c (f x `o` r))
-- | A generic query that processes the immediate subterms and returns a list
-- of results. The list is given in the same order as originally specified
-- in the declaratoin of the data constructors.
gmapQ :: (forall d. Data d => d -> u) -> a -> [u]
gmapQ f = gmapQr (:) [] f
-- | A generic query that processes one child by index (zero-based)
gmapQi :: forall u. Int -> (forall d. Data d => d -> u) -> a -> u
gmapQi i f x = case gfoldl k z x of { Qi _ q -> fromJust q }
where
k :: Data d => Qi u (d -> b) -> d -> Qi u b
k (Qi i' q) a = Qi (i'+1) (if i==i' then Just (f a) else q)
z :: g -> Qi q g
z _ = Qi 0 Nothing
-- | A generic monadic transformation that maps over the immediate subterms
--
-- The default definition instantiates the type constructor @c@ in
-- the type of 'gfoldl' to the monad datatype constructor, defining
-- injection and projection using 'return' and '>>='.
gmapM :: forall m. Monad m => (forall d. Data d => d -> m d) -> a -> m a
-- Use immediately the monad datatype constructor
-- to instantiate the type constructor c in the type of gfoldl,
-- so injection and projection is done by return and >>=.
--
gmapM f = gfoldl k return
where
k :: Data d => m (d -> b) -> d -> m b
k c x = do c' <- c
x' <- f x
return (c' x')
-- | Transformation of at least one immediate subterm does not fail
gmapMp :: forall m. MonadPlus m => (forall d. Data d => d -> m d) -> a -> m a
{-
The type constructor that we use here simply keeps track of the fact
if we already succeeded for an immediate subterm; see Mp below. To
this end, we couple the monadic computation with a Boolean.
-}
gmapMp f x = unMp (gfoldl k z x) >>= \(x',b) ->
if b then return x' else mzero
where
z :: g -> Mp m g
z g = Mp (return (g,False))
k :: Data d => Mp m (d -> b) -> d -> Mp m b
k (Mp c) y
= Mp ( c >>= \(h, b) ->
(f y >>= \y' -> return (h y', True))
`mplus` return (h y, b)
)
-- | Transformation of one immediate subterm with success
gmapMo :: forall m. MonadPlus m => (forall d. Data d => d -> m d) -> a -> m a
{-
We use the same pairing trick as for gmapMp,
i.e., we use an extra Bool component to keep track of the
fact whether an immediate subterm was processed successfully.
However, we cut of mapping over subterms once a first subterm
was transformed successfully.
-}
gmapMo f x = unMp (gfoldl k z x) >>= \(x',b) ->
if b then return x' else mzero
where
z :: g -> Mp m g
z g = Mp (return (g,False))
k :: Data d => Mp m (d -> b) -> d -> Mp m b
k (Mp c) y
= Mp ( c >>= \(h,b) -> if b
then return (h y, b)
else (f y >>= \y' -> return (h y',True))
`mplus` return (h y, b)
)
-- | The identity type constructor needed for the definition of gmapT
newtype ID x = ID { unID :: x }
-- | The constant type constructor needed for the definition of gmapQl
newtype CONST c a = CONST { unCONST :: c }
-- | Type constructor for adding counters to queries
data Qi q a = Qi Int (Maybe q)
-- | The type constructor used in definition of gmapQr
newtype Qr r a = Qr { unQr :: r -> r }
-- | The type constructor used in definition of gmapMp
newtype Mp m x = Mp { unMp :: m (x, Bool) }
------------------------------------------------------------------------------
--
-- Generic unfolding
--
------------------------------------------------------------------------------
-- | Build a term skeleton
fromConstr :: Data a => Constr -> a
fromConstr = fromConstrB (error "Data.Data.fromConstr")
-- | Build a term and use a generic function for subterms
fromConstrB :: Data a
=> (forall d. Data d => d)
-> Constr
-> a
fromConstrB f = unID . gunfold k z
where
k :: forall b r. Data b => ID (b -> r) -> ID r
k c = ID (unID c f)
z :: forall r. r -> ID r
z = ID
-- | Monadic variation on 'fromConstrB'
fromConstrM :: forall m a. (Monad m, Data a)
=> (forall d. Data d => m d)
-> Constr
-> m a
fromConstrM f = gunfold k z
where
k :: forall b r. Data b => m (b -> r) -> m r
k c = do { c' <- c; b <- f; return (c' b) }
z :: forall r. r -> m r
z = return
------------------------------------------------------------------------------
--
-- Datatype and constructor representations
--
------------------------------------------------------------------------------
--
-- | Representation of datatypes.
-- A package of constructor representations with names of type and module.
--
data DataType = DataType
{ tycon :: String
, datarep :: DataRep
}
deriving Show
-- | Representation of constructors. Note that equality on constructors
-- with different types may not work -- i.e. the constructors for 'False' and
-- 'Nothing' may compare equal.
data Constr = Constr
{ conrep :: ConstrRep
, constring :: String
, confields :: [String] -- for AlgRep only
, confixity :: Fixity -- for AlgRep only
, datatype :: DataType
}
instance Show Constr where
show = constring
-- | Equality of constructors
instance Eq Constr where
c == c' = constrRep c == constrRep c'
-- | Public representation of datatypes
data DataRep = AlgRep [Constr]
| IntRep
| FloatRep
| CharRep
| NoRep
deriving (Eq,Show)
-- The list of constructors could be an array, a balanced tree, or others.
-- | Public representation of constructors
data ConstrRep = AlgConstr ConIndex
| IntConstr Integer
| FloatConstr Rational
| CharConstr Char
deriving (Eq,Show)
-- | Unique index for datatype constructors,
-- counting from 1 in the order they are given in the program text.
type ConIndex = Int
-- | Fixity of constructors
data Fixity = Prefix
| Infix -- Later: add associativity and precedence
deriving (Eq,Show)
------------------------------------------------------------------------------
--
-- Observers for datatype representations
--
------------------------------------------------------------------------------
-- | Gets the type constructor including the module
dataTypeName :: DataType -> String
dataTypeName = tycon
-- | Gets the public presentation of a datatype
dataTypeRep :: DataType -> DataRep
dataTypeRep = datarep
-- | Gets the datatype of a constructor
constrType :: Constr -> DataType
constrType = datatype
-- | Gets the public presentation of constructors
constrRep :: Constr -> ConstrRep
constrRep = conrep
-- | Look up a constructor by its representation
repConstr :: DataType -> ConstrRep -> Constr
repConstr dt cr =
case (dataTypeRep dt, cr) of
(AlgRep cs, AlgConstr i) -> cs !! (i-1)
(IntRep, IntConstr i) -> mkIntConstr dt i
(FloatRep, FloatConstr f) -> mkRealConstr dt f
(CharRep, CharConstr c) -> mkCharConstr dt c
_ -> error "Data.Data.repConstr"
------------------------------------------------------------------------------
--
-- Representations of algebraic data types
--
------------------------------------------------------------------------------
-- | Constructs an algebraic datatype
mkDataType :: String -> [Constr] -> DataType
mkDataType str cs = DataType
{ tycon = str
, datarep = AlgRep cs
}
-- | Constructs a constructor
mkConstr :: DataType -> String -> [String] -> Fixity -> Constr
mkConstr dt str fields fix =
Constr
{ conrep = AlgConstr idx
, constring = str
, confields = fields
, confixity = fix
, datatype = dt
}
where
idx = head [ i | (c,i) <- dataTypeConstrs dt `zip` [1..],
showConstr c == str ]
-- | Gets the constructors of an algebraic datatype
dataTypeConstrs :: DataType -> [Constr]
dataTypeConstrs dt = case datarep dt of
(AlgRep cons) -> cons
_ -> error "Data.Data.dataTypeConstrs"
-- | Gets the field labels of a constructor. The list of labels
-- is returned in the same order as they were given in the original
-- constructor declaration.
constrFields :: Constr -> [String]
constrFields = confields
-- | Gets the fixity of a constructor
constrFixity :: Constr -> Fixity
constrFixity = confixity
------------------------------------------------------------------------------
--
-- From strings to constr's and vice versa: all data types
--
------------------------------------------------------------------------------
-- | Gets the string for a constructor
showConstr :: Constr -> String
showConstr = constring
-- | Lookup a constructor via a string
readConstr :: DataType -> String -> Maybe Constr
readConstr dt str =
case dataTypeRep dt of
AlgRep cons -> idx cons
IntRep -> mkReadCon (\i -> (mkPrimCon dt str (IntConstr i)))
FloatRep -> mkReadCon ffloat
CharRep -> mkReadCon (\c -> (mkPrimCon dt str (CharConstr c)))
NoRep -> Nothing
where
-- Read a value and build a constructor
mkReadCon :: Read t => (t -> Constr) -> Maybe Constr
mkReadCon f = case (reads str) of
[(t,"")] -> Just (f t)
_ -> Nothing
-- Traverse list of algebraic datatype constructors
idx :: [Constr] -> Maybe Constr
idx cons = let fit = filter ((==) str . showConstr) cons
in if fit == []
then Nothing
else Just (head fit)
ffloat :: Double -> Constr
ffloat = mkPrimCon dt str . FloatConstr . toRational
------------------------------------------------------------------------------
--
-- Convenience funtions: algebraic data types
--
------------------------------------------------------------------------------
-- | Test for an algebraic type
isAlgType :: DataType -> Bool
isAlgType dt = case datarep dt of
(AlgRep _) -> True
_ -> False
-- | Gets the constructor for an index (algebraic datatypes only)
indexConstr :: DataType -> ConIndex -> Constr
indexConstr dt idx = case datarep dt of
(AlgRep cs) -> cs !! (idx-1)
_ -> error "Data.Data.indexConstr"
-- | Gets the index of a constructor (algebraic datatypes only)
constrIndex :: Constr -> ConIndex
constrIndex con = case constrRep con of
(AlgConstr idx) -> idx
_ -> error "Data.Data.constrIndex"
-- | Gets the maximum constructor index of an algebraic datatype
maxConstrIndex :: DataType -> ConIndex
maxConstrIndex dt = case dataTypeRep dt of
AlgRep cs -> length cs
_ -> error "Data.Data.maxConstrIndex"
------------------------------------------------------------------------------
--
-- Representation of primitive types
--
------------------------------------------------------------------------------
-- | Constructs the 'Int' type
mkIntType :: String -> DataType
mkIntType = mkPrimType IntRep
-- | Constructs the 'Float' type
mkFloatType :: String -> DataType
mkFloatType = mkPrimType FloatRep
-- | This function is now deprecated. Please use 'mkCharType' instead.
{-# DEPRECATED mkStringType "Use mkCharType instead" #-}
mkStringType :: String -> DataType
mkStringType = mkCharType
-- | Constructs the 'Char' type
mkCharType :: String -> DataType
mkCharType = mkPrimType CharRep
-- | Helper for 'mkIntType', 'mkFloatType', 'mkStringType'
mkPrimType :: DataRep -> String -> DataType
mkPrimType dr str = DataType
{ tycon = str
, datarep = dr
}
-- Makes a constructor for primitive types
mkPrimCon :: DataType -> String -> ConstrRep -> Constr
mkPrimCon dt str cr = Constr
{ datatype = dt
, conrep = cr
, constring = str
, confields = error "Data.Data.confields"
, confixity = error "Data.Data.confixity"
}
-- | This function is now deprecated. Please use 'mkIntegralConstr' instead.
{-# DEPRECATED mkIntConstr "Use mkIntegralConstr instead" #-}
mkIntConstr :: DataType -> Integer -> Constr
mkIntConstr = mkIntegralConstr
mkIntegralConstr :: (Integral a, Show a) => DataType -> a -> Constr
mkIntegralConstr dt i = case datarep dt of
IntRep -> mkPrimCon dt (show i) (IntConstr (toInteger i))
_ -> error "Data.Data.mkIntegralConstr"
-- | This function is now deprecated. Please use 'mkRealConstr' instead.
{-# DEPRECATED mkFloatConstr "Use mkRealConstr instead" #-}
mkFloatConstr :: DataType -> Double -> Constr
mkFloatConstr dt = mkRealConstr dt . toRational
mkRealConstr :: (Real a, Show a) => DataType -> a -> Constr
mkRealConstr dt f = case datarep dt of
FloatRep -> mkPrimCon dt (show f) (FloatConstr (toRational f))
_ -> error "Data.Data.mkRealConstr"
-- | This function is now deprecated. Please use 'mkCharConstr' instead.
{-# DEPRECATED mkStringConstr "Use mkCharConstr instead" #-}
mkStringConstr :: DataType -> String -> Constr
mkStringConstr dt str =
case datarep dt of
CharRep -> case str of
[c] -> mkPrimCon dt (show c) (CharConstr c)
_ -> error "Data.Data.mkStringConstr: input String must contain a single character"
_ -> error "Data.Data.mkStringConstr"
-- | Makes a constructor for 'Char'.
mkCharConstr :: DataType -> Char -> Constr
mkCharConstr dt c = case datarep dt of
CharRep -> mkPrimCon dt (show c) (CharConstr c)
_ -> error "Data.Data.mkCharConstr"
------------------------------------------------------------------------------
--
-- Non-representations for non-presentable types
--
------------------------------------------------------------------------------
-- | Deprecated version (misnamed)
{-# DEPRECATED mkNorepType "Use mkNoRepType instead" #-}
mkNorepType :: String -> DataType
mkNorepType str = DataType
{ tycon = str
, datarep = NoRep
}
-- | Constructs a non-representation for a non-presentable type
mkNoRepType :: String -> DataType
mkNoRepType str = DataType
{ tycon = str
, datarep = NoRep
}
-- | Test for a non-representable type
isNorepType :: DataType -> Bool
isNorepType dt = case datarep dt of
NoRep -> True
_ -> False
------------------------------------------------------------------------------
--
-- Convenience for qualified type constructors
--
------------------------------------------------------------------------------
-- | Gets the unqualified type constructor:
-- drop *.*.*... before name
--
tyconUQname :: String -> String
tyconUQname x = let x' = dropWhile (not . (==) '.') x
in if x' == [] then x else tyconUQname (tail x')
-- | Gets the module of a type constructor:
-- take *.*.*... before name
tyconModule :: String -> String
tyconModule x = let (a,b) = break ((==) '.') x
in if b == ""
then b
else a ++ tyconModule' (tail b)
where
tyconModule' y = let y' = tyconModule y
in if y' == "" then "" else ('.':y')
------------------------------------------------------------------------------
------------------------------------------------------------------------------
--
-- Instances of the Data class for Prelude-like types.
-- We define top-level definitions for representations.
--
------------------------------------------------------------------------------
falseConstr :: Constr
falseConstr = mkConstr boolDataType "False" [] Prefix
trueConstr :: Constr
trueConstr = mkConstr boolDataType "True" [] Prefix
boolDataType :: DataType
boolDataType = mkDataType "Prelude.Bool" [falseConstr,trueConstr]
instance Data Bool where
toConstr False = falseConstr
toConstr True = trueConstr
gunfold _ z c = case constrIndex c of
1 -> z False
2 -> z True
_ -> error "Data.Data.gunfold(Bool)"
dataTypeOf _ = boolDataType
------------------------------------------------------------------------------
charType :: DataType
charType = mkCharType "Prelude.Char"
instance Data Char where
toConstr x = mkCharConstr charType x
gunfold _ z c = case constrRep c of
(CharConstr x) -> z x
_ -> error "Data.Data.gunfold(Char)"
dataTypeOf _ = charType
------------------------------------------------------------------------------
floatType :: DataType
floatType = mkFloatType "Prelude.Float"
instance Data Float where
toConstr = mkRealConstr floatType
gunfold _ z c = case constrRep c of
(FloatConstr x) -> z (realToFrac x)
_ -> error "Data.Data.gunfold(Float)"
dataTypeOf _ = floatType
------------------------------------------------------------------------------
doubleType :: DataType
doubleType = mkFloatType "Prelude.Double"
instance Data Double where
toConstr = mkRealConstr doubleType
gunfold _ z c = case constrRep c of
(FloatConstr x) -> z (realToFrac x)
_ -> error "Data.Data.gunfold(Double)"
dataTypeOf _ = doubleType
------------------------------------------------------------------------------
intType :: DataType
intType = mkIntType "Prelude.Int"
instance Data Int where
toConstr x = mkIntConstr intType (fromIntegral x)
gunfold _ z c = case constrRep c of
(IntConstr x) -> z (fromIntegral x)
_ -> error "Data.Data.gunfold(Int)"
dataTypeOf _ = intType
------------------------------------------------------------------------------
integerType :: DataType
integerType = mkIntType "Prelude.Integer"
instance Data Integer where
toConstr = mkIntConstr integerType
gunfold _ z c = case constrRep c of
(IntConstr x) -> z x
_ -> error "Data.Data.gunfold(Integer)"
dataTypeOf _ = integerType
------------------------------------------------------------------------------
int8Type :: DataType
int8Type = mkIntType "Data.Int.Int8"
instance Data Int8 where
toConstr x = mkIntConstr int8Type (fromIntegral x)
gunfold _ z c = case constrRep c of
(IntConstr x) -> z (fromIntegral x)
_ -> error "Data.Data.gunfold(Int8)"
dataTypeOf _ = int8Type
------------------------------------------------------------------------------
int16Type :: DataType
int16Type = mkIntType "Data.Int.Int16"
instance Data Int16 where
toConstr x = mkIntConstr int16Type (fromIntegral x)
gunfold _ z c = case constrRep c of
(IntConstr x) -> z (fromIntegral x)
_ -> error "Data.Data.gunfold(Int16)"
dataTypeOf _ = int16Type
------------------------------------------------------------------------------
int32Type :: DataType
int32Type = mkIntType "Data.Int.Int32"
instance Data Int32 where
toConstr x = mkIntConstr int32Type (fromIntegral x)
gunfold _ z c = case constrRep c of
(IntConstr x) -> z (fromIntegral x)
_ -> error "Data.Data.gunfold(Int32)"
dataTypeOf _ = int32Type
------------------------------------------------------------------------------
int64Type :: DataType
int64Type = mkIntType "Data.Int.Int64"
instance Data Int64 where
toConstr x = mkIntConstr int64Type (fromIntegral x)
gunfold _ z c = case constrRep c of
(IntConstr x) -> z (fromIntegral x)
_ -> error "Data.Data.gunfold(Int64)"
dataTypeOf _ = int64Type
------------------------------------------------------------------------------
wordType :: DataType
wordType = mkIntType "Data.Word.Word"
instance Data Word where
toConstr x = mkIntConstr wordType (fromIntegral x)
gunfold _ z c = case constrRep c of
(IntConstr x) -> z (fromIntegral x)
_ -> error "Data.Data.gunfold(Word)"
dataTypeOf _ = wordType
------------------------------------------------------------------------------
word8Type :: DataType
word8Type = mkIntType "Data.Word.Word8"
instance Data Word8 where
toConstr x = mkIntConstr word8Type (fromIntegral x)
gunfold _ z c = case constrRep c of
(IntConstr x) -> z (fromIntegral x)
_ -> error "Data.Data.gunfold(Word8)"
dataTypeOf _ = word8Type
------------------------------------------------------------------------------
word16Type :: DataType
word16Type = mkIntType "Data.Word.Word16"
instance Data Word16 where
toConstr x = mkIntConstr word16Type (fromIntegral x)
gunfold _ z c = case constrRep c of
(IntConstr x) -> z (fromIntegral x)
_ -> error "Data.Data.gunfold(Word16)"
dataTypeOf _ = word16Type
------------------------------------------------------------------------------
word32Type :: DataType
word32Type = mkIntType "Data.Word.Word32"
instance Data Word32 where
toConstr x = mkIntConstr word32Type (fromIntegral x)
gunfold _ z c = case constrRep c of
(IntConstr x) -> z (fromIntegral x)
_ -> error "Data.Data.gunfold(Word32)"
dataTypeOf _ = word32Type
------------------------------------------------------------------------------
word64Type :: DataType
word64Type = mkIntType "Data.Word.Word64"
instance Data Word64 where
toConstr x = mkIntConstr word64Type (fromIntegral x)
gunfold _ z c = case constrRep c of
(IntConstr x) -> z (fromIntegral x)
_ -> error "Data.Data.gunfold(Word64)"
dataTypeOf _ = word64Type
------------------------------------------------------------------------------
ratioConstr :: Constr
ratioConstr = mkConstr ratioDataType ":%" [] Infix
ratioDataType :: DataType
ratioDataType = mkDataType "GHC.Real.Ratio" [ratioConstr]
instance (Data a, Integral a) => Data (Ratio a) where
gfoldl k z (a :% b) = z (:%) `k` a `k` b
toConstr _ = ratioConstr
gunfold k z c | constrIndex c == 1 = k (k (z (:%)))
gunfold _ _ _ = error "Data.Data.gunfold(Ratio)"
dataTypeOf _ = ratioDataType
------------------------------------------------------------------------------
nilConstr :: Constr
nilConstr = mkConstr listDataType "[]" [] Prefix
consConstr :: Constr
consConstr = mkConstr listDataType "(:)" [] Infix
listDataType :: DataType
listDataType = mkDataType "Prelude.[]" [nilConstr,consConstr]
instance Data a => Data [a] where
gfoldl _ z [] = z []
gfoldl f z (x:xs) = z (:) `f` x `f` xs
toConstr [] = nilConstr
toConstr (_:_) = consConstr
gunfold k z c = case constrIndex c of
1 -> z []
2 -> k (k (z (:)))
_ -> error "Data.Data.gunfold(List)"
dataTypeOf _ = listDataType
dataCast1 f = gcast1 f
--
-- The gmaps are given as an illustration.
-- This shows that the gmaps for lists are different from list maps.
--
gmapT _ [] = []
gmapT f (x:xs) = (f x:f xs)
gmapQ _ [] = []
gmapQ f (x:xs) = [f x,f xs]
gmapM _ [] = return []
gmapM f (x:xs) = f x >>= \x' -> f xs >>= \xs' -> return (x':xs')
------------------------------------------------------------------------------
nothingConstr :: Constr
nothingConstr = mkConstr maybeDataType "Nothing" [] Prefix
justConstr :: Constr
justConstr = mkConstr maybeDataType "Just" [] Prefix
maybeDataType :: DataType
maybeDataType = mkDataType "Prelude.Maybe" [nothingConstr,justConstr]
instance Data a => Data (Maybe a) where
gfoldl _ z Nothing = z Nothing
gfoldl f z (Just x) = z Just `f` x
toConstr Nothing = nothingConstr
toConstr (Just _) = justConstr
gunfold k z c = case constrIndex c of
1 -> z Nothing
2 -> k (z Just)
_ -> error "Data.Data.gunfold(Maybe)"
dataTypeOf _ = maybeDataType
dataCast1 f = gcast1 f
------------------------------------------------------------------------------
ltConstr :: Constr
ltConstr = mkConstr orderingDataType "LT" [] Prefix
eqConstr :: Constr
eqConstr = mkConstr orderingDataType "EQ" [] Prefix
gtConstr :: Constr
gtConstr = mkConstr orderingDataType "GT" [] Prefix
orderingDataType :: DataType
orderingDataType = mkDataType "Prelude.Ordering" [ltConstr,eqConstr,gtConstr]
instance Data Ordering where
gfoldl _ z LT = z LT
gfoldl _ z EQ = z EQ
gfoldl _ z GT = z GT
toConstr LT = ltConstr
toConstr EQ = eqConstr
toConstr GT = gtConstr
gunfold _ z c = case constrIndex c of
1 -> z LT
2 -> z EQ
3 -> z GT
_ -> error "Data.Data.gunfold(Ordering)"
dataTypeOf _ = orderingDataType
------------------------------------------------------------------------------
leftConstr :: Constr
leftConstr = mkConstr eitherDataType "Left" [] Prefix
rightConstr :: Constr
rightConstr = mkConstr eitherDataType "Right" [] Prefix
eitherDataType :: DataType
eitherDataType = mkDataType "Prelude.Either" [leftConstr,rightConstr]
instance (Data a, Data b) => Data (Either a b) where
gfoldl f z (Left a) = z Left `f` a
gfoldl f z (Right a) = z Right `f` a
toConstr (Left _) = leftConstr
toConstr (Right _) = rightConstr
gunfold k z c = case constrIndex c of
1 -> k (z Left)
2 -> k (z Right)
_ -> error "Data.Data.gunfold(Either)"
dataTypeOf _ = eitherDataType
dataCast2 f = gcast2 f
------------------------------------------------------------------------------
tuple0Constr :: Constr
tuple0Constr = mkConstr tuple0DataType "()" [] Prefix
tuple0DataType :: DataType
tuple0DataType = mkDataType "Prelude.()" [tuple0Constr]
instance Data () where
toConstr () = tuple0Constr
gunfold _ z c | constrIndex c == 1 = z ()
gunfold _ _ _ = error "Data.Data.gunfold(unit)"
dataTypeOf _ = tuple0DataType
------------------------------------------------------------------------------
tuple2Constr :: Constr
tuple2Constr = mkConstr tuple2DataType "(,)" [] Infix
tuple2DataType :: DataType
tuple2DataType = mkDataType "Prelude.(,)" [tuple2Constr]
instance (Data a, Data b) => Data (a,b) where
gfoldl f z (a,b) = z (,) `f` a `f` b
toConstr (_,_) = tuple2Constr
gunfold k z c | constrIndex c == 1 = k (k (z (,)))
gunfold _ _ _ = error "Data.Data.gunfold(tup2)"
dataTypeOf _ = tuple2DataType
dataCast2 f = gcast2 f
------------------------------------------------------------------------------
tuple3Constr :: Constr
tuple3Constr = mkConstr tuple3DataType "(,,)" [] Infix
tuple3DataType :: DataType
tuple3DataType = mkDataType "Prelude.(,,)" [tuple3Constr]
instance (Data a, Data b, Data c) => Data (a,b,c) where
gfoldl f z (a,b,c) = z (,,) `f` a `f` b `f` c
toConstr (_,_,_) = tuple3Constr
gunfold k z c | constrIndex c == 1 = k (k (k (z (,,))))
gunfold _ _ _ = error "Data.Data.gunfold(tup3)"
dataTypeOf _ = tuple3DataType
------------------------------------------------------------------------------
tuple4Constr :: Constr
tuple4Constr = mkConstr tuple4DataType "(,,,)" [] Infix
tuple4DataType :: DataType
tuple4DataType = mkDataType "Prelude.(,,,)" [tuple4Constr]
instance (Data a, Data b, Data c, Data d)
=> Data (a,b,c,d) where
gfoldl f z (a,b,c,d) = z (,,,) `f` a `f` b `f` c `f` d
toConstr (_,_,_,_) = tuple4Constr
gunfold k z c = case constrIndex c of
1 -> k (k (k (k (z (,,,)))))
_ -> error "Data.Data.gunfold(tup4)"
dataTypeOf _ = tuple4DataType
------------------------------------------------------------------------------
tuple5Constr :: Constr
tuple5Constr = mkConstr tuple5DataType "(,,,,)" [] Infix
tuple5DataType :: DataType
tuple5DataType = mkDataType "Prelude.(,,,,)" [tuple5Constr]
instance (Data a, Data b, Data c, Data d, Data e)
=> Data (a,b,c,d,e) where
gfoldl f z (a,b,c,d,e) = z (,,,,) `f` a `f` b `f` c `f` d `f` e
toConstr (_,_,_,_,_) = tuple5Constr
gunfold k z c = case constrIndex c of
1 -> k (k (k (k (k (z (,,,,))))))
_ -> error "Data.Data.gunfold(tup5)"
dataTypeOf _ = tuple5DataType
------------------------------------------------------------------------------
tuple6Constr :: Constr
tuple6Constr = mkConstr tuple6DataType "(,,,,,)" [] Infix
tuple6DataType :: DataType
tuple6DataType = mkDataType "Prelude.(,,,,,)" [tuple6Constr]
instance (Data a, Data b, Data c, Data d, Data e, Data f)
=> Data (a,b,c,d,e,f) where
gfoldl f z (a,b,c,d,e,f') = z (,,,,,) `f` a `f` b `f` c `f` d `f` e `f` f'
toConstr (_,_,_,_,_,_) = tuple6Constr
gunfold k z c = case constrIndex c of
1 -> k (k (k (k (k (k (z (,,,,,)))))))
_ -> error "Data.Data.gunfold(tup6)"
dataTypeOf _ = tuple6DataType
------------------------------------------------------------------------------
tuple7Constr :: Constr
tuple7Constr = mkConstr tuple7DataType "(,,,,,,)" [] Infix
tuple7DataType :: DataType
tuple7DataType = mkDataType "Prelude.(,,,,,,)" [tuple7Constr]
instance (Data a, Data b, Data c, Data d, Data e, Data f, Data g)
=> Data (a,b,c,d,e,f,g) where
gfoldl f z (a,b,c,d,e,f',g) =
z (,,,,,,) `f` a `f` b `f` c `f` d `f` e `f` f' `f` g
toConstr (_,_,_,_,_,_,_) = tuple7Constr
gunfold k z c = case constrIndex c of
1 -> k (k (k (k (k (k (k (z (,,,,,,))))))))
_ -> error "Data.Data.gunfold(tup7)"
dataTypeOf _ = tuple7DataType
------------------------------------------------------------------------------
instance Typeable a => Data (Ptr a) where
toConstr _ = error "Data.Data.toConstr(Ptr)"
gunfold _ _ = error "Data.Data.gunfold(Ptr)"
dataTypeOf _ = mkNoRepType "GHC.Ptr.Ptr"
------------------------------------------------------------------------------
instance Typeable a => Data (ForeignPtr a) where
toConstr _ = error "Data.Data.toConstr(ForeignPtr)"
gunfold _ _ = error "Data.Data.gunfold(ForeignPtr)"
dataTypeOf _ = mkNoRepType "GHC.ForeignPtr.ForeignPtr"
------------------------------------------------------------------------------
-- The Data instance for Array preserves data abstraction at the cost of
-- inefficiency. We omit reflection services for the sake of data abstraction.
instance (Typeable a, Data b, Ix a) => Data (Array a b)
where
gfoldl f z a = z (listArray (bounds a)) `f` (elems a)
toConstr _ = error "Data.Data.toConstr(Array)"
gunfold _ _ = error "Data.Data.gunfold(Array)"
dataTypeOf _ = mkNoRepType "Data.Array.Array"
| beni55/haste-compiler | libraries/ghc-7.8/base/Data/Data.hs | bsd-3-clause | 44,901 | 0 | 24 | 11,749 | 9,245 | 4,992 | 4,253 | 644 | 7 |
module PackageTests.BuildDeps.InternalLibrary2.Check where
import qualified Data.ByteString.Char8 as C
import PackageTests.PackageTester
import System.FilePath
import Test.Tasty.HUnit
suite :: SuiteConfig -> Assertion
suite config = do
let spec = PackageSpec
{ directory = "PackageTests" </> "BuildDeps" </> "InternalLibrary2"
, configOpts = []
, distPref = Nothing
}
let specTI = PackageSpec
{ directory = directory spec </> "to-install"
, configOpts = []
, distPref = Nothing
}
unregister config "InternalLibrary2"
iResult <- cabal_install config specTI
assertInstallSucceeded iResult
bResult <- cabal_build config spec
assertBuildSucceeded bResult
unregister config "InternalLibrary2"
(_, _, output) <- run (Just $ directory spec) (directory spec </> "dist" </> "build" </> "lemon" </> "lemon") [] []
C.appendFile (directory spec </> "test-log.txt") (C.pack $ "\ndist/build/lemon/lemon\n"++output)
assertEqual "executable should have linked with the internal library" "myLibFunc internal" (concat $ lines output)
| trskop/cabal | Cabal/tests/PackageTests/BuildDeps/InternalLibrary2/Check.hs | bsd-3-clause | 1,161 | 0 | 14 | 273 | 293 | 151 | 142 | 24 | 1 |
{-# htermination readHex :: String -> [(Int,String)] #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_readHex_1.hs | mit | 57 | 0 | 2 | 8 | 3 | 2 | 1 | 1 | 0 |
----------------------------------------------------------------
--
-- | Compilation
-- Monad and combinators for quickly assembling simple
-- compilers.
--
-- @Control\/Compilation\/Fresh.hs@
--
-- State extension class and combinators for implementations
-- of a state that support generation of fresh (i.e., unique)
-- values (integers and strings).
--
----------------------------------------------------------------
--
{-# LANGUAGE TypeSynonymInstances #-}
module Control.Compilation.Fresh
where
import Control.Compilation
----------------------------------------------------------------
-- | Type synonyms and class memberships.
type FreshIndex = Integer
type StateExtensionFresh = FreshIndex
instance StateExtension StateExtensionFresh where
initial = 0
----------------------------------------------------------------
-- | State extension class definition, including combinators
-- and convenient synonyms.
class StateExtension a => HasFresh a where
project :: a -> StateExtensionFresh
inject :: StateExtensionFresh -> a -> a
freshInteger :: Compilation a Integer
freshInteger =
do s <- get
i <- return $ project s
set $ inject (i+1) s
return $ i
freshString :: Compilation a String
freshString =
do i <- freshInteger
return $ show i
freshStringWithPrefix :: String -> Compilation a String
freshStringWithPrefix prefix =
do s <- freshString
return $ prefix ++ s
freshWithPrefix :: String -> Compilation a String
freshWithPrefix = freshStringWithPrefix
fresh :: Compilation a String
fresh = freshString
fresh_ :: String -> Compilation a String
fresh_ = freshStringWithPrefix
freshes :: Integer -> Compilation a [String]
freshes i =
do ns <- mapM (\_ -> fresh) [0..i-1]
return $ [show n | n <- ns]
freshes_ :: String -> Integer -> Compilation a [String]
freshes_ prefix i =
do ns <- mapM (\_ -> fresh) [0..i-1]
return $ [prefix ++ show n | n <- ns]
--eof
| lapets/compilation | Control/Compilation/Fresh.hs | mit | 2,007 | 0 | 12 | 401 | 443 | 235 | 208 | 38 | 0 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TemplateHaskell #-}
module Circuit.Builder.Internals where
import Circuit
import Control.Monad.State.Strict
import Control.Monad.Identity
import Lens.Micro.Platform
import qualified Data.Map.Strict as M
import qualified Data.IntMap.Strict as IM
import qualified Data.IntSet as IS
import qualified Data.Vector as V
type BuilderT g = StateT (BuildSt g)
type Builder g = BuilderT g Identity
data BuildSt g = BuildSt
{ _bs_circ :: !(Circuit g)
, _bs_next_inp :: !InputId
, _bs_next_const :: !ConstId
, _bs_next_secret :: !SecretId
, _bs_next_sym :: !Int
, _bs_dedup :: !(M.Map g Ref)
, _bs_constants :: !(M.Map Int Ref)
}
makeLenses ''BuildSt
emptyBuild :: BuildSt g
emptyBuild = BuildSt emptyCirc 0 0 0 0 M.empty M.empty
-- TODO: if circ_refsave is on, find the refs that can be added to circ_refskip
runCircuitT :: Monad m => BuilderT g m a -> m (Circuit g, a)
runCircuitT b = do
(a, st) <- runStateT b emptyBuild
return (st^.bs_circ, a)
buildCircuitT :: Monad m => BuilderT g m a -> m (Circuit g)
buildCircuitT b = view bs_circ <$> execStateT b emptyBuild
runCircuit :: Builder g a -> (Circuit g, a)
runCircuit b = runIdentity (runCircuitT b)
buildCircuit :: Builder g a -> Circuit g
buildCircuit = view bs_circ . flip execState emptyBuild
--------------------------------------------------------------------------------
-- operations
setSymlen :: Monad m => SymId -> Int -> BuilderT g m ()
setSymlen !id !n = bs_circ . circ_symlen . at (getSymId id) ?= n
setSigma :: Monad m => SymId -> BuilderT g m ()
setSigma !id = bs_circ . circ_sigma_vecs %= IS.insert (getSymId id)
insertGate :: (Gate g, Ord g, Monad m) => Ref -> g -> BuilderT g m ()
insertGate !ref !gate = do
refs <- use $ bs_circ . circ_refmap
when (IM.member (getRef ref) refs) $
error ("redefinition of ref " ++ show ref)
bs_circ . circ_refmap . at (getRef ref) ?= gate
bs_dedup . at gate ?= ref
mapM_ bumpRefCount (gateArgs gate)
insertConst :: (Gate g, Monad m) => Ref -> ConstId -> BuilderT g m ()
insertConst !ref !id = do
bs_circ . circ_consts . at (getConstId id) ?= ref
insertGate ref (gateBase (Const id))
insertSecret :: (Gate g, Monad m) => Ref -> SecretId -> BuilderT g m ()
insertSecret !ref !id = do
bs_circ . circ_secrets . at (getSecretId id) ?= ref
insertGate ref (gateBase (Secret id))
insertConstVal :: Monad m => ConstId -> Int -> BuilderT g m ()
insertConstVal !id !val = bs_circ . circ_const_vals . at (getConstId id) ?= val
insertSecretVal :: Monad m => SecretId -> Int -> BuilderT g m ()
insertSecretVal !id !val = bs_circ . circ_secret_vals . at (getSecretId id) ?= val
insertInput :: (Gate g, Monad m) => Ref -> InputId -> BuilderT g m ()
insertInput !ref !id = do
bs_circ . circ_inputs . at (getInputId id) ?= ref
insertGate ref (gateBase (Input id))
newGate :: (Ord g, Monad m, Gate g) => g -> BuilderT g m Ref
newGate !gate = do
dedup <- use bs_dedup
case M.lookup gate dedup of
Nothing -> do
ref <- nextRef
insertGate ref gate
return ref
Just ref -> do
return ref
nextRef :: Monad m => BuilderT g m Ref
nextRef = do
ref <- use (bs_circ . circ_maxref)
bs_circ . circ_maxref += 1
return (Ref ref)
nextInputId :: Monad m => BuilderT g m InputId
nextInputId = do
id <- use bs_next_inp
bs_next_inp += 1
return id
nextConstId :: Monad m => BuilderT g m ConstId
nextConstId = do
id <- use bs_next_const
bs_next_const += 1
return id
nextSecretId :: Monad m => BuilderT g m SecretId
nextSecretId = do
id <- use bs_next_secret
bs_next_secret += 1
return id
nextSymbol :: Monad m => BuilderT g m (SymId)
nextSymbol = do
i <- use bs_next_sym
bs_next_sym += 1
return (SymId i)
bumpRefCount :: Monad m => Ref -> BuilderT g m ()
bumpRefCount ref = bs_circ . circ_refcount %= IM.insertWith (+) (getRef ref) 1
-- XXX: marks everything in the circuit before this ref as Skip
saveRef :: (Gate g, Monad m) => Ref -> BuilderT g m ()
saveRef ref = do
markSave ref
c <- use bs_circ
mapM_ (skipRec c) (gateArgs (getGate c ref))
where
skipRec c ref = do
markSkip ref
let g = getGate c ref
when (gateIsGate g) $
mapM_ (skipRec c) (gateArgs g)
markSave :: Monad m => Ref -> BuilderT g m ()
markSave ref = bs_circ . circ_refsave %= IS.insert (getRef ref)
markSkip :: Monad m => Ref -> BuilderT g m ()
markSkip ref = bs_circ . circ_refskip %= IS.insert (getRef ref)
markOutput :: Monad m => Ref -> BuilderT g m ()
markOutput !ref = do
bs_circ . circ_outputs %= flip V.snoc ref
bumpRefCount ref
markConstant :: Monad m => Int -> Ref -> BuilderT g m ()
markConstant !x !ref = bs_constants . at x ?= ref
existingConstant :: Monad m => Int -> BuilderT g m (Maybe Ref)
existingConstant !x = use (bs_constants . at x)
| spaceships/circuit-synthesis | src/Circuit/Builder/Internals.hs | mit | 4,959 | 0 | 12 | 1,164 | 1,950 | 942 | 1,008 | -1 | -1 |
{- arch-tag: Generic Server Support
Copyright (c) 2004-2011 John Goerzen <[email protected]>
All rights reserved.
For license and copyright information, see the file LICENSE
-}
{- |
Module : Network.SocketServer
Copyright : Copyright (C) 2004-2011 John Goerzen
License : BSD3
Maintainer : John Goerzen <[email protected]>
Stability : experimental
Portability: systems with networking
This module provides an infrastructure to simplify server design.
Written by John Goerzen, jgoerzen\@complete.org
Please note: this module is designed to work with TCP, UDP, and Unix domain
sockets, but only TCP sockets have been tested to date.
This module is presently under-documented. For an example of usage, please
see the description of "Network.FTP.Server".
-}
module Network.SocketServer(-- * Generic Options and Types
InetServerOptions(..),
simpleTCPOptions,
SocketServer(..),
HandlerT,
-- * TCP server convenient setup
serveTCPforever,
-- * Lower-Level Processing
setupSocketServer,
handleOne,
serveForever,
closeSocketServer,
-- * Combinators
loggingHandler,
threadedHandler,
handleHandler
)
where
import Network.Socket
import Network.BSD
import Network.Utils
import Control.Concurrent
import System.IO
import qualified System.Log.Logger
{- | Options for your server. -}
data InetServerOptions = InetServerOptions {listenQueueSize :: Int,
portNumber :: PortNumber,
interface :: HostAddress,
reuse :: Bool,
family :: Family,
sockType :: SocketType,
protoStr :: String
}
deriving (Eq, Show)
{- | The main handler type.
The first parameter is the socket itself.
The second is the address of the remote endpoint.
The third is the address of the local endpoint.
-}
type HandlerT = Socket -> SockAddr -> SockAddr -> IO ()
{- | Get Default options. You can always modify it later. -}
simpleTCPOptions :: Int -- ^ Port Number
-> InetServerOptions
simpleTCPOptions p = InetServerOptions {listenQueueSize = 5,
portNumber = (fromIntegral p),
interface = iNADDR_ANY,
reuse = False,
family = AF_INET,
sockType = Stream,
protoStr = "tcp"
}
data SocketServer = SocketServer {optionsSS :: InetServerOptions,
sockSS :: Socket}
deriving (Eq, Show)
{- | Takes some options and sets up the 'SocketServer'. I will bind
and begin listening, but will not accept any connections itself. -}
setupSocketServer :: InetServerOptions -> IO SocketServer
setupSocketServer opts =
do proto <- getProtocolNumber (protoStr opts)
s <- socket (family opts) (sockType opts) proto
setSocketOption s ReuseAddr (case (reuse opts) of
True -> 1
False -> 0)
bindSocket s (SockAddrInet (portNumber opts)
(interface opts))
listen s (listenQueueSize opts)
return $ SocketServer {optionsSS = opts, sockSS = s}
{- | Close the socket server. Does not terminate active
handlers, if any. -}
closeSocketServer :: SocketServer -> IO ()
closeSocketServer ss =
sClose (sockSS ss)
{- | Handle one incoming request from the given 'SocketServer'. -}
handleOne :: SocketServer -> HandlerT -> IO ()
handleOne ss func =
let opts = (optionsSS ss)
in do a <- accept (sockSS ss)
localaddr <- getSocketName (fst a)
func (fst a) (snd a) localaddr
{- | Handle all incoming requests from the given 'SocketServer'. -}
serveForever :: SocketServer -> HandlerT -> IO ()
serveForever ss func =
sequence_ (repeat (handleOne ss func))
{- | Convenience function to completely set up a TCP
'SocketServer' and handle all incoming requests.
This function is literally this:
>serveTCPforever options func =
> do sockserv <- setupSocketServer options
> serveForever sockserv func
-}
serveTCPforever :: InetServerOptions -- ^ Server options
-> HandlerT -- ^ Handler function
-> IO ()
serveTCPforever options func =
do sockserv <- setupSocketServer options
serveForever sockserv func
----------------------------------------------------------------------
-- Combinators
----------------------------------------------------------------------
{- | Log each incoming connection using the interface in
"System.Log.Logger".
Log when the incoming connection disconnects.
Also, log any failures that may occur in the child handler. -}
loggingHandler :: String -- ^ Name of logger to use
-> System.Log.Logger.Priority -- ^ Priority of logged messages
-> HandlerT -- ^ Handler to call after logging
-> HandlerT -- ^ Resulting handler
loggingHandler hname prio nexth socket r_sockaddr l_sockaddr =
do sockStr <- showSockAddr r_sockaddr
System.Log.Logger.logM hname prio
("Received connection from " ++ sockStr)
System.Log.Logger.traplogging hname
System.Log.Logger.WARNING "" (nexth socket r_sockaddr
l_sockaddr)
System.Log.Logger.logM hname prio
("Connection " ++ sockStr ++ " disconnected")
-- | Handle each incoming connection in its own thread to
-- make the server multi-tasking.
threadedHandler :: HandlerT -- ^ Handler to call in the new thread
-> HandlerT -- ^ Resulting handler
threadedHandler nexth socket r_sockaddr l_sockaddr=
do forkIO (nexth socket r_sockaddr l_sockaddr)
return ()
{- | Give your handler function a Handle instead of a Socket.
The Handle will be opened with ReadWriteMode (you use one handle for both
directions of the Socket). Also, it will be initialized with LineBuffering.
Unlike other handlers, the handle will be closed when the function returns.
Therefore, if you are doing threading, you should to it before you call this
handler.
-}
handleHandler :: (Handle -> SockAddr -> SockAddr -> IO ()) -- ^ Handler to call
-> HandlerT
handleHandler func socket r_sockaddr l_sockaddr =
do h <- socketToHandle socket ReadWriteMode
hSetBuffering h LineBuffering
func h r_sockaddr l_sockaddr
hClose h
| haskellbr/missingh | missingh-all/src/Network/SocketServer.hs | mit | 7,507 | 0 | 12 | 2,760 | 931 | 501 | 430 | 94 | 2 |
module Main where
--
-- BASE LANGUAGE
-- The base language includes integers, addition, and subtraction.
--
--
-- EXTENDED LANGUAGE
-- The extended language includes the base language plus factorial, log (base
-- e), multiplication, and division.
--
--------------------------------------------------------------------------------
-- BASE LANGUAGE evaluation
--
-- This is how expressions of the base language are evaluated. Note that none
-- of these functions are particular to an AST or ADT; they only hint at
-- necessary features.
--------------------------------------------------------------------------------
-- | Evaluates a binary operation expression.
evalExprBinOp ::
(binOp -> Int -> Int -> Int)
-- ^ How to evaluate binary operators
-> (expr -> Int)
-- ^ How to evaluate expressions
-> expr
-- ^ Left argument
-> binOp
-- ^ Binary operator
-> expr
-- ^ Right argument
-> Int
-- ^ Evaluation returns some Int
evalExprBinOp evalBinOp' evalExpr' l op r
= evalBinOp' op (evalExpr' l) (evalExpr' r)
--
-- | Evaluates an integer value.
evalExprInt :: Int -> Int
evalExprInt i = i
-- | Evaluate an integer addition operator.
evalAdd :: Int -> Int -> Int
evalAdd = (+)
-- | Evaluate an integer subtraction operator.
evalSub :: Int -> Int -> Int
evalSub = (-)
--------------------------------------------------------------------------------
-- EXTENDED LANGUAGE evaluation
--
-- This is how expressions of the extended language are evaluated. Note that
-- none of these functions are particular to an AST or ADT, nor do they need to
-- reference the base language; they only hint at necessary features and
-- only explain how to evaluate what is unique to the extended language.
--------------------------------------------------------------------------------
-- | Evalute a unary integer operation.
evalExprUniOp :: (uniOp -> Int -> Int)
-- ^ How to evaluate unary operators
-> (expr -> Int)
-- ^ How to evaluate expressions
-> uniOp
-- ^ Unary operator
-> expr
-- ^ Argument
-> Int
-- ^ Evaluation returns some Int
evalExprUniOp evalUniOp' evalExpr' op arg = evalUniOp' op (evalExpr' arg)
-- | Evaluate an integer multiplication operator.
evalMul :: Int -> Int -> Int
evalMul = (*)
-- | Evaluate an integer division operator.
evalDiv :: Int -> Int -> Int
evalDiv = div
-- | Evaluates an integer factorial operator.
evalFac :: Int -> Int
evalFac = product . flip take [1..]
-- | Evaluates an integer log operator.
evalLog :: Int -> Int
evalLog = floor . log . fromIntegral
--------------------------------------------------------------------------------
-- BASE LANGUAGE representation and evaluation
--
-- The base language can be represented using ADTs. To permit the extended
-- language representation to reuse the base language representation type
-- parameters are added.
--
-- Evaluating the ADT only requires case analysis and application of the
-- predefined evaluation logic.
--------------------------------------------------------------------------------
-- | BASE LANGUAGE expressions
data Expression binOp expr =
ExprInt { exprInt :: Int
}
| ExprBinOp { exprLeft :: expr
, exprBinOp :: binOp
, exprRight :: expr
}
--
-- | BASE LANGUAGE binary operators
data BinOp = Add | Sub
-- | Evaluate an `Expression` value. Note that this is simply applying
-- `evalExprBinOp` and `evalExprInt` to the `Expression` ADT.
evalExpr :: (binOp -> Int -> Int -> Int)
-- ^ How to evaluate binary operators
-> (expr -> Int)
-- ^ How to evaluate expressions
-> Expression binOp expr
-- ^ `Expression` value to evaluate
-> Int
-- ^ Evaluation returns some Int
evalExpr evalBinOp' evalExpr' expr =
case expr of
ExprInt i -> evalExprInt i
ExprBinOp l op r -> evalExprBinOp evalBinOp' evalExpr' l op r
--
-- | Evaluate a `BinOp` value. Note that this is simply applying `evalAdd` and
-- `evalSub` to the `BinOp` ADT.
evalBinOp :: BinOp -> Int -> Int -> Int
evalBinOp Add = evalAdd
evalBinOp Sub = evalSub
--------------------------------------------------------------------------------
-- EXTENDED LANGUAGE representation and evaluation
--
-- The extended language can also be represented using ADTs. Because the base
-- language representation is parameterized the extended language representation
-- can reuse it. An alternative approach is to replicate the features of the
-- base language representation in the extended language representation.
--
-- The extended language representation is parameterized so that it can be
-- further extended in similar fashion.
--
-- Evaluating the ADT only requires case analysis and application of the
-- predefined evaluation logic.
--------------------------------------------------------------------------------
-- | EXTENDED LANGUAGE expressions
data ExpressionExt uniOp binOp expr =
ExprUniOp { exprUniOp :: uniOp
, exprArg :: expr
}
| ExprBase (Expression binOp expr)
--
-- | EXTENDED LANGUAGE binary operators
data BinOpExt = Mul | Div | BinOpBase BinOp
-- | EXTENDED LANGUAGE unary operators
data UniOp = Fac | Log
-- | Evaluate a `ExpressionExt` value. Note that this simply applies
-- `evalExprUniOp` and `evalExpr` to the `ExpressionExt` ADT.
evalExprExt :: (uniOp -> Int -> Int)
-- ^ How to evaluate unary operators
-> (binOp -> Int -> Int -> Int)
-- ^ How to evaluate binary operators
-> (expr -> Int)
-- ^ How to evaluate expressions
-> ExpressionExt uniOp binOp expr
-- ^ Expression
-> Int
-- ^ Evaluation returns some Int
evalExprExt evalUniOp' evalBinOp' evalExpr' expr =
case expr of
ExprUniOp op arg -> evalUniOp' op (evalExpr' arg)
ExprBase base -> evalExpr evalBinOp' evalExpr' base
--
-- | Evaluate a `BinOpExt` value. Note that this is simply applying `evalMul`,
-- `evalDiv`, and `evalBinOp` to the `BinOpExt` ADT.
evalBinOpExt :: BinOpExt -> Int -> Int -> Int
evalBinOpExt Mul = evalMul
evalBinOpExt Div = evalDiv
evalBinOpExt (BinOpBase binOp) = evalBinOp binOp
-- | Evaluates a `UniOp` value. Note that this simply applies `evalFac` and
-- `evalLog` to the `UniOp` ADT.
evalUniOp :: UniOp -> Int -> Int
evalUniOp Fac = evalFac
evalUniOp Log = evalLog
--------------------------------------------------------------------------------
-- BASE LANGUAGE representation instantiation, evaluation, and example
--
-- A concrete base language representation can be instantiated by choosing
-- BinOp for binary operators and choosing similar recursive expressions (done
-- by Fix).
--
-- Evaluating the instantiated base language representation only requires using
-- the predefined evaluation logic for the parameterized ADTs.
--------------------------------------------------------------------------------
-- | Instantiation of BASE LANGUAGE representation.
type SimpleExpr = Fix (Expression BinOp)
-- | Evaluate a `SimpleExpr` value.
evalSimpleExpr :: SimpleExpr -> Int
evalSimpleExpr (Fix expr) = evalExpr evalBinOp evalSimpleExpr expr
-- | Sample `SimpleExpr` value.
simple01 :: SimpleExpr
simple01 = Fix (ExprBinOp (Fix (ExprInt 5)) Add (Fix (ExprInt 5)))
--------------------------------------------------------------------------------
-- EXTENDED LANGUAGE representation instantiation, evaluation, and example
--
-- An extended base language representation can be instantiated by choosing
-- UniOp for unary operators, BinOpExt for binary operators, and similar
-- recursive expressions (done by Fix).
--
-- Evaluating the instantiated extended language representation only requires
-- using the predefined evaluation logic for the parameterized ADTs.
--------------------------------------------------------------------------------
-- | Instantiation of EXTENDED LANGUAGE representation.
type ExtendedExpr = Fix (ExpressionExt UniOp BinOpExt)
-- | Evaluate a `ExtendedExpr` value.
evalExtendedExpr :: ExtendedExpr -> Int
evalExtendedExpr (Fix expr) =
evalExprExt evalUniOp evalBinOpExt evalExtendedExpr expr
--
-- | Sample `ExtendedExpr` value.
extended01 :: ExtendedExpr
extended01 = Fix (ExprUniOp Fac (Fix (ExprBase (ExprBinOp (Fix (ExprBase
(ExprInt 3))) Mul (Fix (ExprBase (ExprInt 2)))))))
--------------------------------------------------------------------------------
-- Miscellaneous definitions
--------------------------------------------------------------------------------
-- | Type level `fix`.
data Fix f = Fix (f (Fix f))
-- | This is to make the compiler happy.
main :: IO ()
main = putStrLn "Hello World"
| erisco/extensible-ast | example02/main.hs | mit | 9,150 | 0 | 19 | 2,062 | 1,119 | 653 | 466 | 84 | 2 |
{-# LANGUAGE ScopedTypeVariables, Safe #-}
module Data.Generics.Record (
RecordT,
isRecord,
recordT,
fields,
emptyRecord,
recordStructure) where
import Data.Data
import Data.Maybe
import Control.Monad (guard)
-- | A phantom type used to parameterize functions based on records.
-- This let's us avoid passing @undefined@s or manually creating instances
-- all the time. It can only be created for types which are records and
-- is used as a token to most of the API's functions.
data RecordT a = RecordT { constr :: Constr
, fs :: [String]}
-- | Returns @True@ if @a@ is a data type with a single constructor
-- and is a record. @a@ may be bottom.
isRecord :: forall a . Data a => a -> Bool
isRecord _ = isJust (recordT :: Maybe (RecordT a))
-- | The smart constructor for @RecordT@s. This
-- will return a @RecordT@ if and only if the type is a record.
recordT :: forall a. Data a => Maybe (RecordT a)
recordT = recordTAt 0
-- | A constructor for @RecordT@s that selects the @i@th constructor
-- from the left. This starts from 0.
recordTAt :: forall a. Data a => Int -> Maybe (RecordT a)
recordTAt i = guard (length cs > i && length (fields r) > 0) >> Just r
where cs = dataTypeConstrs . dataTypeOf $ (undefined :: a)
r = RecordT (cs !! i) (constrFields $ cs !! i) :: RecordT a
-- | Returns the fields for the record @a@
fields :: forall a. Data a => RecordT a -> [String]
fields = fs
-- | Return a record where all fields are _|_
emptyRecord :: forall a. Data a => RecordT a -> a
emptyRecord = fromConstr . constr
-- | Return a records structure of as a list of types paired with field names.
recordStructure :: forall a. Data a => RecordT a -> [(TypeRep, String)]
recordStructure a = zip (gmapQ typeOf (emptyRecord a)) $ fields a
| jozefg/reified-records | src/Data/Generics/Record.hs | mit | 1,792 | 0 | 12 | 382 | 427 | 234 | 193 | 27 | 1 |
import System.Random
import Control.Monad(when)
main = do
g <- getStdGen
guess g
guess :: StdGen -> IO ()
guess gen = do
putStrLn "What number from 1 to 10 am I thinking of?"
numberString <- getLine
--let number = (fst . head $ reads numberString) :: Int
let number = reads numberString :: [(Int,String)]
when (number /= []) $ do
let (cpuNumber, g') = randomR (1,10) gen :: (Int, StdGen)
number' = fst . head $ number
if number' == cpuNumber
then putStrLn "Wow! You've guessed it!"
else putStrLn $ "Bad luck mate! It was " ++ show cpuNumber
guess g' | RAFIRAF/HASKELL | IO/guessNumber2.hs | mit | 610 | 0 | 14 | 161 | 197 | 99 | 98 | 17 | 2 |
{-# LANGUAGE OverloadedStrings, BangPatterns #-}
module CSV_Transport where
import Data.Time
import Data.Csv
import Prelude hiding (FilePath)
import DatabaseTransport
import Control.Applicative
import Control.Concurrent.Spawn
import Filesystem ()
import Filesystem.Path (FilePath)
import Debug.Trace
import Control.Monad.State
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.List as L
import qualified Data.Vector as V
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as LB
-- import Control.Concurrent.Async
import Types
-- | Makes a CSV of all the parameters of a certain site with pid vals as column headers
-- makeLocationCSV :: FilePath -> IO ()
timeStart :: Maybe UTCTime
timeStart = parseArchiveTime "2012-08-02 00:00:00"
timeEnd :: Maybe UTCTime
timeEnd = parseArchiveTime "2012-08-16 00:12:45"
data OnpingReportRow = OPRR { oprrTime :: UTCTime, oprrData :: S.Set OnpingTagHistory}
deriving (Eq, Show)
newtype OnpingReport = OnpingReport (M.Map UTCTime OnpingReportRow)
deriving (Eq,Show)
instance ToNamedRecord OnpingReportRow where
toNamedRecord (OPRR t setOD) = let
oD = V.fromList.S.toList $ setOD
timeResult = "time" .= (encodeArchiveTime.Just $ t)
valNames = (BC.pack.show.pid) `V.map` oD
valResult = V.zipWith (\d n -> n .= d) (val `V.map` oD) (valNames)
in namedRecord $ timeResult : (V.toList valResult)
insertOnpingReportRow :: OnpingTagHistory -> OnpingReportRow -> OnpingReportRow
insertOnpingReportRow tgt o@(OPRR tm od) = case S.member tgt od of
True -> o
False -> OPRR tm (S.insert tgt od )
emptyReportRow :: NameSet -> UTCTime -> OnpingReportRow
emptyReportRow ns t = OPRR t (S.map (\p -> p { time = (Just t)} ) ns)
nameSet :: S.Set OnpingTagHistory -> S.Set OnpingTagHistory
nameSet s = S.map nothingButTheName s
where nothingButTheName (OnpingTagHistory _ p _) = OnpingTagHistory Nothing p Nothing
type NameSet = S.Set OnpingTagHistory
makeOnpingReportMap :: NameSet -> V.Vector OnpingTagHistory -> OnpingReport
makeOnpingReportMap ns v = OnpingReport $ V.foldl' foldFcn M.empty v
where foldFcn = (\opr cand@(OnpingTagHistory (Just t) _ _) ->
case M.lookup t opr of
(Just reportRow) -> M.insert t (insertOnpingReportRow cand reportRow ) opr
Nothing -> M.insert t (insertOnpingReportRow cand $ (emptyReportRow ns t)) opr )
makeReportVector :: NominalDiffTime -> OnpingReport -> V.Vector OnpingReportRow
makeReportVector delta (OnpingReport onpingR) = V.fromList $ M.foldl foldFcn [] onpingR
where foldFcn [] rr_target = rr_target : []
foldFcn rr_list@((OPRR tlast _):_) rr_target@(OPRR t _)
|(abs (diffUTCTime tlast t)) >= (abs delta) = rr_target:rr_list
| otherwise = rr_list
makeLocationCSV :: FilePath -> IO ()
makeLocationCSV f = do
putStrLn "Get Time"
t <- getCurrentTime
putStrLn "Get Location"
-- lfp <- getLocationPaths f
let lp = (LocationPath (DatedFile t f))
let selectedFilter = dateRangeFilter timeStart timeEnd -- idFilter
delta = realToFrac 60
putStrLn "put params"
pp <- getParamPaths lp
!pf <- (mapM getParamFileNames pp)>>= (\lst -> return $ concat lst)
putStrLn "build data"
let pbsz = 4
parSeparator [] = []
parSeparator !lst = (take pbsz lst):(parSeparator (drop pbsz lst))
!othLst <- parMapIO (mapM (buildMongoRecords $ selectedFilter )) (parSeparator pf)
putStrLn "build names"
let othSet = S.fromList $ concat $ concat othLst
ns = nameSet othSet
names = V.fromList $ "time" : ( S.toList $ S.map (BC.pack.show.pid) othSet )
putStrLn "build CSV"
let repVect = (makeReportVector delta).(makeOnpingReportMap ns).V.fromList.S.toList $ othSet
B.writeFile "report_output.csv" $ LB.toStrict $ encodeByName names $ repVect
putStrLn "done"
| smurphy8/dbTransport | CSV_Transport.hs | mit | 4,009 | 5 | 17 | 835 | 1,268 | 658 | 610 | 81 | 2 |
module Philed.Data.SemigroupExtras where
import Data.Function
import Data.Semigroup
import Philed.Data.Pos
import Prelude hiding (pred)
-- | Recursive definitions of natural number multiplication
multiplyP1 :: Semigroup m => P -> m -> m
multiplyP1 SZ x = x
multiplyP1 (S p) x = x <> multiplyP1 p x
multiply1 :: (Integral a, Semigroup m) => Pos a -> m -> m
multiply1 p = (toP p `multiplyP1`)
multiplyInf :: Semigroup m => m -> m
multiplyInf x = fix (x <>)
| Chattered/PhilEdCommon | Philed/Data/SemigroupExtras.hs | mit | 462 | 0 | 7 | 86 | 167 | 91 | 76 | 12 | 1 |
{-# LANGUAGE CPP, NoImplicitPrelude #-}
#if __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
#if MIN_VERSION_base(4,10,0) && !(MIN_VERSION_base(4,12,0))
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeInType #-}
#endif
module Prelude.Compat (
#if MIN_VERSION_base(4,12,0)
module Base
#else
either
, all
, and
, any
, concat
, concatMap
, mapM_
, notElem
, or
, sequence_
, (<$>)
, maybe
, lines
, unlines
, unwords
, words
, curry
, fst
, snd
, uncurry
, ($!)
, (++)
, (.)
, (=<<)
, asTypeOf
, const
, flip
, id
, map
, otherwise
, until
, ioError
, userError
, (!!)
, break
, cycle
, drop
, dropWhile
, filter
, head
, init
, iterate
, last
, lookup
, repeat
, replicate
, reverse
, scanl
, scanl1
, scanr
, scanr1
, span
, splitAt
, tail
, take
, takeWhile
, unzip
, unzip3
, zip
, zip3
, zipWith
, zipWith3
, subtract
, lex
, readParen
, (^)
, (^^)
, even
, fromIntegral
, gcd
, lcm
, odd
, realToFrac
, showChar
, showParen
, showString
, shows
, appendFile
, getChar
, getContents
, getLine
, interact
, print
, putChar
, putStr
, putStrLn
, readFile
, readIO
, readLn
, writeFile
, read
, reads
, (&&)
, not
, (||)
, ($)
, error
, errorWithoutStackTrace
, undefined
, seq
, elem
, foldMap
, foldl
, foldl1
, foldr
, foldr1
, length
, maximum
, minimum
, null
, product
, sum
, mapM
, sequence
, sequenceA
, traverse
, (*>)
, (<*)
, (<*>)
, pure
, (<$)
, fmap
, (>>)
, (>>=)
, fail
, return
, mappend
, mconcat
, mempty
# if MIN_VERSION_base(4,9,0)
, (<>)
# endif
, maxBound
, minBound
, enumFrom
, enumFromThen
, enumFromThenTo
, enumFromTo
, fromEnum
, pred
, succ
, toEnum
, (**)
, acos
, acosh
, asin
, asinh
, atan
, atanh
, cos
, cosh
, exp
, log
, logBase
, pi
, sin
, sinh
, sqrt
, tan
, tanh
, atan2
, decodeFloat
, encodeFloat
, exponent
, floatDigits
, floatRadix
, floatRange
, isDenormalized
, isIEEE
, isInfinite
, isNaN
, isNegativeZero
, scaleFloat
, significand
, (*)
, (+)
, (-)
, abs
, negate
, signum
, readList
, readsPrec
, (/)
, fromRational
, recip
, div
, divMod
, mod
, quot
, quotRem
, rem
, toInteger
, toRational
, ceiling
, floor
, properFraction
, round
, truncate
, show
, showList
, showsPrec
, (/=)
, (==)
, (<)
, (<=)
, (>)
, (>=)
, compare
, max
, min
-- classes
, Applicative
, Bounded
, Enum
, Eq
, Floating
, Foldable
, Fractional
, Functor
, Integral
, Monad
#if MIN_VERSION_base(4,9,0)
, MonadFail
#endif
, Monoid
, Num (fromInteger)
, Ord
, Read
, Real
, RealFloat
, RealFrac
# if MIN_VERSION_base(4,9,0)
, Semigroup
# endif
, Show
, Traversable
-- data types
, IO
, Char
, Double
, Float
, Int
, Integer
, Word
, Bool (True, False)
, Either(Left, Right)
, Maybe(Just, Nothing)
, Ordering (EQ, GT, LT)
-- type synonyms
, FilePath
, IOError
, Rational
, ReadS
, ShowS
, String
#endif
) where
#if MIN_VERSION_base(4,9,0)
import Prelude as Base hiding (
# if !(MIN_VERSION_base(4,13,0))
fail
# if MIN_VERSION_base(4,10,0) && !(MIN_VERSION_base(4,12,0))
, ($!)
# endif
# endif
)
#else
import Prelude hiding (
length
, null
, foldr
, mapM
, sequence
, all
, and
, any
, concat
, concatMap
, mapM
, mapM_
, notElem
, or
, sequence
, sequence_
, elem
, foldl
, foldl1
, foldr1
, maximum
, minimum
, product
, sum
)
import Data.Foldable.Compat
import Data.Traversable
# if !(MIN_VERSION_base(4,8,0))
import Control.Applicative
import Data.Monoid
import Data.Word
# endif
#endif
#if MIN_VERSION_base(4,9,0) && !(MIN_VERSION_base(4,11,0))
import Data.Semigroup as Base (Semigroup((<>)))
#endif
#if MIN_VERSION_base(4,9,0) && !(MIN_VERSION_base(4,13,0))
import Control.Monad.Fail as Base (MonadFail(fail))
#endif
#if MIN_VERSION_base(4,10,0) && !(MIN_VERSION_base(4,12,0))
import GHC.Exts (TYPE)
#endif
#if !(MIN_VERSION_base(4,9,0))
-- | A variant of 'error' that does not produce a stack trace.
--
-- /Since: 4.9.0.0/
errorWithoutStackTrace :: [Char] -> a
errorWithoutStackTrace s = error s
{-# NOINLINE errorWithoutStackTrace #-}
#endif
#if MIN_VERSION_base(4,10,0) && !(MIN_VERSION_base(4,12,0))
-- | Strict (call-by-value) application operator. It takes a function and an
-- argument, evaluates the argument to weak head normal form (WHNF), then calls
-- the function with that value.
infixr 0 $!
($!) :: forall r a (b :: TYPE r). (a -> b) -> a -> b
f $! x = let !vx = x in f vx -- see #2273
#endif
| haskell-compat/base-compat | base-compat/src/Prelude/Compat.hs | mit | 4,365 | 0 | 9 | 870 | 319 | 221 | 98 | 289 | 1 |
--
--
--
------------------
-- Exercise 12.42.
------------------
--
--
--
module E'12'42 where
| pascal-knodel/haskell-craft | _/links/E'12'42.hs | mit | 106 | 0 | 2 | 24 | 13 | 12 | 1 | 1 | 0 |
-- Reverse a list.
module Reverse where
import Prelude hiding (reverse)
reverse :: [t] -> [t]
reverse list
= reverse' list []
where
reverse' :: [t] -> [t] -> [t]
reverse' [] listAccumulator = listAccumulator
reverse' (item : remainingItems) listAccumulator = reverse' remainingItems $! (item : listAccumulator)
{- GHCi>
reverse []
reverse [1]
reverse [1, 2]
-}
-- []
-- [1]
-- [2, 1]
| pascal-knodel/haskell-craft | Examples/· Recursion/· Tail Recursion/Lists/Reverse.hs | mit | 413 | 0 | 9 | 93 | 115 | 66 | 49 | 8 | 2 |
module MonadPlus
()where
import Control.Monad
lookupM :: (MonadPlus m, Eq a) => a -> [(a, b)] -> m b
lookupM _ [] = mzero
lookupM k ((x,y):xys)
| x == k = return y `mplus` lookupM k xys
| otherwise = lookupM k xys
x `zeroMod` n = guard ((x `mod` n) == 0) >> return x
| Numberartificial/workflow | snipets/src/RealWordHaskell/Ch15/MonadPlus.hs | mit | 282 | 0 | 10 | 72 | 164 | 87 | 77 | 9 | 1 |
{-# LANGUAGE CPP #-}
{- |
Module : $Header$
Description : utility functions that can't be found in the libraries
Copyright : (c) Klaus Luettich, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Utility functions that can't be found in the libraries
but should be shared across Hets.
-}
module Common.Utils
( isSingleton
, replace
, hasMany
, number
, combine
, trim
, trimLeft
, trimRight
, nubOrd
, nubOrdOn
, atMaybe
, readMaybe
, mapAccumLM
, mapAccumLCM
, concatMapM
, composeMap
, keepMins
, splitOn
, splitPaths
, splitBy
, splitByList
, numberSuffix
, basename
, dirname
, fileparse
, stripDir
, stripSuffix
, makeRelativeDesc
, getEnvSave
, getEnvDef
, filterMapWithList
, timeoutSecs
, executeProcess
, timeoutCommand
, withinDirectory
, writeTempFile
, getTempFile
, getTempFifo
, readFifo
, verbMsg
, verbMsgLn
, verbMsgIO
, verbMsgIOLn
) where
import Data.Char
import Data.List
import Data.Maybe
import qualified Data.Map as Map
import qualified Data.Set as Set
import System.Directory
import System.Environment
import System.Exit
import System.FilePath (joinPath, makeRelative, equalFilePath, takeDirectory)
import System.IO
import System.IO.Error (isEOFError)
import System.Process
import System.Timeout
#ifdef UNIX
import System.Posix.Files (createNamedPipe, unionFileModes,
ownerReadMode, ownerWriteMode)
import System.Posix.IO (OpenMode (ReadWrite), defaultFileFlags,
openFd, closeFd, fdRead)
import Control.Concurrent (threadDelay, forkIO, killThread)
import Control.Concurrent.MVar (MVar, newEmptyMVar, takeMVar, putMVar)
import Control.Exception as Exception
import System.IO.Unsafe (unsafeInterleaveIO)
#endif
import Control.Monad
{- | Writes the message to the given handle unless the verbosity is less than
the message level. -}
verbMsg :: Handle -- ^ Output handle
-> Int -- ^ global verbosity
-> Int -- ^ message level
-> String -- ^ message level
-> IO ()
verbMsg hdl v lvl = when (lvl <= v) . hPutStr hdl
-- | Same as 'verbMsg' but with a newline at the end
verbMsgLn :: Handle -> Int -> Int -> String -> IO ()
verbMsgLn hdl v lvl = when (lvl <= v) . hPutStrLn hdl
-- | 'verbMsg' with stdout as handle
verbMsgIO :: Int -> Int -> String -> IO ()
verbMsgIO = verbMsg stdout
-- | 'verbMsgLn' with stdout as handle
verbMsgIOLn :: Int -> Int -> String -> IO ()
verbMsgIOLn = verbMsgLn stdout
{- | replace all occurrences of the first (non-empty sublist) argument
with the second argument in the third (list) argument. -}
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace sl r = case sl of
[] -> error "Common.Utils.replace: empty list"
_ -> concat . unfoldr (\ l -> case l of
[] -> Nothing
hd : tl -> Just $ case stripPrefix sl l of
Nothing -> ([hd], tl)
Just rt -> (r, rt))
-- | add indices to a list starting from one
number :: [a] -> [(a, Int)]
number = flip zip [1 ..]
-- | /O(1)/ test if the set's size is one
isSingleton :: Set.Set a -> Bool
isSingleton s = Set.size s == 1
-- | /O(1)/ test if the set's size is greater one
hasMany :: Set.Set a -> Bool
hasMany s = Set.size s > 1
{- | Transform a list @[l1, l2, ... ln]@ to (in sloppy notation)
@[[x1, x2, ... xn] | x1 <- l1, x2 <- l2, ... xn <- ln]@
(this is just the 'sequence' function!) -}
combine :: [[a]] -> [[a]]
combine = sequence
-- see http://www.haskell.org/pipermail/haskell-cafe/2009-November/069490.html
-- | trims a string both on left and right hand side
trim :: String -> String
trim = trimRight . trimLeft
-- | trims a string only on the left side
trimLeft :: String -> String
trimLeft = dropWhile isSpace
-- | trims a string only on the right side
trimRight :: String -> String
trimRight = foldr (\ c cs -> if isSpace c && null cs then [] else c : cs) ""
{- | The 'nubWith' function accepts as an argument a \"stop list\" update
function and an initial stop list. The stop list is a set of list elements
that 'nubWith' uses as a filter to remove duplicate elements. The stop list
is normally initially empty. The stop list update function is given a list
element a and the current stop list b, and returns 'Nothing' if the element is
already in the stop list, else 'Just' b', where b' is a new stop list updated
to contain a. -}
nubWith :: (a -> b -> Maybe b) -> b -> [a] -> [a]
nubWith f s es = case es of
[] -> []
e : rs -> case f e s of
Just s' -> e : nubWith f s' rs
Nothing -> nubWith f s rs
nubOrd :: Ord a => [a] -> [a]
nubOrd = nubOrdOn id
nubOrdOn :: Ord b => (a -> b) -> [a] -> [a]
nubOrdOn g = let f a s = let e = g a in
if Set.member e s then Nothing else Just (Set.insert e s)
in nubWith f Set.empty
-- | safe variant of !!
atMaybe :: [a] -> Int -> Maybe a
atMaybe l i = if i < 0 then Nothing else case l of
[] -> Nothing
x : r -> if i == 0 then Just x else atMaybe r (i - 1)
readMaybe :: Read a => String -> Maybe a
readMaybe s = case filter (all isSpace . snd) $ reads s of
[(a, _)] -> Just a
_ -> Nothing
-- | generalization of mapAccumL to monads
mapAccumLM :: Monad m
=> (acc -> x -> m (acc, y))
{- ^ Function taking accumulator and list element,
returning new accumulator and modified list element -}
-> acc -- ^ Initial accumulator
-> [x] -- ^ Input list
-> m (acc, [y]) -- ^ Final accumulator and result list
mapAccumLM f s l = case l of
[] -> return (s, [])
x : xs -> do
(s', y) <- f s x
(s'', ys) <- mapAccumLM f s' xs
return (s'', y : ys)
-- | generalization of mapAccumL to monads with combine function
mapAccumLCM :: (Monad m) => (a -> b -> c) -> (acc -> a -> m (acc, b))
-> acc -> [a] -> m (acc, [c])
mapAccumLCM g f s l = case l of
[] -> return (s, [])
x : xs -> do
(s', y) <- f s x
(s'', ys) <- mapAccumLCM g f s' xs
return (s'', g x y : ys)
{- | Monadic version of concatMap
taken from http://darcs.haskell.org/ghc/compiler/utils/MonadUtils.hs -}
concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM f = liftM concat . mapM f
-- | composition of arbitrary maps
composeMap :: Ord a => Map.Map a b -> Map.Map a a -> Map.Map a a -> Map.Map a a
composeMap s m1 m2 = if Map.null m2 then m1 else Map.intersection
(Map.foldWithKey ( \ i j ->
let k = Map.findWithDefault j j m2 in
if i == k then Map.delete i else Map.insert i k) m2 m1) s
-- | keep only minimal elements
keepMins :: (a -> a -> Bool) -> [a] -> [a]
keepMins lt l = case l of
[] -> []
x : r -> let s = filter (not . lt x) r
m = keepMins lt s
in if any (`lt` x) s then m
else x : m
{- |
A function inspired by the perl function split. A list is splitted
on a separator element in smaller non-empty lists.
The separator element is dropped from the resulting list.
-}
splitOn :: Eq a => a -- ^ separator
-> [a] -- ^ list to split
-> [[a]]
splitOn x = filter (not . null) . splitBy x
-- | split a colon (or on windows semicolon) separated list of paths
splitPaths :: String -> [FilePath]
splitPaths = splitOn
#ifdef UNIX
':'
#else
';'
#endif
{- |
Same as splitOn but empty lists are kept. Even the empty list is split into
a singleton list containing the empty list.
-}
splitBy :: Eq a => a -- ^ separator
-> [a] -- ^ list to split
-> [[a]]
splitBy c l = let (p, q) = break (c ==) l in p : case q of
[] -> []
_ : r -> splitBy c r
{- | Same as splitBy but the separator is a sublist not only one element.
Note that the separator must be non-empty. -}
splitByList :: Eq a => [a] -> [a] -> [[a]]
splitByList sep l = case l of
[] -> [[]]
h : t -> case stripPrefix sep l of
Just suf -> [] : splitByList sep suf
Nothing -> let f : r = splitByList sep t in (h : f) : r
{- | If the given string is terminated by a decimal number
this number and the nonnumber prefix is returned. -}
numberSuffix :: String -> Maybe (String, Int)
numberSuffix s =
let f a r@(x, y, b) =
let b' = isDigit a
y' = y + x * digitToInt a
out | not b = r
| b && b' = (x * 10, y', b')
| otherwise = (x, y, False)
in out
in case foldr f (1, 0, True) s of
(1, _, _) ->
Nothing
(p, n, _) ->
Just (take (1 + length s - length (show p)) s, n)
{- |
A function inspired by a perl function from the standard perl-module
File::Basename. It removes the directory part of a filepath.
-}
basename :: FilePath -> FilePath
basename = snd . stripDir
{- |
A function inspired by a perl function from the standard perl-module
File::Basename. It gives the directory part of a filepath.
-}
dirname :: FilePath -> FilePath
dirname = fst . stripDir
{- |
A function inspired by a perl function from the standard perl-module
File::Basename. It splits a filepath into the basename, the
directory and gives the suffix that matched from the list of
suffixes. If a suffix matched it is removed from the basename.
-}
fileparse :: [String] -- ^ list of suffixes
-> FilePath
-> (FilePath, FilePath, Maybe String)
-- ^ (basename,directory,matched suffix)
fileparse sufs fp = let (path, base) = stripDir fp
(base', suf) = stripSuffix sufs base
in (base', path, suf)
stripDir :: FilePath -> (FilePath, FilePath)
stripDir =
(\ (x, y) -> (if null y then "./" else reverse y, reverse x))
. break (== '/') . reverse
stripSuffix :: [String] -> FilePath -> (FilePath, Maybe String)
stripSuffix suf fp = case filter isJust $ map (stripSuf fp) suf of
Just (x, s) : _ -> (x, Just s)
_ -> (fp, Nothing)
where stripSuf f s | s `isSuffixOf` f =
Just (take (length f - length s) f, s)
| otherwise = Nothing
{- |
This function generalizes makeRelative in that it computes also a relative
path with descents such as ../../test.txt
-}
makeRelativeDesc :: FilePath -- ^ path to a directory
-> FilePath -- ^ to be computed relatively to given directory
-> FilePath -- ^ resulting relative path
makeRelativeDesc dp fp = f dp fp []
where f "" y l = joinPath $ l ++ [y]
f x y l = let y' = makeRelative x y
in if equalFilePath y y'
then f (takeDirectory x) y $ ".." : l
else joinPath $ l ++ [y']
{- | filter a map according to a given list of keys (it dosen't hurt
if a key is not present in the map) -}
filterMapWithList :: Ord k => [k] -> Map.Map k e -> Map.Map k e
filterMapWithList = filterMapWithSet . Set.fromList
{- | filter a map according to a given set of keys (it dosen't hurt if
a key is not present in the map) -}
filterMapWithSet :: Ord k => Set.Set k -> Map.Map k e -> Map.Map k e
filterMapWithSet s = Map.filterWithKey (\ k _ -> Set.member k s)
{- | get, parse and check an environment variable; provide the default
value, only if the envionment variable is not set or the
parse-check-function returns Nothing -}
getEnvSave :: a -- ^ default value
-> String -- ^ name of environment variable
-> (String -> Maybe a) -- ^ parse and check value of variable
-> IO a
getEnvSave defValue envVar readFun =
liftM (maybe defValue (fromMaybe defValue . readFun)
. lookup envVar) getEnvironment
-- | get environment variable
getEnvDef :: String -- ^ environment variable
-> String -- ^ default value
-> IO String
getEnvDef envVar defValue = getEnvSave defValue envVar Just
-- | the timeout function taking seconds instead of microseconds
timeoutSecs :: Int -> IO a -> IO (Maybe a)
timeoutSecs time = timeout $ let
m = 1000000
u = div maxBound m
in if time > u then maxBound else
if time < 1 then 100000 -- 1/10 of a second
else m * time
-- | like readProcessWithExitCode, but checks the command argument first
executeProcess
:: FilePath -- ^ command to run
-> [String] -- ^ any arguments
-> String -- ^ standard input
-> IO (ExitCode, String, String) -- ^ exitcode, stdout, stderr
executeProcess cmd args input = do
mp <- findExecutable cmd
case mp of
Nothing -> return (ExitFailure 127, "", "command not found: " ++ cmd)
Just exe -> readProcessWithExitCode exe args input
-- | runs a command with timeout
timeoutCommand :: Int -> FilePath -> [String]
-> IO (Maybe (ExitCode, String, String))
timeoutCommand time cmd args =
timeoutSecs time $
executeProcess cmd args "" -- no input from stdin
{- | runs an action in a different directory without changing the current
directory globally. -}
withinDirectory :: FilePath -> IO a -> IO a
withinDirectory p a = do
d <- getCurrentDirectory
setCurrentDirectory p
r <- a
setCurrentDirectory d
return r
-- | calls openTempFile but directly writes content and closes the file
writeTempFile :: String -- ^ Content
-> FilePath -- ^ Directory in which to create the file
-> String -- ^ File name template
-> IO FilePath -- ^ create file
writeTempFile str tmpDir file = do
(tmpFile, hdl) <- openTempFile tmpDir file
hPutStr hdl str
hFlush hdl
hClose hdl
return tmpFile
-- | create file in temporary directory (the first argument is the content)
getTempFile :: String -- ^ Content
-> String -- ^ File name template
-> IO FilePath -- ^ create file
getTempFile str file = do
tmpDir <- getTemporaryDirectory
writeTempFile str tmpDir file
#ifdef UNIX
getTempFifo :: String -> IO FilePath
getTempFifo f = do
tmpDir <- getTemporaryDirectory
(tmpFile, hdl) <- openTempFile tmpDir f
hClose hdl
removeFile tmpFile
createNamedPipe tmpFile $ unionFileModes ownerReadMode ownerWriteMode
return tmpFile
#else
getTempFifo :: String -> IO FilePath
getTempFifo _ = return ""
#endif
#ifdef UNIX
type Pipe = (IO (), MVar String)
#endif
#ifdef UNIX
openFifo :: FilePath -> IO Pipe
openFifo fp = do
mvar <- newEmptyMVar
let readF fd = forever (fmap fst (fdRead fd 100) >>= putMVar mvar)
`Exception.catch`
\ e -> const (threadDelay 100) (e :: Exception.IOException)
let reader = forever $ do
fd <- openFd fp ReadWrite Nothing defaultFileFlags
readF fd `Exception.catch`
\ e -> closeFd fd >>
if isEOFError e then reader
else throwIO (e :: Exception.IOException)
return (reader, mvar)
readFifo' :: MVar String -> IO [String]
readFifo' mvar = do
x <- unsafeInterleaveIO $ takeMVar mvar
xs <- unsafeInterleaveIO $ readFifo' mvar
return $ x : xs
readFifo :: FilePath -> IO ([String], IO ())
readFifo fp = do
(reader, pipe) <- openFifo fp
tid <- forkIO reader
l <- readFifo' pipe
m <- newEmptyMVar
forkIO $ takeMVar m >> killThread tid
return (l, putMVar m ())
#else
readFifo :: FilePath -> IO ([String], IO ())
readFifo _ = return ([], return ())
#endif
| nevrenato/HetsAlloy | Common/Utils.hs | gpl-2.0 | 15,344 | 0 | 20 | 4,100 | 4,174 | 2,202 | 1,972 | 273 | 4 |
module Weeder where
import Control.Applicative
import Control.Monad
import Data.Maybe
import Data.List
import AST
import Util
type WeedError = Maybe String
-- Takes a filename and CompilationUnit and returns Just an error message if invalid and Nothing if valid
weed :: String -> CompilationUnit -> WeedError
weed filename unit = weedTypeDec filename $ definition unit
weedTypeDec :: String -> TypeDec -> WeedError
weedTypeDec filename (CLS modifiers name _ _ constructors fields methods info)
| all (`elem` modifiers) ["abstract", "final"] = Just $ "Cannot have a class that is abstract AND final" ++ show info
| (nub modifiers) /= modifiers = Just $ "Class modifiers cannot be repeated" ++ show info
| "private" `elem` modifiers = Just $ "Classes cannot be private" ++ show info
| not (any (`elem` modifiers) ["public", "protected"]) = Just $ "Class must have acces modifier" ++ show info
| methodError /= Nothing = methodError
| fieldError /= Nothing = fieldError
| constructorError /= Nothing = constructorError
| name /= correctName = Just $ "Expected class to be named '" ++ correctName ++ "' but saw '" ++ name ++ "'" ++ show info
| shouldBeAbstract && not ("abstract" `elem` modifiers) = Just $ name ++ " has an abstract method but isn't abstract"
| otherwise = Nothing
where methodError = weedClassMethods methods
fieldError = weedFields fields
constructorError = msum $ map weedConstructor constructors
fileName = last $ splitOneOf "/" filename
fileNameSplit = splitOneOf "." fileName
correctName = foldl (++) "" (take ((length fileNameSplit) - 1) fileNameSplit)
shouldBeAbstract = any (\mthd -> "abstract" `elem` (methodModifiers mthd)) methods
weedTypeDec filename (ITF modifiers name _ methods info)
| name == "ObjectInterface" = Nothing
| "private" `elem` modifiers = Just $ "Interfaces cannot be private" ++ show info
| (nub modifiers) /= modifiers = Just $ "Interface modifiers cannot be repeated" ++ show info
| methodError /= Nothing = methodError
| name /= correctName = Just $ "Expected class to be named '" ++ correctName ++ "' but saw '" ++ name ++ "'" ++ show info
| otherwise = Nothing
where methodError = weedInterfaceMethods methods
correctName = head $ splitOneOf "." (last (splitOneOf "/" filename))
weedConstructor :: Constructor -> WeedError
weedConstructor (Cons modifiers name params invocation definition info)
| isJust definitionError = definitionError
| isJust invocationError = invocationError
| otherwise = Nothing
where definitionError = weedStatementBlock definition
invocationError = if isJust invocation then weedExpression $ fromJust invocation else Nothing
weedTypedVar :: TypedVar -> WeedError
weedTypedVar typedVar = Nothing
weedClassMethods :: [Method] -> WeedError
weedClassMethods methods = msum $ map weedClassMethod methods
weedClassMethod :: Method -> WeedError
weedClassMethod (MTD modifiers var params definition info)
| (nub modifiers) /= modifiers = Just $ "Method modifiers cannot be repeated" ++ show info
| length (filter (`elem` modifiers) ["public", "protected"]) /= 1 = Just $ "One and only one access modifier is allowed" ++ show info
| all (`elem` modifiers) ["static", "final"] = Just $ "A static method cannot be final" ++ show info
| ("native" `elem` modifiers) && not ("static" `elem` modifiers) = Just $ "Native methods must be static" ++ show info
| "private" `elem` modifiers = Just $ "Methods cannot be private" ++ show info
| "abstract" `elem` modifiers && "static" `elem` modifiers = Just $ "Abstract methods cannot be static" ++ show info
| "abstract" `elem` modifiers && "final" `elem` modifiers = Just $ "Abstract methods cannot be final" ++ show info
| "abstract" `elem` modifiers && "native" `elem` modifiers = Just $ "Abstract methods cannot be native" ++ show info
| "abstract" `elem` modifiers && "strictfp" `elem` modifiers = Just $ "Abstract methods cannot be strictfp" ++ show info
| "abstract" `elem` modifiers && "synchronized" `elem` modifiers = Just $ "Abstract methods cannot be synchronized" ++ show info
| "native" `elem` modifiers && "strictfp" `elem` modifiers = Just $ "Native methods cannot be strictfp" ++ show info
| any (`elem` modifiers) ["abstract", "native"] && isJust definition = Just $ "Abstract/Native methods cannot have a body" ++ show info
| not (any (`elem` modifiers) ["abstract", "native"]) && isNothing definition = Just $ "Non-abstract non-native methods must have a body" ++ show info
| isJust bodyError = bodyError
| otherwise = Nothing
where bodyError = weedStatementBlock definition
weedInterfaceMethods :: [Method] -> WeedError
weedInterfaceMethods methods = msum $ map weedInterfaceMethod methods
weedInterfaceMethod :: Method -> WeedError
weedInterfaceMethod (MTD modifiers var params definition info)
| (nub modifiers) /= modifiers = Just $ "Method modifiers cannot be repeated" ++ show info
| not (all (`elem` ["public", "abstract"]) modifiers) = Just $ "Interface methods can only have modifiers 'public' and 'abstract'" ++ show info
| isJust definition = Just $ "Interface methods cannot have a body" ++ show info
| otherwise = Nothing
weedStatementBlock :: Maybe StatementBlock -> WeedError
weedStatementBlock Nothing = Nothing
weedStatementBlock (Just block) = fmap (++ (show (statementsInfo block))) (msum $ map weedStatement (statements block))
weedStatement :: Statement -> WeedError
weedStatement (LocalVar (TV typeName name info) value)
| identifierInExpr name value = Just $ "Variable assignment cannot reference itself" ++ show info
| isJust exprError = exprError
| otherwise = Nothing
where exprError = weedExpression value
weedStatement (If ifExpression ifBlock elseBlock) = (weedExpression ifExpression)
<|> (weedStatementBlock $ Just ifBlock)
<|> (weedStatementBlock elseBlock)
weedStatement (For initializer expression statement statementBlock)
| isJust initError = initError
| isJust exprError = exprError
| isJust stmtError = stmtError
where initError = if isJust initializer then weedStatement $ fromJust initializer else Nothing
exprError = if isJust expression then weedExpression $ fromJust expression else Nothing
stmtError = if isJust statement then weedStatement $ fromJust statement else Nothing
weedStatement (While expression block)
| isJust exprError = exprError
| isJust blockError = blockError
where exprError = weedExpression expression
blockError = weedStatementBlock $ Just block
weedStatement (Block statementBlock) = weedStatementBlock $ Just statementBlock
weedStatement (Expr expr) = weedExpression expr
weedStatement (Return exp) = if isJust exp then weedExpression $ fromJust exp else Nothing
weedStatement _ = Nothing
-- TODO: Allow 2147483648 in negation
weedExpression :: Expression -> WeedError
weedExpression (Unary "-" (Value TypeInt value innerDepth) outerDepth)
| intVal > 2147483648 = Just "Integer literal out of range"
-- Again, a dirty trick to detect if the integer literal was parenthesized
| (innerDepth > outerDepth + 11) && intVal > 2147483647 = Just "Integer literal out of range"
| otherwise = Nothing
where intVal = read value
weedExpression (Unary operator expression _) = weedExpression expression
weedExpression (Binary operator left right _) = weedExpression left <|> weedExpression right
weedExpression (Attribute expression mem _) = Nothing
weedExpression (ArrayAccess array index _) = weedExpression array <|> weedExpression index
weedExpression (NewArray arrayType dimexprs _) = Nothing
weedExpression (Dimension left index _) = Nothing
weedExpression (NewObject classType args _) = Nothing
weedExpression (FunctionCall This _ _) = Just "Cannot call 'this'"
weedExpression (FunctionCall function arguments _) = Nothing
weedExpression (CastA castType dims expression _) = Nothing
weedExpression (CastB (ID _ depthA) expression depthB)
-- this is a dirty trick to detect invalidly nested expressions since they are rightfully flattened by the AST Builder
| depthA > depthB + 11 = Just "Invalid cast"
| otherwise = Nothing
weedExpression (CastB castExpression expression _) = Just "Invalid Cast"
weedExpression (CastC _ _ _ _) = Nothing
weedExpression (InstanceOf refType expression _) = Nothing
weedExpression (ID identifier _) = Nothing
weedExpression (Value TypeInt value depth)
| intVal > 2147483647 = Just "Integer literal out of range"
| otherwise = Nothing
where intVal = read value
weedExpression (Value valueType value _) = Nothing
weedExpression (This) = Nothing
weedExpression (Null) = Nothing
weedFields :: [Field] -> WeedError
weedFields fields = msum $ map weedField fields
weedField :: Field -> WeedError
weedField (FLD modifiers var val info)
| (nub modifiers) /= modifiers = Just $ "Field modifiers cannot be repeated" ++ show info
| "private" `elem` modifiers = Just $ "Class fields cannot be private" ++ show info
| not (any (`elem` modifiers) ["public", "protected"]) = Just $ "Class field must have access modifier" ++ show info
| "final" `elem` modifiers && isNothing val = Just $ "Final fields must have values" ++ show info
| otherwise = Nothing
| yangsiwei880813/CS644 | src/Weeder.hs | gpl-2.0 | 9,296 | 0 | 13 | 1,674 | 2,735 | 1,364 | 1,371 | 142 | 5 |
module Game where
import Graphics.Gloss
import Graphics.Gloss.Interface.IO.Game
import Graphics.Gloss.Data.ViewPort
import Player
import Enemies
import Background
data Direction = North | East | South | West
data GameState = Game { player :: Player, enemyList :: [Enemy], backgroundList :: [Background] , wdown :: Bool, adown :: Bool, sdown :: Bool, ddown :: Bool}
-- Polygon testwaardes
linePath :: Path
linePath = [(0, 0), (100, 0), (100, 100)]
trianglePath :: Path
trianglePath = [(0.0, 0.0), (100, 100), (-200, 200)]
lijn = line trianglePath
driehoek = polygon trianglePath
vierkant = polygon (rectanglePath 100 100)
window :: Display
-- Naam van de Window, (Breedte Window, Hoogte Window) (X-positie Window in scherm, Y-positie Window in scherm)
window = InWindow "Nice Window" (1000, 600) (10,10)
-- De kleur van de achtergrond onder de backgroundObjecten.
backgroundColor :: Color
backgroundColor = white
-- Hoeveel keer per seconde een GameState wordt gerendered.
fps :: Int
fps = 60
startPlayer :: Player
startPlayer = PlayerInfo { playerX = 0.0, playerY = 0.0, health = 100, playerSprite = color blue vierkant }
initialState :: GameState
initialState = Game { player = startPlayer, enemyList = enemies, backgroundList = [backGround] , wdown = False, adown = False, sdown = False, ddown = False}
update :: Float -> GameState -> GameState
update _ game = combinedMove (checkOnKeys game)
-- Pas playerX of playerY aan als de speler W, A, S of D indrukt.
-- De nieuwe playerX en playerY waardes worden dan in render gebruikt om ook de Picture aan te passen.
movePlayer :: Direction -> GameState -> GameState
movePlayer North game = game { player = (player game) { playerY = yv } }
where
y = playerY (player game)
yv = y + 10
movePlayer East game = game { player = (player game) { playerX = xv } }
where
x= playerX (player game)
xv = x + 10
movePlayer South game = game { player = (player game) { playerY = yv } }
where
y = playerY (player game)
yv = y - 10
movePlayer West game = game { player = (player game) { playerX = xv } }
where
x= playerX (player game)
xv = x - 10
-- Functie die de positie van alle vijanden en achtergrondobjecten aanpast.
-- De functie geeft dus een GameState terug waarin de enemyX, enemyY, backX en backY van alle vijanden en achtergrondobjecten zijn aangepast.
combinedMove :: GameState -> GameState
combinedMove game = game { enemyList = newEnemyList, backgroundList = newBackgroundList }
where
newEnemyList = map moveEnemy (enemyList game)
newBackgroundList = map moveBackground (backgroundList game)
-- Neemt een GameState en lijst van Pictures en zet het om naar één Picture voor de display methode in main.
render :: GameState -> Picture
render game = pictures pics
where
-- De volgorde bepaalt welke Pictures als eerste worden gerendered.
-- Meest linkse gaan als eerste.
pics = backgroundPics ++ enemyPics ++ playerPic
backgroundPics = map moveBackgroundPicture (backgroundList game)
enemyPics = map moveEnemyPicture (enemyList game)
playerPic = [movePlayerPicture (player game)]
checkOnKeys :: GameState -> GameState
checkOnKeys game | w = movePlayer North game
| a = movePlayer West game
| s = movePlayer South game
| d = movePlayer East game
| otherwise = game
where
w = wdown game
a = adown game
s = sdown game
d = ddown game | ThomasBDev/Iron-Rat | src/Game.hs | gpl-2.0 | 3,878 | 0 | 10 | 1,152 | 907 | 514 | 393 | 61 | 1 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Algebraic2.Instance where
import Expression.Op
import qualified Autolib.TES.Binu as B
import Autolib.TES.Identifier
import Data.Typeable
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Set
import Autolib.FiniteMap
data Ops a => Type c a =
Make { context :: c
, target :: a
, description :: Maybe String
, operators :: B.Binu ( Op a )
, predefined :: FiniteMap Identifier a
, max_size :: Int
}
deriving ( Typeable )
$(derives [makeReader, makeToDoc] [''Type])
-- local variables:
-- mode: haskell
-- end;
| Erdwolf/autotool-bonn | src/Algebraic2/Instance.hs | gpl-2.0 | 624 | 2 | 11 | 134 | 160 | 96 | 64 | 19 | 0 |
{-# LANGUAGE DeriveDataTypeable, CPP, MultiParamTypeClasses,
FlexibleContexts, ScopedTypeVariables #-}
{-
Copyright (C) 2006-2014 John MacFarlane <[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
-}
{- |
Module : Text.Pandoc.Shared
Copyright : Copyright (C) 2006-2014 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Utility functions and definitions used by the various Pandoc modules.
-}
module Text.Pandoc.Shared (
-- * List processing
splitBy,
splitByIndices,
splitStringByIndices,
substitute,
-- * Text processing
backslashEscapes,
escapeStringUsing,
stripTrailingNewlines,
trim,
triml,
trimr,
stripFirstAndLast,
camelCaseToHyphenated,
toRomanNumeral,
escapeURI,
tabFilter,
-- * Date/time
normalizeDate,
-- * Pandoc block and inline list processing
orderedListMarkers,
normalizeSpaces,
normalize,
stringify,
compactify,
compactify',
compactify'DL,
Element (..),
hierarchicalize,
uniqueIdent,
isHeaderBlock,
headerShift,
isTightList,
addMetaField,
makeMeta,
-- * TagSoup HTML handling
renderTags',
-- * File handling
inDirectory,
readDataFile,
readDataFileUTF8,
fetchItem,
openURL,
-- * Error handling
err,
warn,
-- * Safe read
safeRead
) where
import Text.Pandoc.Definition
import Text.Pandoc.Walk
import Text.Pandoc.Generic
import Text.Pandoc.Builder (Inlines, Blocks, ToMetaValue(..))
import qualified Text.Pandoc.Builder as B
import qualified Text.Pandoc.UTF8 as UTF8
import System.Environment (getProgName)
import System.Exit (exitWith, ExitCode(..))
import Data.Char ( toLower, isLower, isUpper, isAlpha,
isLetter, isDigit, isSpace )
import Data.List ( find, isPrefixOf, intercalate )
import qualified Data.Map as M
import Network.URI ( escapeURIString, isURI, nonStrictRelativeTo,
unEscapeString, parseURIReference )
import System.Directory
import Text.Pandoc.MIME (getMimeType)
import System.FilePath ( (</>), takeExtension, dropExtension )
import Data.Generics (Typeable, Data)
import qualified Control.Monad.State as S
import qualified Control.Exception as E
import Control.Monad (msum, unless)
import Text.Pandoc.Pretty (charWidth)
import System.Locale (defaultTimeLocale)
import Data.Time
import System.IO (stderr)
import Text.HTML.TagSoup (renderTagsOptions, RenderOptions(..), Tag(..),
renderOptions)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B8
import Text.Pandoc.Compat.Monoid
import Data.ByteString.Base64 (decodeLenient)
#ifdef EMBED_DATA_FILES
import Text.Pandoc.Data (dataFiles)
import System.FilePath ( joinPath, splitDirectories )
#else
import Paths_pandoc (getDataFileName)
#endif
#ifdef HTTP_CLIENT
import Data.ByteString.Lazy (toChunks)
import Network.HTTP.Client (httpLbs, parseUrl, withManager,
responseBody, responseHeaders,
Request(port,host))
import Network.HTTP.Client.Internal (addProxy)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import System.Environment (getEnv)
import Network.HTTP.Types.Header ( hContentType)
import Network (withSocketsDo)
#else
import Network.URI (parseURI)
import Network.HTTP (findHeader, rspBody,
RequestMethod(..), HeaderName(..), mkRequest)
import Network.Browser (browse, setAllowRedirects, setOutHandler, request)
#endif
--
-- List processing
--
-- | Split list by groups of one or more sep.
splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy _ [] = []
splitBy isSep lst =
let (first, rest) = break isSep lst
rest' = dropWhile isSep rest
in first:(splitBy isSep rest')
splitByIndices :: [Int] -> [a] -> [[a]]
splitByIndices [] lst = [lst]
splitByIndices (x:xs) lst = first:(splitByIndices (map (\y -> y - x) xs) rest)
where (first, rest) = splitAt x lst
-- | Split string into chunks divided at specified indices.
splitStringByIndices :: [Int] -> [Char] -> [[Char]]
splitStringByIndices [] lst = [lst]
splitStringByIndices (x:xs) lst =
let (first, rest) = splitAt' x lst in
first : (splitStringByIndices (map (\y -> y - x) xs) rest)
splitAt' :: Int -> [Char] -> ([Char],[Char])
splitAt' _ [] = ([],[])
splitAt' n xs | n <= 0 = ([],xs)
splitAt' n (x:xs) = (x:ys,zs)
where (ys,zs) = splitAt' (n - charWidth x) xs
-- | Replace each occurrence of one sublist in a list with another.
substitute :: (Eq a) => [a] -> [a] -> [a] -> [a]
substitute _ _ [] = []
substitute [] _ xs = xs
substitute target replacement lst@(x:xs) =
if target `isPrefixOf` lst
then replacement ++ substitute target replacement (drop (length target) lst)
else x : substitute target replacement xs
--
-- Text processing
--
-- | Returns an association list of backslash escapes for the
-- designated characters.
backslashEscapes :: [Char] -- ^ list of special characters to escape
-> [(Char, String)]
backslashEscapes = map (\ch -> (ch, ['\\',ch]))
-- | Escape a string of characters, using an association list of
-- characters and strings.
escapeStringUsing :: [(Char, String)] -> String -> String
escapeStringUsing _ [] = ""
escapeStringUsing escapeTable (x:xs) =
case (lookup x escapeTable) of
Just str -> str ++ rest
Nothing -> x:rest
where rest = escapeStringUsing escapeTable xs
-- | Strip trailing newlines from string.
stripTrailingNewlines :: String -> String
stripTrailingNewlines = reverse . dropWhile (== '\n') . reverse
-- | Remove leading and trailing space (including newlines) from string.
trim :: String -> String
trim = triml . trimr
-- | Remove leading space (including newlines) from string.
triml :: String -> String
triml = dropWhile (`elem` " \r\n\t")
-- | Remove trailing space (including newlines) from string.
trimr :: String -> String
trimr = reverse . triml . reverse
-- | Strip leading and trailing characters from string
stripFirstAndLast :: String -> String
stripFirstAndLast str =
drop 1 $ take ((length str) - 1) str
-- | Change CamelCase word to hyphenated lowercase (e.g., camel-case).
camelCaseToHyphenated :: String -> String
camelCaseToHyphenated [] = ""
camelCaseToHyphenated (a:b:rest) | isLower a && isUpper b =
a:'-':(toLower b):(camelCaseToHyphenated rest)
camelCaseToHyphenated (a:rest) = (toLower a):(camelCaseToHyphenated rest)
-- | Convert number < 4000 to uppercase roman numeral.
toRomanNumeral :: Int -> String
toRomanNumeral x =
if x >= 4000 || x < 0
then "?"
else case x of
_ | x >= 1000 -> "M" ++ toRomanNumeral (x - 1000)
_ | x >= 900 -> "CM" ++ toRomanNumeral (x - 900)
_ | x >= 500 -> "D" ++ toRomanNumeral (x - 500)
_ | x >= 400 -> "CD" ++ toRomanNumeral (x - 400)
_ | x >= 100 -> "C" ++ toRomanNumeral (x - 100)
_ | x >= 90 -> "XC" ++ toRomanNumeral (x - 90)
_ | x >= 50 -> "L" ++ toRomanNumeral (x - 50)
_ | x >= 40 -> "XL" ++ toRomanNumeral (x - 40)
_ | x >= 10 -> "X" ++ toRomanNumeral (x - 10)
_ | x == 9 -> "IX"
_ | x >= 5 -> "V" ++ toRomanNumeral (x - 5)
_ | x == 4 -> "IV"
_ | x >= 1 -> "I" ++ toRomanNumeral (x - 1)
_ -> ""
-- | Escape whitespace in URI.
escapeURI :: String -> String
escapeURI = escapeURIString (not . isSpace)
-- | Convert tabs to spaces and filter out DOS line endings.
-- Tabs will be preserved if tab stop is set to 0.
tabFilter :: Int -- ^ Tab stop
-> String -- ^ Input
-> String
tabFilter tabStop =
let go _ [] = ""
go _ ('\n':xs) = '\n' : go tabStop xs
go _ ('\r':'\n':xs) = '\n' : go tabStop xs
go _ ('\r':xs) = '\n' : go tabStop xs
go spsToNextStop ('\t':xs) =
if tabStop == 0
then '\t' : go tabStop xs
else replicate spsToNextStop ' ' ++ go tabStop xs
go 1 (x:xs) =
x : go tabStop xs
go spsToNextStop (x:xs) =
x : go (spsToNextStop - 1) xs
in go tabStop
--
-- Date/time
--
-- | Parse a date and convert (if possible) to "YYYY-MM-DD" format.
normalizeDate :: String -> Maybe String
normalizeDate s = fmap (formatTime defaultTimeLocale "%F")
(msum $ map (\fs -> parsetimeWith fs s) formats :: Maybe Day)
where parsetimeWith = parseTime defaultTimeLocale
formats = ["%x","%m/%d/%Y", "%D","%F", "%d %b %Y",
"%d %B %Y", "%b. %d, %Y", "%B %d, %Y", "%Y"]
--
-- Pandoc block and inline list processing
--
-- | Generate infinite lazy list of markers for an ordered list,
-- depending on list attributes.
orderedListMarkers :: (Int, ListNumberStyle, ListNumberDelim) -> [String]
orderedListMarkers (start, numstyle, numdelim) =
let singleton c = [c]
nums = case numstyle of
DefaultStyle -> map show [start..]
Example -> map show [start..]
Decimal -> map show [start..]
UpperAlpha -> drop (start - 1) $ cycle $
map singleton ['A'..'Z']
LowerAlpha -> drop (start - 1) $ cycle $
map singleton ['a'..'z']
UpperRoman -> map toRomanNumeral [start..]
LowerRoman -> map (map toLower . toRomanNumeral) [start..]
inDelim str = case numdelim of
DefaultDelim -> str ++ "."
Period -> str ++ "."
OneParen -> str ++ ")"
TwoParens -> "(" ++ str ++ ")"
in map inDelim nums
-- | Normalize a list of inline elements: remove leading and trailing
-- @Space@ elements, collapse double @Space@s into singles, and
-- remove empty Str elements.
normalizeSpaces :: [Inline] -> [Inline]
normalizeSpaces = cleanup . dropWhile isSpaceOrEmpty
where cleanup [] = []
cleanup (Space:rest) = case dropWhile isSpaceOrEmpty rest of
[] -> []
(x:xs) -> Space : x : cleanup xs
cleanup ((Str ""):rest) = cleanup rest
cleanup (x:rest) = x : cleanup rest
isSpaceOrEmpty :: Inline -> Bool
isSpaceOrEmpty Space = True
isSpaceOrEmpty (Str "") = True
isSpaceOrEmpty _ = False
-- | Normalize @Pandoc@ document, consolidating doubled 'Space's,
-- combining adjacent 'Str's and 'Emph's, remove 'Null's and
-- empty elements, etc.
normalize :: (Eq a, Data a) => a -> a
normalize = topDown removeEmptyBlocks .
topDown consolidateInlines .
bottomUp (removeEmptyInlines . removeTrailingInlineSpaces)
removeEmptyBlocks :: [Block] -> [Block]
removeEmptyBlocks (Null : xs) = removeEmptyBlocks xs
removeEmptyBlocks (BulletList [] : xs) = removeEmptyBlocks xs
removeEmptyBlocks (OrderedList _ [] : xs) = removeEmptyBlocks xs
removeEmptyBlocks (DefinitionList [] : xs) = removeEmptyBlocks xs
removeEmptyBlocks (RawBlock _ [] : xs) = removeEmptyBlocks xs
removeEmptyBlocks (x:xs) = x : removeEmptyBlocks xs
removeEmptyBlocks [] = []
removeEmptyInlines :: [Inline] -> [Inline]
removeEmptyInlines (Emph [] : zs) = removeEmptyInlines zs
removeEmptyInlines (Strong [] : zs) = removeEmptyInlines zs
removeEmptyInlines (Subscript [] : zs) = removeEmptyInlines zs
removeEmptyInlines (Superscript [] : zs) = removeEmptyInlines zs
removeEmptyInlines (SmallCaps [] : zs) = removeEmptyInlines zs
removeEmptyInlines (Strikeout [] : zs) = removeEmptyInlines zs
removeEmptyInlines (RawInline _ [] : zs) = removeEmptyInlines zs
removeEmptyInlines (Code _ [] : zs) = removeEmptyInlines zs
removeEmptyInlines (Str "" : zs) = removeEmptyInlines zs
removeEmptyInlines (x : xs) = x : removeEmptyInlines xs
removeEmptyInlines [] = []
removeTrailingInlineSpaces :: [Inline] -> [Inline]
removeTrailingInlineSpaces = reverse . removeLeadingInlineSpaces . reverse
removeLeadingInlineSpaces :: [Inline] -> [Inline]
removeLeadingInlineSpaces = dropWhile isSpaceOrEmpty
consolidateInlines :: [Inline] -> [Inline]
consolidateInlines (Str x : ys) =
case concat (x : map fromStr strs) of
"" -> consolidateInlines rest
n -> Str n : consolidateInlines rest
where
(strs, rest) = span isStr ys
isStr (Str _) = True
isStr _ = False
fromStr (Str z) = z
fromStr _ = error "consolidateInlines - fromStr - not a Str"
consolidateInlines (Space : ys) = Space : rest
where isSp Space = True
isSp _ = False
rest = consolidateInlines $ dropWhile isSp ys
consolidateInlines (Emph xs : Emph ys : zs) = consolidateInlines $
Emph (xs ++ ys) : zs
consolidateInlines (Strong xs : Strong ys : zs) = consolidateInlines $
Strong (xs ++ ys) : zs
consolidateInlines (Subscript xs : Subscript ys : zs) = consolidateInlines $
Subscript (xs ++ ys) : zs
consolidateInlines (Superscript xs : Superscript ys : zs) = consolidateInlines $
Superscript (xs ++ ys) : zs
consolidateInlines (SmallCaps xs : SmallCaps ys : zs) = consolidateInlines $
SmallCaps (xs ++ ys) : zs
consolidateInlines (Strikeout xs : Strikeout ys : zs) = consolidateInlines $
Strikeout (xs ++ ys) : zs
consolidateInlines (RawInline f x : RawInline f' y : zs) | f == f' =
consolidateInlines $ RawInline f (x ++ y) : zs
consolidateInlines (Code a1 x : Code a2 y : zs) | a1 == a2 =
consolidateInlines $ Code a1 (x ++ y) : zs
consolidateInlines (x : xs) = x : consolidateInlines xs
consolidateInlines [] = []
-- | Convert pandoc structure to a string with formatting removed.
-- Footnotes are skipped (since we don't want their contents in link
-- labels).
stringify :: Walkable Inline a => a -> String
stringify = query go . walk deNote
where go :: Inline -> [Char]
go Space = " "
go (Str x) = x
go (Code _ x) = x
go (Math _ x) = x
go LineBreak = " "
go _ = ""
deNote (Note _) = Str ""
deNote x = x
-- | Change final list item from @Para@ to @Plain@ if the list contains
-- no other @Para@ blocks.
compactify :: [[Block]] -- ^ List of list items (each a list of blocks)
-> [[Block]]
compactify [] = []
compactify items =
case (init items, last items) of
(_,[]) -> items
(others, final) ->
case last final of
Para a -> case (filter isPara $ concat items) of
-- if this is only Para, change to Plain
[_] -> others ++ [init final ++ [Plain a]]
_ -> items
_ -> items
-- | Change final list item from @Para@ to @Plain@ if the list contains
-- no other @Para@ blocks. Like compactify, but operates on @Blocks@ rather
-- than @[Block]@.
compactify' :: [Blocks] -- ^ List of list items (each a list of blocks)
-> [Blocks]
compactify' [] = []
compactify' items =
let (others, final) = (init items, last items)
in case reverse (B.toList final) of
(Para a:xs) -> case [Para x | Para x <- concatMap B.toList items] of
-- if this is only Para, change to Plain
[_] -> others ++ [B.fromList (reverse $ Plain a : xs)]
_ -> items
_ -> items
-- | Like @compactify'@, but akts on items of definition lists.
compactify'DL :: [(Inlines, [Blocks])] -> [(Inlines, [Blocks])]
compactify'DL items =
let defs = concatMap snd items
defBlocks = reverse $ concatMap B.toList defs
in case defBlocks of
(Para x:_) -> if not $ any isPara (drop 1 defBlocks)
then let (t,ds) = last items
lastDef = B.toList $ last ds
ds' = init ds ++
[B.fromList $ init lastDef ++ [Plain x]]
in init items ++ [(t, ds')]
else items
_ -> items
isPara :: Block -> Bool
isPara (Para _) = True
isPara _ = False
-- | Data structure for defining hierarchical Pandoc documents
data Element = Blk Block
| Sec Int [Int] Attr [Inline] [Element]
-- lvl num attributes label contents
deriving (Eq, Read, Show, Typeable, Data)
instance Walkable Inline Element where
walk f (Blk x) = Blk (walk f x)
walk f (Sec lev nums attr ils elts) = Sec lev nums attr (walk f ils) (walk f elts)
walkM f (Blk x) = Blk `fmap` walkM f x
walkM f (Sec lev nums attr ils elts) = do
ils' <- walkM f ils
elts' <- walkM f elts
return $ Sec lev nums attr ils' elts'
query f (Blk x) = query f x
query f (Sec _ _ _ ils elts) = query f ils <> query f elts
instance Walkable Block Element where
walk f (Blk x) = Blk (walk f x)
walk f (Sec lev nums attr ils elts) = Sec lev nums attr (walk f ils) (walk f elts)
walkM f (Blk x) = Blk `fmap` walkM f x
walkM f (Sec lev nums attr ils elts) = do
ils' <- walkM f ils
elts' <- walkM f elts
return $ Sec lev nums attr ils' elts'
query f (Blk x) = query f x
query f (Sec _ _ _ ils elts) = query f ils <> query f elts
-- | Convert Pandoc inline list to plain text identifier. HTML
-- identifiers must start with a letter, and may contain only
-- letters, digits, and the characters _-.
inlineListToIdentifier :: [Inline] -> String
inlineListToIdentifier =
dropWhile (not . isAlpha) . intercalate "-" . words .
map (nbspToSp . toLower) .
filter (\c -> isLetter c || isDigit c || c `elem` "_-. ") .
stringify
where nbspToSp '\160' = ' '
nbspToSp x = x
-- | Convert list of Pandoc blocks into (hierarchical) list of Elements
hierarchicalize :: [Block] -> [Element]
hierarchicalize blocks = S.evalState (hierarchicalizeWithIds blocks) []
hierarchicalizeWithIds :: [Block] -> S.State [Int] [Element]
hierarchicalizeWithIds [] = return []
hierarchicalizeWithIds ((Header level attr@(_,classes,_) title'):xs) = do
lastnum <- S.get
let lastnum' = take level lastnum
let newnum = case length lastnum' of
x | "unnumbered" `elem` classes -> []
| x >= level -> init lastnum' ++ [last lastnum' + 1]
| otherwise -> lastnum ++
replicate (level - length lastnum - 1) 0 ++ [1]
unless (null newnum) $ S.put newnum
let (sectionContents, rest) = break (headerLtEq level) xs
sectionContents' <- hierarchicalizeWithIds sectionContents
rest' <- hierarchicalizeWithIds rest
return $ Sec level newnum attr title' sectionContents' : rest'
hierarchicalizeWithIds (x:rest) = do
rest' <- hierarchicalizeWithIds rest
return $ (Blk x) : rest'
headerLtEq :: Int -> Block -> Bool
headerLtEq level (Header l _ _) = l <= level
headerLtEq _ _ = False
-- | Generate a unique identifier from a list of inlines.
-- Second argument is a list of already used identifiers.
uniqueIdent :: [Inline] -> [String] -> String
uniqueIdent title' usedIdents =
let baseIdent = case inlineListToIdentifier title' of
"" -> "section"
x -> x
numIdent n = baseIdent ++ "-" ++ show n
in if baseIdent `elem` usedIdents
then case find (\x -> numIdent x `notElem` usedIdents) ([1..60000] :: [Int]) of
Just x -> numIdent x
Nothing -> baseIdent -- if we have more than 60,000, allow repeats
else baseIdent
-- | True if block is a Header block.
isHeaderBlock :: Block -> Bool
isHeaderBlock (Header _ _ _) = True
isHeaderBlock _ = False
-- | Shift header levels up or down.
headerShift :: Int -> Pandoc -> Pandoc
headerShift n = walk shift
where shift :: Block -> Block
shift (Header level attr inner) = Header (level + n) attr inner
shift x = x
-- | Detect if a list is tight.
isTightList :: [[Block]] -> Bool
isTightList = all firstIsPlain
where firstIsPlain (Plain _ : _) = True
firstIsPlain _ = False
-- | Set a field of a 'Meta' object. If the field already has a value,
-- convert it into a list with the new value appended to the old value(s).
addMetaField :: ToMetaValue a
=> String
-> a
-> Meta
-> Meta
addMetaField key val (Meta meta) =
Meta $ M.insertWith combine key (toMetaValue val) meta
where combine newval (MetaList xs) = MetaList (xs ++ tolist newval)
combine newval x = MetaList [x, newval]
tolist (MetaList ys) = ys
tolist y = [y]
-- | Create 'Meta' from old-style title, authors, date. This is
-- provided to ease the transition from the old API.
makeMeta :: [Inline] -> [[Inline]] -> [Inline] -> Meta
makeMeta title authors date =
addMetaField "title" (B.fromList title)
$ addMetaField "author" (map B.fromList authors)
$ addMetaField "date" (B.fromList date)
$ nullMeta
--
-- TagSoup HTML handling
--
-- | Render HTML tags.
renderTags' :: [Tag String] -> String
renderTags' = renderTagsOptions
renderOptions{ optMinimize = matchTags ["hr", "br", "img",
"meta", "link"]
, optRawTag = matchTags ["script", "style"] }
where matchTags = \tags -> flip elem tags . map toLower
--
-- File handling
--
-- | Perform an IO action in a directory, returning to starting directory.
inDirectory :: FilePath -> IO a -> IO a
inDirectory path action = do
oldDir <- getCurrentDirectory
setCurrentDirectory path
result <- action
setCurrentDirectory oldDir
return result
readDefaultDataFile :: FilePath -> IO BS.ByteString
readDefaultDataFile fname =
#ifdef EMBED_DATA_FILES
case lookup (makeCanonical fname) dataFiles of
Nothing -> err 97 $ "Could not find data file " ++ fname
Just contents -> return contents
where makeCanonical = joinPath . transformPathParts . splitDirectories
transformPathParts = reverse . foldl go []
go as "." = as
go (_:as) ".." = as
go as x = x : as
#else
getDataFileName ("data" </> fname) >>= checkExistence >>= BS.readFile
where checkExistence fn = do
exists <- doesFileExist fn
if exists
then return fn
else err 97 ("Could not find data file " ++ fname)
#endif
-- | Read file from specified user data directory or, if not found there, from
-- Cabal data directory.
readDataFile :: Maybe FilePath -> FilePath -> IO BS.ByteString
readDataFile Nothing fname = readDefaultDataFile fname
readDataFile (Just userDir) fname = do
exists <- doesFileExist (userDir </> fname)
if exists
then BS.readFile (userDir </> fname)
else readDefaultDataFile fname
-- | Same as 'readDataFile' but returns a String instead of a ByteString.
readDataFileUTF8 :: Maybe FilePath -> FilePath -> IO String
readDataFileUTF8 userDir fname =
UTF8.toString `fmap` readDataFile userDir fname
-- | Fetch an image or other item from the local filesystem or the net.
-- Returns raw content and maybe mime type.
fetchItem :: Maybe String -> String
-> IO (Either E.SomeException (BS.ByteString, Maybe String))
fetchItem sourceURL s
| isURI s = openURL s
| otherwise =
case sourceURL >>= parseURIReference of
Just u -> case parseURIReference s of
Just s' -> openURL $ show $
s' `nonStrictRelativeTo` u
Nothing -> openURL $ show u ++ "/" ++ s
Nothing -> E.try readLocalFile
where readLocalFile = do
let mime = case takeExtension s of
".gz" -> getMimeType $ dropExtension s
x -> getMimeType x
cont <- BS.readFile s
return (cont, mime)
-- | Read from a URL and return raw data and maybe mime type.
openURL :: String -> IO (Either E.SomeException (BS.ByteString, Maybe String))
openURL u
| "data:" `isPrefixOf` u =
let mime = takeWhile (/=',') $ drop 5 u
contents = B8.pack $ unEscapeString $ drop 1 $ dropWhile (/=',') u
in return $ Right (decodeLenient contents, Just mime)
#ifdef HTTP_CLIENT
| otherwise = withSocketsDo $ E.try $ do
req <- parseUrl u
(proxy :: Either E.SomeException String) <- E.try $ getEnv "http_proxy"
let req' = case proxy of
Left _ -> req
Right pr -> case parseUrl pr of
Just r -> addProxy (host r) (port r) req
Nothing -> req
resp <- withManager tlsManagerSettings $ httpLbs req'
return (BS.concat $ toChunks $ responseBody resp,
UTF8.toString `fmap` lookup hContentType (responseHeaders resp))
#else
| otherwise = E.try $ getBodyAndMimeType `fmap` browse
(do S.liftIO $ UTF8.hPutStrLn stderr $ "Fetching " ++ u ++ "..."
setOutHandler $ const (return ())
setAllowRedirects True
request (getRequest' u'))
where getBodyAndMimeType (_, r) = (rspBody r, findHeader HdrContentType r)
getRequest' uriString = case parseURI uriString of
Nothing -> error ("Not a valid URL: " ++
uriString)
Just v -> mkRequest GET v
u' = escapeURIString (/= '|') u -- pipes are rejected by Network.URI
#endif
--
-- Error reporting
--
err :: Int -> String -> IO a
err exitCode msg = do
name <- getProgName
UTF8.hPutStrLn stderr $ name ++ ": " ++ msg
exitWith $ ExitFailure exitCode
return undefined
warn :: String -> IO ()
warn msg = do
name <- getProgName
UTF8.hPutStrLn stderr $ name ++ ": " ++ msg
--
-- Safe read
--
safeRead :: (Monad m, Read a) => String -> m a
safeRead s = case reads s of
(d,x):_
| all isSpace x -> return d
_ -> fail $ "Could not read `" ++ s ++ "'"
| nickbart1980/pandoc | src/Text/Pandoc/Shared.hs | gpl-2.0 | 27,889 | 0 | 20 | 8,440 | 7,528 | 3,930 | 3,598 | 490 | 15 |
{- Chapter 9 :: The countdown problem -}
data Op = Add | Sub | Mul | Div
instance Show Op where
show Add = "+"
show Sub = "-"
show Mul = "*"
show Div = "/"
-- valid function to decide if the application of
-- an operation to two positive natural numbers
-- gives another positive natural number.
{-
-- valid basic definition:
valid :: Op -> Int -> Int -> Bool
valid Add x y = True
valid Sub x y = x > y
valid Mul x y = True
valid Div x y = x `mod` y == 0
-}
-- valid defintion which exploits algebraic properties:
valid :: Op -> Int -> Int -> Bool
valid Add x y = x <= y
valid Sub x y = x > y
valid Mul x y = x /= 1 && y /= 1 && x <= y
valid Div x y = y /= 1 && x `mod` y == 0
apply :: Op -> Int -> Int -> Int
apply Add x y = x + y
apply Sub x y = x - y
apply Mul x y = x * y
apply Div x y = x `div` y
data Expr = Val Int | App Op Expr Expr
instance Show Expr where
show (Val n) = show n
show (App o l r) = brak l ++ show o ++ brak r
where
brak (Val n) = show n
brak e = "(" ++ show e ++ ")"
{-
show (Val 1)
= "1"
show (App Add (Val 1) (Val 10))
= "1+10"
show (App Add (Val 1) (App Mul (Val 2) (Val 3)))
= "1+(2*3)"
-}
values :: Expr -> [Int]
values (Val n) = [n]
values (App _ l r) = values l ++ values r
eval :: Expr -> [Int]
eval (Val n) = [n | n > 0]
eval (App o l r) = [apply o x y | x <- eval l,
y <- eval r,
valid o x y]
{-
values (App Add (Val 1) (App Mul (Val 2) (Val 3)))
= [1,2,3]
eval (App Add (Val 2) (Val 3))
= [5]
eval (App Sub (Val 2) (Val 3))
= []
eval (App Add (Val 1) (App Mul (Val 2) (Val 3)))
= [7]
-}
-- powerset
subs :: [a] -> [[a]]
subs [] = [[]]
subs (x:xs) = yss ++ map (x:) yss
where
yss = subs xs
{-
subs [3]
= subs [] ++ map (3:) subs []
= [[]] ++ map (3:) [[]]
= [[]] ++ [[3]]
= [[],[3]]
subs [2,3]
= subs [3] ++ map (2:) subs [3]
= [[],[3]] ++ map (2:) [[],[3]]
= [[],[3]] ++ [[2],[2,3]]
= [[],[3],[2],[2,3]]
subs [1,2,3]
= subs [2,3] ++ map (1:) (subs [2,3])
= [[],[3],[2],[2,3]] ++ map (1:) [[],[3],[2],[2,3]]
= [[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]
-}
interleave :: a -> [a] -> [[a]]
interleave x [] = [[x]]
interleave x (y:ys) = (x:y:ys) : map (y:) (interleave x ys)
{-
interleave 1 [4]
= (1:4:[]) : map (4:) interleave 1 []
= (1:4:[]) : map (4:) [[1]]
= (1:4:[]) : [[4,1]]
= [1,4] : [[4,1]]
= [[1,4],[4,1]]
interleave 1 [3,4]
= (1:3:[4]) : map (3:) interleave 1 [4]
= (1:3:[4]) : map (3:) [[1,4],[4,1]]
= (1:3:[4]) : [[3,1,4],[3,4,1]]
= [[1,3,4],[3,1,4],[3,4,1]]
interleave 1 [2,3,4]
= (1:2:[3,4]) : map (2:) (interleave 1 ys)
= [1,2,3,4] : map (2:) interleave 1 [3,4]
= [1,2,3,4] : map (2:) [[1,3,4],[3,1,4],[3,4,1]]
= [1,2,3,4] : [[2,1,3,4],[2,3,1,4],[2,3,4,1]]
= [[1,2,3,4],[2,1,3,4],[2,3,1,4],[2,3,4,1]]
-}
perms :: [a] -> [[a]]
perms [] = [[]]
perms (x:xs) = concat (map (interleave x) (perms xs))
{-
perms [2,3]
= concat (map (interleave 2) (perms [3]))
= concat (map (interleave 2) [[3]])
= concat [[[2,3],[3,2]]]
= [[2,3],[3,2]]
perms [1,2,3]
= concat (map (interleave 1) (perms [2,3]))
= concat (map (interleave 1) [[2,3],[3,2]])
= concat [[[1,2,3],[2,1,3],[2,3,1]],[[1,3,2],[3,1,2],[3,2,1]]]
= [[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]]
-}
-- get all permutations of the powerset subsequences
choices :: [a] -> [[a]]
choices = concat . map perms . subs
{-
choices [1,2,3]
= [[],[3],[2],[2,3],[3,2],[1],[1,3],[3,1],[1,2],[2,1],[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]]
elem 5 [1,2,3,5]
= True
eval (App Mul (App Add (Val 1) (Val 50)) (App Sub (Val 25) (Val 10)))
= [765]
-- Reminder: eval returns either singleton or empty list.
-}
e1 :: Expr
e1 = (App Mul (App Add (Val 1) (Val 50)) (App Sub (Val 25) (Val 10)))
solution :: Expr -> [Int] -> Int -> Bool
solution e ns n =
elem (values e) (choices ns) && eval e == [n]
{-
solution e1 [1,3,7,10,25,50] 765
= True
-}
-- brute force solution
split :: [a] -> [([a],[a])]
split [] = []
split [_] = []
split (x:xs) = ([x],xs) : [(x:ls,rs) | (ls,rs) <- split xs]
{-
split [1,2,3,4]
= [([1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4])]
-}
exprs :: [Int] -> [Expr]
exprs [] = []
exprs [n] = [Val n]
exprs ns = [e | (ls,rs) <- split ns,
l <- exprs ls,
r <- exprs rs,
e <- combine l r]
{-
exprs [1,2]
= [1+2,1-2,1*2,1/2]
exprs [1,2,3]
= [1+(2+3),1-(2+3),1*(2+3),1/(2+3),1+(2-3),1-(2-3),1*(2-3),1/(2-3),
1+(2*3),1-(2*3),1*(2*3),1/(2*3),1+(2/3),1-(2/3),1*(2/3),1/(2/3),
(1+2)+3,(1+2)-3,(1+2)*3,(1+2)/3,(1-2)+3,(1-2)-3,(1-2)*3,(1-2)/3,
(1*2)+3,(1*2)-3,(1*2)*3,(1*2)/3,(1/2)+3,(1/2)-3,(1/2)*3,(1/2)/3]
-}
combine :: Expr -> Expr -> [Expr]
combine l r = [App o l r | o <- ops]
ops :: [Op]
ops = [Add,Sub,Mul,Div]
solutions :: [Int] -> Int -> [Expr]
solutions ns n = [e | ns' <- choices ns,
e <- exprs ns',
eval e == [n]]
{-
check countdown.hs for performance test
-}
-- combining generation and evalution
type Result = (Expr,Int)
results :: [Int] -> [Result]
results [] = []
results [n] = [(Val n, n) | n > 0]
results ns = [res | (ls,rs) <- split ns,
lx <- results ls,
ry <- results rs,
res <- combine' lx ry]
combine' :: Result -> Result -> [Result]
combine' (l,x) (r,y) = [(App o l r, apply o x y) | o <- ops,
valid o x y]
solutions' :: [Int] -> Int -> [Expr]
solutions' ns n = [e | ns' <- choices ns,
(e,m) <- results ns',
m == n]
| rad1al/hutton_exercises | notes_ch09.hs | gpl-2.0 | 5,722 | 0 | 10 | 1,594 | 1,569 | 836 | 733 | 81 | 1 |
--
-- (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".
import System.IO.Unsafe
import System.Process
import System.Directory
import System.Environment
import System.FilePath
import Control.Monad(void,when,unless,liftM,forM,filterM)
import Control.Applicative
import Text.Regex.Posix
import Data.List
import Data.Maybe
import Data.Function(on)
pfq_omatic_ver,pfq_kcompat,proc_cpuinfo :: String
pfq_symvers :: [String]
pfq_omatic_ver = "5.2"
proc_cpuinfo = "/proc/cpuinfo"
pfq_kcompat = "/usr/include/linux/pf_q-kcompat.h"
pfq_symvers = [ "/lib/modules/" ++ uname_r ++ "/kernel/net/pfq/Module.symvers",
home_dir ++ "/PFQ/kernel/Module.symvers",
"/opt/PFQ/kernel/Module.symvers"
]
getMostRecentFile :: [FilePath] -> IO (Maybe FilePath)
getMostRecentFile xs = do
xs' <- filterM doesFileExist xs >>=
mapM (\f -> liftM (\m -> (f,m)) $ getModificationTime f) >>= \x ->
return $ sortBy (flip compare `on` snd) x
return $ listToMaybe (map fst xs')
main :: IO ()
main = do
args <- getArgs
putStrLn $ "[PFQ] pfq-omatic: v" ++ pfq_omatic_ver
generalChecks
getRecursiveContents "." [".c"] >>= mapM_ tryPatch
symver <- liftM fromJust $ getMostRecentFile pfq_symvers
copyFile symver "Module.symvers"
let cmd = "make KBUILD_EXTRA_SYMBOLS=" ++ symver ++ " -j" ++ show getNumberOfPhyCores ++ " " ++ unwords args
putStrLn $ "[PFQ] compiling: " ++ cmd ++ "..."
void $ system cmd
putStrLn "[PFQ] done."
{-# NOINLINE uname_r #-}
uname_r :: String
uname_r = unsafePerformIO $
head . lines <$> readProcess "/bin/uname" ["-r"] ""
{-# NOINLINE home_dir #-}
home_dir :: String
home_dir = unsafePerformIO getHomeDirectory
regexFunCall :: String -> Int -> String
regexFunCall fun n =
fun ++ "[[:space:]]*" ++ "\\(" ++ args n ++ "\\)"
where args 0 = "[[:space:]]*"
args 1 = "[^,]*"
args x = "[^,]*," ++ args (x-1)
tryPatch :: FilePath -> IO ()
tryPatch file =
readFile file >>= \c ->
when (c =~ (regexFunCall "netif_rx" 1 ++ "|" ++ regexFunCall "netif_receive_skb" 1 ++ "|" ++ regexFunCall "napi_gro_receive" 2)) $
doesFileExist (file ++ ".omatic") >>= \orig ->
if orig
then putStrLn $ "[PFQ] " ++ file ++ " is already patched :)"
else makePatch file
makePatch :: FilePath -> IO ()
makePatch file = do
putStrLn $ "[PFQ] patching " ++ file
src <- readFile file
renameFile file $ file ++ ".omatic"
writeFile file $ "#include " ++ show pfq_kcompat ++ "\n" ++ src
generalChecks :: IO ()
generalChecks = do
doesFileExist pfq_kcompat >>= \kc ->
unless kc $ error "error: could not locate pfq-kcompat header!"
symver <- getMostRecentFile pfq_symvers
unless (isJust symver) $ error "error: could not locate pfq Module.symvers!"
putStrLn $ "[PFQ] using " ++ fromJust symver ++ " file (most recent)"
doesFileExist "Makefile" >>= \mf ->
unless mf $ error "error: Makefile not found!"
type Ext = String
getRecursiveContents :: FilePath -> [Ext] -> IO [FilePath]
getRecursiveContents topdir ext = do
names <- getDirectoryContents topdir
let properNames = filter (`notElem` [".", ".."]) names
paths <- forM properNames $ \fname -> do
let path = topdir </> fname
isDirectory <- doesDirectoryExist path
if isDirectory
then getRecursiveContents path ext
else return [path | takeExtensions path `elem` ext]
return (concat paths)
{-# NOINLINE getNumberOfPhyCores #-}
getNumberOfPhyCores :: Int
getNumberOfPhyCores = unsafePerformIO $
length . filter (isInfixOf "processor") . lines <$> readFile proc_cpuinfo
| pandaychen/PFQ | user/pfq-omatic/pfq-omatic.hs | gpl-2.0 | 4,571 | 0 | 17 | 1,023 | 1,082 | 553 | 529 | 89 | 3 |
module Main (main) where
import Control.Monad
import Data.IORef
import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
import System.Random
import Data
import Display
import Piece
import Scene
import Stats
gameArea :: Area
gameArea = Area 10 20
main = do
getArgsAndInitialize
initialDisplayMode $= [DoubleBuffered]
createWindow "Haskell-blocks"
windowSize $= Size (fromIntegral (width gameArea) * 25) (fromIntegral (height gameArea) * 25)
startNewGame
mainLoop
startNewGame :: IO ()
startNewGame = do
sceneRef <- newIORef $ createEmptyScene gameArea
displayCallback $= drawingCallback sceneRef
keyboardMouseCallback $= Just (inputCallback sceneRef)
timerCallback sceneRef
drawingCallback :: IORef Scene -> IO ()
drawingCallback sceneRef = get sceneRef >>= drawScene
timerCallback :: IORef Scene -> TimerCallback
timerCallback sceneRef = do
scene <- get sceneRef
when (isValidScene scene) $ do
nextScene <- nextScene scene
sceneRef $= nextScene
postRedisplay Nothing
addTimerCallback (delayForScene nextScene) (timerCallback sceneRef)
delayForScene :: Scene -> Int
delayForScene scene =
if isPiecePresentInScene scene then
500 - 20 * (levelInStats $ statsInScene scene) else 0
nextScene :: Scene -> IO Scene
nextScene scene =
if isPiecePresentInScene scene then
return $ lowerPieceInScene scene
else do
piece <- nextPiece
return $ addPieceToScene piece scene
nextPiece :: IO Piece
nextPiece = choiceOneOf pieces
where choiceOneOf :: [a] -> IO a
choiceOneOf xs = randomRIO (0, (length xs - 1)) >>= return . (xs !!)
inputCallback :: IORef Scene -> KeyboardMouseCallback
inputCallback sceneRef (SpecialKey key) Down _ _ = do
scene <- get sceneRef
if isValidScene scene then do
sceneRef $= reactionOn key scene
postRedisplay Nothing
else when (key == KeyDown) startNewGame
inputCallback _ _ _ _ _ = return ()
reactionOn :: SpecialKey -> Scene -> Scene
reactionOn KeyLeft = movePieceLeftInScene
reactionOn KeyRight = movePieceRightInScene
reactionOn KeyUp = rotatePieceInScene
reactionOn KeyDown = dropPieceInScene
reactionOn _ = id | pavelfatin/haskell-blocks | src/Main.hs | gpl-3.0 | 2,212 | 0 | 13 | 461 | 659 | 323 | 336 | 65 | 2 |
module Main where
import HMail.Types
import HMail.Init
import HMail.Main (hmailMain)
import Control.Applicative
import Control.Monad
import qualified Data.Foldable as F
import Text.Read (readMaybe)
import Options.Applicative as OA
import Options.Applicative.Builder as OB
-- import Options.Applicative.Help.Types (ParserHelp)
instance Semigroup a => Semigroup (OA.Parser a) where
(<>) = liftA2 (<>)
instance Monoid a => Monoid (OA.Parser a) where
mempty = pure mempty
main :: IO ()
main = parseCmdline
parseCmdline :: IO ()
parseCmdline = join $ customExecParser hmailPrefs parser
where
hmailPrefs = OB.defaultPrefs
{ prefDisambiguate = True
, prefShowHelpOnError = True }
parser = info (helper <*> hmailOptions)
(fullDesc
<> header
"hmail: a mutt-style mail client, written in haskell"
-- <> progDescDoc (Just description)
<> failureCode 1)
hmailOptions :: OA.Parser (IO ())
hmailOptions = pure hmailMain
<*> ( (fmap Verbosity . switch) (long "verbose" <> help "write debug output") )
<*> ( hmailImapOptions <> hmailSmtpOptions )
hmailImapOptions :: OA.Parser (DInit Maybe)
hmailImapOptions = F.fold
[ hostOpt d_imapHostnamel (long "imap-hostname" <> metavar "HOST"
<> help "The (imap) host to connect to")
, portOpt d_imapPortl (long "imap-port" <> metavar "PORT"
<> value 993 <> help "The (imap) port to connect to"
<> showDefault )
, userOpt d_imapUsernamel (long "imap-username" <> metavar "USER"
<> help "The username of the (imap) account to log into")
, passOpt d_imapPasswordl (long "imap-password" <> metavar "PWD"
<> help "The password for the (imap) account") ]
hmailSmtpOptions :: OA.Parser (DInit Maybe)
hmailSmtpOptions = F.fold
[ hostOpt d_smtpHostnamel (long "smtp-hostname" <> metavar "HOST"
<> help "The (smtp) host to connect to")
, portOpt d_smtpPortl (long "smtp-port" <> metavar "PORT"
<> help "The (smtp) port to connect to")
, userOpt d_smtpUsernamel (long "smtp-username" <> metavar "USER"
<> help "The username of the (smtp) account to log into")
, passOpt d_smtpPasswordl (long "smtp-password" <> metavar "PWD"
<> help "The password for the (smtp) account") ]
genOpt f l = fmap (maybe mempty $ fromLens l . f) . optional . OB.option str
hostOpt = genOpt Hostname
userOpt = genOpt Username
passOpt = genOpt Password
portOpt l = fmap (maybe mempty $ fromLens l . Port) . optional . OB.option
(maybeReader $ fmap fromInteger . readMaybe)
| xaverdh/hmail | Main.hs | gpl-3.0 | 2,503 | 0 | 13 | 491 | 710 | 359 | 351 | 57 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Codec.Compression.GZip
import Control.Applicative
import Control.Lens
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Maybe
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.Default
import qualified Data.Foldable as F
import Data.List (foldl')
import System.Environment
import System.IO as IO
--
import HEP.Automation.EventGeneration.Config
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Model.SM
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Type
import HEP.Automation.MadGraph.Util
import HEP.Parser.LHCOAnalysis.PhysObj
import HEP.Parser.LHCOAnalysis.Parse
import HEP.Storage.WebDAV.CURL
import HEP.Storage.WebDAV.Type
--
import HEP.Physics.Analysis.Common.Lens
import HEP.Physics.Analysis.Common.Merge
import HEP.Physics.Analysis.Common.PhyEventNoTau
import HEP.Physics.Analysis.Common.PhyEventNoTauNoBJet
mergeBJetFromNoTauEv :: PhyEventNoTau -> PhyEventNoTauNoBJet
mergeBJetFromNoTauEv ev =
let alljs = (map (\case JO_Jet j ->j ; JO_BJet b -> bJet2Jet b) . view jetBJets) ev
es = view electrons $ ev
ms = view muons $ ev
in ( set electrons es
. set muons ms
. set jets alljs
. set eventId (view eventId ev)
. set photons (view photons ev)
. set missingET (view missingET ev) ) def
psetup :: ProcessSetup SM
psetup = PS { model = SM
, process = MGProc [] [ "p p > t t~ QCD=99 QED=2 @0"
, "p p > t t~ j QCD=99 QED=2 @1"
, "p p > t t~ j j QCD=99 QED=2 @2" ]
, processBrief = "tt012j"
, workname = "tt012j"
, hashSalt = HashSalt Nothing }
param :: ModelParam SM
param = SMParam
rsetupgen :: Int -> RunSetup
rsetupgen x =
RS { numevent = 10000
, machine = LHC14 ATLAS
, rgrun = Auto
, rgscale = 91.0
, match = MLM
, cut = DefCut
, pythia = RunPYTHIA
, lhesanitizer = []
, pgs = RunPGS (AntiKTJet 0.4, WithTau)
, uploadhep = NoUploadHEP
, setnum = x
}
{-
eventsets :: [EventSet]
eventsets = [ EventSet psetup param (rsetupgen x) | x <- [1..1000] ]
-}
rdir :: WebDAVRemoteDir
rdir = WebDAVRemoteDir "newtest2"
checkAndDownload :: WebDAVConfig -> WebDAVRemoteDir -> FilePath -> MaybeT IO ()
checkAndDownload cfg rdir fpath = do
b <- liftIO $ doesFileExistInDAV cfg rdir fpath
guard b
liftIO $ downloadFile False cfg rdir fpath
liftIO $ putStrLn $ fpath ++ " is successfully downloaded"
{-
main :: IO ()
main = do
print $ combine [("ttest",1,2,3,4,5,[(100,33),(200,34)])
,("ttest2",1,2,3,4,5,[(100,47),(200,39)]) ]
-}
main' :: IO ()
main' = do
args <- getArgs
let pkey = args !! 0
pswd = args !! 1
whost = args !! 2
let fpaths = map (++ "_pgs_events.lhco.gz") . map (\x -> makeRunName psetup param (rsetupgen x)) $ [901..1000]
Just cr <- getCredential pkey pswd
let cfg = WebDAVConfig { webdav_credential = cr, webdav_baseurl = whost }
withFile "dummy.txt" WriteMode $ \h ->
runMaybeT $ do
r <- flip mapM fpaths $ \fpath -> do
-- checkAndDownload cfg rdir fpath
{- analysis h fpath -}
analysis fpath
liftIO $ print (combine r)
return r
return ()
main :: IO ()
main = runMaybeT (analysis "fourtopsimpl_pgs_events.lhco.gz") >>= print -- return ()
main'' :: IO ()
main'' = do
str <- readFile "resultfinal.txt"
-- print (lines str)
let rf = read :: String -> (Int,Int,Int,Int,Int,[(Double,Int)])
print $ lines str !! 1
print $ rf (lines str !! 1)
let rs = map rf . take 10 $ lines str
print (combine2 rs)
combine :: [(String,Int,Int,Int,Int,Int,[(Double,Int)])] -> (Int,Int,Int,Int,Int,[(Double,Int)])
combine = foldl' f (0,0,0,0,0,map (\x->(x,0)) [10,20..300])
where f (b1,b2,b3,b4,b5,acc) (_,a1,a2,a3,a4,a5,lst) =
(b1+a1,b2+a2,b3+a3,b4+a4,b5+a5,zipWith (\(x1,y1) (x2,y2) -> (x1,y1+y2)) acc lst)
combine2 :: [(Int,Int,Int,Int,Int,[(Double,Int)])] -> (Int,Int,Int,Int,Int,[(Double,Int)])
combine2 = foldl' f (0,0,0,0,0,map (\x->(x,0)) [10,20..300])
where f (b1,b2,b3,b4,b5,acc) (a1,a2,a3,a4,a5,lst) =
(b1+a1,b2+a2,b3+a3,b4+a4,b5+a5,zipWith (\(x1,y1) (x2,y2) -> (x1,y1+y2)) acc lst)
analysis fpath = do
liftIO $ putStrLn $ "analyzing " ++ fpath
bstr <- liftIO $ LB.readFile fpath
let unzipped = decompress bstr
unmergedevts = parsestr unzipped
taumergedevts = map mkPhyEventNoTau unmergedevts
-- totnum = length evts
-- evt = head mergedevts :: PhyEventNoTau
--- evt' = mergeBJetFromNoTauEv evt
fullmergedevts = map mergeBJetFromNoTauEv taumergedevts
etarangeevts = map filterEtaRange fullmergedevts
test = (,,) <$> checkj <*> checkl <*> checkj2
pass1 x = view (_1._1) x
pass2 x = pass1 x && view (_1._2) x
pass3 x = pass1 x && pass2 x && view (_1._3) x
pass4 x = pass1 x && pass2 x && pass3 x && view _2 x
-- pass5 x = pass1 x && pass2 x && pass3 x && pass4 x && view (_3._1) x
-- pass6 x = pass1 x && pass2 x && pass3 x && pass4 x && pass5 x && view (_3._2) x
pass1evts = filter (pass1.test) etarangeevts -- fullmergedevts
pass2evts = filter (pass2.test) etarangeevts -- fullmergedevts
pass3evts = filter (pass3.test) etarangeevts -- fullmergedevts
pass4evts = filter (pass4.test) etarangeevts -- fullmergedevts
-- pass5evts = filter (pass5.test) etarangeevts -- fullmergedevts
-- pass6evts = filter (pass6.test) etarangeevts -- fullmergedevts
assoclist = map (\x -> (x, (length . filter (ptlcut x)) pass4evts)) [10,20..300]
-- liftIO $ print assoclist
return (fpath, length fullmergedevts, length pass1evts, length pass2evts, length pass3evts, length pass4evts, assoclist)
{- liftIO $ IO.hPutStrLn h
(fpath ++ ": " ++ show (length fullmergedevts, length pass1evts, length pass2evts, length pass3evts, length pass4evts)
++ show assoclist
) -}
-- show (length fullmergedevts, length pass1evts,length pass2evts,length pass3evts,length pass4evts,length pass5evts,length pass6evts))
-- countFiltered p lst = length (filter p lst)
ptlcut :: Double -> PhyEventNoTauNoBJet -> Bool
ptlcut cut ev = let lst = view leptons ev
f x = abs (eta x) < 1.5 && pt x > cut
in any f lst
-- (not . null . filter (\x -> abs x < 1.5)) etalst
filterEtaRange = over jets (filter (\x -> abs (eta (JO_Jet x)) < 2.5))
jetpts = map (pt . JO_Jet) . view jets
jetetas = map (eta . JO_Jet) . view jets
checkl :: PhyEventNoTauNoBJet -> Bool
checkl ev = let etalst = leptonetas ev
in (not . null . filter (\x -> abs x < 1.5)) etalst
{-
checkj :: PhyEventNoTauNoBJet -> Bool
checkj ev = let etalst = jetetas ev
eta_1_5 = filter (\x -> abs x < 1.5) etalst
eta_2_5 = filter (\x -> abs x < 2.5) etalst
in length eta_1_5 >= 4 && length eta_2_5 >= 6
-}
checkj :: PhyEventNoTauNoBJet -> (Bool,Bool,Bool)
checkj ev = let ptlst = jetpts ev
in case ptlst of
[] -> (False,False,False)
x:xs ->
let b1 = x > 120
in case xs of
_:_:y:ys -> let b2 = y > 70
in case ys of
_:z:zs -> let b3 = z > 40
in (b1,b2,b3)
_ -> (b1,b2,False)
_ -> (b1,False,False)
leptonetas = map eta . view leptons
checkj2 :: PhyEventNoTauNoBJet -> (Bool,Bool)
checkj2 ev = let etalst = jetetas ev
in case etalst of
x1:x2:x3:x4:xs -> let b1 = abs x1 < 1.5 && abs x2 < 1.5 && abs x3 < 1.5 && abs x4 < 1.5
in case xs of
y1:y2:ys -> let b2 = abs y1 <2.5 && abs y2 < 2.5
in (b1,b2)
_ -> (b1,False)
_ -> (False,False)
| wavewave/lhc-analysis-collection | heavyhiggs/firstcut.hs | gpl-3.0 | 8,502 | 0 | 24 | 2,629 | 2,556 | 1,393 | 1,163 | 156 | 4 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Grid.Output.Draw
(
drawGround,
{-
drawPath,
drawSegment,
drawSegmentAlpha,
-}
) where
import MyPrelude
import Game
import Game.Grid.GridWorld
import Game.Grid.Helpers
import OpenGL
--------------------------------------------------------------------------------
-- drawings
-- draw ground centered at node
drawGround node = io $ do
let Node x y z = node
x0 = x - radius
z0 = z - radius
x1 = x + radius
z1 = z + radius
-- tmp
glColor4f 1 1 1 0.4
glBegin gl_LINES
forM_ [x0.. x1] $ \x -> do
glVertex3f (fromIntegral x) 0 (fromIntegral z0)
glVertex3f (fromIntegral x) 0 (fromIntegral z1)
forM_ [z0..z1] $ \z -> do
glVertex3f (fromIntegral x0) 0 (fromIntegral z)
glVertex3f (fromIntegral x1) 0 (fromIntegral z)
glEnd
--
where
radius = 5
{-
drawPath path = do
-- draw segments
io $ glColor4f 1 0 0 1
forM_ (pathSegments path) $ drawSegment
-- draw current
io $ glColor4f 0 1 0 1
drawSegmentAlpha (pathCurrent path) (pathAlpha path)
drawSegment (Segment (Node nx ny nz) turn) = do
let x = fromIntegral nx
y = fromIntegral ny
z = fromIntegral nz
(dx, dy, dz) = direction turn
x' = fromIntegral $ nx + dx
y' = fromIntegral $ ny + dy
z' = fromIntegral $ nz + dz
io $ do
glBegin gl_LINES
glVertex3f x y z
glVertex3f x' y' z'
glEnd
drawSegmentAlpha (Segment (Node nx ny nz) turn) alpha = do
let x = fromIntegral nx
y = fromIntegral ny
z = fromIntegral nz
(dx, dy, dz) = direction turn
x' = x + realToFrac alpha * fromIntegral dx
z' = z + realToFrac alpha * fromIntegral dz
y' = y + realToFrac alpha * fromIntegral dy
io $ do
glBegin gl_LINES
glVertex3f x y z
glVertex3f x' y' z'
glEnd
-}
| karamellpelle/grid | designer/source/Game/Grid/Output/Draw.hs | gpl-3.0 | 2,671 | 0 | 14 | 753 | 281 | 154 | 127 | 24 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Types (
Id, unId, mkId', randomId, HasId(..),
NodeInfo(..),
-- * Locations
HasLocation(..), Location, mkLocation, toLocation,
unLocation, rightOf,
LocDistance, unDistance, locDist, absLocDist, scaleDist, locMove,
-- * state aware serialization
ToStateJSON(..)
) where
import Control.Applicative ( pure, (<$>), (<*>) )
import Control.Concurrent.STM
import Control.Monad ( mzero )
import Data.Aeson
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import Data.Bits ( shiftL )
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as HEX
import qualified Data.ByteString.Char8 as BSC
import Data.Ratio ( (%) )
import Data.Text.Encoding ( decodeUtf8, encodeUtf8 )
import System.Random ( RandomGen, random )
import Test.QuickCheck
----------------------------------------------------------------------
-- STM aware serialization
----------------------------------------------------------------------
class ToStateJSON a where
toStateJSON :: a -> STM Value
instance ToStateJSON a => ToStateJSON [a] where
toStateJSON xs = toJSON <$> mapM toStateJSON xs
instance ToStateJSON a => ToStateJSON (TVar a) where
toStateJSON v = readTVar v >>= toStateJSON
----------------------------------------------------------------------
-- Node IDs
----------------------------------------------------------------------
-- |
-- An 256 bit identifier.
newtype Id = Id { unId :: BS.ByteString } deriving ( Eq, Ord )
class HasId a where
getId :: a -> Id
instance Binary Id where
put = putByteString . unId
get = Id <$> getByteString 32
instance Show Id where
show nid = BSC.unpack (HEX.encode $ unId nid)
instance FromJSON Id where
parseJSON (String s) = pure $ Id $ fst (HEX.decode $ encodeUtf8 s)
parseJSON _ = mzero
instance ToJSON Id where
toJSON (Id bs) = toJSON $ decodeUtf8 $ HEX.encode bs
instance HasLocation Id where
hasLocToInteger = idToInteger
hasLocMax = Id $ BS.replicate 32 255
idToInteger :: Id -> Integer
idToInteger (Id bs) = BS.foldl' (\i bb -> (i `shiftL` 8) + fromIntegral bb) 0 bs
mkId' :: BS.ByteString -> Id
mkId' bs
| BS.length bs /= 32 = error "mkId': expected 32 bytes"
| otherwise = Id bs
randomId :: RandomGen g => g -> (Id, g)
randomId g = let (bs, Just g') = BS.unfoldrN 32 (Just . random) g in (mkId' bs, g')
-------------------------------------------------------------------------------------------
-- Locations
-------------------------------------------------------------------------------------------
class HasLocation a where
hasLocToInteger :: a -> Integer
hasLocMax :: a
newtype Location = Location { unLocation :: Rational } deriving ( Eq, Show )
instance ToJSON Location where
toJSON (Location l) = toJSON $ (fromRational l :: Double)
instance Arbitrary Location where
arbitrary = do
d <- arbitrary
if d > 0
then choose (0, d - 1) >>= (\n -> return $ Location (n % d))
else return $ Location (0 % 1)
mkLocation :: Real a => a -> Location
mkLocation l
| l < 0 || l >= 1 = error "mkLocation: location must be in [0..1)"
| otherwise = Location $ toRational l
-- |
-- Determines if the shortes path on the circle goes to the right.
rightOf :: Location -> Location -> Bool
rightOf (Location l1) (Location l2)
| l1 < l2 = l2 - l1 >= (1 % 2)
| otherwise = l1 - l2 < (1 % 2)
toLocation :: HasLocation a => a -> Location
toLocation x = Location $ (hasLocToInteger x) % (1 + (hasLocToInteger $ hasLocMax `asTypeOf` x))
locMove :: Location -> LocDistance -> Location
locMove (Location l) (LocDistance d)
| l' >= 1 = Location $ l' - 1
| l' < 0 = Location $ l' + 1
| otherwise = Location l'
where
l' = l + d
-- |
-- Distance between two locations, always in [-0.5, 0.5].
newtype LocDistance = LocDistance { unDistance :: Rational } deriving ( Eq, Ord )
instance Show LocDistance where
show (LocDistance d) = show (fromRational d :: Float)
instance Arbitrary LocDistance where
arbitrary = locDist <$> arbitrary <*> arbitrary
absLocDist :: Location -> Location -> LocDistance
absLocDist (Location l1) (Location l2) = LocDistance $ (min d (1 - d)) where
d = if l1 > l2 then l1 - l2 else l2 - l1
locDist :: Location -> Location -> LocDistance
locDist ll1@(Location l1) ll2@(Location l2) = LocDistance $ f * (min d (1 - d)) where
d = if l1 > l2 then l1 - l2 else l2 - l1
f = if ll1 `rightOf` ll2 then 1 else (-1)
scaleDist :: LocDistance -> Rational -> LocDistance
scaleDist (LocDistance d) f
| f > 1 = error "scaleDist: factor > 1"
| otherwise = LocDistance $ d * f
----------------------------------------------------------------------
-- Node Info
----------------------------------------------------------------------
-- |
-- The node information which can be exchanged between peers.
data NodeInfo a = NodeInfo
{ nodeId :: Id -- ^ the globally unique node ID of 256 bits
, nodeAddresses :: [a]
} deriving ( Eq, Show )
instance Binary a => Binary (NodeInfo a) where
put ni = put (nodeId ni) >> put (nodeAddresses ni)
get = NodeInfo <$> get <*> get
instance FromJSON a => FromJSON (NodeInfo a) where
parseJSON (Object v) = NodeInfo
<$> v .: "id"
<*> v .: "addresses"
parseJSON _ = mzero
instance ToJSON a => ToJSON (NodeInfo a) where
toJSON ni = object
[ "id" .= nodeId ni
, "addresses" .= nodeAddresses ni
]
| waldheinz/ads | src/lib/Types.hs | gpl-3.0 | 5,543 | 0 | 15 | 1,181 | 1,754 | 944 | 810 | 113 | 3 |
{-# LANGUAGE RecursiveDo, OverloadedStrings #-}
module Estuary.Widgets.Tempo where
import Reflex
import Reflex.Dom
import Control.Monad.Trans
import Text.Read
import Data.Text
import Data.Time
import Data.Map
import Sound.MusicW.AudioContext
import Data.Text (Text)
import qualified Data.Text as T
import TextShow
import Estuary.Types.Tempo
import Estuary.Types.Context
import Estuary.Types.EnsembleResponse
import Estuary.Widgets.Text
import Estuary.Widgets.Reflex
import qualified Estuary.Types.Term as Term
import Estuary.Types.Language
import Estuary.Types.EnsembleC
import Estuary.Types.Ensemble
import Estuary.Widgets.W
tempoWidget :: MonadWidget t m => Dynamic t Tempo -> W t m (Event t Tempo)
tempoWidget tempoDyn = do
v <- variableWidget tempoDyn $ \a eventA -> divClass "ensembleTempo ui-font primary-color" $ mdo
let initialText = showt (freq a)
let updatedText = fmap (showt . freq) eventA
(tValue,_,tEval) <- textWidget 1 (constDyn False) initialText updatedText
b <- dynButton =<< term Term.NewTempo
let evalEvent = tagPromptlyDyn tValue $ leftmost [b,tEval]
let cpsEvent = fmapMaybe ((readMaybe :: String -> Maybe Rational) . T.unpack) evalEvent
edits <- performEvent $ fmap liftIO $ attachPromptlyDynWith (flip changeTempoNow) tempoDyn cpsEvent -- *** attachPromptlyDynWith here might not be right!!!
return edits
return $ localEdits v
-- context :: Monad m => W t m (Dynamic t Context)
visualiseTempoWidget:: MonadWidget t m => Dynamic t Tempo -> W t m (Variable t Tempo)
visualiseTempoWidget delta = divClass "tempoVisualiser" $ mdo
c <- context
let currentTempo = fmap (tempo . ensemble . ensembleC) c
widgetBuildTime <- liftIO $ getCurrentTime
tick <- tickLossy 0.01 widgetBuildTime
elapsedBeatsRunning <- performEvent $ attachWith getElapsedBeats (current currentTempo) $ fmap _tickInfo_lastUTC tick
dynTempo <- holdDyn 0 elapsedBeatsRunning
out <- visualiseCycles dynTempo
v <- variable delta never
return v
getElapsedBeats :: MonadIO m => Tempo -> UTCTime -> m Rational
getElapsedBeats t now = do
let x = timeToCount t now
return x
---- separate the view Box from the circle, so this function can be a generic container for the metric and cyclic vis
visualiseCycles :: MonadWidget t m => Dynamic t Rational -> W t m ()
visualiseCycles delta = do
let class' = constDyn $ "class" =: "human-to-human-comm code-font"
let style = constDyn $ "style" =: "height: auto;"
let vB = constDyn $ "viewBox" =: "-1.5 -1.5 3 3"
let w' = constDyn $ "width" =: "100"
let h' = constDyn $ "height" =: "100"
let attrs = mconcat [class',w',h',style,vB]
let (cx,cy) = (constDyn $ "cx" =: "0", constDyn $ "cy" =: "0")
let r = constDyn $ "r" =: "1"
let stroke = constDyn $ "stroke" =: "var(--primary-color)"
let strokeWidth = constDyn $ "stroke-width" =: "0.05"
let attrsCircle = mconcat [cx,cy,r,stroke,strokeWidth]
let (x1,x2) = (constDyn $ "x1" =: "0",constDyn $ "x2" =: "0")
let (y1,y2) = (constDyn $ "y1" =: "0",constDyn $ "y2" =: "-1")
let transform = beatToRotation <$> delta
let attrsLine = mconcat [x1,y1,x2,y2,stroke,strokeWidth,transform]
-- elDynAttr "stopwatch" attrs $ dynText $ fmap (showt) $ fmap (showt) delta
elDynAttrNS' (Just "http://www.w3.org/2000/svg") "svg" attrs $ do
-- create circular dial
elDynAttrNS' (Just "http://www.w3.org/2000/svg") "circle" attrsCircle $ return ()
-- manecilla
elDynAttrNS' (Just "http://www.w3.org/2000/svg") "line" attrsLine $ return ()
-- mark
generatePieSegments 1
return ()
beatToRotation:: Rational -> Map Text Text
beatToRotation r = "transform" =: ("rotate(" <> (showt radio) <> ")")
where radio = fromIntegral (round $ radio' * 360) :: Double
radio' = r - (realToFrac $ floor r)
beatToPercentage:: Text -> Rational -> Map Text Text
beatToPercentage atr beat = atr =: (showt percen)
where percen = fromIntegral (round $ percen' * 100) :: Double
percen' = beat - (realToFrac $ floor beat)
visualiseMetre :: MonadWidget t m => Dynamic t Rational -> W t m ()
visualiseMetre delta = do
let class' = constDyn $ "class" =: "human-to-human-comm code-font"
let style = constDyn $ "style" =: "height: auto;"
let vB = constDyn $ "viewBox" =: "0 0 100 100"
let w' = constDyn $ "width" =: "100"
let h' = constDyn $ "height" =: "100"
let stroke = constDyn $ "stroke" =: "var(--primary-color)"
let strokeWidth = constDyn $ "stroke-width" =: "0.05;"
let attrs = mconcat [class',w',h',style,vB]
let x1 = beatToPercentage "x1" <$> delta
let x2 = beatToPercentage "x2" <$> delta
let (y1,y2) = (constDyn $ "y1" =: "0",constDyn $ "y2" =: "100")
let attrsLine = mconcat [x1,y1,x2,y2,stroke,strokeWidth]
-- elDynAttr "stopwatch" attrs $ dynText $ fmap (showt) $ fmap (showt) delta
elDynAttrNS' (Just "http://www.w3.org/2000/svg") "svg" attrs $ do
-- manecilla
elDynAttrNS' (Just "http://www.w3.org/2000/svg") "line" attrsLine $ return ()
-- mark
generateSegments 100 4
return ()
-- simpleList :: MonadWidget t m => Dynamic t [v] -> (Dynamic t v -> m a) -> m (Dynamic t [a])
generateSegments:: MonadWidget t m => Rational -> Rational -> m ()
generateSegments width nLines = do
let segmentsSize = width / nLines
lineList = constDyn $ Prelude.take (floor nLines) $ iterate (+ segmentsSize) 0
x <- simpleList lineList (generateSegment)
return ()
generateSegment:: MonadWidget t m => Dynamic t Rational -> m ()
generateSegment x = do
let x1 = generateAttr "x1" <$> x
let x2 = generateAttr "x2" <$> x
let y1 = constDyn $ "y1" =: "0"
let y2 = constDyn $ "y2" =: "100"
let stroke = constDyn $ "stroke" =: "var(--primary-color)"
let strokeWidth = constDyn $ "stroke-width" =: "0.05;"
let attrsLine = mconcat [x1,y1,x2,y2,stroke,strokeWidth]
elDynAttrNS' (Just "http://www.w3.org/2000/svg") "line" attrsLine $ return ()
return ()
generateAttr :: Text -> Rational -> Map Text Text
generateAttr atr x = atr =: (showt (realToFrac x :: Double))
generatePieSegments:: MonadWidget t m => Rational -> m ()
generatePieSegments nLines = do
let segmentsSize = 360 / nLines
lineList = constDyn $ Prelude.take (floor nLines) $ iterate (+ segmentsSize) 0
x <- simpleList lineList (generatePieSegment)
return ()
generatePieSegment:: MonadWidget t m => Dynamic t Rational -> m ()
generatePieSegment x = do
let stroke = constDyn $ "stroke" =: "var(--primary-color)"
let strokeWidth = constDyn $ "stroke-width" =: "0.05"
let (x1,x2) = (constDyn $ "x1" =: "0",constDyn $ "x2" =: "0")
let (y1,y2) = (constDyn $ "y1" =: "0",constDyn $ "y2" =: "-1")
let transform = (\x -> "transform" =: ("rotate(" <> (showt (realToFrac x :: Double)) <> ")")) <$> x
let attrsLine = mconcat [x1,y1,x2,y2,stroke,strokeWidth,transform]
elDynAttrNS' (Just "http://www.w3.org/2000/svg") "line" attrsLine $ return ()
return ()
| d0kt0r0/estuary | client/src/Estuary/Widgets/Tempo.hs | gpl-3.0 | 6,912 | 0 | 21 | 1,301 | 2,346 | 1,167 | 1,179 | 133 | 1 |
import Test.Tasty
import qualified Granada.Tests.Parser as Parser
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests" [properties, unitTests]
properties :: TestTree
properties = testGroup "Properties" [Parser.propTests]
unitTests :: TestTree
unitTests = testGroup "Unit Tests" [Parser.unitTests]
| adolfosilva/granada | tests/Main.hs | gpl-3.0 | 343 | 0 | 7 | 57 | 94 | 53 | 41 | 10 | 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.ServiceUsage.Services.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns the service configuration and enabled state for a given service.
--
-- /See:/ <https://cloud.google.com/service-usage/ Service Usage API Reference> for @serviceusage.services.get@.
module Network.Google.Resource.ServiceUsage.Services.Get
(
-- * REST Resource
ServicesGetResource
-- * Creating a Request
, servicesGet
, ServicesGet
-- * Request Lenses
, sgXgafv
, sgUploadProtocol
, sgAccessToken
, sgUploadType
, sgName
, sgCallback
) where
import Network.Google.Prelude
import Network.Google.ServiceUsage.Types
-- | A resource alias for @serviceusage.services.get@ method which the
-- 'ServicesGet' request conforms to.
type ServicesGetResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GoogleAPIServiceusageV1Service
-- | Returns the service configuration and enabled state for a given service.
--
-- /See:/ 'servicesGet' smart constructor.
data ServicesGet =
ServicesGet'
{ _sgXgafv :: !(Maybe Xgafv)
, _sgUploadProtocol :: !(Maybe Text)
, _sgAccessToken :: !(Maybe Text)
, _sgUploadType :: !(Maybe Text)
, _sgName :: !Text
, _sgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ServicesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sgXgafv'
--
-- * 'sgUploadProtocol'
--
-- * 'sgAccessToken'
--
-- * 'sgUploadType'
--
-- * 'sgName'
--
-- * 'sgCallback'
servicesGet
:: Text -- ^ 'sgName'
-> ServicesGet
servicesGet pSgName_ =
ServicesGet'
{ _sgXgafv = Nothing
, _sgUploadProtocol = Nothing
, _sgAccessToken = Nothing
, _sgUploadType = Nothing
, _sgName = pSgName_
, _sgCallback = Nothing
}
-- | V1 error format.
sgXgafv :: Lens' ServicesGet (Maybe Xgafv)
sgXgafv = lens _sgXgafv (\ s a -> s{_sgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
sgUploadProtocol :: Lens' ServicesGet (Maybe Text)
sgUploadProtocol
= lens _sgUploadProtocol
(\ s a -> s{_sgUploadProtocol = a})
-- | OAuth access token.
sgAccessToken :: Lens' ServicesGet (Maybe Text)
sgAccessToken
= lens _sgAccessToken
(\ s a -> s{_sgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
sgUploadType :: Lens' ServicesGet (Maybe Text)
sgUploadType
= lens _sgUploadType (\ s a -> s{_sgUploadType = a})
-- | Name of the consumer and service to get the \`ConsumerState\` for. An
-- example name would be:
-- \`projects\/123\/services\/serviceusage.googleapis.com\` where \`123\`
-- is the project number.
sgName :: Lens' ServicesGet Text
sgName = lens _sgName (\ s a -> s{_sgName = a})
-- | JSONP
sgCallback :: Lens' ServicesGet (Maybe Text)
sgCallback
= lens _sgCallback (\ s a -> s{_sgCallback = a})
instance GoogleRequest ServicesGet where
type Rs ServicesGet = GoogleAPIServiceusageV1Service
type Scopes ServicesGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient ServicesGet'{..}
= go _sgName _sgXgafv _sgUploadProtocol
_sgAccessToken
_sgUploadType
_sgCallback
(Just AltJSON)
serviceUsageService
where go
= buildClient (Proxy :: Proxy ServicesGetResource)
mempty
| brendanhay/gogol | gogol-serviceusage/gen/Network/Google/Resource/ServiceUsage/Services/Get.hs | mpl-2.0 | 4,549 | 0 | 15 | 1,063 | 700 | 410 | 290 | 100 | 1 |
module Handler.SupplierActions where
import Import
import Handler.Common
import qualified Data.Text as T
import Text.Blaze
getSupplierActionsR :: SupplierId -> Handler Html
getSupplierActionsR sId = do
mSup <- runDB $ get sId
case mSup of
Just sup ->
defaultLayout $
$(widgetFile "supplierActions")
Nothing -> do
setMessageI MsgSupplierUnknown
redirect SupplierR
data BevDigest = BevDigest
{ bdCrates :: Int
, bdTotal :: Int
, bdBev :: Beverage
}
getSupplierDigestR :: SupplierId -> Handler Html
getSupplierDigestR sId = do
mSup <- runDB $ get sId
case mSup of
Just sup -> do
master <- getYesod
bevs <- runDB $ selectList [BeverageSupplier ==. (Just sId)] [Asc BeverageIdent]
digests <- return $ map genBevDigest bevs
w <- return $ [whamlet|$newline always
<p>
#{supplierIdent sup}<br>
#{unTextarea $ supplierAddress sup}<br>
#{supplierTel sup}<br>
#{supplierEmail sup}<br>
<hr>
<p>
<b>
_{MsgCustomerId}: #{supplierCustomerId sup}
<p>
<table>
<thead>
<tr>
<th>
<span .transp>|
_{MsgArtNr}
<span .transp>|
<th>
_{MsgName}
<span .transp>|
<th>
_{MsgVolume}
<span .transp>|
<th>
_{MsgCrateCount}
<span .transp>|
<th>
_{MsgPricePerCrate}
<span .transp>|
<th>
_{MsgTotalValue}
<span .transp>|
<tr>
<th colspan="6" .transp>
|---:|---:|---:|---:|---:|---:|
$forall dig <- digests
$if bdCrates dig /= 0
<tr>
<td>
<span .transp>|
#{fromMaybe "" $ beverageArtNr $ bdBev dig}
<span .transp>|
<td>#{beverageIdent $ bdBev dig}
<span .transp>|
<td>#{formatIntVolume $ beverageMl $ bdBev dig}
<span .transp>|
<td>#{T.pack $ show $ bdCrates dig}
<span .transp>|
<td style="text-align: right;">#{formatIntCurrency $ fromMaybe 0 $ beveragePricePerCrate $ bdBev dig} #{appCurrency $ appSettings master}
<span .transp>|
<td style="text-align: right;">#{formatIntCurrency $ bdTotal dig} #{appCurrency $ appSettings master}
<span .transp>|
<tr>
<td colspan="3">
<span .transp>
|
|_{MsgTotalCrates}
<span .transp>
|
<span .transp>|
<td>#{T.pack $ show $ sum $ map bdCrates digests}
<span .transp>|
<td>_{MsgBuyValue}
<span .transp>|
<td style="text-align: right;">#{formatIntCurrency $ sum $ map bdTotal digests} #{appCurrency $ appSettings master}
<span .transp>|
|]
tableLayout w
Nothing -> do
setMessageI MsgSupplierUnknown
redirect SupplierR
-- tableLayout :: Widget -> WidgetT site0 IO ()
tableLayout :: WidgetT App IO () -> HandlerT App IO Markup
tableLayout widget = do
cont <- widgetToPageContent $ do
$(combineStylesheets 'StaticR
[ css_bootstrap_css
, css_main_css
])
widget
withUrlRenderer [hamlet|$newline never
$doctype 5
<html>
<head>
<meta charset="UTF-8">
^{pageHead cont}
<body>
^{pageBody cont}
|]
genBevDigest :: Entity Beverage -> BevDigest
genBevDigest bev =
BevDigest amount (amount * (fromMaybe 0 $ beveragePricePerCrate $ entityVal bev)) (entityVal bev)
where
amount =
if ((beverageMaxAmount (entityVal bev) - beverageAmount (entityVal bev)) `div` (fromMaybe 1 $ beveragePerCrate (entityVal bev))) < 0
then
0
else
((beverageMaxAmount (entityVal bev) - beverageAmount (entityVal bev)) `div` (fromMaybe 1 $ beveragePerCrate (entityVal bev)))
getDeleteSupplierR :: SupplierId -> Handler Html
getDeleteSupplierR sId = do
mSup <- runDB $ get sId
case mSup of
Just _ -> do
a <- runDB $ selectList [BeverageSupplier ==. (Just sId)] []
if null a
then do
runDB $ delete sId
setMessageI MsgSupplierDeleted
redirect SupplierR
else do
setMessageI MsgSupplierInUseError
redirect SupplierR
Nothing -> do
setMessageI MsgSupplierUnknown
redirect SupplierR
| Mic92/yammat | Handler/SupplierActions.hs | agpl-3.0 | 4,742 | 0 | 18 | 1,743 | 686 | 334 | 352 | -1 | -1 |
--Zaoqilc
--Copyright (C) 2017 Zaoqi
--This program is free software: you can redistribute it and/or modify
--it under the terms of the GNU Affero General Public License as published
--by the Free Software Foundation, either version 3 of the License, or
--(at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
--GNU Affero General Public License for more details.
--You should have received a copy of the GNU Affero General Public License
--along with this program. If not, see <http://www.gnu.org/licenses/>.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE GADTs #-}
module Data.Atom where
data Atom :: [Char] -> * where
Atom :: Atom a
| zaoqi/zaoqilc | featuring/Data/Atom.hs | agpl-3.0 | 868 | 0 | 6 | 164 | 43 | 32 | 11 | 6 | 0 |
{-
Habit of Fate, a game to incentivize habit formation.
Copyright (C) 2017 Gregory Crosswhite
This program is free software: you can redistribute it and/or modify
it under version 3 of the terms of the GNU Affero General Public License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE UnicodeSyntax #-}
module HabitOfFate.Server.Actions.Results where
import HabitOfFate.Prelude
import Control.DeepSeq (NFData, force)
import Control.Exception (SomeException, catch, displayException, evaluate)
import Data.Aeson (ToJSON)
import qualified Data.Text.Lazy as Lazy
import Network.HTTP.Types.Status (Status(..))
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Text.Blaze.Html5 (Html, toHtml)
import Web.Scotty (ActionM, finish, redirect, status)
import qualified Web.Scotty as Scotty
import HabitOfFate.Logging (logIO)
import HabitOfFate.Server.Common
finishWithStatus ∷ Status → ActionM α
finishWithStatus s = do
logIO $ "Finished with status: " ⊕ show s
status s
finish
finishWithStatusMessage ∷ Int → String → ActionM α
finishWithStatusMessage code = pack >>> encodeUtf8 >>> Status code >>> finishWithStatus
data Content =
NoContent
| TextContent Lazy.Text
| HtmlContent (Device → Html)
| ∀ α. (NFData α, ToJSON α) ⇒ JSONContent α
setContent ∷ Device → Content → ActionM ()
setContent device = \case
NoContent → pure ()
TextContent t → check t >>= Scotty.text
HtmlContent h → check (h device |> toHtml |> renderHtml) >>= Scotty.html
JSONContent j → check j >>= Scotty.json
where
check ∷ NFData α ⇒ α → ActionM α
check x =
liftIO
(
(Right <$> (x |> force |> evaluate))
`catch`
(\(e ∷ SomeException) → pure $ Left e)
)
>>=
\case
Right result → pure result
Left exc → do
logIO "ERROR RENDERING PAGE CONTENT:"
logIO $ pack $ displayException exc
Scotty.raise "A server error occurred when rendering the page content. Please try reloading the page."
setStatusAndLog ∷ Status → ActionM ()
setStatusAndLog status_@(Status code message) = do
status status_
let result
| code < 200 || code >= 300 = "failed"
| otherwise = "succeeded"
logIO [i|Request #{result} - #{code} #{decodeUtf8 >>> unpack $ message}|]
setStatusAndRedirect ∷ Status → Lazy.Text → ActionM α
setStatusAndRedirect status_ url = do
logIO [i|Redirecting to #{url} with code #{status_}|]
status status_
redirect url
| gcross/habit-of-fate | sources/library/HabitOfFate/Server/Actions/Results.hs | agpl-3.0 | 3,102 | 0 | 15 | 614 | 669 | 355 | 314 | 64 | 5 |
import Data.List
import qualified Data.Set as S
import Debug.Trace
import Data.Maybe
isPrime = ((==1).length.primeFactors)
primes = 2 : filter ((==1) . length . primeFactors) [3,5..]
primeFactors n = factor n primes
where
factor n (p:ps)
| p*p > n = [n]
| n `mod` p == 0 = p : factor (n `div` p) (p:ps)
| otherwise = factor n ps
isCube x = head (dropWhile (<x) cubes) == x
f n p = n^3 + n^2*p
icubes = zip cubes [1..]
cubes = map (^3) [1..]
target = 1000000
-- For n^3 + n^2*p = m^3 we can rewrite so that
-- n^2 * (n + p) = m^3
-- Since we presuppose that m^3 / n^2 must be
-- a whole number, m^3/n^2 must reform into
-- some other cube or p must be 0
prob131 t =
map (\(n,p) -> (n, p, round $ (fromIntegral $ f n p) ** (1/3) )) $
map fromJust $
filter (not.isNothing) $
map solve $
takeWhile (<t*1000) cubes -- hack. Not sure what the upper bound for (n+p) actually is?
where solve s =
if length primelist == 0 then Nothing else Just $ (s, head primelist)
where primelist =
filter isPrime $
takeWhile (<=t) $
map (\c-> c-s) $
(dropWhile (<=s) cubes)
main = putStrLn $ show $ length $ prob131 target
| jdavidberger/project-euler | prob131.hs | lgpl-3.0 | 1,281 | 3 | 13 | 403 | 505 | 267 | 238 | 30 | 2 |
module Network.Haskoin.Transaction.Builder
( Coin(..)
, buildTx
, buildAddrTx
, SigInput(..)
, signTx
, signInput
, mergeTxs
, verifyStdTx
, verifyStdInput
, guessTxSize
, chooseCoins
, chooseCoinsSink
, chooseMSCoins
, chooseMSCoinsSink
, getFee
, getMSFee
) where
import Control.Arrow (first)
import Control.Monad (mzero, foldM, unless)
import Control.Monad.Identity (runIdentity)
import Control.DeepSeq (NFData, rnf)
import Data.Maybe (catMaybes, maybeToList, isJust, fromJust, fromMaybe)
import Data.List (find, nub)
import Data.Word (Word64)
import Data.Conduit (Sink, await, ($$))
import Data.Conduit.List (sourceList)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS (length, replicate, empty, null)
import Data.String.Conversions (cs)
import Data.Aeson
( Value (Object)
, FromJSON
, ToJSON
, (.=), (.:), (.:?)
, object
, parseJSON
, toJSON
)
import Network.Haskoin.Util
import Network.Haskoin.Crypto
import Network.Haskoin.Node.Types
import Network.Haskoin.Script
import Network.Haskoin.Transaction.Types
-- | Any type can be used as a Coin if it can provide a value in Satoshi.
-- The value is used in coin selection algorithms.
class Coin c where
coinValue :: c -> Word64
-- | Coin selection algorithm for normal (non-multisig) transactions. This
-- function returns the selected coins together with the amount of change to
-- send back to yourself, taking the fee into account.
chooseCoins :: Coin c
=> Word64 -- ^ Target price to pay.
-> Word64 -- ^ Fee price per 1000 bytes.
-> Bool -- ^ Try to find better solution when one is found
-> [c] -- ^ List of ordered coins to choose from.
-> Either String ([c], Word64)
-- ^ Coin selection result and change amount.
chooseCoins target kbfee continue coins =
runIdentity $ sourceList coins $$ chooseCoinsSink target kbfee continue
-- | Coin selection algorithm for normal (non-multisig) transactions. This
-- function returns the selected coins together with the amount of change to
-- send back to yourself, taking the fee into account. This version uses a
-- Sink if you need conduit-based coin selection.
chooseCoinsSink :: (Monad m, Coin c)
=> Word64 -- ^ Target price to pay.
-> Word64 -- ^ Fee price per 1000 bytes.
-> Bool -- ^ Try to find better solution when one is found
-> Sink c m (Either String ([c], Word64))
-- ^ Coin selection result and change amount.
chooseCoinsSink target kbfee continue
| target > 0 =
maybeToEither err <$> greedyAddSink target (getFee kbfee) continue
| otherwise = return $ Left "chooseCoins: Target must be > 0"
where
err = "chooseCoins: No solution found"
-- | Coin selection algorithm for multisignature transactions. This function
-- returns the selected coins together with the amount of change to send back
-- to yourself, taking the fee into account. This function assumes all the
-- coins are script hash outputs that send funds to a multisignature address.
chooseMSCoins :: Coin c
=> Word64 -- ^ Target price to pay.
-> Word64 -- ^ Fee price per 1000 bytes.
-> (Int, Int) -- ^ Multisig parameters m of n (m,n).
-> Bool -- ^ Try to find better solution when one is found
-> [c]
-> Either String ([c], Word64)
-- ^ Coin selection result and change amount.
chooseMSCoins target kbfee ms continue coins =
runIdentity $ sourceList coins $$ chooseMSCoinsSink target kbfee ms continue
-- | Coin selection algorithm for multisignature transactions. This function
-- returns the selected coins together with the amount of change to send back
-- to yourself, taking the fee into account. This function assumes all the
-- coins are script hash outputs that send funds to a multisignature address.
-- This version uses a Sink if you need conduit-based coin selection.
chooseMSCoinsSink :: (Monad m, Coin c)
=> Word64 -- ^ Target price to pay.
-> Word64 -- ^ Fee price per 1000 bytes.
-> (Int, Int) -- ^ Multisig parameters m of n (m,n).
-> Bool -- ^ Try to find better solution when one is found
-> Sink c m (Either String ([c], Word64))
-- ^ Coin selection result and change amount.
chooseMSCoinsSink target kbfee ms continue
| target > 0 =
maybeToEither err <$> greedyAddSink target (getMSFee kbfee ms) continue
| otherwise = return $ Left "chooseMSCoins: Target must be > 0"
where
err = "chooseMSCoins: No solution found"
-- Select coins greedily by starting from an empty solution. If the continue
-- value is set to True, the algorithm will try to find a better solution in
-- the stream once a solution is found. If the next solution found is not
-- strictly better than the previously found solution, the algorithm stops and
-- returns the previous solution. If the continue value is set to False, the
-- algorithm will return the first solution it finds in the stream.
greedyAddSink :: (Monad m, Coin c)
=> Word64 -- ^ Target to reach
-> (Int -> Word64) -- ^ Coin count to fee function
-> Bool -- ^ Try to find better solutions
-> Sink c m (Maybe ([c], Word64)) -- (Selected coins, change)
greedyAddSink target fee continue =
go [] 0 [] 0
where
-- The goal is the value we must reach (including the fee) for a certain
-- amount of selected coins.
goal c = target + fee c
go acc aTot ps pTot = await >>= \coinM -> case coinM of
-- A coin is available in the stream
Just coin -> do
let val = coinValue coin
-- We have reached the goal using this coin
if val + aTot >= (goal $ length acc + 1)
-- If we want to continue searching for better solutions
then if continue
-- This solution is the first one or
-- This solution is better than the previous one
then if pTot == 0 || val + aTot < pTot
-- Continue searching for better solutions in the stream
then go [] 0 (coin:acc) (val + aTot)
-- Otherwise, we stop here and return the previous
-- solution
else return $ Just (ps, pTot - (goal $ length ps))
-- Otherwise, return this solution
else return $
Just (coin:acc, val + aTot - (goal $ length acc + 1))
-- We have not yet reached the goal. Add the coin to the
-- accumulator
else go (coin:acc) (val + aTot) ps pTot
-- We reached the end of the stream
Nothing ->
return $ if null ps
-- If no solution was found, return Nothing
then Nothing
-- If we have a solution, return it
else Just (ps, pTot - (goal $ length ps))
getFee :: Word64 -> Int -> Word64
getFee kbfee count =
kbfee*((len + 999) `div` 1000)
where
len = fromIntegral $ guessTxSize count [] 2 0
getMSFee :: Word64 -> (Int, Int) -> Int -> Word64
getMSFee kbfee ms count =
kbfee*((len + 999) `div` 1000)
where
len = fromIntegral $ guessTxSize 0 (replicate count ms) 2 0
-- | Computes an upper bound on the size of a transaction based on some known
-- properties of the transaction.
guessTxSize :: Int -- ^ Number of regular transaction inputs.
-> [(Int,Int)]
-- ^ For every multisig input in the transaction, provide
-- the multisig parameters m of n (m,n) for that input.
-> Int -- ^ Number of pay to public key hash outputs.
-> Int -- ^ Number of pay to script hash outputs.
-> Int -- ^ Upper bound on the transaction size.
guessTxSize pki msi pkout msout =
8 + inpLen + inp + outLen + out
where
inpLen = BS.length $ encode' $ VarInt $ fromIntegral $ (length msi) + pki
outLen = BS.length $ encode' $ VarInt $ fromIntegral $ pkout + msout
inp = pki*148 + (sum $ map guessMSSize msi)
-- (20: hash160) + (5: opcodes) +
-- (1: script len) + (8: Word64)
out = pkout*34 +
-- (20: hash160) + (3: opcodes) +
-- (1: script len) + (8: Word64)
msout*32
-- Size of a multisig pay2sh input
guessMSSize :: (Int,Int) -> Int
guessMSSize (m,n) =
-- OutPoint (36) + Sequence (4) + Script
40 + (BS.length $ encode' $ VarInt $ fromIntegral scp) + scp
where
-- OP_M + n*PubKey + OP_N + OP_CHECKMULTISIG
rdm = BS.length $ encode' $ opPushData $ BS.replicate (n*34 + 3) 0
-- Redeem + m*sig + OP_0
scp = rdm + m*73 + 1
{- Build a new Tx -}
-- | Build a transaction by providing a list of outpoints as inputs
-- and a list of recipients addresses and amounts as outputs.
buildAddrTx :: [OutPoint] -> [(ByteString, Word64)] -> Either String Tx
buildAddrTx xs ys =
buildTx xs =<< mapM f ys
where
f (s, v) = case base58ToAddr s of
Just a@(PubKeyAddress _) -> return (PayPKHash a,v)
Just a@(ScriptAddress _) -> return (PayScriptHash a,v)
_ -> Left $ "buildAddrTx: Invalid address " ++ cs s
-- | Build a transaction by providing a list of outpoints as inputs
-- and a list of 'ScriptOutput' and amounts as outputs.
buildTx :: [OutPoint] -> [(ScriptOutput, Word64)] -> Either String Tx
buildTx xs ys =
mapM fo ys >>= \os -> return $ Tx 1 (map fi xs) os 0
where
fi outPoint = TxIn outPoint BS.empty maxBound
fo (o, v)
| v <= 2100000000000000 = return $ TxOut v $ encodeOutputBS o
| otherwise =
Left $ "buildTx: Invalid amount " ++ show v
-- | Data type used to specify the signing parameters of a transaction input.
-- To sign an input, the previous output script, outpoint and sighash are
-- required. When signing a pay to script hash output, an additional redeem
-- script is required.
data SigInput = SigInput
{ sigDataOut :: !ScriptOutput -- ^ Output script to spend.
, sigDataOP :: !OutPoint -- ^ Spending tranasction OutPoint
, sigDataSH :: !SigHash -- ^ Signature type.
, sigDataRedeem :: !(Maybe RedeemScript) -- ^ Redeem script
} deriving (Eq, Read, Show)
instance NFData SigInput where
rnf (SigInput o p h b) = rnf o `seq` rnf p `seq` rnf h `seq` rnf b
instance ToJSON SigInput where
toJSON (SigInput so op sh rdm) = object $
[ "pkscript" .= so
, "outpoint" .= op
, "sighash" .= sh
] ++ [ "redeem" .= r | r <- maybeToList rdm ]
instance FromJSON SigInput where
parseJSON (Object o) = do
so <- o .: "pkscript"
op <- o .: "outpoint"
sh <- o .: "sighash"
rdm <- o .:? "redeem"
return $ SigInput so op sh rdm
parseJSON _ = mzero
-- | Sign a transaction by providing the 'SigInput' signing paramters and
-- a list of private keys. The signature is computed deterministically as
-- defined in RFC-6979.
signTx :: Tx -- ^ Transaction to sign
-> [SigInput] -- ^ SigInput signing parameters
-> [PrvKey] -- ^ List of private keys to use for signing
-> Either String Tx -- ^ Signed transaction
signTx otx@(Tx _ ti _ _) sigis allKeys
| null ti = Left "signTx: Transaction has no inputs"
| otherwise = foldM go otx $ findSigInput sigis ti
where
go tx (sigi@(SigInput so _ _ rdmM), i) = do
keys <- sigKeys so rdmM allKeys
foldM (\t k -> signInput t i sigi k) tx keys
-- | Sign a single input in a transaction deterministically (RFC-6979).
signInput :: Tx -> Int -> SigInput -> PrvKey -> Either String Tx
signInput tx i (SigInput so _ sh rdmM) key = do
let sig = TxSignature (signMsg msg key) sh
si <- buildInput tx i so rdmM sig $ derivePubKey key
return tx{ txIn = updateIndex i (txIn tx) (f si) }
where
f si x = x{ scriptInput = encodeInputBS si }
msg = txSigHash tx (encodeOutput $ fromMaybe so rdmM) i sh
-- Order the SigInput with respect to the transaction inputs. This allow the
-- users to provide the SigInput in any order. Users can also provide only a
-- partial set of SigInputs.
findSigInput :: [SigInput] -> [TxIn] -> [(SigInput, Int)]
findSigInput si ti =
catMaybes $ map g $ zip (matchTemplate si ti f) [0..]
where
f s txin = sigDataOP s == prevOutput txin
g (Just s, i) = Just (s,i)
g (Nothing, _) = Nothing
-- Find from the list of private keys which one is required to sign the
-- provided ScriptOutput.
sigKeys :: ScriptOutput -> (Maybe RedeemScript) -> [PrvKey]
-> Either String [PrvKey]
sigKeys so rdmM keys = do
case (so, rdmM) of
(PayPK p, Nothing) -> return $
map fst $ maybeToList $ find ((== p) . snd) zipKeys
(PayPKHash a, Nothing) -> return $
map fst $ maybeToList $ find ((== a) . pubKeyAddr . snd) zipKeys
(PayMulSig ps r, Nothing) -> return $
map fst $ take r $ filter ((`elem` ps) . snd) zipKeys
(PayScriptHash _, Just rdm) ->
sigKeys rdm Nothing keys
_ -> Left "sigKeys: Could not decode output script"
where
zipKeys = zip keys (map derivePubKey keys)
-- Construct an input, given a signature and a public key
buildInput :: Tx -> Int -> ScriptOutput -> (Maybe RedeemScript)
-> TxSignature -> PubKey -> Either String ScriptInput
buildInput tx i so rdmM sig pub = case (so, rdmM) of
(PayPK _, Nothing) ->
return $ RegularInput $ SpendPK sig
(PayPKHash _, Nothing) ->
return $ RegularInput $ SpendPKHash sig pub
(PayMulSig msPubs r, Nothing) -> do
let mSigs = take r $ catMaybes $ matchTemplate allSigs msPubs f
return $ RegularInput $ SpendMulSig mSigs
(PayScriptHash _, Just rdm) -> do
inp <- buildInput tx i rdm Nothing sig pub
return $ ScriptHashInput (getRegularInput inp) rdm
_ -> Left "buildInput: Invalid output/redeem script combination"
where
scp = scriptInput $ txIn tx !! i
allSigs = nub $ sig : case decodeInputBS scp of
Right (ScriptHashInput (SpendMulSig xs) _) -> xs
Right (RegularInput (SpendMulSig xs)) -> xs
_ -> []
out = encodeOutput so
f (TxSignature x sh) p = verifySig (txSigHash tx out i sh) x p
{- Merge multisig transactions -}
mergeTxs :: [Tx] -> [(ScriptOutput, OutPoint)] -> Either String Tx
mergeTxs txs os
| null txs = error "Transaction list is empty"
| length (nub emptyTxs) /= 1 = Left "Transactions do not match"
| length txs == 1 = return $ head txs
| otherwise = foldM (mergeTxInput txs) (head emptyTxs) outs
where
zipOp = zip (matchTemplate os (txIn $ head txs) f) [0..]
outs = map (first $ fst . fromJust) $ filter (isJust . fst) zipOp
f (_,o) txin = o == prevOutput txin
emptyTxs = map (\tx -> foldl clearInput tx outs) txs
clearInput tx (_, i) = tx{ txIn =
updateIndex i (txIn tx) (\ti -> ti{ scriptInput = BS.empty }) }
mergeTxInput :: [Tx] -> Tx -> (ScriptOutput, Int) -> Either String Tx
mergeTxInput txs tx (so, i) = do
-- Ignore transactions with empty inputs
let ins = map (scriptInput . (!! i) . txIn) txs
sigRes <- mapM extractSigs $ filter (not . BS.null) ins
let rdm = snd $ head sigRes
unless (all (== rdm) $ map snd sigRes) $
Left "Redeem scripts do not match"
si <- encodeInputBS <$> go (nub $ concat $ map fst sigRes) so rdm
return tx{ txIn = updateIndex i (txIn tx) (\ti -> ti{ scriptInput = si }) }
where
go allSigs out rdmM = case out of
PayMulSig msPubs r ->
let sigs = take r $ catMaybes $ matchTemplate allSigs msPubs $ f out
in return $ RegularInput $ SpendMulSig sigs
PayScriptHash _ -> case rdmM of
Just rdm -> do
si <- go allSigs rdm Nothing
return $ ScriptHashInput (getRegularInput si) rdm
_ -> Left "Invalid output script type"
_ -> Left "Invalid output script type"
extractSigs si = case decodeInputBS si of
Right (RegularInput (SpendMulSig sigs)) -> Right (sigs, Nothing)
Right (ScriptHashInput (SpendMulSig sigs) rdm) -> Right (sigs, Just rdm)
_ -> Left "Invalid script input type"
f out (TxSignature x sh) p =
verifySig (txSigHash tx (encodeOutput out) i sh) x p
{- Tx verification -}
-- | Verify if a transaction is valid and all of its inputs are standard.
verifyStdTx :: Tx -> [(ScriptOutput, OutPoint)] -> Bool
verifyStdTx tx xs =
all go $ zip (matchTemplate xs (txIn tx) f) [0..]
where
f (_,o) txin = o == prevOutput txin
go (Just (so,_), i) = verifyStdInput tx i so
go _ = False
-- | Verify if a transaction input is valid and standard.
verifyStdInput :: Tx -> Int -> ScriptOutput -> Bool
verifyStdInput tx i so' =
go (scriptInput $ txIn tx !! i) so'
where
go inp so = case decodeInputBS inp of
Right (RegularInput (SpendPK (TxSignature sig sh))) ->
let pub = getOutputPubKey so
in verifySig (txSigHash tx out i sh) sig pub
Right (RegularInput (SpendPKHash (TxSignature sig sh) pub)) ->
let a = getOutputAddress so
in pubKeyAddr pub == a &&
verifySig (txSigHash tx out i sh) sig pub
Right (RegularInput (SpendMulSig sigs)) ->
let pubs = getOutputMulSigKeys so
r = getOutputMulSigRequired so
in countMulSig tx out i pubs sigs == r
Right (ScriptHashInput si rdm) ->
scriptAddr rdm == getOutputAddress so &&
go (encodeInputBS $ RegularInput si) rdm
_ -> False
where
out = encodeOutput so
-- Count the number of valid signatures
countMulSig :: Tx -> Script -> Int -> [PubKey] -> [TxSignature] -> Int
countMulSig _ _ _ [] _ = 0
countMulSig _ _ _ _ [] = 0
countMulSig tx out i (pub:pubs) sigs@(TxSignature sig sh:rest)
| verifySig (txSigHash tx out i sh) sig pub =
1 + countMulSig tx out i pubs rest
| otherwise = countMulSig tx out i pubs sigs
| tphyahoo/haskoin | haskoin-core/Network/Haskoin/Transaction/Builder.hs | unlicense | 18,390 | 0 | 23 | 5,297 | 4,792 | 2,510 | 2,282 | 303 | 7 |
-- | To represent a version map,
-- that is, which version numbers exist for each package.
module VersionFile.Types where
import Distribution.Package (PackageName)
import Distribution.Version (Version)
-- A simple association list. Profile before you optimize :)
type VersionMap = [(PackageName, [Version])]
restricted_to :: VersionMap -> [PackageName] -> VersionMap
restricted_to v packages = filter (go . fst) v
where
go :: PackageName -> Bool
go = (`elem` packages)
| gelisam/cabal-rangefinder | src/VersionFile/Types.hs | unlicense | 485 | 0 | 7 | 83 | 107 | 65 | 42 | 8 | 1 |
import Data.List (group, permutations)
data Tree = Branch [Tree] | Leaf deriving (Eq, Show)
type Forest = [Tree]
type Harvestable = Forest
type OldGrowth = Forest
type Lumberyard = (Harvestable, OldGrowth)
type Partition = [Int]
type Composition = [Int]
fromParenthesis :: String -> Tree
-- fromParenthesis "" = Leaf
fromParenthesis "()" = Leaf
fromParenthesis parens = Branch $ map fromParenthesis $ partitionParenthesis $ inner parens
inner :: String -> String
inner "" = error "empty"
inner "a" = error "length 1"
inner s = init $ tail s
-- () is a single leaf
-- (()) is a 2-vertex tree
-- ((())) and (()()) are 3-vertex trees rooted at first and second vertex respectively.
partitionParenthesis :: String -> [String]
partitionParenthesis "" = []
partitionParenthesis parens = recurse 0 "" parens where
recurse :: Int -> String -> String -> [String]
recurse 1 s (')':remaining) = reverse (')':s) : partitionParenthesis remaining
recurse n s ('(':remaining) = recurse (n+1) ('(':s) remaining
recurse n s (')':remaining) = recurse (n-1) (')':s) remaining
recurse n s "" = error $ show n
-- recurse n ("(":remaining)) =
-- gretasFunction :: Forest -> Partition -> Integer
-- gretasFunction f (p:ps) = recurse ps (takeFromTree p f) where
-- recurse [] forests
size :: Tree -> Int
size Leaf = 1
size (Branch trees) = 1 + sum (map size trees)
takeOne :: Tree -> Forest
takeOne Leaf = []
takeOne (Branch subTrees) = subTrees
takeFromTree :: Int -> Tree -> [Forest]
takeFromTree n t = recurse n [([t], [])] where
recurse :: Int -> [Lumberyard] -> [Forest]
recurse 0 f = map (uncurry (++)) f
recurse n f = recurse (n - 1) (concatMap nextGen f)
takeFromForest :: Int -> Forest -> [Forest]
takeFromForest n forest = concatMap takeTree $ tailsAndInits forest where
-- First forest can be harvested, second forest is old growth.
takeTree :: Lumberyard -> [Forest]
takeTree (t:ts, is)
| size t >= n = map (++ ts ++ is) $ takeFromTree n t
| otherwise = []
takeFromForest' :: Int -> Forest -> [Lumberyard]
takeFromForest' n forest = concatMap (takeFromFirstTreeInLumberyard n) $ tailsAndInits forest
takeFromFirstTreeInLumberyard :: Int -> Lumberyard -> [Lumberyard]
takeFromFirstTreeInLumberyard n (t:ts, is)
| size t >= n = map (\forest -> (forest ++ ts, is)) $ takeFromTree n t
| otherwise = []
takeFromLumberyard :: Int -> Lumberyard -> [Lumberyard]
takeFromLumberyard n (harvestable, oldGrowths) = map (\(hs, os) -> (hs, os ++ oldGrowths)) $ takeFromForest' n harvestable
nextGen :: Lumberyard -> [Lumberyard]
nextGen (harvestable, oldGrowth) = map (\(t:ts, is) -> (takeOne t ++ ts, is ++ oldGrowth)) $ tailsAndInits harvestable
tailsAndInits :: [a] -> [([a], [a])]
tailsAndInits [] = []
tailsAndInits as = recurse as [] where
recurse :: [a] -> [a] -> [([a], [a])]
recurse [] ts = [] -- [([], ts)]
recurse is'@(i:is) ts = (is', ts) : recurse is (i:ts)
partitionOrders :: Partition -> [Composition]
partitionOrders = map concat . permutations . group
treeDissectionCount :: Tree -> Partition -> Int
treeDissectionCount t (p:ps) = recurse p ps [([t],[])] where
recurse :: Int -> Partition -> [Lumberyard] -> Int
recurse n [] lumberyards = length $ concatMap (takeFromLumberyard n) lumberyards
recurse n (c:cs) lumberyards
| n == c = recurse c cs $ concatMap (takeFromLumberyard n) lumberyards
| otherwise = recurse c cs $ map (\(h, o) -> (h ++ o, [])) $ concatMap (takeFromLumberyard n) lumberyards
treePartitionCount :: Tree -> Partition -> Int
treePartitionCount t p = sum $ map (treeDissectionCount t) $ partitionOrders p
| peterokagey/haskellOEIS | src/Sandbox/Greta/TreeFunction.hs | apache-2.0 | 3,606 | 1 | 14 | 669 | 1,403 | 743 | 660 | 67 | 4 |
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE NamedFieldPuns #-}
{-|
Module: Crypto.Spake2
Description: Implementation of SPAKE2 key exchange protocol
Say that you and someone else share a secret password, and you want to use
this password to arrange some secure channel of communication. You want:
* to know that the other party also knows the secret password (maybe
they're an imposter!)
* the password to be secure against offline dictionary attacks
* probably some other things
SPAKE2 is an algorithm for agreeing on a key exchange that meets these
criteria. See [Simple Password-Based Encrypted Key Exchange
Protocols](http://www.di.ens.fr/~pointche/Documents/Papers/2005_rsa.pdf) by
Michel Abdalla and David Pointcheval for more details.
== How it works
=== Preliminaries
Before exchanging, two nodes need to agree on the following, out-of-band:
In general:
* hash algorithm, \(H\)
* group to use, \(G\)
* arbitrary members of group to use for blinding
* a means of converting this password to a scalar of group
For a specific exchange:
* whether the connection is symmetric or asymmetric
* the IDs of the respective sides
* a shared, secret password in bytes
#protocol#
=== Protocol
==== How we map the password to a scalar
Use HKDF expansion (see 'expandData') to expand the password by 16 bytes,
using an empty salt, and "SPAKE2 pw" as the info.
Then, use a group-specific mapping from bytes to scalars.
Since scalars are normally isomorphic to integers,
this will normally be a matter of converting the bytes to an integer
using standard deserialization
and then turning the integer into a scalar.
==== How we exchange information
See 'Crypto.Spake2.Math' for details on the mathematics of the exchange.
==== How python-spake2 works
- Message to other side is prepended with a single character, @A@, @B@, or
@S@, to indicate which side it came from
- The hash function for generating the session key has a few interesting properties:
- uses SHA256 for hashing
- does not include password or IDs directly, but rather uses /their/ SHA256
digests as inputs to the hash
- for the symmetric version, it sorts \(X^{\star}\) and \(Y^{\star}\),
because neither side knows which is which
- By default, the ID of either side is the empty bytestring
== Open questions
* how does endianness come into play?
* what is Shallue-Woestijne-Ulas and why is it relevant?
== References
* [Javascript implementation](https://github.com/bitwiseshiftleft/sjcl/pull/273/), includes long, possibly relevant discussion
* [Python implementation](https://github.com/warner/python-spake2)
* [SPAKE2 random elements](http://www.lothar.com/blog/54-spake2-random-elements/) - blog post by warner about choosing \(M\) and \(N\)
* [Simple Password-Based Encrypted Key Exchange Protocols](http://www.di.ens.fr/~pointche/Documents/Papers/2005_rsa.pdf) by Michel Abdalla and David Pointcheval
* [draft-irtf-cfrg-spake2-03](https://tools.ietf.org/html/draft-irtf-cfrg-spake2-03) - expired IRTF draft for SPAKE2
-}
module Crypto.Spake2
( Password
, makePassword
-- * The SPAKE2 protocol
, Protocol
, makeAsymmetricProtocol
, makeSymmetricProtocol
, spake2Exchange
, startSpake2
, Math.computeOutboundMessage
, Math.generateKeyMaterial
, extractElement
, MessageError
, formatError
, elementToMessage
, createSessionKey
, SideID(..)
, WhichSide(..)
) where
import Protolude hiding (group)
import Crypto.Error (CryptoError, CryptoFailable(..))
import Crypto.Hash (HashAlgorithm, hashWith)
import Crypto.Random.Types (MonadRandom(..))
import Data.ByteArray (ByteArrayAccess)
import qualified Data.ByteArray as ByteArray
import qualified Data.ByteString as ByteString
import Crypto.Spake2.Group (AbelianGroup(..), Group(..), decodeScalar, scalarSizeBytes)
import qualified Crypto.Spake2.Math as Math
import Crypto.Spake2.Util (expandData)
-- | Shared secret password used to negotiate the connection.
--
-- Constructor deliberately not exported,
-- so that once a 'Password' has been created, the actual password cannot be retrieved by other modules.
--
-- Construct with 'makePassword'.
newtype Password = Password ByteString deriving (Eq, Ord)
-- | Construct a password.
makePassword :: ByteString -> Password
makePassword = Password
-- | Bytes that identify a side of the protocol
newtype SideID = SideID { unSideID :: ByteString } deriving (Eq, Ord, Show)
-- | Convert a user-supplied password into a scalar on a group.
passwordToScalar :: AbelianGroup group => group -> Password -> Scalar group
passwordToScalar group password =
decodeScalar group oversized
where
oversized = expandPassword password (scalarSizeBytes group + 16) :: ByteString
expandPassword (Password bytes) = expandData info bytes
-- This needs to be exactly "SPAKE2 pw"
-- See <https://github.com/bitwiseshiftleft/sjcl/pull/273/#issuecomment-185251593>
info = "SPAKE2 pw"
-- | Turn an element into a message from this side of the protocol.
elementToMessage :: Group group => Protocol group hashAlgorithm -> Element group -> ByteString
elementToMessage protocol element = prefix <> encodeElement (group protocol) element
where
prefix =
case relation protocol of
Symmetric _ -> "S"
Asymmetric{us=SideA} -> "A"
Asymmetric{us=SideB} -> "B"
-- | An error that occurs when interpreting messages from the other side of the exchange.
data MessageError e
= EmptyMessage -- ^ We received an empty bytestring.
| UnexpectedPrefix Word8 Word8
-- ^ The bytestring had an unexpected prefix.
-- We expect the prefix to be @A@ if the other side is side A,
-- @B@ if they are side B,
-- or @S@ if the connection is symmetric.
-- First argument is received prefix, second is expected.
| BadCrypto CryptoError ByteString
-- ^ Message could not be decoded to an element of the group.
-- This can indicate either an error in serialization logic,
-- or in mathematics.
| UnknownError e
-- ^ An error arising from the "receive" action in 'spake2Exchange'.
-- Since 0.4.0
deriving (Eq, Show)
-- | Turn a 'MessageError' into human-readable text.
formatError :: Show e => MessageError e -> Text
formatError EmptyMessage = "Other side sent us an empty message"
formatError (UnexpectedPrefix got expected) = "Other side claims to be " <> show (chr (fromIntegral got)) <> ", expected " <> show (chr (fromIntegral expected))
formatError (BadCrypto err message) = "Could not decode message (" <> show message <> ") to element: " <> show err
formatError (UnknownError err) = "Error receiving message from other side: " <> show err
-- | Extract an element on the group from an incoming message.
--
-- Returns a 'MessageError' if we cannot decode the message,
-- or the other side does not appear to be the expected other side.
--
-- TODO: Need to protect against reflection attack at some point.
extractElement :: Group group => Protocol group hashAlgorithm -> ByteString -> Either (MessageError error) (Element group)
extractElement protocol message =
case ByteString.uncons message of
Nothing -> throwError EmptyMessage
Just (prefix, msg)
| prefix /= theirPrefix (relation protocol) -> throwError $ UnexpectedPrefix prefix (theirPrefix (relation protocol))
| otherwise ->
case decodeElement (group protocol) msg of
CryptoFailed err -> throwError (BadCrypto err msg)
CryptoPassed element -> pure element
-- | One side of the SPAKE2 protocol.
data Side group
= Side
{ sideID :: SideID -- ^ Bytes identifying this side
, blind :: Element group -- ^ Arbitrarily chosen element in the group
-- used by this side to blind outgoing messages.
}
-- | Which side we are.
data WhichSide = SideA | SideB deriving (Eq, Ord, Show, Bounded, Enum)
-- | Relation between two sides in SPAKE2.
-- Can be either symmetric (both sides are the same), or asymmetric.
data Relation group
= Asymmetric
{ sideA :: Side group -- ^ Side A. Both sides need to agree who side A is.
, sideB :: Side group -- ^ Side B. Both sides need to agree who side B is.
, us :: WhichSide -- ^ Which side we are
}
| Symmetric
{ bothSides :: Side group -- ^ Description used by both sides.
}
theirPrefix :: Relation a -> Word8
theirPrefix relation =
fromIntegral . ord $ case relation of
Asymmetric{us=SideA} -> 'B'
Asymmetric{us=SideB} -> 'A'
Symmetric{} -> 'S'
-- | Everything required for the SPAKE2 protocol.
--
-- Both sides must agree on these values for the protocol to work.
-- This /mostly/ means value equality, except for 'Relation.us',
-- where each side must have complementary values.
--
-- Construct with 'makeAsymmetricProtocol' or 'makeSymmetricProtocol'.
data Protocol group hashAlgorithm
= Protocol
{ group :: group -- ^ The group to use for encryption
, hashAlgorithm :: hashAlgorithm -- ^ Hash algorithm used for generating the session key
, relation :: Relation group -- ^ How the two sides relate to each other
}
-- | Construct an asymmetric SPAKE2 protocol.
makeAsymmetricProtocol :: hashAlgorithm -> group -> Element group -> Element group -> SideID -> SideID -> WhichSide -> Protocol group hashAlgorithm
makeAsymmetricProtocol hashAlgorithm group blindA blindB sideA sideB whichSide =
Protocol
{ group = group
, hashAlgorithm = hashAlgorithm
, relation = Asymmetric
{ sideA = Side { sideID = sideA, blind = blindA }
, sideB = Side { sideID = sideB, blind = blindB }
, us = whichSide
}
}
-- | Construct a symmetric SPAKE2 protocol.
makeSymmetricProtocol :: hashAlgorithm -> group -> Element group -> SideID -> Protocol group hashAlgorithm
makeSymmetricProtocol hashAlgorithm group blind id =
Protocol
{ group = group
, hashAlgorithm = hashAlgorithm
, relation = Symmetric Side { sideID = id, blind = blind }
}
-- | Get the parameters for the mathematical part of SPAKE2 from the protocol specification.
getParams :: Protocol group hashAlgorithm -> Math.Params group
getParams Protocol{group, relation} =
case relation of
Symmetric{bothSides} -> mkParams bothSides bothSides
Asymmetric{sideA, sideB, us} ->
case us of
SideA -> mkParams sideA sideB
SideB -> mkParams sideB sideA
where
mkParams ours theirs =
Math.Params
{ Math.group = group
, Math.ourBlind = blind ours
, Math.theirBlind = blind theirs
}
-- | Perform an entire SPAKE2 exchange.
--
-- Given a SPAKE2 protocol that has all of the parameters for this exchange,
-- generate a one-off message from this side and receive a one off message
-- from the other.
--
-- Once we are done, return a key shared between both sides for a single
-- session.
--
-- Note: as per the SPAKE2 definition, the session key is not guaranteed
-- to actually /work/. If the other side has failed to authenticate, you will
-- still get a session key. Therefore, you must exchange some other message
-- that has been encrypted using this key in order to confirm that the session
-- key is indeed shared.
--
-- Note: the "send" and "receive" actions are performed 'concurrently'. If you
-- have ordering requirements, consider using a 'TVar' or 'MVar' to coordinate,
-- or implementing your own equivalent of 'spake2Exchange'.
--
-- If the message received from the other side cannot be parsed, return a
-- 'MessageError'.
--
-- Since 0.4.0.
spake2Exchange
:: (AbelianGroup group, HashAlgorithm hashAlgorithm)
=> Protocol group hashAlgorithm
-- ^ A 'Protocol' with all the parameters for the exchange. These parameters
-- must be shared by both sides. Construct with 'makeAsymmetricProtocol' or
-- 'makeSymmetricProtocol'.
-> Password
-- ^ The password shared between both sides. Construct with 'makePassword'.
-> (ByteString -> IO ())
-- ^ An action to send a message. The 'ByteString' parameter is this side's
-- SPAKE2 element, encoded using the group encoding, prefixed according to
-- the parameters in the 'Protocol'.
-> IO (Either error ByteString)
-- ^ An action to receive a message. The 'ByteString' generated ought to be
-- the protocol-prefixed, group-encoded version of the other side's SPAKE2
-- element.
-> IO (Either (MessageError error) ByteString)
-- ^ Either the shared session key or an error indicating we couldn't parse
-- the other side's message.
spake2Exchange protocol password send receive = do
exchange <- startSpake2 protocol password
let outboundElement = Math.computeOutboundMessage exchange
let outboundMessage = elementToMessage protocol outboundElement
(_, inboundMessage) <- concurrently (send outboundMessage) receive
pure $ do
inboundMessage' <- first UnknownError inboundMessage
inboundElement <- extractElement protocol inboundMessage'
let keyMaterial = Math.generateKeyMaterial exchange inboundElement
pure (createSessionKey protocol inboundElement outboundElement keyMaterial password)
-- | Commence a SPAKE2 exchange.
startSpake2
:: (MonadRandom randomly, AbelianGroup group)
=> Protocol group hashAlgorithm
-> Password
-> randomly (Math.Spake2Exchange group)
startSpake2 protocol password =
Math.startSpake2 Math.Spake2 { Math.params = getParams protocol
, Math.password = passwordToScalar (group protocol) password
}
-- | Create a session key based on the output of SPAKE2.
--
-- \[SK \leftarrow H(A, B, X^{\star}, Y^{\star}, K, pw)\]
--
-- Including \(pw\) in the session key is what makes this SPAKE2, not SPAKE1.
--
-- __Note__: In spake2 0.3 and earlier, The \(X^{\star}\) and \(Y^{\star}\)
-- were expected to be from side A and side B respectively. Since spake2 0.4,
-- they are the outbound and inbound elements respectively. This fixes an
-- interoperability concern with the Python library, and reduces the burden on
-- the caller. Apologies for the possibly breaking change to any users of
-- older versions of spake2.
createSessionKey
:: (Group group, HashAlgorithm hashAlgorithm)
=> Protocol group hashAlgorithm -- ^ The protocol used for this exchange
-> Element group -- ^ The outbound message, generated by this, \(X^{\star}\), or either side if symmetric
-> Element group -- ^ The inbound message, generated by the other side, \(Y^{\star}\), or either side if symmetric
-> Element group -- ^ The calculated key material, \(K\)
-> Password -- ^ The shared secret password
-> ByteString -- ^ A session key to use for further communication
createSessionKey Protocol{group, hashAlgorithm, relation} outbound inbound k (Password password) =
hashDigest transcript
where
-- The protocol expects that when we include the hash of various
-- components (e.g. the password) as input for the session key hash,
-- that we use the *byte* representation of these elements.
hashDigest :: ByteArrayAccess input => input -> ByteString
hashDigest thing = ByteArray.convert (hashWith hashAlgorithm thing)
transcript =
case relation of
Asymmetric{sideA, sideB, us} ->
let (x, y) = case us of
SideA -> (inbound, outbound)
SideB -> (outbound, inbound)
in mconcat [ hashDigest password
, hashDigest (unSideID (sideID sideA))
, hashDigest (unSideID (sideID sideB))
, encodeElement group x
, encodeElement group y
, encodeElement group k
]
Symmetric{bothSides} ->
mconcat [ hashDigest password
, hashDigest (unSideID (sideID bothSides))
, symmetricElements
, encodeElement group k
]
symmetricElements =
let [ firstMessage, secondMessage ] = sort [ encodeElement group inbound, encodeElement group outbound ]
in firstMessage <> secondMessage
| jml/haskell-spake2 | src/Crypto/Spake2.hs | apache-2.0 | 16,069 | 0 | 18 | 3,339 | 2,181 | 1,201 | 980 | 175 | 3 |
{-# LANGUAGE GeneralizedNewtypeDeriving, CPP, UnboxedTuples, RecordWildCards, MultiParamTypeClasses, FlexibleContexts, NamedFieldPuns, MagicHash, OverloadedStrings #-}
module Codec.JVM.ASM.Code.Instr where
import Control.Monad.IO.Class
import Control.Monad.State
import Control.Monad.Reader
import Data.ByteString (ByteString)
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Maybe(fromMaybe)
import Data.List(sortBy)
import Data.Int(Int32)
import Data.Ord(comparing)
import GHC.Base
import qualified Data.ByteString as BS
import qualified Data.IntMap.Strict as IntMap
import Codec.JVM.ASM.Code.CtrlFlow (CtrlFlow, Stack, VerifType(..), Stack(..))
import Codec.JVM.ASM.Code.Types
import Codec.JVM.Const (Const(..))
import Codec.JVM.Internal (packI16, packI32)
import Codec.JVM.Opcode (Opcode, opcode)
import Codec.JVM.ConstPool (ConstPool)
import Codec.JVM.Types
import qualified Codec.JVM.Types as T
import qualified Codec.JVM.ASM.Code.CtrlFlow as CF
import qualified Codec.JVM.ConstPool as CP
import qualified Codec.JVM.Opcode as OP
data InstrState =
InstrState { isByteCode :: !ByteString
, isStackMapTable :: StackMapTable
, isOffset :: !Offset
, isCtrlFlow :: CtrlFlow
, isLabelTable :: LabelTable
, isLastBranch :: LastBranch
, isRunAgain :: Bool
, isNextLabel :: Int
, isLineNumberTable :: LineNumberTable
, isExceptionTable :: ExceptionTable }
newtype InstrM a = InstrM { runInstrM :: ConstPool -> InstrState -> (# a, InstrState #) }
newtype Instr = Instr { unInstr :: InstrM () }
instance Functor InstrM where
fmap = liftM
instance Applicative InstrM where
pure = return
(<*>) = ap
instance Monad InstrM where
return x = InstrM $ \_ s -> (# x, s #)
(InstrM m) >>= f =
InstrM $ \e s ->
case m e s of
(# x, s' #) ->
case runInstrM (f x) e s' of
(# x', s'' #) -> (# x', s'' #)
instance MonadIO InstrM where
liftIO (IO io) = InstrM $ \_ s ->
case io realWorld# of
(# _, a #) -> (# a, s #)
instance MonadState InstrState InstrM where
get = InstrM $ \_ s -> (# s, s #)
put s' = InstrM $ \_ _ -> (# (), s' #)
instance MonadReader ConstPool InstrM where
ask = InstrM $ \e s -> (# e, s #)
local f (InstrM m) = InstrM $ \e s -> m (f e) s
instance Monoid Instr where
mempty = Instr $ return ()
mappend (Instr rws0) (Instr rws1) = Instr $ do
rws0
rws1
#if MIN_VERSION_base(4,10,0)
instance Semigroup Instr where
(<>) (Instr rws0) (Instr rws1) = Instr $ do
rws0
rws1
#endif
instance Show Instr where
show _ = "Instructions"
withOffset :: (Int -> Instr) -> Instr
withOffset f = Instr $ do
InstrState { isOffset = Offset offset } <- get
unInstr $ f offset
emptyInstrState :: InstrState
emptyInstrState =
InstrState { isByteCode = mempty
, isStackMapTable = mempty
, isOffset = 0
, isCtrlFlow = CF.empty
, isLabelTable = mempty
, isLastBranch = NoBranch
, isRunAgain = False
, isNextLabel = 1
, isLineNumberTable = mempty
, isExceptionTable = mempty }
getBCS :: InstrState -> (ByteString, CtrlFlow, StackMapTable)
getBCS InstrState{..} = (isByteCode, isCtrlFlow, isStackMapTable)
getBCSL :: InstrState -> (ByteString, CtrlFlow, StackMapTable, LineNumberTable)
getBCSL InstrState{..} = (isByteCode, isCtrlFlow, isStackMapTable, isLineNumberTable)
getBCSLE :: InstrState -> (ByteString, CtrlFlow, StackMapTable, LineNumberTable,
[ExceptionTableEntry])
getBCSLE InstrState{..} =
(isByteCode, isCtrlFlow, isStackMapTable, isLineNumberTable,
toETEs isExceptionTable isLabelTable)
runInstr :: Instr -> ConstPool -> InstrState
runInstr instr cp = multiPass 0 emptyInstrState { isRunAgain = True }
where multiPass :: Int -> InstrState -> InstrState
multiPass n s@InstrState { isRunAgain, isLabelTable = lt }
| isRunAgain =
case runInstr' instr cp $ emptyInstrState { isLabelTable = lt } of
s' -> multiPass (n + 1) s'
| otherwise = s
runInstrBCS :: Instr -> ConstPool -> (ByteString, CtrlFlow, StackMapTable)
runInstrBCS instr cp = getBCS $ runInstr instr cp
runInstrBCSL :: Instr -> ConstPool -> (ByteString, CtrlFlow, StackMapTable, LineNumberTable)
runInstrBCSL instr cp = getBCSL $ runInstr instr cp
runInstrBCSLE :: Instr -> ConstPool -> (ByteString, CtrlFlow, StackMapTable, LineNumberTable, [ExceptionTableEntry])
runInstrBCSLE instr cp = getBCSLE $ runInstr instr cp
runInstr' :: Instr -> ConstPool -> InstrState -> InstrState
runInstr' (Instr m) e s = case runInstrM m e s of (# _, s' #) -> s'
runInstrBCS' :: Instr -> ConstPool -> InstrState -> (ByteString, CtrlFlow, StackMapTable)
runInstrBCS' instr e s = getBCS $ runInstr' instr e s
runInstrBCSL' :: Instr -> ConstPool -> InstrState ->
(ByteString, CtrlFlow, StackMapTable, LineNumberTable)
runInstrBCSL' instr e s = getBCSL $ runInstr' instr e s
recordBranch :: BranchType -> InstrM ()
recordBranch bt = do
off <- getOffset
modify' $ \s -> s { isLastBranch = HasBranch bt (Offset off) }
saveLastBranch :: InstrM LastBranch
saveLastBranch = do
InstrState { isLastBranch = lb } <- get
modify' $ \s -> s { isLastBranch = NoBranch }
return lb
resetLastBranch :: LastBranch -> InstrM ()
resetLastBranch lb = modify' $ \s -> s { isLastBranch = lb }
recordLineNumber' :: LineNumber -> InstrM ()
recordLineNumber' ln = do
off <- getOffset
modify' $ \s@InstrState { isLineNumberTable = lnt } ->
s { isLineNumberTable = insertLNT (Offset off) ln lnt }
recordLineNumber :: LineNumber -> Instr
recordLineNumber = Instr . recordLineNumber'
gotoInstr :: Special -> InstrM ()
gotoInstr = gotoInstrSpec OP.goto
gotoWInstr :: Special -> InstrM ()
gotoWInstr = gotoInstrSpec OP.goto_w
gotoInstrSpec :: Opcode -> Special -> InstrM ()
gotoInstrSpec opc special = do
when (special == NotSpecial) $
recordBranch (if opc == OP.goto_w then GotoW else Goto)
op' opc
gotoInstrGen :: Special -> Int -> InstrM ()
gotoInstrGen special offset
| offset >= 0 && offset <= 3 = return ()
| outsideGotoRange offset = do
gotoWInstr special
writeBytes . packI32 $ offset
| otherwise = do
gotoInstr special
writeBytes . packI16 $ offset
returnInstr :: Opcode -> Instr
returnInstr opc = Instr $ do
recordBranch Return
op' opc
modifyStack' :: (Stack -> Stack) -> InstrM ()
modifyStack' f = ctrlFlow' $ CF.mapStack f
modifyStack :: (Stack -> Stack) -> Instr
modifyStack = Instr . modifyStack'
-- TODO:
-- Account for Instr & Instr being empty
-- Account for jumpoffset being > 2^15 - 1
gbranch :: (FieldType -> Stack -> Stack)
-> FieldType -> Opcode -> Instr -> Instr -> Instr
gbranch f ft oc ok ko = Instr $ do
[defaultLabel, okLabel] <- mkSystemLabels 2
jumpOffset <- offsetToLabel okLabel
lb <- saveLastBranch
unInstr ifop
InstrState { isCtrlFlow = cf
, isLabelTable = lt } <- get
writeBytes . packI16 $ jumpOffset
(koCF, koLT, mkoLB) <- withCFState cf lt $ unInstr $
ko <> condGoto Special defaultLabel
(okCF, okLT, mokLB) <- withCFState cf lt $ unInstr $
putLabel okLabel <> ok
putCtrlFlow' $ CF.merge cf [okCF, koCF]
mergeLabels [koLT, okLT]
unInstr $ putLabel defaultLabel
resetLastBranch $ fromMaybe lb (selectLatestLB mkoLB mokLB)
where ifop = op oc <> modifyStack (f ft)
bytes :: ByteString -> Instr
bytes = Instr . writeBytes
ix :: Const -> Instr
ix c = Instr $ do
cp <- ask
writeBytes . packI16 $ CP.ix $ CP.unsafeIndex "ix" c cp
op :: Opcode -> Instr
op = Instr . op'
op' :: Opcode -> InstrM ()
op' = writeBytes . BS.singleton . opcode
ctrlFlow' :: (CtrlFlow -> CtrlFlow) -> InstrM ()
ctrlFlow' f = modify' $ \s@InstrState { isCtrlFlow = cf } -> s { isCtrlFlow = f cf }
ctrlFlow :: (CtrlFlow -> CtrlFlow) -> Instr
ctrlFlow = Instr . ctrlFlow'
withStack :: ([VerifType] -> [VerifType]) -> Instr
withStack f = modifyStack (\s -> let stack' = f (stackVal s)
stackSize' = length stack'
in s { stackVal = stack'
, stackMax = max (stackMax s) stackSize'
, stackSize = stackSize' })
initCtrl :: (CtrlFlow -> CtrlFlow) -> Instr
initCtrl f = Instr $ do
unInstr $ ctrlFlow f
modify' $ \s@InstrState { isCtrlFlow = cf
, isStackMapTable = smt } ->
s { isStackMapTable = insertSMT (-1) cf smt }
-- NOTE: The (-1) is done as a special case for when a stack map frame has to
-- be generated for offset 0.
putCtrlFlow :: CtrlFlow -> Instr
putCtrlFlow = Instr . putCtrlFlow'
putCtrlFlow' :: CtrlFlow -> InstrM ()
putCtrlFlow' = ctrlFlow' . const
withCFState :: CtrlFlow -> LabelTable -> InstrM () -> InstrM (CtrlFlow, LabelTable, Maybe LastBranch)
withCFState cf lt instr = do
InstrState { isCtrlFlow = cf', isLabelTable = lt' } <- get
modify' $ \s -> s { isCtrlFlow = cf, isLabelTable = lt }
instr
s' <- get
modify' $ \s -> s { isCtrlFlow = cf', isLabelTable = lt' }
let mLastBranch
| ifLastBranch (isOffset s') lb = Just lb
| otherwise = Nothing
where lb = isLastBranch s'
return (isCtrlFlow s', isLabelTable s', mLastBranch)
incOffset :: Int -> Instr
incOffset = Instr . incOffset'
incOffset' :: Int -> InstrM ()
incOffset' i =
modify' $ \s@InstrState { isOffset = Offset off } ->
s { isOffset = Offset $ off + i}
write :: ByteString -> StackMapTable -> InstrM ()
write bs smfs = do
incOffset' $ BS.length bs
modify' $ \s@InstrState { isByteCode = bs'
, isStackMapTable = smfs' } ->
s { isByteCode = bs' <> bs
, isStackMapTable = smfs' <> smfs }
writeBytes :: ByteString -> InstrM ()
writeBytes bs = write bs mempty
markStackMapFrame :: Instr
markStackMapFrame = Instr writeStackMapFrame
writeStackMapFrame :: InstrM ()
writeStackMapFrame = do
modify' $ \s@InstrState { isOffset = Offset offset
, isCtrlFlow = cf
, isStackMapTable = smt } ->
s { isStackMapTable = insertSMT offset cf smt }
getOffset :: InstrM Int
getOffset = do
Offset offset <- gets isOffset
return offset
addExceptionHandler :: Label -> Label -> Label -> Maybe FieldType -> InstrM ()
addExceptionHandler start end handler mft = do
let f (Just (ObjectType (IClassName text))) = Just text
f _ = Nothing
modify' $ \s@InstrState { isExceptionTable = et } ->
s { isExceptionTable = insertIntoET start end handler (f mft) et }
type BranchMap = IntMap.IntMap Instr
toInt32AscList :: IntMap.IntMap a -> [(Int, a)]
toInt32AscList = sortBy (comparing ((fromIntegral :: Int -> Int32) . fst)) . IntMap.toAscList
tableswitch :: BranchMap -> Maybe Instr -> Instr
tableswitch = switches OP.tableswitch header
where header ~(defaultLabel:_:labels) branchMap relOffsetToLabel = do
debug $ liftIO $ print ("tableswitch", branchMap, low, high)
writeI32 low
writeI32 high
go labels [low..high]
where go ls@(l:ls') (x:xs)
| IntMap.member x branchMap = do
relOffsetToLabel l >>= writeI32
go ls' xs
| otherwise = do
relOffsetToLabel defaultLabel >>= writeI32
go ls xs
go _ _ = return ()
low = fst . IntMap.findMin $ branchMap
high = fst . IntMap.findMax $ branchMap
lookupswitch :: BranchMap -> Maybe Instr -> Instr
lookupswitch = switches OP.lookupswitch header
where header ~(_:_:labels) branchMap relOffsetToLabel = do
writeI32 (IntMap.size branchMap)
let keys = map fst $ toInt32AscList branchMap
forM_ (zip keys labels) $ \(int, l) -> do
writeI32 int
relOffsetToLabel l >>= writeI32
switches :: Opcode -> ([Label] -> BranchMap -> (Label -> InstrM Int) -> InstrM ())
-> BranchMap -> Maybe Instr -> Instr
switches opc f branchMap deflt = Instr $ do
baseOffset <- getOffset
lb <- saveLastBranch
unInstr $ op opc
modifyStack' $ CF.pop jint
InstrState { isOffset = offset
, isCtrlFlow = cf
, isLabelTable = lt } <- get
-- Align to 4-byte boundary
let padding = (4 - (offset `mod` 4)) `mod` 4
numBranches = IntMap.size branchMap
branchList = map snd $ toInt32AscList branchMap
writeBytes . BS.pack . replicate (fromIntegral padding) $ 0
ls@(defaultLabel:breakLabel:labels) <- mkSystemLabels (1 + 1 + numBranches)
let relOffsetToLabel = offsetToLabel' (Offset baseOffset)
relOffsetToLabel defaultLabel >>= writeI32
f ls branchMap relOffsetToLabel
let branches = (defaultLabel, fromMaybe mempty deflt)
: zip labels branchList
cfsAndLtsAndLbs <- forM branches $ \(l, i) ->
withCFState cf lt $ unInstr $
putLabel l <> i <> condGoto Special breakLabel
let (cfs, lts, mlbs) = unzip3 cfsAndLtsAndLbs
putCtrlFlow' $ CF.merge cf cfs
mergeLabels lts
unInstr $ putLabel breakLabel
resetLastBranch $ fromMaybe lb (selectLatestLBs mlbs)
lookupLabel :: Label -> InstrM Offset
lookupLabel l = do
InstrState { isLabelTable = lt } <- get
return $ lookupLT l lt
mergeLabels :: [LabelTable] -> InstrM ()
mergeLabels tables = do
debug $ do
InstrState { isLabelTable = table } <- get
liftIO $ print ("mergeLabels", map (`differenceLT` table) tables)
modify' $ \s@InstrState { isLabelTable = table
, isRunAgain = ra } ->
let diffTables = map (`differenceLT` table) tables
updates = any (\m -> sizeLT m > 0) diffTables
in s { isLabelTable = unionsLT (table : diffTables)
, isRunAgain = updateRunAgain ra updates }
gotoLabel :: Special -> Label -> Instr
gotoLabel special label = Instr $ offsetToLabel label >>= gotoInstrGen special
condGoto :: Special -> Label -> Instr
condGoto special l = Instr $ do
InstrState { isLastBranch, isOffset } <- get
unless (ifLastBranch isOffset isLastBranch) $
unInstr (gotoLabel special l)
putLabel' :: Label -> Instr
putLabel' l = Instr $ do
debug $ do
offset <- getOffset
liftIO $ print ("putLabel'", l, offset)
modify' $ \s@InstrState { isLabelTable = lt
, isRunAgain = ra
, isOffset = off } ->
s { isLabelTable = insertLT l off lt
, isRunAgain = updateRunAgain ra (isDifferentLT l off lt) }
putLabel :: Label -> Instr
putLabel l = Instr $ do
unInstr (putLabel' l)
writeStackMapFrame
offsetToLabel :: Label -> InstrM Int
offsetToLabel label = do
offset <- getOffset
offsetToLabel' (Offset offset) label
offsetToLabel' :: Offset -> Label -> InstrM Int
offsetToLabel' (Offset offset) label = do
Offset labelOffset <- lookupLabel label
debug $
liftIO $ print ("offsetToLabel'", label, labelOffset,
offset, labelOffset - offset)
return $ labelOffset - offset
ifLastBranch :: Offset -> LastBranch -> Bool
ifLastBranch _ NoBranch = False
ifLastBranch offset (HasBranch bt off) = off == (offset - branchSize bt)
selectLatestLB :: Maybe LastBranch -> Maybe LastBranch -> Maybe LastBranch
selectLatestLB (Just _) b@(Just _) = b
selectLatestLB _ _ = Nothing
selectLatestLBs :: [Maybe LastBranch] -> Maybe LastBranch
selectLatestLBs = foldl1 selectLatestLB
outsideGotoRange :: Int -> Bool
outsideGotoRange offset = offset > 32767 || offset < -32768
mkSystemLabels :: Int -> InstrM [Label]
mkSystemLabels n = do
s@InstrState { isNextLabel }<- get
put s { isNextLabel = isNextLabel + n }
return $ map (\x -> Label (- (isNextLabel + x))) [0..(n - 1)]
writeI16, writeI32 :: Int -> InstrM ()
writeI32 = writeBytes . packI32
writeI16 = writeBytes . packI16
-- For debugging purposes
whenClass :: String -> InstrM () -> InstrM ()
whenClass cls m = do
InstrState { isCtrlFlow } <- get
when (CF.getThis (CF.locals isCtrlFlow) == cls) m
debug :: InstrM () -> InstrM ()
debug = const (return ())
updateRunAgain :: Bool -> Bool -> Bool
updateRunAgain = (||)
toETEs :: ExceptionTable -> LabelTable -> [ExceptionTableEntry]
toETEs et lt =
map (\(start, end, handler, const) ->
ExceptionTableEntry { eteStartPc = unOffset $ lookupLT start lt
, eteEndPc = unOffset $ lookupLT end lt
, eteHandlerPc = unOffset $ lookupLT handler lt
, eteCatchType = fmap (CClass . IClassName) const })
$ toListET et
data ExceptionTableEntry
= ExceptionTableEntry { eteStartPc :: Int
, eteEndPc :: Int
, eteHandlerPc :: Int
, eteCatchType :: Maybe Const -- Must be CClass
}
tryFinally :: (Instr, Instr, Instr) -> Instr -> Instr -> Instr
tryFinally (storeCode, loadCode, throwCode) tryCode finallyCode = Instr $ do
[startLabel, endLabel, finallyLabel, defaultLabel] <- mkSystemLabels 4
lb <- saveLastBranch
InstrState { isCtrlFlow = cf
, isLabelTable = lt } <- get
(tryCF, tryLT, mtryLB) <- withCFState cf lt $ unInstr $
putLabel' startLabel
<> tryCode
<> putLabel' endLabel
<> finallyCode
<> condGoto Special defaultLabel
(finallyCF, finallyLT, mfinallyLB) <- withCFState cf lt $ unInstr $
ctrlFlow (CF.mapStack (CF.push jthrowable))
<> putLabel finallyLabel
<> storeCode
<> finallyCode
<> loadCode
<> throwCode
addExceptionHandler startLabel endLabel finallyLabel Nothing
putCtrlFlow' $ CF.merge cf [tryCF, finallyCF]
mergeLabels [tryLT, finallyLT]
unInstr $ putLabel defaultLabel
resetLastBranch $ fromMaybe lb (selectLatestLB mtryLB mfinallyLB)
synchronized :: (Instr, Instr, Instr, Instr, Instr) -> Instr -> Instr
synchronized (storeCode, loadCode, throwCode, monEnter, monExit) syncCode = Instr $ do
let tryCode = syncCode
finallyCode = monExit
[startLabel, endLabel, finallyLabel, finallyEndLabel, defaultLabel]
<- mkSystemLabels 5
lb <- saveLastBranch
unInstr $ monEnter
InstrState { isCtrlFlow = cf
, isLabelTable = lt } <- get
(tryCF, tryLT, mtryLB) <- withCFState cf lt $ unInstr $
putLabel' startLabel
<> tryCode
<> finallyCode
<> putLabel' endLabel
<> condGoto Special defaultLabel
(finallyCF, finallyLT, mfinallyLB) <- withCFState cf lt $ unInstr $
ctrlFlow (CF.mapStack (CF.push jthrowable))
<> putLabel finallyLabel
<> storeCode
<> finallyCode
<> putLabel' finallyEndLabel
<> loadCode
<> throwCode
addExceptionHandler startLabel endLabel finallyLabel Nothing
addExceptionHandler finallyLabel finallyEndLabel finallyLabel Nothing
putCtrlFlow' $ CF.merge cf [tryCF, finallyCF]
mergeLabels [tryLT, finallyLT]
unInstr $ putLabel defaultLabel
resetLastBranch $ fromMaybe lb (selectLatestLB mtryLB mfinallyLB)
throwable :: Text
throwable = "java/lang/Throwable"
jthrowable :: FieldType
jthrowable = T.obj throwable
| rahulmutt/codec-jvm | src/Codec/JVM/ASM/Code/Instr.hs | apache-2.0 | 19,326 | 0 | 21 | 4,868 | 6,254 | 3,263 | 2,991 | 457 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Prelude
import Data.Maybe (isNothing, catMaybes, fromMaybe)
import Text.Read (readMaybe)
import Haste.Ajax (ajaxRequest, Method(POST), noParams)
import FormEngine.JQuery (ready, errorIO)
import qualified Questionnaire
import FormEngine.FormData (FormData)
import FormEngine.FormElement.FormElement as Element
import Form (generateForm, renderSpinner)
import Overlay (initOverlay)
import qualified Actions
--import Debug.Trace
main :: IO ()
main = ready $ do
Actions.doExports
_ <- initOverlay
renderSpinner
ajaxRequest POST "api/plan/getData" noParams buildQuestionnaire
where
buildQuestionnaire :: Maybe String -> IO ()
buildQuestionnaire maybeDataString = do
let maybeFormData = readMaybe (fromMaybe "" maybeDataString) :: Maybe FormData
--let tabMaybes = map (Element.makeChapter $ traceShow maybeFormData maybeFormData) Questionnaire.formItems
let tabMaybes = map (Element.makeChapter maybeFormData) Questionnaire.formItems
if any isNothing tabMaybes then do
errorIO "Error generating tabs"
return ()
else do
let tabs = catMaybes tabMaybes
--generateForm (traceShow tabs tabs)
generateForm tabs
| DataStewardshipPortal/ds-wizard | src/Main.hs | apache-2.0 | 1,253 | 0 | 15 | 225 | 286 | 153 | 133 | 29 | 2 |
-- |
-- Module : Data.Packer.IEEE754
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
-- fully rewritten to use primops.
--
-- original implementation based on IEEE-754 parsing, lifted from the cereal package by Christian Marie <[email protected]>
-- Implementation is described here:
-- <http://stackoverflow.com/questions/6976684/converting-ieee-754-floating-point-in-haskell-word32-64-to-and-from-haskell-float/7002812#7002812>
--
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE BangPatterns #-}
module Data.Packer.IEEE754 (
wordToDouble
, wordToFloat
, doubleToWord
, floatToWord
) where
#if ! MIN_VERSION_base (4,11,0)
import Data.Word (Word32, Word64)
#endif
import GHC.Prim
import GHC.Float
import GHC.Word
import GHC.ST
wordToFloat :: Word32 -> Float
wordToFloat (W32# x) = runST $ ST $ \s1 ->
case newByteArray# 4# s1 of
(# s2, mbarr #) ->
let !s3 = writeWord32Array# mbarr 0# x s2
in case readFloatArray# mbarr 0# s3 of
(# s4, f #) -> (# s4, F# f #)
{-# INLINE wordToFloat #-}
floatToWord :: Float -> Word32
floatToWord (F# x) = runST $ ST $ \s1 ->
case newByteArray# 4# s1 of
(# s2, mbarr #) ->
let !s3 = writeFloatArray# mbarr 0# x s2
in case readWord32Array# mbarr 0# s3 of
(# s4, w #) -> (# s4, W32# w #)
{-# INLINE floatToWord #-}
wordToDouble :: Word64 -> Double
wordToDouble (W64# x) = runST $ ST $ \s1 ->
case newByteArray# 8# s1 of
(# s2, mbarr #) ->
let !s3 = writeWord64Array# mbarr 0# x s2
in case readDoubleArray# mbarr 0# s3 of
(# s4, f #) -> (# s4, D# f #)
{-# INLINE wordToDouble #-}
doubleToWord :: Double -> Word64
doubleToWord (D# x) = runST $ ST $ \s1 ->
case newByteArray# 8# s1 of
(# s2, mbarr #) ->
let !s3 = writeDoubleArray# mbarr 0# x s2
in case readWord64Array# mbarr 0# s3 of
(# s4, w #) -> (# s4, W64# w #)
{-# INLINE doubleToWord #-}
| erikd/hs-packer | Data/Packer/IEEE754.hs | bsd-2-clause | 2,197 | 0 | 17 | 586 | 511 | 270 | 241 | 47 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.