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 DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.ElastiCache.DeleteSnapshot -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | The /DeleteSnapshot/ action deletes an existing snapshot. When you receive a -- successful response from this action, ElastiCache immediately begins deleting -- the snapshot; you cannot cancel or revert this action. -- -- <http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DeleteSnapshot.html> module Network.AWS.ElastiCache.DeleteSnapshot ( -- * Request DeleteSnapshot -- ** Request constructor , deleteSnapshot -- ** Request lenses , ds1SnapshotName -- * Response , DeleteSnapshotResponse -- ** Response constructor , deleteSnapshotResponse -- ** Response lenses , dsrSnapshot ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.ElastiCache.Types import qualified GHC.Exts newtype DeleteSnapshot = DeleteSnapshot { _ds1SnapshotName :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'DeleteSnapshot' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ds1SnapshotName' @::@ 'Text' -- deleteSnapshot :: Text -- ^ 'ds1SnapshotName' -> DeleteSnapshot deleteSnapshot p1 = DeleteSnapshot { _ds1SnapshotName = p1 } -- | The name of the snapshot to be deleted. ds1SnapshotName :: Lens' DeleteSnapshot Text ds1SnapshotName = lens _ds1SnapshotName (\s a -> s { _ds1SnapshotName = a }) newtype DeleteSnapshotResponse = DeleteSnapshotResponse { _dsrSnapshot :: Maybe Snapshot } deriving (Eq, Read, Show) -- | 'DeleteSnapshotResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dsrSnapshot' @::@ 'Maybe' 'Snapshot' -- deleteSnapshotResponse :: DeleteSnapshotResponse deleteSnapshotResponse = DeleteSnapshotResponse { _dsrSnapshot = Nothing } dsrSnapshot :: Lens' DeleteSnapshotResponse (Maybe Snapshot) dsrSnapshot = lens _dsrSnapshot (\s a -> s { _dsrSnapshot = a }) instance ToPath DeleteSnapshot where toPath = const "/" instance ToQuery DeleteSnapshot where toQuery DeleteSnapshot{..} = mconcat [ "SnapshotName" =? _ds1SnapshotName ] instance ToHeaders DeleteSnapshot instance AWSRequest DeleteSnapshot where type Sv DeleteSnapshot = ElastiCache type Rs DeleteSnapshot = DeleteSnapshotResponse request = post "DeleteSnapshot" response = xmlResponse instance FromXML DeleteSnapshotResponse where parseXML = withElement "DeleteSnapshotResult" $ \x -> DeleteSnapshotResponse <$> x .@? "Snapshot"
romanb/amazonka
amazonka-elasticache/gen/Network/AWS/ElastiCache/DeleteSnapshot.hs
mpl-2.0
3,543
0
9
748
423
259
164
53
1
module Test.Utils where import Test.HUnit import HN.Intermediate import Debug.Trace xtrace a b = trace (a ++ " = " ++ show b) b ci int = Constant $ ConstInt int sv name int = Definition name [] $ In $ ci int st testName expected actual = testName ~: expected ~=? actual stt t2f = map (\(n, e, def) -> n ~: e ~=? t2f def)
kayuri/HNC
Test/Utils.hs
lgpl-3.0
325
0
9
70
152
78
74
9
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GHCForeignImportPrim #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE UnliftedFFITypes #-} {-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE NegativeLiterals #-} {-# LANGUAGE ExplicitForAll #-} -- | -- Module : GHC.Integer.Type -- Copyright : (c) Herbert Valerio Riedel 2014 -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : non-portable (GHC Extensions) -- -- GHC needs this module to be named "GHC.Integer.Type" and provide -- all the low-level 'Integer' operations. module GHC.Integer.Type where #include "MachDeps.h" -- Sanity check as CPP defines are implicitly 0-valued when undefined #if !(defined(SIZEOF_LONG) && defined(SIZEOF_HSWORD) \ && defined(WORD_SIZE_IN_BITS)) # error missing defines #endif import GHC.Classes import GHC.Magic import GHC.Prim import GHC.Types #if WORD_SIZE_IN_BITS < 64 import GHC.IntWord64 #endif default () -- Most high-level operations need to be marked `NOINLINE` as -- otherwise GHC doesn't recognize them and fails to apply constant -- folding to `Integer`-typed expression. -- -- To this end, the CPP hack below allows to write the pseudo-pragma -- -- {-# CONSTANT_FOLDED plusInteger #-} -- -- which is simply expaned into a -- -- {-# NOINLINE plusInteger #-} -- #define CONSTANT_FOLDED NOINLINE ---------------------------------------------------------------------------- -- type definitions -- NB: all code assumes GMP_LIMB_BITS == WORD_SIZE_IN_BITS -- The C99 code in cbits/wrappers.c will fail to compile if this doesn't hold -- | Type representing a GMP Limb type GmpLimb = Word -- actually, 'CULong' type GmpLimb# = Word# -- | Count of 'GmpLimb's, must be positive (unless specified otherwise). type GmpSize = Int -- actually, a 'CLong' type GmpSize# = Int# narrowGmpSize# :: Int# -> Int# #if SIZEOF_LONG == SIZEOF_HSWORD narrowGmpSize# x = x #elif (SIZEOF_LONG == 4) && (SIZEOF_HSWORD == 8) -- On IL32P64 (i.e. Win64), we have to be careful with CLong not being -- 64bit. This is mostly an issue on values returned from C functions -- due to sign-extension. narrowGmpSize# = narrow32Int# #endif type GmpBitCnt = Word -- actually, 'CULong' type GmpBitCnt# = Word# -- actually, 'CULong' -- Pseudo FFI CType type CInt = Int type CInt# = Int# narrowCInt# :: Int# -> Int# narrowCInt# = narrow32Int# -- | Bits in a 'GmpLimb'. Same as @WORD_SIZE_IN_BITS@. gmpLimbBits :: Word -- 8 `shiftL` gmpLimbShift gmpLimbBits = W# WORD_SIZE_IN_BITS## #if WORD_SIZE_IN_BITS == 64 # define GMP_LIMB_SHIFT 3 # define GMP_LIMB_BYTES 8 # define GMP_LIMB_BITS 64 # define INT_MINBOUND -0x8000000000000000 # define INT_MAXBOUND 0x7fffffffffffffff # define ABS_INT_MINBOUND 0x8000000000000000 # define SQRT_INT_MAXBOUND 0xb504f333 #elif WORD_SIZE_IN_BITS == 32 # define GMP_LIMB_SHIFT 2 # define GMP_LIMB_BYTES 4 # define GMP_LIMB_BITS 32 # define INT_MINBOUND -0x80000000 # define INT_MAXBOUND 0x7fffffff # define ABS_INT_MINBOUND 0x80000000 # define SQRT_INT_MAXBOUND 0xb504 #else # error unsupported WORD_SIZE_IN_BITS config #endif -- | Type representing /raw/ arbitrary-precision Naturals -- -- This is common type used by 'Natural' and 'Integer'. As this type -- consists of a single constructor wrapping a 'ByteArray#' it can be -- unpacked. -- -- Essential invariants: -- -- - 'ByteArray#' size is an exact multiple of 'Word#' size -- - limbs are stored in least-significant-limb-first order, -- - the most-significant limb must be non-zero, except for -- - @0@ which is represented as a 1-limb. data BigNat = BN# ByteArray# instance Eq BigNat where (==) = eqBigNat instance Ord BigNat where compare = compareBigNat -- | Invariant: 'Jn#' and 'Jp#' are used iff value doesn't fit in 'S#' -- -- Useful properties resulting from the invariants: -- -- - @abs ('S#' _) <= abs ('Jp#' _)@ -- - @abs ('S#' _) < abs ('Jn#' _)@ -- data Integer = S# !Int# -- ^ iff value in @[minBound::'Int', maxBound::'Int']@ range | Jp# {-# UNPACK #-} !BigNat -- ^ iff value in @]maxBound::'Int', +inf[@ range | Jn# {-# UNPACK #-} !BigNat -- ^ iff value in @]-inf, minBound::'Int'[@ range -- TODO: experiment with different constructor-ordering instance Eq Integer where (==) = eqInteger (/=) = neqInteger instance Ord Integer where compare = compareInteger (>) = gtInteger (>=) = geInteger (<) = ltInteger (<=) = leInteger ---------------------------------------------------------------------------- -- | Construct 'Integer' value from list of 'Int's. -- -- This function is used by GHC for constructing 'Integer' literals. mkInteger :: Bool -- ^ sign of integer ('True' if non-negative) -> [Int] -- ^ absolute value expressed in 31 bit chunks, least -- significant first (ideally these would be machine-word -- 'Word's rather than 31-bit truncated 'Int's) -> Integer mkInteger nonNegative is | nonNegative = f is | True = negateInteger (f is) where f [] = S# 0# f (I# i : is') = smallInteger (i `andI#` 0x7fffffff#) `orInteger` shiftLInteger (f is') 31# {-# CONSTANT_FOLDED mkInteger #-} -- | Test whether all internal invariants are satisfied by 'Integer' value -- -- Returns @1#@ if valid, @0#@ otherwise. -- -- This operation is mostly useful for test-suites and/or code which -- constructs 'Integer' values directly. isValidInteger# :: Integer -> Int# isValidInteger# (S# _) = 1# isValidInteger# (Jp# bn) = isValidBigNat# bn `andI#` (bn `gtBigNatWord#` INT_MAXBOUND##) isValidInteger# (Jn# bn) = isValidBigNat# bn `andI#` (bn `gtBigNatWord#` ABS_INT_MINBOUND##) -- | Should rather be called @intToInteger@ smallInteger :: Int# -> Integer smallInteger i# = S# i# {-# CONSTANT_FOLDED smallInteger #-} ---------------------------------------------------------------------------- -- Int64/Word64 specific primitives #if WORD_SIZE_IN_BITS < 64 int64ToInteger :: Int64# -> Integer int64ToInteger i | isTrue# (i `leInt64#` intToInt64# 0x7FFFFFFF#) , isTrue# (i `geInt64#` intToInt64# -0x80000000#) = S# (int64ToInt# i) | isTrue# (i `geInt64#` intToInt64# 0#) = Jp# (word64ToBigNat (int64ToWord64# i)) | True = Jn# (word64ToBigNat (int64ToWord64# (negateInt64# i))) {-# CONSTANT_FOLDED int64ToInteger #-} word64ToInteger :: Word64# -> Integer word64ToInteger w | isTrue# (w `leWord64#` wordToWord64# 0x7FFFFFFF##) = S# (int64ToInt# (word64ToInt64# w)) | True = Jp# (word64ToBigNat w) {-# CONSTANT_FOLDED word64ToInteger #-} integerToInt64 :: Integer -> Int64# integerToInt64 (S# i#) = intToInt64# i# integerToInt64 (Jp# bn) = word64ToInt64# (bigNatToWord64 bn) integerToInt64 (Jn# bn) = negateInt64# (word64ToInt64# (bigNatToWord64 bn)) {-# CONSTANT_FOLDED integerToInt64 #-} integerToWord64 :: Integer -> Word64# integerToWord64 (S# i#) = int64ToWord64# (intToInt64# i#) integerToWord64 (Jp# bn) = bigNatToWord64 bn integerToWord64 (Jn# bn) = int64ToWord64# (negateInt64# (word64ToInt64# (bigNatToWord64 bn))) {-# CONSTANT_FOLDED integerToWord64 #-} #if GMP_LIMB_BITS == 32 word64ToBigNat :: Word64# -> BigNat word64ToBigNat w64 = wordToBigNat2 wh# wl# where wh# = word64ToWord# (uncheckedShiftRL64# w64 32#) wl# = word64ToWord# w64 bigNatToWord64 :: BigNat -> Word64# bigNatToWord64 bn | isTrue# (sizeofBigNat# bn ># 1#) = let wh# = wordToWord64# (indexBigNat# bn 1#) in uncheckedShiftL64# wh# 32# `or64#` wl# | True = wl# where wl# = wordToWord64# (bigNatToWord bn) #endif #endif -- End of Int64/Word64 specific primitives ---------------------------------------------------------------------------- -- | Truncates 'Integer' to least-significant 'Int#' integerToInt :: Integer -> Int# integerToInt (S# i#) = i# integerToInt (Jp# bn) = bigNatToInt bn integerToInt (Jn# bn) = negateInt# (bigNatToInt bn) {-# CONSTANT_FOLDED integerToInt #-} hashInteger :: Integer -> Int# hashInteger = integerToInt -- emulating what integer-{simple,gmp} already do integerToWord :: Integer -> Word# integerToWord (S# i#) = int2Word# i# integerToWord (Jp# bn) = bigNatToWord bn integerToWord (Jn# bn) = int2Word# (negateInt# (bigNatToInt bn)) {-# CONSTANT_FOLDED integerToWord #-} wordToInteger :: Word# -> Integer wordToInteger w# | isTrue# (i# >=# 0#) = S# i# | True = Jp# (wordToBigNat w#) where i# = word2Int# w# {-# CONSTANT_FOLDED wordToInteger #-} wordToNegInteger :: Word# -> Integer wordToNegInteger w# | isTrue# (i# <=# 0#) = S# i# | True = Jn# (wordToBigNat w#) where i# = negateInt# (word2Int# w#) -- we could almost auto-derive Ord if it wasn't for the Jn#-Jn# case compareInteger :: Integer -> Integer -> Ordering compareInteger (Jn# x) (Jn# y) = compareBigNat y x compareInteger (S# x) (S# y) = compareInt# x y compareInteger (Jp# x) (Jp# y) = compareBigNat x y compareInteger (Jn# _) _ = LT compareInteger (S# _) (Jp# _) = LT compareInteger (S# _) (Jn# _) = GT compareInteger (Jp# _) _ = GT {-# CONSTANT_FOLDED compareInteger #-} isNegInteger# :: Integer -> Int# isNegInteger# (S# i#) = i# <# 0# isNegInteger# (Jp# _) = 0# isNegInteger# (Jn# _) = 1# -- | Not-equal predicate. neqInteger :: Integer -> Integer -> Bool neqInteger x y = isTrue# (neqInteger# x y) eqInteger, leInteger, ltInteger, gtInteger, geInteger :: Integer -> Integer -> Bool eqInteger x y = isTrue# (eqInteger# x y) leInteger x y = isTrue# (leInteger# x y) ltInteger x y = isTrue# (ltInteger# x y) gtInteger x y = isTrue# (gtInteger# x y) geInteger x y = isTrue# (geInteger# x y) eqInteger#, neqInteger#, leInteger#, ltInteger#, gtInteger#, geInteger# :: Integer -> Integer -> Int# eqInteger# (S# x#) (S# y#) = x# ==# y# eqInteger# (Jn# x) (Jn# y) = eqBigNat# x y eqInteger# (Jp# x) (Jp# y) = eqBigNat# x y eqInteger# _ _ = 0# {-# CONSTANT_FOLDED eqInteger# #-} neqInteger# (S# x#) (S# y#) = x# /=# y# neqInteger# (Jn# x) (Jn# y) = neqBigNat# x y neqInteger# (Jp# x) (Jp# y) = neqBigNat# x y neqInteger# _ _ = 1# {-# CONSTANT_FOLDED neqInteger# #-} gtInteger# (S# x#) (S# y#) = x# ># y# gtInteger# x y | inline compareInteger x y == GT = 1# gtInteger# _ _ = 0# {-# CONSTANT_FOLDED gtInteger# #-} leInteger# (S# x#) (S# y#) = x# <=# y# leInteger# x y | inline compareInteger x y /= GT = 1# leInteger# _ _ = 0# {-# CONSTANT_FOLDED leInteger# #-} ltInteger# (S# x#) (S# y#) = x# <# y# ltInteger# x y | inline compareInteger x y == LT = 1# ltInteger# _ _ = 0# {-# CONSTANT_FOLDED ltInteger# #-} geInteger# (S# x#) (S# y#) = x# >=# y# geInteger# x y | inline compareInteger x y /= LT = 1# geInteger# _ _ = 0# {-# CONSTANT_FOLDED geInteger# #-} -- | Compute absolute value of an 'Integer' absInteger :: Integer -> Integer absInteger (Jn# n) = Jp# n absInteger (S# INT_MINBOUND#) = Jp# (wordToBigNat ABS_INT_MINBOUND##) absInteger (S# i#) | isTrue# (i# <# 0#) = S# (negateInt# i#) absInteger i@(S# _) = i absInteger i@(Jp# _) = i {-# CONSTANT_FOLDED absInteger #-} -- | Return @-1@, @0@, and @1@ depending on whether argument is -- negative, zero, or positive, respectively signumInteger :: Integer -> Integer signumInteger j = S# (signumInteger# j) {-# CONSTANT_FOLDED signumInteger #-} -- | Return @-1#@, @0#@, and @1#@ depending on whether argument is -- negative, zero, or positive, respectively signumInteger# :: Integer -> Int# signumInteger# (Jn# _) = -1# signumInteger# (S# i#) = sgnI# i# signumInteger# (Jp# _ ) = 1# -- | Negate 'Integer' negateInteger :: Integer -> Integer negateInteger (Jn# n) = Jp# n negateInteger (S# INT_MINBOUND#) = Jp# (wordToBigNat ABS_INT_MINBOUND##) negateInteger (S# i#) = S# (negateInt# i#) negateInteger (Jp# bn) | isTrue# (eqBigNatWord# bn ABS_INT_MINBOUND##) = S# INT_MINBOUND# | True = Jn# bn {-# CONSTANT_FOLDED negateInteger #-} -- one edge-case issue to take into account is that Int's range is not -- symmetric around 0. I.e. @minBound+maxBound = -1@ -- -- Jp# is used iff n > maxBound::Int -- Jn# is used iff n < minBound::Int -- | Add two 'Integer's plusInteger :: Integer -> Integer -> Integer plusInteger x (S# 0#) = x plusInteger (S# 0#) y = y plusInteger (S# x#) (S# y#) = case addIntC# x# y# of (# z#, 0# #) -> S# z# (# 0#, _ #) -> Jn# (wordToBigNat2 1## 0##) -- 2*minBound::Int (# z#, _ #) | isTrue# (z# ># 0#) -> Jn# (wordToBigNat ( (int2Word# (negateInt# z#)))) | True -> Jp# (wordToBigNat ( (int2Word# z#))) plusInteger y@(S# _) x = plusInteger x y -- no S# as first arg from here on plusInteger (Jp# x) (Jp# y) = Jp# (plusBigNat x y) plusInteger (Jn# x) (Jn# y) = Jn# (plusBigNat x y) plusInteger (Jp# x) (S# y#) -- edge-case: @(maxBound+1) + minBound == 0@ | isTrue# (y# >=# 0#) = Jp# (plusBigNatWord x (int2Word# y#)) | True = bigNatToInteger (minusBigNatWord x (int2Word# (negateInt# y#))) plusInteger (Jn# x) (S# y#) -- edge-case: @(minBound-1) + maxBound == -2@ | isTrue# (y# >=# 0#) = bigNatToNegInteger (minusBigNatWord x (int2Word# y#)) | True = Jn# (plusBigNatWord x (int2Word# (negateInt# y#))) plusInteger y@(Jn# _) x@(Jp# _) = plusInteger x y plusInteger (Jp# x) (Jn# y) = case compareBigNat x y of LT -> bigNatToNegInteger (minusBigNat y x) EQ -> S# 0# GT -> bigNatToInteger (minusBigNat x y) {-# CONSTANT_FOLDED plusInteger #-} -- | Subtract one 'Integer' from another. minusInteger :: Integer -> Integer -> Integer minusInteger x (S# 0#) = x minusInteger (S# 0#) (S# INT_MINBOUND#) = Jp# (wordToBigNat ABS_INT_MINBOUND##) minusInteger (S# 0#) (S# y#) = S# (negateInt# y#) minusInteger (S# x#) (S# y#) = case subIntC# x# y# of (# z#, 0# #) -> S# z# (# 0#, _ #) -> Jn# (wordToBigNat2 1## 0##) (# z#, _ #) | isTrue# (z# ># 0#) -> Jn# (wordToBigNat ( (int2Word# (negateInt# z#)))) | True -> Jp# (wordToBigNat ( (int2Word# z#))) minusInteger (S# x#) (Jp# y) | isTrue# (x# >=# 0#) = bigNatToNegInteger (minusBigNatWord y (int2Word# x#)) | True = Jn# (plusBigNatWord y (int2Word# (negateInt# x#))) minusInteger (S# x#) (Jn# y) | isTrue# (x# >=# 0#) = Jp# (plusBigNatWord y (int2Word# x#)) | True = bigNatToInteger (minusBigNatWord y (int2Word# (negateInt# x#))) minusInteger (Jp# x) (Jp# y) = case compareBigNat x y of LT -> bigNatToNegInteger (minusBigNat y x) EQ -> S# 0# GT -> bigNatToInteger (minusBigNat x y) minusInteger (Jp# x) (Jn# y) = Jp# (plusBigNat x y) minusInteger (Jn# x) (Jp# y) = Jn# (plusBigNat x y) minusInteger (Jn# x) (Jn# y) = case compareBigNat x y of LT -> bigNatToInteger (minusBigNat y x) EQ -> S# 0# GT -> bigNatToNegInteger (minusBigNat x y) minusInteger (Jp# x) (S# y#) | isTrue# (y# >=# 0#) = bigNatToInteger (minusBigNatWord x (int2Word# y#)) | True = Jp# (plusBigNatWord x (int2Word# (negateInt# y#))) minusInteger (Jn# x) (S# y#) | isTrue# (y# >=# 0#) = Jn# (plusBigNatWord x (int2Word# y#)) | True = bigNatToNegInteger (minusBigNatWord x (int2Word# (negateInt# y#))) {-# CONSTANT_FOLDED minusInteger #-} -- | Multiply two 'Integer's timesInteger :: Integer -> Integer -> Integer timesInteger !_ (S# 0#) = S# 0# timesInteger (S# 0#) _ = S# 0# timesInteger x (S# 1#) = x timesInteger (S# 1#) y = y timesInteger x (S# -1#) = negateInteger x timesInteger (S# -1#) y = negateInteger y timesInteger (S# x#) (S# y#) = case mulIntMayOflo# x# y# of 0# -> S# (x# *# y#) _ -> timesInt2Integer x# y# timesInteger x@(S# _) y = timesInteger y x -- no S# as first arg from here on timesInteger (Jp# x) (Jp# y) = Jp# (timesBigNat x y) timesInteger (Jp# x) (Jn# y) = Jn# (timesBigNat x y) timesInteger (Jp# x) (S# y#) | isTrue# (y# >=# 0#) = Jp# (timesBigNatWord x (int2Word# y#)) | True = Jn# (timesBigNatWord x (int2Word# (negateInt# y#))) timesInteger (Jn# x) (Jn# y) = Jp# (timesBigNat x y) timesInteger (Jn# x) (Jp# y) = Jn# (timesBigNat x y) timesInteger (Jn# x) (S# y#) | isTrue# (y# >=# 0#) = Jn# (timesBigNatWord x (int2Word# y#)) | True = Jp# (timesBigNatWord x (int2Word# (negateInt# y#))) {-# CONSTANT_FOLDED timesInteger #-} -- | Square 'Integer' sqrInteger :: Integer -> Integer sqrInteger (S# INT_MINBOUND#) = timesInt2Integer INT_MINBOUND# INT_MINBOUND# sqrInteger (S# j#) | isTrue# (absI# j# <=# SQRT_INT_MAXBOUND#) = S# (j# *# j#) sqrInteger (S# j#) = timesInt2Integer j# j# sqrInteger (Jp# bn) = Jp# (sqrBigNat bn) sqrInteger (Jn# bn) = Jp# (sqrBigNat bn) -- | Construct 'Integer' from the product of two 'Int#'s timesInt2Integer :: Int# -> Int# -> Integer timesInt2Integer x# y# = case (# isTrue# (x# >=# 0#), isTrue# (y# >=# 0#) #) of (# False, False #) -> case timesWord2# (int2Word# (negateInt# x#)) (int2Word# (negateInt# y#)) of (# 0##,l #) -> inline wordToInteger l (# h ,l #) -> Jp# (wordToBigNat2 h l) (# True, False #) -> case timesWord2# (int2Word# x#) (int2Word# (negateInt# y#)) of (# 0##,l #) -> wordToNegInteger l (# h ,l #) -> Jn# (wordToBigNat2 h l) (# False, True #) -> case timesWord2# (int2Word# (negateInt# x#)) (int2Word# y#) of (# 0##,l #) -> wordToNegInteger l (# h ,l #) -> Jn# (wordToBigNat2 h l) (# True, True #) -> case timesWord2# (int2Word# x#) (int2Word# y#) of (# 0##,l #) -> inline wordToInteger l (# h ,l #) -> Jp# (wordToBigNat2 h l) bigNatToInteger :: BigNat -> Integer bigNatToInteger bn | isTrue# ((sizeofBigNat# bn ==# 1#) `andI#` (i# >=# 0#)) = S# i# | True = Jp# bn where i# = word2Int# (bigNatToWord bn) bigNatToNegInteger :: BigNat -> Integer bigNatToNegInteger bn | isTrue# ((sizeofBigNat# bn ==# 1#) `andI#` (i# <=# 0#)) = S# i# | True = Jn# bn where i# = negateInt# (word2Int# (bigNatToWord bn)) -- | Count number of set bits. For negative arguments returns negative -- population count of negated argument. popCountInteger :: Integer -> Int# popCountInteger (S# i#) | isTrue# (i# >=# 0#) = popCntI# i# | True = negateInt# (popCntI# (negateInt# i#)) popCountInteger (Jp# bn) = popCountBigNat bn popCountInteger (Jn# bn) = negateInt# (popCountBigNat bn) {-# CONSTANT_FOLDED popCountInteger #-} -- | 'Integer' for which only /n/-th bit is set. Undefined behaviour -- for negative /n/ values. bitInteger :: Int# -> Integer bitInteger i# | isTrue# (i# <# (GMP_LIMB_BITS# -# 1#)) = S# (uncheckedIShiftL# 1# i#) | True = Jp# (bitBigNat i#) {-# CONSTANT_FOLDED bitInteger #-} -- | Test if /n/-th bit is set. testBitInteger :: Integer -> Int# -> Bool testBitInteger !_ n# | isTrue# (n# <# 0#) = False testBitInteger (S# i#) n# | isTrue# (n# <# GMP_LIMB_BITS#) = isTrue# (((uncheckedIShiftL# 1# n#) `andI#` i#) /=# 0#) | True = isTrue# (i# <# 0#) testBitInteger (Jp# bn) n = testBitBigNat bn n testBitInteger (Jn# bn) n = testBitNegBigNat bn n {-# CONSTANT_FOLDED testBitInteger #-} -- | Bitwise @NOT@ operation complementInteger :: Integer -> Integer complementInteger (S# i#) = S# (notI# i#) complementInteger (Jp# bn) = Jn# (plusBigNatWord bn 1##) complementInteger (Jn# bn) = Jp# (minusBigNatWord bn 1##) {-# CONSTANT_FOLDED complementInteger #-} -- | Arithmetic shift-right operation -- -- Even though the shift-amount is expressed as `Int#`, the result is -- undefined for negative shift-amounts. shiftRInteger :: Integer -> Int# -> Integer shiftRInteger x 0# = x shiftRInteger (S# i#) n# = S# (iShiftRA# i# n#) where iShiftRA# a b | isTrue# (b >=# WORD_SIZE_IN_BITS#) = (a <# 0#) *# (-1#) | True = a `uncheckedIShiftRA#` b shiftRInteger (Jp# bn) n# = bigNatToInteger (shiftRBigNat bn n#) shiftRInteger (Jn# bn) n# = case bigNatToNegInteger (shiftRNegBigNat bn n#) of S# 0# -> S# -1# r -> r {-# CONSTANT_FOLDED shiftRInteger #-} -- | Shift-left operation -- -- Even though the shift-amount is expressed as `Int#`, the result is -- undefined for negative shift-amounts. shiftLInteger :: Integer -> Int# -> Integer shiftLInteger x 0# = x shiftLInteger (S# 0#) _ = S# 0# shiftLInteger (S# 1#) n# = bitInteger n# shiftLInteger (S# i#) n# | isTrue# (i# >=# 0#) = bigNatToInteger (shiftLBigNat (wordToBigNat (int2Word# i#)) n#) | True = bigNatToNegInteger (shiftLBigNat (wordToBigNat (int2Word# (negateInt# i#))) n#) shiftLInteger (Jp# bn) n# = Jp# (shiftLBigNat bn n#) shiftLInteger (Jn# bn) n# = Jn# (shiftLBigNat bn n#) {-# CONSTANT_FOLDED shiftLInteger #-} -- | Bitwise OR operation orInteger :: Integer -> Integer -> Integer -- short-cuts orInteger (S# 0#) y = y orInteger x (S# 0#) = x orInteger (S# -1#) _ = S# -1# orInteger _ (S# -1#) = S# -1# -- base-cases orInteger (S# x#) (S# y#) = S# (orI# x# y#) orInteger (Jp# x) (Jp# y) = Jp# (orBigNat x y) orInteger (Jn# x) (Jn# y) = bigNatToNegInteger (plusBigNatWord (andBigNat (minusBigNatWord x 1##) (minusBigNatWord y 1##)) 1##) orInteger x@(Jn# _) y@(Jp# _) = orInteger y x -- retry with swapped args orInteger (Jp# x) (Jn# y) = bigNatToNegInteger (plusBigNatWord (andnBigNat (minusBigNatWord y 1##) x) 1##) -- TODO/FIXpromotion-hack orInteger x@(S# _) y = orInteger (unsafePromote x) y orInteger x y {- S# -}= orInteger x (unsafePromote y) {-# CONSTANT_FOLDED orInteger #-} -- | Bitwise XOR operation xorInteger :: Integer -> Integer -> Integer -- short-cuts xorInteger (S# 0#) y = y xorInteger x (S# 0#) = x -- TODO: (S# -1) cases -- base-cases xorInteger (S# x#) (S# y#) = S# (xorI# x# y#) xorInteger (Jp# x) (Jp# y) = bigNatToInteger (xorBigNat x y) xorInteger (Jn# x) (Jn# y) = bigNatToInteger (xorBigNat (minusBigNatWord x 1##) (minusBigNatWord y 1##)) xorInteger x@(Jn# _) y@(Jp# _) = xorInteger y x -- retry with swapped args xorInteger (Jp# x) (Jn# y) = bigNatToNegInteger (plusBigNatWord (xorBigNat x (minusBigNatWord y 1##)) 1##) -- TODO/FIXME promotion-hack xorInteger x@(S# _) y = xorInteger (unsafePromote x) y xorInteger x y {- S# -} = xorInteger x (unsafePromote y) {-# CONSTANT_FOLDED xorInteger #-} -- | Bitwise AND operation andInteger :: Integer -> Integer -> Integer -- short-cuts andInteger (S# 0#) !_ = S# 0# andInteger _ (S# 0#) = S# 0# andInteger (S# -1#) y = y andInteger x (S# -1#) = x -- base-cases andInteger (S# x#) (S# y#) = S# (andI# x# y#) andInteger (Jp# x) (Jp# y) = bigNatToInteger (andBigNat x y) andInteger (Jn# x) (Jn# y) = bigNatToNegInteger (plusBigNatWord (orBigNat (minusBigNatWord x 1##) (minusBigNatWord y 1##)) 1##) andInteger x@(Jn# _) y@(Jp# _) = andInteger y x andInteger (Jp# x) (Jn# y) = bigNatToInteger (andnBigNat x (minusBigNatWord y 1##)) -- TODO/FIXME promotion-hack andInteger x@(S# _) y = andInteger (unsafePromote x) y andInteger x y {- S# -}= andInteger x (unsafePromote y) {-# CONSTANT_FOLDED andInteger #-} -- HACK warning! breaks invariant on purpose unsafePromote :: Integer -> Integer unsafePromote (S# x#) | isTrue# (x# >=# 0#) = Jp# (wordToBigNat (int2Word# x#)) | True = Jn# (wordToBigNat (int2Word# (negateInt# x#))) unsafePromote x = x -- | Simultaneous 'quotInteger' and 'remInteger'. -- -- Divisor must be non-zero otherwise the GHC runtime will terminate -- with a division-by-zero fault. quotRemInteger :: Integer -> Integer -> (# Integer, Integer #) quotRemInteger n (S# 1#) = (# n, S# 0# #) quotRemInteger n (S# -1#) = let !q = negateInteger n in (# q, (S# 0#) #) quotRemInteger !_ (S# 0#) = (# S# (quotInt# 0# 0#),S# (remInt# 0# 0#) #) quotRemInteger (S# 0#) _ = (# S# 0#, S# 0# #) quotRemInteger (S# n#) (S# d#) = case quotRemInt# n# d# of (# q#, r# #) -> (# S# q#, S# r# #) quotRemInteger (Jp# n) (Jp# d) = case quotRemBigNat n d of (# q, r #) -> (# bigNatToInteger q, bigNatToInteger r #) quotRemInteger (Jp# n) (Jn# d) = case quotRemBigNat n d of (# q, r #) -> (# bigNatToNegInteger q, bigNatToInteger r #) quotRemInteger (Jn# n) (Jn# d) = case quotRemBigNat n d of (# q, r #) -> (# bigNatToInteger q, bigNatToNegInteger r #) quotRemInteger (Jn# n) (Jp# d) = case quotRemBigNat n d of (# q, r #) -> (# bigNatToNegInteger q, bigNatToNegInteger r #) quotRemInteger (Jp# n) (S# d#) | isTrue# (d# >=# 0#) = case quotRemBigNatWord n (int2Word# d#) of (# q, r# #) -> (# bigNatToInteger q, inline wordToInteger r# #) | True = case quotRemBigNatWord n (int2Word# (negateInt# d#)) of (# q, r# #) -> (# bigNatToNegInteger q, inline wordToInteger r# #) quotRemInteger (Jn# n) (S# d#) | isTrue# (d# >=# 0#) = case quotRemBigNatWord n (int2Word# d#) of (# q, r# #) -> (# bigNatToNegInteger q, wordToNegInteger r# #) | True = case quotRemBigNatWord n (int2Word# (negateInt# d#)) of (# q, r# #) -> (# bigNatToInteger q, wordToNegInteger r# #) quotRemInteger n@(S# _) (Jn# _) = (# S# 0#, n #) -- since @n < d@ quotRemInteger n@(S# n#) (Jp# d) -- need to account for (S# minBound) | isTrue# (n# ># 0#) = (# S# 0#, n #) | isTrue# (gtBigNatWord# d (int2Word# (negateInt# n#))) = (# S# 0#, n #) | True {- abs(n) == d -} = (# S# -1#, S# 0# #) {-# CONSTANT_FOLDED quotRemInteger #-} quotInteger :: Integer -> Integer -> Integer quotInteger n (S# 1#) = n quotInteger n (S# -1#) = negateInteger n quotInteger !_ (S# 0#) = S# (quotInt# 0# 0#) quotInteger (S# 0#) _ = S# 0# quotInteger (S# n#) (S# d#) = S# (quotInt# n# d#) quotInteger (Jp# n) (S# d#) | isTrue# (d# >=# 0#) = bigNatToInteger (quotBigNatWord n (int2Word# d#)) | True = bigNatToNegInteger (quotBigNatWord n (int2Word# (negateInt# d#))) quotInteger (Jn# n) (S# d#) | isTrue# (d# >=# 0#) = bigNatToNegInteger (quotBigNatWord n (int2Word# d#)) | True = bigNatToInteger (quotBigNatWord n (int2Word# (negateInt# d#))) quotInteger (Jp# n) (Jp# d) = bigNatToInteger (quotBigNat n d) quotInteger (Jp# n) (Jn# d) = bigNatToNegInteger (quotBigNat n d) quotInteger (Jn# n) (Jp# d) = bigNatToNegInteger (quotBigNat n d) quotInteger (Jn# n) (Jn# d) = bigNatToInteger (quotBigNat n d) -- handle remaining non-allocating cases quotInteger n d = case inline quotRemInteger n d of (# q, _ #) -> q {-# CONSTANT_FOLDED quotInteger #-} remInteger :: Integer -> Integer -> Integer remInteger !_ (S# 1#) = S# 0# remInteger _ (S# -1#) = S# 0# remInteger _ (S# 0#) = S# (remInt# 0# 0#) remInteger (S# 0#) _ = S# 0# remInteger (S# n#) (S# d#) = S# (remInt# n# d#) remInteger (Jp# n) (S# d#) = wordToInteger (remBigNatWord n (int2Word# (absI# d#))) remInteger (Jn# n) (S# d#) = wordToNegInteger (remBigNatWord n (int2Word# (absI# d#))) remInteger (Jp# n) (Jp# d) = bigNatToInteger (remBigNat n d) remInteger (Jp# n) (Jn# d) = bigNatToInteger (remBigNat n d) remInteger (Jn# n) (Jp# d) = bigNatToNegInteger (remBigNat n d) remInteger (Jn# n) (Jn# d) = bigNatToNegInteger (remBigNat n d) -- handle remaining non-allocating cases remInteger n d = case inline quotRemInteger n d of (# _, r #) -> r {-# CONSTANT_FOLDED remInteger #-} -- | Simultaneous 'divInteger' and 'modInteger'. -- -- Divisor must be non-zero otherwise the GHC runtime will terminate -- with a division-by-zero fault. divModInteger :: Integer -> Integer -> (# Integer, Integer #) divModInteger n d | isTrue# (signumInteger# r ==# negateInt# (signumInteger# d)) = let !q' = plusInteger q (S# -1#) -- TODO: optimize !r' = plusInteger r d in (# q', r' #) | True = qr where qr@(# q, r #) = quotRemInteger n d {-# CONSTANT_FOLDED divModInteger #-} divInteger :: Integer -> Integer -> Integer -- same-sign ops can be handled by more efficient 'quotInteger' divInteger n d | isTrue# (isNegInteger# n ==# isNegInteger# d) = quotInteger n d divInteger n d = case inline divModInteger n d of (# q, _ #) -> q {-# CONSTANT_FOLDED divInteger #-} modInteger :: Integer -> Integer -> Integer -- same-sign ops can be handled by more efficient 'remInteger' modInteger n d | isTrue# (isNegInteger# n ==# isNegInteger# d) = remInteger n d modInteger n d = case inline divModInteger n d of (# _, r #) -> r {-# CONSTANT_FOLDED modInteger #-} -- | Compute greatest common divisor. gcdInteger :: Integer -> Integer -> Integer gcdInteger (S# 0#) b = absInteger b gcdInteger a (S# 0#) = absInteger a gcdInteger (S# 1#) _ = S# 1# gcdInteger (S# -1#) _ = S# 1# gcdInteger _ (S# 1#) = S# 1# gcdInteger _ (S# -1#) = S# 1# gcdInteger (S# a#) (S# b#) = wordToInteger (gcdWord# (int2Word# (absI# a#)) (int2Word# (absI# b#))) gcdInteger a@(S# _) b = gcdInteger b a gcdInteger (Jn# a) b = gcdInteger (Jp# a) b gcdInteger (Jp# a) (Jp# b) = bigNatToInteger (gcdBigNat a b) gcdInteger (Jp# a) (Jn# b) = bigNatToInteger (gcdBigNat a b) gcdInteger (Jp# a) (S# b#) = wordToInteger (gcdBigNatWord a (int2Word# (absI# b#))) {-# CONSTANT_FOLDED gcdInteger #-} -- | Compute least common multiple. lcmInteger :: Integer -> Integer -> Integer lcmInteger (S# 0#) !_ = S# 0# lcmInteger (S# 1#) b = absInteger b lcmInteger (S# -1#) b = absInteger b lcmInteger _ (S# 0#) = S# 0# lcmInteger a (S# 1#) = absInteger a lcmInteger a (S# -1#) = absInteger a lcmInteger a b = (aa `quotInteger` (aa `gcdInteger` ab)) `timesInteger` ab where aa = absInteger a ab = absInteger b {-# CONSTANT_FOLDED lcmInteger #-} -- | Compute greatest common divisor. -- -- __Warning__: result may become negative if (at least) one argument -- is 'minBound' gcdInt :: Int# -> Int# -> Int# gcdInt x# y# = word2Int# (gcdWord# (int2Word# (absI# x#)) (int2Word# (absI# y#))) -- | Compute greatest common divisor. -- -- @since 1.0.0.0 gcdWord :: Word# -> Word# -> Word# gcdWord = gcdWord# ---------------------------------------------------------------------------- -- BigNat operations compareBigNat :: BigNat -> BigNat -> Ordering compareBigNat x@(BN# x#) y@(BN# y#) | isTrue# (nx# ==# ny#) = compareInt# (narrowCInt# (c_mpn_cmp x# y# nx#)) 0# | isTrue# (nx# <# ny#) = LT | True = GT where nx# = sizeofBigNat# x ny# = sizeofBigNat# y compareBigNatWord :: BigNat -> GmpLimb# -> Ordering compareBigNatWord bn w# | isTrue# (sizeofBigNat# bn ==# 1#) = cmpW# (bigNatToWord bn) w# | True = GT gtBigNatWord# :: BigNat -> GmpLimb# -> Int# gtBigNatWord# bn w# = (sizeofBigNat# bn ># 1#) `orI#` (bigNatToWord bn `gtWord#` w#) eqBigNat :: BigNat -> BigNat -> Bool eqBigNat x y = isTrue# (eqBigNat# x y) eqBigNat# :: BigNat -> BigNat -> Int# eqBigNat# x@(BN# x#) y@(BN# y#) | isTrue# (nx# ==# ny#) = c_mpn_cmp x# y# nx# ==# 0# | True = 0# where nx# = sizeofBigNat# x ny# = sizeofBigNat# y neqBigNat# :: BigNat -> BigNat -> Int# neqBigNat# x@(BN# x#) y@(BN# y#) | isTrue# (nx# ==# ny#) = c_mpn_cmp x# y# nx# /=# 0# | True = 1# where nx# = sizeofBigNat# x ny# = sizeofBigNat# y eqBigNatWord :: BigNat -> GmpLimb# -> Bool eqBigNatWord bn w# = isTrue# (eqBigNatWord# bn w#) eqBigNatWord# :: BigNat -> GmpLimb# -> Int# eqBigNatWord# bn w# = (sizeofBigNat# bn ==# 1#) `andI#` (bigNatToWord bn `eqWord#` w#) -- | Same as @'indexBigNat#' bn 0\#@ bigNatToWord :: BigNat -> Word# bigNatToWord bn = indexBigNat# bn 0# -- | Equivalent to @'word2Int#' . 'bigNatToWord'@ bigNatToInt :: BigNat -> Int# bigNatToInt (BN# ba#) = indexIntArray# ba# 0# -- | CAF representing the value @0 :: BigNat@ zeroBigNat :: BigNat zeroBigNat = runS $ do mbn <- newBigNat# 1# _ <- svoid (writeBigNat# mbn 0# 0##) unsafeFreezeBigNat# mbn {-# NOINLINE zeroBigNat #-} -- | Test if 'BigNat' value is equal to zero. isZeroBigNat :: BigNat -> Bool isZeroBigNat bn = eqBigNatWord bn 0## -- | CAF representing the value @1 :: BigNat@ oneBigNat :: BigNat oneBigNat = runS $ do mbn <- newBigNat# 1# _ <- svoid (writeBigNat# mbn 0# 1##) unsafeFreezeBigNat# mbn {-# NOINLINE oneBigNat #-} czeroBigNat :: BigNat czeroBigNat = runS $ do mbn <- newBigNat# 1# _ <- svoid (writeBigNat# mbn 0# (not# 0##)) unsafeFreezeBigNat# mbn {-# NOINLINE czeroBigNat #-} -- | Special 0-sized bigNat returned in case of arithmetic underflow -- -- This is currently only returned by the following operations: -- -- - 'minusBigNat' -- - 'minusBigNatWord' -- -- Other operations such as 'quotBigNat' may return 'nullBigNat' as -- well as a dummy/place-holder value instead of 'undefined' since we -- can't throw exceptions. But that behaviour should not be relied -- upon. -- -- NB: @isValidBigNat# nullBigNat@ is false nullBigNat :: BigNat nullBigNat = runS (newBigNat# 0# >>= unsafeFreezeBigNat#) {-# NOINLINE nullBigNat #-} -- | Test for special 0-sized 'BigNat' representing underflows. isNullBigNat# :: BigNat -> Int# isNullBigNat# (BN# ba#) = sizeofByteArray# ba# ==# 0# -- | Construct 1-limb 'BigNat' from 'Word#' wordToBigNat :: Word# -> BigNat wordToBigNat 0## = zeroBigNat wordToBigNat 1## = oneBigNat wordToBigNat w# | isTrue# (not# w# `eqWord#` 0##) = czeroBigNat | True = runS $ do mbn <- newBigNat# 1# _ <- svoid (writeBigNat# mbn 0# w#) unsafeFreezeBigNat# mbn -- | Construct BigNat from 2 limbs. -- The first argument is the most-significant limb. wordToBigNat2 :: Word# -> Word# -> BigNat wordToBigNat2 0## lw# = wordToBigNat lw# wordToBigNat2 hw# lw# = runS $ do mbn <- newBigNat# 2# _ <- svoid (writeBigNat# mbn 0# lw#) _ <- svoid (writeBigNat# mbn 1# hw#) unsafeFreezeBigNat# mbn plusBigNat :: BigNat -> BigNat -> BigNat plusBigNat x y | isTrue# (eqBigNatWord# x 0##) = y | isTrue# (eqBigNatWord# y 0##) = x | isTrue# (nx# >=# ny#) = go x nx# y ny# | True = go y ny# x nx# where go (BN# a#) na# (BN# b#) nb# = runS $ do mbn@(MBN# mba#) <- newBigNat# na# (W# c#) <- liftIO (c_mpn_add mba# a# na# b# nb#) case c# of 0## -> unsafeFreezeBigNat# mbn _ -> unsafeSnocFreezeBigNat# mbn c# nx# = sizeofBigNat# x ny# = sizeofBigNat# y plusBigNatWord :: BigNat -> GmpLimb# -> BigNat plusBigNatWord x 0## = x plusBigNatWord x@(BN# x#) y# = runS $ do mbn@(MBN# mba#) <- newBigNat# nx# (W# c#) <- liftIO (c_mpn_add_1 mba# x# nx# y#) case c# of 0## -> unsafeFreezeBigNat# mbn _ -> unsafeSnocFreezeBigNat# mbn c# where nx# = sizeofBigNat# x -- | Returns 'nullBigNat' (see 'isNullBigNat#') in case of underflow minusBigNat :: BigNat -> BigNat -> BigNat minusBigNat x@(BN# x#) y@(BN# y#) | isZeroBigNat y = x | isTrue# (nx# >=# ny#) = runS $ do mbn@(MBN# mba#) <- newBigNat# nx# (W# b#) <- liftIO (c_mpn_sub mba# x# nx# y# ny#) case b# of 0## -> unsafeRenormFreezeBigNat# mbn _ -> return nullBigNat | True = nullBigNat where nx# = sizeofBigNat# x ny# = sizeofBigNat# y -- | Returns 'nullBigNat' (see 'isNullBigNat#') in case of underflow minusBigNatWord :: BigNat -> GmpLimb# -> BigNat minusBigNatWord x 0## = x minusBigNatWord x@(BN# x#) y# = runS $ do mbn@(MBN# mba#) <- newBigNat# nx# (W# b#) <- liftIO $ c_mpn_sub_1 mba# x# nx# y# case b# of 0## -> unsafeRenormFreezeBigNat# mbn _ -> return nullBigNat where nx# = sizeofBigNat# x timesBigNat :: BigNat -> BigNat -> BigNat timesBigNat x y | isZeroBigNat x = zeroBigNat | isZeroBigNat y = zeroBigNat | isTrue# (nx# >=# ny#) = go x nx# y ny# | True = go y ny# x nx# where go (BN# a#) na# (BN# b#) nb# = runS $ do let n# = nx# +# ny# mbn@(MBN# mba#) <- newBigNat# n# (W# msl#) <- liftIO (c_mpn_mul mba# a# na# b# nb#) case msl# of 0## -> unsafeShrinkFreezeBigNat# mbn (n# -# 1#) _ -> unsafeFreezeBigNat# mbn nx# = sizeofBigNat# x ny# = sizeofBigNat# y -- | Square 'BigNat' sqrBigNat :: BigNat -> BigNat sqrBigNat x | isZeroBigNat x = zeroBigNat -- TODO: 1-limb BigNats below sqrt(maxBound::GmpLimb) sqrBigNat x = timesBigNat x x -- TODO: mpn_sqr timesBigNatWord :: BigNat -> GmpLimb# -> BigNat timesBigNatWord !_ 0## = zeroBigNat timesBigNatWord x 1## = x timesBigNatWord x@(BN# x#) y# | isTrue# (nx# ==# 1#) = let (# !h#, !l# #) = timesWord2# (bigNatToWord x) y# in wordToBigNat2 h# l# | True = runS $ do mbn@(MBN# mba#) <- newBigNat# nx# (W# msl#) <- liftIO (c_mpn_mul_1 mba# x# nx# y#) case msl# of 0## -> unsafeFreezeBigNat# mbn _ -> unsafeSnocFreezeBigNat# mbn msl# where nx# = sizeofBigNat# x -- | Specialised version of -- -- > bitBigNat = shiftLBigNat (wordToBigNat 1##) -- -- avoiding a few redundant allocations bitBigNat :: Int# -> BigNat bitBigNat i# | isTrue# (i# <# 0#) = zeroBigNat -- or maybe 'nullBigNat'? | isTrue# (i# ==# 0#) = oneBigNat | True = runS $ do mbn@(MBN# mba#) <- newBigNat# (li# +# 1#) -- FIXME: do we really need to zero-init MBAs returned by 'newByteArray#'? -- clear all limbs (except for the most-significant limb) _ <- svoid (setByteArray# mba# 0# (li# `uncheckedIShiftL#` GMP_LIMB_SHIFT#) 0#) -- set single bit in most-significant limb _ <- svoid (writeBigNat# mbn li# (uncheckedShiftL# 1## bi#)) unsafeFreezeBigNat# mbn where (# li#, bi# #) = quotRemInt# i# GMP_LIMB_BITS# testBitBigNat :: BigNat -> Int# -> Bool testBitBigNat bn i# | isTrue# (i# <# 0#) = False | isTrue# (li# <# nx#) = isTrue# (testBitWord# (indexBigNat# bn li#) bi#) | True = False where (# li#, bi# #) = quotRemInt# i# GMP_LIMB_BITS# nx# = sizeofBigNat# bn testBitNegBigNat :: BigNat -> Int# -> Bool testBitNegBigNat bn i# | isTrue# (i# <# 0#) = False | isTrue# (li# >=# nx#) = True | allZ li# = isTrue# ((testBitWord# (indexBigNat# bn li# `minusWord#` 1##) bi#) ==# 0#) | True = isTrue# ((testBitWord# (indexBigNat# bn li#) bi#) ==# 0#) where (# li#, bi# #) = quotRemInt# i# GMP_LIMB_BITS# nx# = sizeofBigNat# bn allZ 0# = True allZ j | isTrue# (indexBigNat# bn (j -# 1#) `eqWord#` 0##) = allZ (j -# 1#) | True = False popCountBigNat :: BigNat -> Int# popCountBigNat bn@(BN# ba#) = word2Int# (c_mpn_popcount ba# (sizeofBigNat# bn)) shiftLBigNat :: BigNat -> Int# -> BigNat shiftLBigNat x 0# = x shiftLBigNat x _ | isZeroBigNat x = zeroBigNat shiftLBigNat x@(BN# xba#) n# = runS $ do ymbn@(MBN# ymba#) <- newBigNat# yn# W# ymsl <- liftIO (c_mpn_lshift ymba# xba# xn# (int2Word# n#)) case ymsl of 0## -> unsafeShrinkFreezeBigNat# ymbn (yn# -# 1#) _ -> unsafeFreezeBigNat# ymbn where xn# = sizeofBigNat# x yn# = xn# +# nlimbs# +# (nbits# /=# 0#) (# nlimbs#, nbits# #) = quotRemInt# n# GMP_LIMB_BITS# shiftRBigNat :: BigNat -> Int# -> BigNat shiftRBigNat x 0# = x shiftRBigNat x _ | isZeroBigNat x = zeroBigNat shiftRBigNat x@(BN# xba#) n# | isTrue# (nlimbs# >=# xn#) = zeroBigNat | True = runS $ do ymbn@(MBN# ymba#) <- newBigNat# yn# W# ymsl <- liftIO (c_mpn_rshift ymba# xba# xn# (int2Word# n#)) case ymsl of 0## -> unsafeRenormFreezeBigNat# ymbn -- may shrink more than one _ -> unsafeFreezeBigNat# ymbn where xn# = sizeofBigNat# x yn# = xn# -# nlimbs# nlimbs# = quotInt# n# GMP_LIMB_BITS# shiftRNegBigNat :: BigNat -> Int# -> BigNat shiftRNegBigNat x 0# = x shiftRNegBigNat x _ | isZeroBigNat x = zeroBigNat shiftRNegBigNat x@(BN# xba#) n# | isTrue# (nlimbs# >=# xn#) = zeroBigNat | True = runS $ do ymbn@(MBN# ymba#) <- newBigNat# yn# W# ymsl <- liftIO (c_mpn_rshift_2c ymba# xba# xn# (int2Word# n#)) case ymsl of 0## -> unsafeRenormFreezeBigNat# ymbn -- may shrink more than one _ -> unsafeFreezeBigNat# ymbn where xn# = sizeofBigNat# x yn# = xn# -# nlimbs# nlimbs# = quotInt# n# GMP_LIMB_BITS# orBigNat :: BigNat -> BigNat -> BigNat orBigNat x@(BN# x#) y@(BN# y#) | isZeroBigNat x = y | isZeroBigNat y = x | isTrue# (nx# >=# ny#) = runS (ior' x# nx# y# ny#) | True = runS (ior' y# ny# x# nx#) where ior' a# na# b# nb# = do -- na >= nb mbn@(MBN# mba#) <- newBigNat# na# _ <- liftIO (c_mpn_ior_n mba# a# b# nb#) _ <- case isTrue# (na# ==# nb#) of False -> svoid (copyWordArray# a# nb# mba# nb# (na# -# nb#)) True -> return () unsafeFreezeBigNat# mbn nx# = sizeofBigNat# x ny# = sizeofBigNat# y xorBigNat :: BigNat -> BigNat -> BigNat xorBigNat x@(BN# x#) y@(BN# y#) | isZeroBigNat x = y | isZeroBigNat y = x | isTrue# (nx# >=# ny#) = runS (xor' x# nx# y# ny#) | True = runS (xor' y# ny# x# nx#) where xor' a# na# b# nb# = do -- na >= nb mbn@(MBN# mba#) <- newBigNat# na# _ <- liftIO (c_mpn_xor_n mba# a# b# nb#) case isTrue# (na# ==# nb#) of False -> do _ <- svoid (copyWordArray# a# nb# mba# nb# (na# -# nb#)) unsafeFreezeBigNat# mbn True -> unsafeRenormFreezeBigNat# mbn nx# = sizeofBigNat# x ny# = sizeofBigNat# y -- | aka @\x y -> x .&. (complement y)@ andnBigNat :: BigNat -> BigNat -> BigNat andnBigNat x@(BN# x#) y@(BN# y#) | isZeroBigNat x = zeroBigNat | isZeroBigNat y = x | True = runS $ do mbn@(MBN# mba#) <- newBigNat# nx# _ <- liftIO (c_mpn_andn_n mba# x# y# n#) _ <- case isTrue# (nx# ==# n#) of False -> svoid (copyWordArray# x# n# mba# n# (nx# -# n#)) True -> return () unsafeRenormFreezeBigNat# mbn where n# | isTrue# (nx# <# ny#) = nx# | True = ny# nx# = sizeofBigNat# x ny# = sizeofBigNat# y andBigNat :: BigNat -> BigNat -> BigNat andBigNat x@(BN# x#) y@(BN# y#) | isZeroBigNat x = zeroBigNat | isZeroBigNat y = zeroBigNat | True = runS $ do mbn@(MBN# mba#) <- newBigNat# n# _ <- liftIO (c_mpn_and_n mba# x# y# n#) unsafeRenormFreezeBigNat# mbn where n# | isTrue# (nx# <# ny#) = nx# | True = ny# nx# = sizeofBigNat# x ny# = sizeofBigNat# y -- | If divisor is zero, @(\# 'nullBigNat', 'nullBigNat' \#)@ is returned quotRemBigNat :: BigNat -> BigNat -> (# BigNat,BigNat #) quotRemBigNat n@(BN# nba#) d@(BN# dba#) | isZeroBigNat d = (# nullBigNat, nullBigNat #) | eqBigNatWord d 1## = (# n, zeroBigNat #) | n < d = (# zeroBigNat, n #) | True = case runS go of (!q,!r) -> (# q, r #) where nn# = sizeofBigNat# n dn# = sizeofBigNat# d qn# = 1# +# nn# -# dn# rn# = dn# go = do qmbn@(MBN# qmba#) <- newBigNat# qn# rmbn@(MBN# rmba#) <- newBigNat# rn# _ <- liftIO (c_mpn_tdiv_qr qmba# rmba# 0# nba# nn# dba# dn#) q <- unsafeRenormFreezeBigNat# qmbn r <- unsafeRenormFreezeBigNat# rmbn return (q, r) quotBigNat :: BigNat -> BigNat -> BigNat quotBigNat n@(BN# nba#) d@(BN# dba#) | isZeroBigNat d = nullBigNat | eqBigNatWord d 1## = n | n < d = zeroBigNat | True = runS $ do let nn# = sizeofBigNat# n let dn# = sizeofBigNat# d let qn# = 1# +# nn# -# dn# qmbn@(MBN# qmba#) <- newBigNat# qn# _ <- liftIO (c_mpn_tdiv_q qmba# nba# nn# dba# dn#) unsafeRenormFreezeBigNat# qmbn remBigNat :: BigNat -> BigNat -> BigNat remBigNat n@(BN# nba#) d@(BN# dba#) | isZeroBigNat d = nullBigNat | eqBigNatWord d 1## = zeroBigNat | n < d = n | True = runS $ do let nn# = sizeofBigNat# n let dn# = sizeofBigNat# d rmbn@(MBN# rmba#) <- newBigNat# dn# _ <- liftIO (c_mpn_tdiv_r rmba# nba# nn# dba# dn#) unsafeRenormFreezeBigNat# rmbn -- | Note: Result of div/0 undefined quotRemBigNatWord :: BigNat -> GmpLimb# -> (# BigNat, GmpLimb# #) quotRemBigNatWord !_ 0## = (# nullBigNat, 0## #) quotRemBigNatWord n 1## = (# n, 0## #) quotRemBigNatWord n@(BN# nba#) d# = case compareBigNatWord n d# of LT -> (# zeroBigNat, bigNatToWord n #) EQ -> (# oneBigNat, 0## #) GT -> case runS go of (!q,!(W# r#)) -> (# q, r# #) -- TODO: handle word/word where go = do let nn# = sizeofBigNat# n qmbn@(MBN# qmba#) <- newBigNat# nn# r <- liftIO (c_mpn_divrem_1 qmba# 0# nba# nn# d#) q <- unsafeRenormFreezeBigNat# qmbn return (q,r) quotBigNatWord :: BigNat -> GmpLimb# -> BigNat quotBigNatWord n d# = case inline quotRemBigNatWord n d# of (# q, _ #) -> q -- | div/0 not checked remBigNatWord :: BigNat -> GmpLimb# -> Word# remBigNatWord n@(BN# nba#) d# = c_mpn_mod_1 nba# (sizeofBigNat# n) d# gcdBigNatWord :: BigNat -> Word# -> Word# gcdBigNatWord bn@(BN# ba#) = c_mpn_gcd_1# ba# (sizeofBigNat# bn) gcdBigNat :: BigNat -> BigNat -> BigNat gcdBigNat x@(BN# x#) y@(BN# y#) | isZeroBigNat x = y | isZeroBigNat y = x | isTrue# (nx# >=# ny#) = runS (gcd' x# nx# y# ny#) | True = runS (gcd' y# ny# x# nx#) where gcd' a# na# b# nb# = do -- na >= nb mbn@(MBN# mba#) <- newBigNat# nb# I# rn'# <- liftIO (c_mpn_gcd# mba# a# na# b# nb#) let rn# = narrowGmpSize# rn'# case isTrue# (rn# ==# nb#) of False -> unsafeShrinkFreezeBigNat# mbn rn# True -> unsafeFreezeBigNat# mbn nx# = sizeofBigNat# x ny# = sizeofBigNat# y -- | Extended euclidean algorithm. -- -- For @/a/@ and @/b/@, compute their greatest common divisor @/g/@ -- and the coefficient @/s/@ satisfying @/a//s/ + /b//t/ = /g/@. -- -- @since 0.5.1.0 {-# NOINLINE gcdExtInteger #-} gcdExtInteger :: Integer -> Integer -> (# Integer, Integer #) gcdExtInteger a b = case gcdExtSBigNat a' b' of (# g, s #) -> let !g' = bigNatToInteger g !s' = sBigNatToInteger s in (# g', s' #) where a' = integerToSBigNat a b' = integerToSBigNat b -- internal helper gcdExtSBigNat :: SBigNat -> SBigNat -> (# BigNat, SBigNat #) gcdExtSBigNat x y = case runS go of (g,s) -> (# g, s #) where go = do g@(MBN# g#) <- newBigNat# gn0# s@(MBN# s#) <- newBigNat# (absI# xn#) I# ssn_# <- liftIO (integer_gmp_gcdext# s# g# x# xn# y# yn#) let ssn# = narrowGmpSize# ssn_# sn# = absI# ssn# s' <- unsafeShrinkFreezeBigNat# s sn# g' <- unsafeRenormFreezeBigNat# g case isTrue# (ssn# >=# 0#) of False -> return ( g', NegBN s' ) True -> return ( g', PosBN s' ) !(BN# x#) = absSBigNat x !(BN# y#) = absSBigNat y xn# = ssizeofSBigNat# x yn# = ssizeofSBigNat# y gn0# = minI# (absI# xn#) (absI# yn#) ---------------------------------------------------------------------------- -- modular exponentiation -- | \"@'powModInteger' /b/ /e/ /m/@\" computes base @/b/@ raised to -- exponent @/e/@ modulo @abs(/m/)@. -- -- Negative exponents are supported if an inverse modulo @/m/@ -- exists. -- -- __Warning__: It's advised to avoid calling this primitive with -- negative exponents unless it is guaranteed the inverse exists, as -- failure to do so will likely cause program abortion due to a -- divide-by-zero fault. See also 'recipModInteger'. -- -- Future versions of @integer_gmp@ may not support negative @/e/@ -- values anymore. -- -- @since 0.5.1.0 {-# NOINLINE powModInteger #-} powModInteger :: Integer -> Integer -> Integer -> Integer powModInteger (S# b#) (S# e#) (S# m#) | isTrue# (b# >=# 0#), isTrue# (e# >=# 0#) = wordToInteger (powModWord (int2Word# b#) (int2Word# e#) (int2Word# (absI# m#))) powModInteger b e m = case m of (S# m#) -> wordToInteger (powModSBigNatWord b' e' (int2Word# (absI# m#))) (Jp# m') -> bigNatToInteger (powModSBigNat b' e' m') (Jn# m') -> bigNatToInteger (powModSBigNat b' e' m') where b' = integerToSBigNat b e' = integerToSBigNat e -- | Version of 'powModInteger' operating on 'BigNat's -- -- @since 1.0.0.0 powModBigNat :: BigNat -> BigNat -> BigNat -> BigNat powModBigNat b e m = inline powModSBigNat (PosBN b) (PosBN e) m -- | Version of 'powModInteger' for 'Word#'-sized moduli -- -- @since 1.0.0.0 powModBigNatWord :: BigNat -> BigNat -> GmpLimb# -> GmpLimb# powModBigNatWord b e m# = inline powModSBigNatWord (PosBN b) (PosBN e) m# -- | Version of 'powModInteger' operating on 'Word#'s -- -- @since 1.0.0.0 foreign import ccall unsafe "integer_gmp_powm_word" powModWord :: GmpLimb# -> GmpLimb# -> GmpLimb# -> GmpLimb# -- internal non-exported helper powModSBigNat :: SBigNat -> SBigNat -> BigNat -> BigNat powModSBigNat b e m@(BN# m#) = runS $ do r@(MBN# r#) <- newBigNat# mn# I# rn_# <- liftIO (integer_gmp_powm# r# b# bn# e# en# m# mn#) let rn# = narrowGmpSize# rn_# case isTrue# (rn# ==# mn#) of False -> unsafeShrinkFreezeBigNat# r rn# True -> unsafeFreezeBigNat# r where !(BN# b#) = absSBigNat b !(BN# e#) = absSBigNat e bn# = ssizeofSBigNat# b en# = ssizeofSBigNat# e mn# = sizeofBigNat# m foreign import ccall unsafe "integer_gmp_powm" integer_gmp_powm# :: MutableByteArray# RealWorld -> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> IO GmpSize -- internal non-exported helper powModSBigNatWord :: SBigNat -> SBigNat -> GmpLimb# -> GmpLimb# powModSBigNatWord b e m# = integer_gmp_powm1# b# bn# e# en# m# where !(BN# b#) = absSBigNat b !(BN# e#) = absSBigNat e bn# = ssizeofSBigNat# b en# = ssizeofSBigNat# e foreign import ccall unsafe "integer_gmp_powm1" integer_gmp_powm1# :: ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> GmpLimb# -> GmpLimb# -- | \"@'recipModInteger' /x/ /m/@\" computes the inverse of @/x/@ modulo @/m/@. If -- the inverse exists, the return value @/y/@ will satisfy @0 < /y/ < -- abs(/m/)@, otherwise the result is @0@. -- -- @since 0.5.1.0 {-# NOINLINE recipModInteger #-} recipModInteger :: Integer -> Integer -> Integer recipModInteger (S# x#) (S# m#) | isTrue# (x# >=# 0#) = wordToInteger (recipModWord (int2Word# x#) (int2Word# (absI# m#))) recipModInteger x m = bigNatToInteger (recipModSBigNat x' m') where x' = integerToSBigNat x m' = absSBigNat (integerToSBigNat m) -- | Version of 'recipModInteger' operating on 'BigNat's -- -- @since 1.0.0.0 recipModBigNat :: BigNat -> BigNat -> BigNat recipModBigNat x m = inline recipModSBigNat (PosBN x) m -- | Version of 'recipModInteger' operating on 'Word#'s -- -- @since 1.0.0.0 foreign import ccall unsafe "integer_gmp_invert_word" recipModWord :: GmpLimb# -> GmpLimb# -> GmpLimb# -- internal non-exported helper recipModSBigNat :: SBigNat -> BigNat -> BigNat recipModSBigNat x m@(BN# m#) = runS $ do r@(MBN# r#) <- newBigNat# mn# I# rn_# <- liftIO (integer_gmp_invert# r# x# xn# m# mn#) let rn# = narrowGmpSize# rn_# case isTrue# (rn# ==# mn#) of False -> unsafeShrinkFreezeBigNat# r rn# True -> unsafeFreezeBigNat# r where !(BN# x#) = absSBigNat x xn# = ssizeofSBigNat# x mn# = sizeofBigNat# m foreign import ccall unsafe "integer_gmp_invert" integer_gmp_invert# :: MutableByteArray# RealWorld -> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> IO GmpSize ---------------------------------------------------------------------------- -- Conversions to/from floating point decodeDoubleInteger :: Double# -> (# Integer, Int# #) -- decodeDoubleInteger 0.0## = (# S# 0#, 0# #) #if WORD_SIZE_IN_BITS == 64 decodeDoubleInteger x = case decodeDouble_Int64# x of (# m#, e# #) -> (# S# m#, e# #) #elif WORD_SIZE_IN_BITS == 32 decodeDoubleInteger x = case decodeDouble_Int64# x of (# m#, e# #) -> (# int64ToInteger m#, e# #) #endif {-# CONSTANT_FOLDED decodeDoubleInteger #-} -- provided by GHC's RTS foreign import ccall unsafe "__int_encodeDouble" int_encodeDouble# :: Int# -> Int# -> Double# encodeDoubleInteger :: Integer -> Int# -> Double# encodeDoubleInteger (S# m#) 0# = int2Double# m# encodeDoubleInteger (S# m#) e# = int_encodeDouble# m# e# encodeDoubleInteger (Jp# bn@(BN# bn#)) e# = c_mpn_get_d bn# (sizeofBigNat# bn) e# encodeDoubleInteger (Jn# bn@(BN# bn#)) e# = c_mpn_get_d bn# (negateInt# (sizeofBigNat# bn)) e# {-# CONSTANT_FOLDED encodeDoubleInteger #-} -- double integer_gmp_mpn_get_d (const mp_limb_t sp[], const mp_size_t sn) foreign import ccall unsafe "integer_gmp_mpn_get_d" c_mpn_get_d :: ByteArray# -> GmpSize# -> Int# -> Double# doubleFromInteger :: Integer -> Double# doubleFromInteger (S# m#) = int2Double# m# doubleFromInteger (Jp# bn@(BN# bn#)) = c_mpn_get_d bn# (sizeofBigNat# bn) 0# doubleFromInteger (Jn# bn@(BN# bn#)) = c_mpn_get_d bn# (negateInt# (sizeofBigNat# bn)) 0# {-# CONSTANT_FOLDED doubleFromInteger #-} -- TODO: Not sure if it's worth to write 'Float' optimized versions here floatFromInteger :: Integer -> Float# floatFromInteger i = double2Float# (doubleFromInteger i) encodeFloatInteger :: Integer -> Int# -> Float# encodeFloatInteger m e = double2Float# (encodeDoubleInteger m e) ---------------------------------------------------------------------------- -- FFI ccall imports foreign import ccall unsafe "integer_gmp_gcd_word" gcdWord# :: GmpLimb# -> GmpLimb# -> GmpLimb# foreign import ccall unsafe "integer_gmp_mpn_gcd_1" c_mpn_gcd_1# :: ByteArray# -> GmpSize# -> GmpLimb# -> GmpLimb# foreign import ccall unsafe "integer_gmp_mpn_gcd" c_mpn_gcd# :: MutableByteArray# s -> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> IO GmpSize foreign import ccall unsafe "integer_gmp_gcdext" integer_gmp_gcdext# :: MutableByteArray# s -> MutableByteArray# s -> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> IO GmpSize -- mp_limb_t mpn_add_1 (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t n, -- mp_limb_t s2limb) foreign import ccall unsafe "gmp.h __gmpn_add_1" c_mpn_add_1 :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpLimb# -> IO GmpLimb -- mp_limb_t mpn_sub_1 (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t n, -- mp_limb_t s2limb) foreign import ccall unsafe "gmp.h __gmpn_sub_1" c_mpn_sub_1 :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpLimb# -> IO GmpLimb -- mp_limb_t mpn_mul_1 (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t n, -- mp_limb_t s2limb) foreign import ccall unsafe "gmp.h __gmpn_mul_1" c_mpn_mul_1 :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpLimb# -> IO GmpLimb -- mp_limb_t mpn_add (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t s1n, -- const mp_limb_t *s2p, mp_size_t s2n) foreign import ccall unsafe "gmp.h __gmpn_add" c_mpn_add :: MutableByteArray# s -> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> IO GmpLimb -- mp_limb_t mpn_sub (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t s1n, -- const mp_limb_t *s2p, mp_size_t s2n) foreign import ccall unsafe "gmp.h __gmpn_sub" c_mpn_sub :: MutableByteArray# s -> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> IO GmpLimb -- mp_limb_t mpn_mul (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t s1n, -- const mp_limb_t *s2p, mp_size_t s2n) foreign import ccall unsafe "gmp.h __gmpn_mul" c_mpn_mul :: MutableByteArray# s -> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> IO GmpLimb -- int mpn_cmp (const mp_limb_t *s1p, const mp_limb_t *s2p, mp_size_t n) foreign import ccall unsafe "gmp.h __gmpn_cmp" c_mpn_cmp :: ByteArray# -> ByteArray# -> GmpSize# -> CInt# -- void mpn_tdiv_qr (mp_limb_t *qp, mp_limb_t *rp, mp_size_t qxn, -- const mp_limb_t *np, mp_size_t nn, -- const mp_limb_t *dp, mp_size_t dn) foreign import ccall unsafe "gmp.h __gmpn_tdiv_qr" c_mpn_tdiv_qr :: MutableByteArray# s -> MutableByteArray# s -> GmpSize# -> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> IO () foreign import ccall unsafe "integer_gmp_mpn_tdiv_q" c_mpn_tdiv_q :: MutableByteArray# s -> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> IO () foreign import ccall unsafe "integer_gmp_mpn_tdiv_r" c_mpn_tdiv_r :: MutableByteArray# s -> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> IO () -- mp_limb_t mpn_divrem_1 (mp_limb_t *r1p, mp_size_t qxn, mp_limb_t *s2p, -- mp_size_t s2n, mp_limb_t s3limb) foreign import ccall unsafe "gmp.h __gmpn_divrem_1" c_mpn_divrem_1 :: MutableByteArray# s -> GmpSize# -> ByteArray# -> GmpSize# -> GmpLimb# -> IO GmpLimb -- mp_limb_t mpn_mod_1 (const mp_limb_t *s1p, mp_size_t s1n, mp_limb_t s2limb) foreign import ccall unsafe "gmp.h __gmpn_mod_1" c_mpn_mod_1 :: ByteArray# -> GmpSize# -> GmpLimb# -> GmpLimb# -- mp_limb_t integer_gmp_mpn_rshift (mp_limb_t rp[], const mp_limb_t sp[], -- mp_size_t sn, mp_bitcnt_t count) foreign import ccall unsafe "integer_gmp_mpn_rshift" c_mpn_rshift :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpBitCnt# -> IO GmpLimb -- mp_limb_t integer_gmp_mpn_rshift (mp_limb_t rp[], const mp_limb_t sp[], -- mp_size_t sn, mp_bitcnt_t count) foreign import ccall unsafe "integer_gmp_mpn_rshift_2c" c_mpn_rshift_2c :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpBitCnt# -> IO GmpLimb -- mp_limb_t integer_gmp_mpn_lshift (mp_limb_t rp[], const mp_limb_t sp[], -- mp_size_t sn, mp_bitcnt_t count) foreign import ccall unsafe "integer_gmp_mpn_lshift" c_mpn_lshift :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpBitCnt# -> IO GmpLimb -- void mpn_and_n (mp_limb_t *rp, const mp_limb_t *s1p, const mp_limb_t *s2p, -- mp_size_t n) foreign import ccall unsafe "integer_gmp_mpn_and_n" c_mpn_and_n :: MutableByteArray# s -> ByteArray# -> ByteArray# -> GmpSize# -> IO () -- void mpn_andn_n (mp_limb_t *rp, const mp_limb_t *s1p, const mp_limb_t *s2p, -- mp_size_t n) foreign import ccall unsafe "integer_gmp_mpn_andn_n" c_mpn_andn_n :: MutableByteArray# s -> ByteArray# -> ByteArray# -> GmpSize# -> IO () -- void mpn_ior_n (mp_limb_t *rp, const mp_limb_t *s1p, const mp_limb_t *s2p, -- mp_size_t n) foreign import ccall unsafe "integer_gmp_mpn_ior_n" c_mpn_ior_n :: MutableByteArray# s -> ByteArray# -> ByteArray# -> GmpSize# -> IO () -- void mpn_xor_n (mp_limb_t *rp, const mp_limb_t *s1p, const mp_limb_t *s2p, -- mp_size_t n) foreign import ccall unsafe "integer_gmp_mpn_xor_n" c_mpn_xor_n :: MutableByteArray# s -> ByteArray# -> ByteArray# -> GmpSize# -> IO () -- mp_bitcnt_t mpn_popcount (const mp_limb_t *s1p, mp_size_t n) foreign import ccall unsafe "gmp.h __gmpn_popcount" c_mpn_popcount :: ByteArray# -> GmpSize# -> GmpBitCnt# ---------------------------------------------------------------------------- -- BigNat-wrapped ByteArray#-primops -- | Return number of limbs contained in 'BigNat'. sizeofBigNat# :: BigNat -> GmpSize# sizeofBigNat# (BN# x#) = sizeofByteArray# x# `uncheckedIShiftRL#` GMP_LIMB_SHIFT# data MutBigNat s = MBN# !(MutableByteArray# s) getSizeofMutBigNat# :: MutBigNat s -> State# s -> (# State# s, GmpSize# #) --getSizeofMutBigNat# :: MutBigNat s -> S s GmpSize# getSizeofMutBigNat# (MBN# x#) s = case getSizeofMutableByteArray# x# s of (# s', n# #) -> (# s', n# `uncheckedIShiftRL#` GMP_LIMB_SHIFT# #) newBigNat# :: GmpSize# -> S s (MutBigNat s) newBigNat# limbs# s = case newByteArray# (limbs# `uncheckedIShiftL#` GMP_LIMB_SHIFT#) s of (# s', mba# #) -> (# s', MBN# mba# #) writeBigNat# :: MutBigNat s -> GmpSize# -> GmpLimb# -> State# s -> State# s writeBigNat# (MBN# mba#) = writeWordArray# mba# -- | Extract /n/-th (0-based) limb in 'BigNat'. -- /n/ must be less than size as reported by 'sizeofBigNat#'. indexBigNat# :: BigNat -> GmpSize# -> GmpLimb# indexBigNat# (BN# ba#) = indexWordArray# ba# unsafeFreezeBigNat# :: MutBigNat s -> S s BigNat unsafeFreezeBigNat# (MBN# mba#) s = case unsafeFreezeByteArray# mba# s of (# s', ba# #) -> (# s', BN# ba# #) resizeMutBigNat# :: MutBigNat s -> GmpSize# -> S s (MutBigNat s) resizeMutBigNat# (MBN# mba0#) nsz# s | isTrue# (bsz# ==# n#) = (# s', MBN# mba0# #) | True = case resizeMutableByteArray# mba0# bsz# s' of (# s'', mba# #) -> (# s'', MBN# mba# #) where bsz# = nsz# `uncheckedIShiftL#` GMP_LIMB_SHIFT# (# s', n# #) = getSizeofMutableByteArray# mba0# s shrinkMutBigNat# :: MutBigNat s -> GmpSize# -> State# s -> State# s shrinkMutBigNat# (MBN# mba0#) nsz# s | isTrue# (bsz# ==# n#) = s' -- no-op | True = shrinkMutableByteArray# mba0# bsz# s' where bsz# = nsz# `uncheckedIShiftL#` GMP_LIMB_SHIFT# (# s', n# #) = getSizeofMutableByteArray# mba0# s unsafeSnocFreezeBigNat# :: MutBigNat s -> GmpLimb# -> S s BigNat unsafeSnocFreezeBigNat# mbn0@(MBN# mba0#) limb# s = go s' where n# = nb0# `uncheckedIShiftRL#` GMP_LIMB_SHIFT# (# s', nb0# #) = getSizeofMutableByteArray# mba0# s go = do (MBN# mba#) <- resizeMutBigNat# mbn0 (n# +# 1#) _ <- svoid (writeWordArray# mba# n# limb#) unsafeFreezeBigNat# (MBN# mba#) -- | May shrink underlyng 'ByteArray#' if needed to satisfy BigNat invariant unsafeRenormFreezeBigNat# :: MutBigNat s -> S s BigNat unsafeRenormFreezeBigNat# mbn s | isTrue# (n0# ==# 0#) = (# s'', nullBigNat #) | isTrue# (n# ==# 0#) = (# s'', zeroBigNat #) | isTrue# (n# ==# n0#) = (unsafeFreezeBigNat# mbn) s'' | True = (unsafeShrinkFreezeBigNat# mbn n#) s'' where (# s', n0# #) = getSizeofMutBigNat# mbn s (# s'', n# #) = normSizeofMutBigNat'# mbn n0# s' -- | Shrink MBN unsafeShrinkFreezeBigNat# :: MutBigNat s -> GmpSize# -> S s BigNat unsafeShrinkFreezeBigNat# x@(MBN# xmba) 1# = \s -> case readWordArray# xmba 0# s of (# s', w# #) -> freezeOneLimb w# s' where freezeOneLimb 0## = return zeroBigNat freezeOneLimb 1## = return oneBigNat freezeOneLimb w# | isTrue# (not# w# `eqWord#` 0##) = return czeroBigNat freezeOneLimb _ = do _ <- svoid (shrinkMutBigNat# x 1#) unsafeFreezeBigNat# x unsafeShrinkFreezeBigNat# x y# = do _ <- svoid (shrinkMutBigNat# x y#) unsafeFreezeBigNat# x copyWordArray# :: ByteArray# -> Int# -> MutableByteArray# s -> Int# -> Int# -> State# s -> State# s copyWordArray# src src_ofs dst dst_ofs len = copyByteArray# src (src_ofs `uncheckedIShiftL#` GMP_LIMB_SHIFT#) dst (dst_ofs `uncheckedIShiftL#` GMP_LIMB_SHIFT#) (len `uncheckedIShiftL#` GMP_LIMB_SHIFT#) -- | Version of 'normSizeofMutBigNat'#' which scans all allocated 'MutBigNat#' normSizeofMutBigNat# :: MutBigNat s -> State# s -> (# State# s, Int# #) normSizeofMutBigNat# mbn@(MBN# mba) s = normSizeofMutBigNat'# mbn sz# s' where (# s', n# #) = getSizeofMutableByteArray# mba s sz# = n# `uncheckedIShiftRA#` GMP_LIMB_SHIFT# -- | Find most-significant non-zero limb and return its index-position -- plus one. Start scanning downward from the initial limb-size -- (i.e. start-index plus one) given as second argument. -- -- NB: The 'normSizeofMutBigNat' of 'zeroBigNat' would be @0#@ normSizeofMutBigNat'# :: MutBigNat s -> GmpSize# -> State# s -> (# State# s, GmpSize# #) normSizeofMutBigNat'# (MBN# mba) = go where go 0# s = (# s, 0# #) go i0# s = case readWordArray# mba (i0# -# 1#) s of (# s', 0## #) -> go (i0# -# 1#) s' (# s', _ #) -> (# s', i0# #) -- | Construct 'BigNat' from existing 'ByteArray#' containing /n/ -- 'GmpLimb's in least-significant-first order. -- -- If possible 'ByteArray#', will be used directly (i.e. shared -- /without/ cloning the 'ByteArray#' into a newly allocated one) -- -- Note: size parameter (times @sizeof(GmpLimb)@) must be less or -- equal to its 'sizeofByteArray#'. byteArrayToBigNat# :: ByteArray# -> GmpSize# -> BigNat byteArrayToBigNat# ba# n0# | isTrue# (n# ==# 0#) = zeroBigNat | isTrue# (baszr# ==# 0#) -- i.e. ba# is multiple of limb-size , isTrue# (baszq# ==# n#) = (BN# ba#) | True = runS $ \s -> let (# s', mbn@(MBN# mba#) #) = newBigNat# n# s (# s'', ba_sz# #) = getSizeofMutableByteArray# mba# s' go = do _ <- svoid (copyByteArray# ba# 0# mba# 0# ba_sz# ) unsafeFreezeBigNat# mbn in go s'' where (# baszq#, baszr# #) = quotRemInt# (sizeofByteArray# ba#) GMP_LIMB_BYTES# n# = fmssl (n0# -# 1#) -- find most significant set limb, return normalized size fmssl i# | isTrue# (i# <# 0#) = 0# | isTrue# (neWord# (indexWordArray# ba# i#) 0##) = i# +# 1# | True = fmssl (i# -# 1#) -- | Read 'Integer' (without sign) from memory location at @/addr/@ in -- base-256 representation. -- -- @'importIntegerFromAddr' /addr/ /size/ /msbf/@ -- -- See description of 'importIntegerFromByteArray' for more details. -- -- @since 1.0.0.0 importIntegerFromAddr :: Addr# -> Word# -> Int# -> IO Integer importIntegerFromAddr addr len msbf = IO $ do bn <- liftIO (importBigNatFromAddr addr len msbf) return (bigNatToInteger bn) -- | Version of 'importIntegerFromAddr' constructing a 'BigNat' importBigNatFromAddr :: Addr# -> Word# -> Int# -> IO BigNat importBigNatFromAddr _ 0## _ = IO (\s -> (# s, zeroBigNat #)) importBigNatFromAddr addr len0 1# = IO $ do -- MSBF W# ofs <- liftIO (c_scan_nzbyte_addr addr 0## len0) let len = len0 `minusWord#` ofs addr' = addr `plusAddr#` (word2Int# ofs) importBigNatFromAddr# addr' len 1# importBigNatFromAddr addr len0 _ = IO $ do -- LSBF W# len <- liftIO (c_rscan_nzbyte_addr addr 0## len0) importBigNatFromAddr# addr len 0# foreign import ccall unsafe "integer_gmp_scan_nzbyte" c_scan_nzbyte_addr :: Addr# -> Word# -> Word# -> IO Word foreign import ccall unsafe "integer_gmp_rscan_nzbyte" c_rscan_nzbyte_addr :: Addr# -> Word# -> Word# -> IO Word -- | Helper for 'importBigNatFromAddr' importBigNatFromAddr# :: Addr# -> Word# -> Int# -> S RealWorld BigNat importBigNatFromAddr# _ 0## _ = return zeroBigNat importBigNatFromAddr# addr len msbf = do mbn@(MBN# mba#) <- newBigNat# n# () <- liftIO (c_mpn_import_addr mba# addr 0## len msbf) unsafeFreezeBigNat# mbn where -- n = ceiling(len / SIZEOF_HSWORD), i.e. number of limbs required n# = (word2Int# len +# (SIZEOF_HSWORD# -# 1#)) `quotInt#` SIZEOF_HSWORD# foreign import ccall unsafe "integer_gmp_mpn_import" c_mpn_import_addr :: MutableByteArray# RealWorld -> Addr# -> Word# -> Word# -> Int# -> IO () -- | Read 'Integer' (without sign) from byte-array in base-256 representation. -- -- The call -- -- @'importIntegerFromByteArray' /ba/ /offset/ /size/ /msbf/@ -- -- reads -- -- * @/size/@ bytes from the 'ByteArray#' @/ba/@ starting at @/offset/@ -- -- * with most significant byte first if @/msbf/@ is @1#@ or least -- significant byte first if @/msbf/@ is @0#@, and -- -- * returns a new 'Integer' -- -- @since 1.0.0.0 importIntegerFromByteArray :: ByteArray# -> Word# -> Word# -> Int# -> Integer importIntegerFromByteArray ba ofs len msbf = bigNatToInteger (importBigNatFromByteArray ba ofs len msbf) -- | Version of 'importIntegerFromByteArray' constructing a 'BigNat' importBigNatFromByteArray :: ByteArray# -> Word# -> Word# -> Int# -> BigNat importBigNatFromByteArray _ _ 0## _ = zeroBigNat importBigNatFromByteArray ba ofs0 len0 1# = runS $ do -- MSBF W# ofs <- liftIO (c_scan_nzbyte_bytearray ba ofs0 len0) let len = (len0 `plusWord#` ofs0) `minusWord#` ofs importBigNatFromByteArray# ba ofs len 1# importBigNatFromByteArray ba ofs len0 _ = runS $ do -- LSBF W# len <- liftIO (c_rscan_nzbyte_bytearray ba ofs len0) importBigNatFromByteArray# ba ofs len 0# foreign import ccall unsafe "integer_gmp_scan_nzbyte" c_scan_nzbyte_bytearray :: ByteArray# -> Word# -> Word# -> IO Word foreign import ccall unsafe "integer_gmp_rscan_nzbyte" c_rscan_nzbyte_bytearray :: ByteArray# -> Word# -> Word# -> IO Word -- | Helper for 'importBigNatFromByteArray' importBigNatFromByteArray# :: ByteArray# -> Word# -> Word# -> Int# -> S RealWorld BigNat importBigNatFromByteArray# _ _ 0## _ = return zeroBigNat importBigNatFromByteArray# ba ofs len msbf = do mbn@(MBN# mba#) <- newBigNat# n# () <- liftIO (c_mpn_import_bytearray mba# ba ofs len msbf) unsafeFreezeBigNat# mbn where -- n = ceiling(len / SIZEOF_HSWORD), i.e. number of limbs required n# = (word2Int# len +# (SIZEOF_HSWORD# -# 1#)) `quotInt#` SIZEOF_HSWORD# foreign import ccall unsafe "integer_gmp_mpn_import" c_mpn_import_bytearray :: MutableByteArray# RealWorld -> ByteArray# -> Word# -> Word# -> Int# -> IO () -- | Test whether all internal invariants are satisfied by 'BigNat' value -- -- Returns @1#@ if valid, @0#@ otherwise. -- -- This operation is mostly useful for test-suites and/or code which -- constructs 'Integer' values directly. isValidBigNat# :: BigNat -> Int# isValidBigNat# (BN# ba#) = (szq# ># 0#) `andI#` (szr# ==# 0#) `andI#` isNorm# where isNorm# | isTrue# (szq# ># 1#) = (indexWordArray# ba# (szq# -# 1#)) `neWord#` 0## | True = 1# sz# = sizeofByteArray# ba# (# szq#, szr# #) = quotRemInt# sz# GMP_LIMB_BYTES# -- | Version of 'nextPrimeInteger' operating on 'BigNat's -- -- @since 1.0.0.0 nextPrimeBigNat :: BigNat -> BigNat nextPrimeBigNat bn@(BN# ba#) = runS $ do mbn@(MBN# mba#) <- newBigNat# n# (W# c#) <- liftIO (nextPrime# mba# ba# n#) case c# of 0## -> unsafeFreezeBigNat# mbn _ -> unsafeSnocFreezeBigNat# mbn c# where n# = sizeofBigNat# bn foreign import ccall unsafe "integer_gmp_next_prime" nextPrime# :: MutableByteArray# RealWorld -> ByteArray# -> GmpSize# -> IO GmpLimb ---------------------------------------------------------------------------- -- monadic combinators for low-level state threading type S s a = State# s -> (# State# s, a #) infixl 1 >>= infixl 1 >> infixr 0 $ {-# INLINE ($) #-} ($) :: (a -> b) -> a -> b f $ x = f x {-# INLINE (>>=) #-} (>>=) :: S s a -> (a -> S s b) -> S s b (>>=) m k = \s -> case m s of (# s', a #) -> k a s' {-# INLINE (>>) #-} (>>) :: S s a -> S s b -> S s b (>>) m k = \s -> case m s of (# s', _ #) -> k s' {-# INLINE svoid #-} svoid :: (State# s -> State# s) -> S s () svoid m0 = \s -> case m0 s of s' -> (# s', () #) {-# INLINE return #-} return :: a -> S s a return a = \s -> (# s, a #) {-# INLINE liftIO #-} liftIO :: IO a -> S RealWorld a liftIO (IO m) = m -- NB: equivalent of GHC.IO.unsafeDupablePerformIO, see notes there runS :: S RealWorld a -> a runS m = case runRW# m of (# _, a #) -> a -- stupid hack fail :: [Char] -> S s a fail s = return (raise# s) ---------------------------------------------------------------------------- -- | Internal helper type for "signed" 'BigNat's -- -- This is a useful abstraction for operations which support negative -- mp_size_t arguments. data SBigNat = NegBN !BigNat | PosBN !BigNat -- | Absolute value of 'SBigNat' absSBigNat :: SBigNat -> BigNat absSBigNat (NegBN bn) = bn absSBigNat (PosBN bn) = bn -- | /Signed/ limb count. Negative sizes denote negative integers ssizeofSBigNat# :: SBigNat -> GmpSize# ssizeofSBigNat# (NegBN bn) = negateInt# (sizeofBigNat# bn) ssizeofSBigNat# (PosBN bn) = sizeofBigNat# bn -- | Construct 'SBigNat' from 'Int#' value intToSBigNat# :: Int# -> SBigNat intToSBigNat# 0# = PosBN zeroBigNat intToSBigNat# 1# = PosBN oneBigNat intToSBigNat# (-1#) = NegBN oneBigNat intToSBigNat# i# | isTrue# (i# ># 0#) = PosBN (wordToBigNat (int2Word# i#)) | True = PosBN (wordToBigNat (int2Word# (negateInt# i#))) -- | Convert 'Integer' into 'SBigNat' integerToSBigNat :: Integer -> SBigNat integerToSBigNat (S# i#) = intToSBigNat# i# integerToSBigNat (Jp# bn) = PosBN bn integerToSBigNat (Jn# bn) = NegBN bn -- | Convert 'SBigNat' into 'Integer' sBigNatToInteger :: SBigNat -> Integer sBigNatToInteger (NegBN bn) = bigNatToNegInteger bn sBigNatToInteger (PosBN bn) = bigNatToInteger bn ---------------------------------------------------------------------------- -- misc helpers, some of these should rather be primitives exported by ghc-prim cmpW# :: Word# -> Word# -> Ordering cmpW# x# y# | isTrue# (x# `ltWord#` y#) = LT | isTrue# (x# `eqWord#` y#) = EQ | True = GT {-# INLINE cmpW# #-} bitWord# :: Int# -> Word# bitWord# = uncheckedShiftL# 1## {-# INLINE bitWord# #-} testBitWord# :: Word# -> Int# -> Int# testBitWord# w# i# = (bitWord# i# `and#` w#) `neWord#` 0## {-# INLINE testBitWord# #-} popCntI# :: Int# -> Int# popCntI# i# = word2Int# (popCnt# (int2Word# i#)) {-# INLINE popCntI# #-} -- branchless version absI# :: Int# -> Int# absI# i# = (i# `xorI#` nsign) -# nsign where -- nsign = negateInt# (i# <# 0#) nsign = uncheckedIShiftRA# i# (WORD_SIZE_IN_BITS# -# 1#) -- branchless version sgnI# :: Int# -> Int# sgnI# x# = (x# ># 0#) -# (x# <# 0#) cmpI# :: Int# -> Int# -> Int# cmpI# x# y# = (x# ># y#) -# (x# <# y#) minI# :: Int# -> Int# -> Int# minI# x# y# | isTrue# (x# <=# y#) = x# | True = y#
olsner/ghc
libraries/integer-gmp/src/GHC/Integer/Type.hs
bsd-3-clause
75,712
14
19
18,480
22,071
11,070
11,001
-1
-1
-- |A convenience module exporting everything in this library. module Graphics.Vty.Widgets.All ( module Graphics.Vty.Widgets.EventLoop , module Graphics.Vty.Widgets.Core , module Graphics.Vty.Widgets.Box , module Graphics.Vty.Widgets.List , module Graphics.Vty.Widgets.Borders , module Graphics.Vty.Widgets.Text , module Graphics.Vty.Widgets.TextClip , module Graphics.Vty.Widgets.TextZipper , module Graphics.Vty.Widgets.Edit , module Graphics.Vty.Widgets.Util , module Graphics.Vty.Widgets.Table , module Graphics.Vty.Widgets.CheckBox , module Graphics.Vty.Widgets.Padding , module Graphics.Vty.Widgets.Limits , module Graphics.Vty.Widgets.Fixed , module Graphics.Vty.Widgets.Fills , module Graphics.Vty.Widgets.Centering , module Graphics.Vty.Widgets.Skins , module Graphics.Vty.Widgets.Events , module Graphics.Vty.Widgets.Dialog , module Graphics.Vty.Widgets.Button , module Graphics.Vty.Widgets.ProgressBar , module Graphics.Vty.Widgets.DirBrowser , module Graphics.Vty.Widgets.Group , module Graphics.Vty.Widgets.Alignment ) where import Graphics.Vty.Widgets.EventLoop import Graphics.Vty.Widgets.Core import Graphics.Vty.Widgets.Box import Graphics.Vty.Widgets.List import Graphics.Vty.Widgets.Borders import Graphics.Vty.Widgets.Text import Graphics.Vty.Widgets.TextClip import Graphics.Vty.Widgets.TextZipper import Graphics.Vty.Widgets.Edit import Graphics.Vty.Widgets.Util import Graphics.Vty.Widgets.Table import Graphics.Vty.Widgets.CheckBox import Graphics.Vty.Widgets.Padding import Graphics.Vty.Widgets.Limits import Graphics.Vty.Widgets.Fixed import Graphics.Vty.Widgets.Fills import Graphics.Vty.Widgets.Centering import Graphics.Vty.Widgets.Skins import Graphics.Vty.Widgets.Events import Graphics.Vty.Widgets.Dialog import Graphics.Vty.Widgets.Button import Graphics.Vty.Widgets.ProgressBar import Graphics.Vty.Widgets.DirBrowser import Graphics.Vty.Widgets.Group import Graphics.Vty.Widgets.Alignment
KommuSoft/vty-ui
src/Graphics/Vty/Widgets/All.hs
bsd-3-clause
2,028
0
5
243
386
283
103
51
0
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} module Aws.ElasticTranscoder.Commands.GetPipeline ( GetPipeline(..) , GetPipelineResponse(..) ) where import Aws.Core import Aws.ElasticTranscoder.Core import Control.Applicative import qualified Data.Text as T data GetPipeline = GetPipeline { gplPipeline :: PipelineId } deriving (Show,Eq) data GetPipelineResponse = GetPipelineResponse { gprName :: PipelineName , gprInputBucket :: S3Object , gprOutputBucket :: S3Object , gprRole :: IAMRole , gprNotifications :: Notifications , gprId :: PipelineId , gprStatus :: PipelineStatus } deriving (Show,Eq) instance SignQuery GetPipeline where type ServiceConfiguration GetPipeline = EtsConfiguration signQuery GetPipeline{..} = etsSignQuery EtsQuery { etsqMethod = Get , etsqRequest = "pipeline/" `T.append` _PipelineId gplPipeline , etsqQuery = [] , etsqBody = Nothing } instance ResponseConsumer GetPipeline GetPipelineResponse where type ResponseMetadata GetPipelineResponse = EtsMetadata responseConsumer _ mref = etsResponseConsumer mref $ \rsp -> cnv <$> jsonConsumer rsp where cnv (PipelineSingle(PipelineIdStatus a b c d e f g)) = GetPipelineResponse a b c d e f g instance Transaction GetPipeline GetPipelineResponse instance AsMemoryResponse GetPipelineResponse where type MemoryResponse GetPipelineResponse = GetPipelineResponse loadToMemory = return
cdornan/aws-elastic-transcoder
Aws/ElasticTranscoder/Commands/GetPipeline.hs
bsd-3-clause
1,921
0
12
648
341
196
145
43
0
{-# LANGUAGE OverloadedStrings #-} import Routes import Web.Scotty import Database.PostgreSQL.Simple import Data.Pool(Pool, createPool, withResource) newConn :: IO Connection newConn = connect defaultConnectInfo { connectDatabase = "postgres", connectPassword = "iamadminpostgres", connectUser = "postgres", connectPort = 5432, connectHost = "localhost" } main :: IO () main = do pool <- createPool (newConn) close 1 32 16 scotty 3000 (routes pool)
OurPrInstH/InstH
app/Main.hs
bsd-3-clause
546
12
9
155
142
79
63
16
1
{-| Module : Idris.Completion Description : Support for command-line completion at the REPL and in the prover. Copyright : License : BSD3 Maintainer : The Idris Community. -} module Idris.Completion (replCompletion, proverCompletion) where import Idris.Core.Evaluate (ctxtAlist) import Idris.Core.TT import Idris.AbsSyntax (runIO) import Idris.AbsSyntaxTree import Idris.Help import Idris.Imports (installedPackages) import Idris.Colours import Idris.Parser.Helpers(opChars) import qualified Idris.Parser.Expr (constants, tactics) import Idris.Parser.Expr (TacticArg (..)) import Idris.REPL.Parser (allHelp, setOptions) import Control.Monad.State.Strict import Data.List import Data.Maybe import Data.Char(toLower) import System.Console.Haskeline import System.Console.ANSI (Color) commands = [ n | (names, _, _) <- allHelp ++ extraHelp, n <- names ] tacticArgs :: [(String, Maybe TacticArg)] tacticArgs = [ (name, args) | (names, args, _) <- Idris.Parser.Expr.tactics , name <- names ] tactics = map fst tacticArgs -- | Convert a name into a string usable for completion. Filters out names -- that users probably don't want to see. nameString :: Name -> Maybe String nameString (UN n) = Just (str n) nameString (NS n _) = nameString n nameString _ = Nothing -- FIXME: Respect module imports -- Issue #1767 in the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1767 -- | Get the user-visible names from the current interpreter state. names :: Idris [String] names = do i <- get let ctxt = tt_ctxt i return . nub $ mapMaybe (nameString . fst) (ctxtAlist ctxt) ++ "Type" : map fst Idris.Parser.Expr.constants metavars :: Idris [String] metavars = do i <- get return . map (show . nsroot) $ map fst (filter (\(_, (_,_,_,t,_)) -> not t) (idris_metavars i)) \\ primDefs modules :: Idris [String] modules = do i <- get return $ map show $ imported i completeWith :: [String] -> String -> [Completion] completeWith ns n = if uniqueExists then [simpleCompletion n] else map simpleCompletion prefixMatches where prefixMatches = filter (isPrefixOf n) ns uniqueExists = [n] == prefixMatches completeName :: [String] -> String -> Idris [Completion] completeName extra n = do ns <- names return $ completeWith (extra ++ ns) n completeExpr :: [String] -> CompletionFunc Idris completeExpr extra = completeWord Nothing (" \t(){}:" ++ opChars) (completeName extra) completeMetaVar :: CompletionFunc Idris completeMetaVar = completeWord Nothing (" \t(){}:" ++ opChars) completeM where completeM m = do mvs <- metavars return $ completeWith mvs m completeOption :: CompletionFunc Idris completeOption = completeWord Nothing " \t" completeOpt where completeOpt = return . completeWith (map fst setOptions) completeConsoleWidth :: CompletionFunc Idris completeConsoleWidth = completeWord Nothing " \t" completeW where completeW = return . completeWith ["auto", "infinite", "80", "120"] isWhitespace :: Char -> Bool isWhitespace = (flip elem) " \t\n" lookupInHelp :: String -> Maybe CmdArg lookupInHelp cmd = lookupInHelp' cmd allHelp where lookupInHelp' cmd ((cmds, arg, _):xs) | elem cmd cmds = Just arg | otherwise = lookupInHelp' cmd xs lookupInHelp' cmd [] = Nothing completeColour :: CompletionFunc Idris completeColour (prev, next) = case words (reverse prev) of [c] | isCmd c -> do cmpls <- completeColourOpt next return (reverse $ c ++ " ", cmpls) [c, o] | o `elem` opts -> let correct = (c ++ " " ++ o) in return (reverse correct, [simpleCompletion ""]) | o `elem` colourTypes -> completeColourFormat (prev, next) | otherwise -> let cmpls = completeWith (opts ++ colourTypes) o in let sofar = (c ++ " ") in return (reverse sofar, cmpls) cmd@(c:o:_) | isCmd c && o `elem` colourTypes -> completeColourFormat (prev, next) _ -> noCompletion (prev, next) where completeColourOpt :: String -> Idris [Completion] completeColourOpt = return . completeWith (opts ++ colourTypes) opts = ["on", "off"] colourTypes = map (map toLower . reverse . drop 6 . reverse . show) $ enumFromTo (minBound::ColourType) maxBound isCmd ":colour" = True isCmd ":color" = True isCmd _ = False colours = map (map toLower . show) $ enumFromTo (minBound::Color) maxBound formats = ["vivid", "dull", "underline", "nounderline", "bold", "nobold", "italic", "noitalic"] completeColourFormat = let getCmpl = completeWith (colours ++ formats) in completeWord Nothing " \t" (return . getCmpl) -- The FIXMEs are Issue #1768 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1768 -- | Get the completion function for a particular command completeCmd :: String -> CompletionFunc Idris completeCmd cmd (prev, next) = fromMaybe completeCmdName $ fmap completeArg $ lookupInHelp cmd where completeArg FileArg = completeFilename (prev, next) completeArg NameArg = completeExpr [] (prev, next) -- FIXME only complete one name completeArg OptionArg = completeOption (prev, next) completeArg ModuleArg = noCompletion (prev, next) -- FIXME do later completeArg NamespaceArg = noCompletion (prev, next) -- FIXME do later completeArg ExprArg = completeExpr [] (prev, next) completeArg MetaVarArg = completeMetaVar (prev, next) -- FIXME only complete one name completeArg ColourArg = completeColour (prev, next) completeArg NoArg = noCompletion (prev, next) completeArg ConsoleWidthArg = completeConsoleWidth (prev, next) completeArg DeclArg = completeExpr [] (prev, next) completeArg PkgArgs = completePkg (prev, next) completeArg (ManyArgs a) = completeArg a completeArg (OptionalArg a) = completeArg a completeArg (SeqArgs a b) = completeArg a completeArg _ = noCompletion (prev, next) completeCmdName = return ("", completeWith commands cmd) -- | Complete REPL commands and defined identifiers replCompletion :: CompletionFunc Idris replCompletion (prev, next) = case firstWord of ':':cmdName -> completeCmd (':':cmdName) (prev, next) _ -> completeExpr [] (prev, next) where firstWord = fst $ break isWhitespace $ dropWhile isWhitespace $ reverse prev completePkg :: CompletionFunc Idris completePkg = completeWord Nothing " \t()" completeP where completeP p = do pkgs <- runIO installedPackages return $ completeWith pkgs p -- The TODOs are Issue #1769 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1769 completeTactic :: [String] -> String -> CompletionFunc Idris completeTactic as tac (prev, next) = fromMaybe completeTacName . fmap completeArg $ lookup tac tacticArgs where completeTacName = return ("", completeWith tactics tac) completeArg Nothing = noCompletion (prev, next) completeArg (Just NameTArg) = noCompletion (prev, next) -- this is for binding new names! completeArg (Just ExprTArg) = completeExpr as (prev, next) completeArg (Just StringLitTArg) = noCompletion (prev, next) completeArg (Just AltsTArg) = noCompletion (prev, next) -- TODO -- | Complete tactics and their arguments proverCompletion :: [String] -- ^ The names of current local assumptions -> CompletionFunc Idris proverCompletion assumptions (prev, next) = completeTactic assumptions firstWord (prev, next) where firstWord = fst $ break isWhitespace $ dropWhile isWhitespace $ reverse prev
tpsinnem/Idris-dev
src/Idris/Completion.hs
bsd-3-clause
8,477
0
16
2,408
2,296
1,211
1,085
133
16
module AI.SVM.Common where import Data.Char import System.Random.MWC import Control.Applicative import Control.Monad import System.Directory import Control.Exception -- * Utilities randomName = withSystemRandom $ \gen -> map chr <$> replicateM 16 (uniformR (97,122::Int) gen) :: IO String -- | Get a name for a temporary file, run operation with the filename and erase the file if the -- operation creates it. withTmp op = do fp <- getTemporaryDirectory out <- randomName bracket (return ()) (\() -> do e <- doesFileExist out when e (removeFile out)) (\() -> op (fp++"/"++out))
openbrainsrc/Simple-SVM
AI/SVM/Common.hs
bsd-3-clause
745
0
14
253
188
100
88
17
1
{-+ Knot-tying definitions for the base+property syntax to Stratego translation. -} module Prop2Stratego where import BaseStruct2Stratego(transP,transD,transE,showId) import PropStruct2Stratego(transPD,transPA,transPP) import PropSyntax --hiding (D,P,E) -- recursive base+prop syntax import PrettyPrint import SpecialNames import StrategoAST(D,P,E) transPat :: PrintableOp i => HsPatI i -> P transPat (Pat p) = transP showId transPat p transDecs ds = map transDec ds transDec :: (IsSpecialName i,PrintableOp i) => HsDeclI i -> D transDec (Dec d) = prop (transD showId transExp transPat transDecs bad bad bad) (transPD showId transAssertion transPredicate) d --transExp :: HsExp -> E transExp (Exp e) = transE showId transExp transPat transDecs bad bad e transAssertion (PA a) = transPA showId transExp bad transAssertion transPredicate a transPredicate (PP p) = transPP showId transExp transPat bad transAssertion transPredicate p bad x = error "Base2Stratego: not yet"
forste/haReFork
tools/Phugs/Prop2Stratego.hs
bsd-3-clause
1,028
0
7
188
286
150
136
23
1
{-# LANGUAGE TypeSynonymInstances, MultiParamTypeClasses, DeriveDataTypeable, PatternGuards #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.Monitor -- Copyright : (c) Roman Cheplyaka -- License : BSD-style (see LICENSE) -- -- Maintainer : Roman Cheplyaka <[email protected]> -- Stability : unstable -- Portability : unportable -- -- Layout modfier for displaying some window (monitor) above other windows -- ----------------------------------------------------------------------------- module XMonad.Layout.Monitor ( -- * Usage -- $usage -- * Hints and issues -- $hints Monitor(..), monitor, Property(..), MonitorMessage(..), doHideIgnore, manageMonitor -- * TODO -- $todo ) where import XMonad import XMonad.Layout.LayoutModifier import XMonad.Util.WindowProperties import XMonad.Hooks.ManageHelpers (doHideIgnore) import XMonad.Hooks.FadeInactive (setOpacity) import Control.Monad -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.Monitor -- -- Define 'Monitor' record. 'monitor' can be used as a template. At least 'prop' -- and 'rect' should be set here. Also consider setting 'persistent' to True. -- -- Minimal example: -- -- > myMonitor = monitor -- > { prop = ClassName "SomeClass" -- > , rect = Rectangle 0 0 40 20 -- rectangle 40x20 in upper left corner -- > } -- -- More interesting example: -- -- > clock = monitor { -- > -- Cairo-clock creates 2 windows with the same classname, thus also using title -- > prop = ClassName "Cairo-clock" `And` Title "MacSlow's Cairo-Clock" -- > -- rectangle 150x150 in lower right corner, assuming 1280x800 resolution -- > , rect = Rectangle (1280-150) (800-150) 150 150 -- > -- avoid flickering -- > , persistent = True -- > -- make the window transparent -- > , opacity = 0.6 -- > -- hide on start -- > , visible = False -- > -- assign it a name to be able to toggle it independently of others -- > , name = "clock" -- > } -- -- Add ManageHook to de-manage monitor windows and apply opacity settings. -- -- > manageHook = myManageHook <+> manageMonitor clock -- -- Apply layout modifier. -- -- > myLayout = ModifiedLayout clock $ tall ||| Full ||| ... -- -- After that, if there exists a window with specified properties, it will be -- displayed on top of all /tiled/ (not floated) windows on specified -- position. -- -- It's also useful to add some keybinding to toggle monitor visibility: -- -- > , ((mod1Mask, xK_u ), broadcastMessage ToggleMonitor >> refresh) -- -- Screenshot: <http://www.haskell.org/haskellwiki/Image:Xmonad-clock.png> data Monitor a = Monitor { prop :: Property -- ^ property which uniquely identifies monitor window , rect :: Rectangle -- ^ specifies where to put monitor , visible :: Bool -- ^ is it visible by default? , name :: String -- ^ name of monitor (useful when we have many of them) , persistent :: Bool -- ^ is it shown on all layouts? , opacity :: Rational -- ^ opacity level } deriving (Read, Show) -- | Template for 'Monitor' record. At least 'prop' and 'rect' should be -- redefined. Default settings: 'visible' is 'True', 'persistent' is 'False'. monitor :: Monitor a monitor = Monitor { prop = Const False , rect = Rectangle 0 0 0 0 , visible = True , name = "" , persistent = False , opacity = 1 } -- | Messages without names affect all monitors. Messages with names affect only -- monitors whose names match. data MonitorMessage = ToggleMonitor | ShowMonitor | HideMonitor | ToggleMonitorNamed String | ShowMonitorNamed String | HideMonitorNamed String deriving (Read,Show,Eq,Typeable) instance Message MonitorMessage withMonitor :: Property -> a -> (Window -> X a) -> X a withMonitor p a fn = do monitorWindows <- allWithProperty p case monitorWindows of [] -> return a w:_ -> fn w instance LayoutModifier Monitor Window where redoLayout mon _ _ rects = withMonitor (prop mon) (rects, Nothing) $ \w -> if visible mon then do tileWindow w (rect mon) reveal w return ((w,rect mon):rects, Nothing) else do hide w return (rects, Nothing) handleMess mon mess | Just ToggleMonitor <- fromMessage mess = return $ Just $ mon { visible = not $ visible mon } | Just (ToggleMonitorNamed n) <- fromMessage mess = return $ if name mon == n then Just $ mon { visible = not $ visible mon } else Nothing | Just ShowMonitor <- fromMessage mess = return $ Just $ mon { visible = True } | Just (ShowMonitorNamed n) <- fromMessage mess = return $ if name mon == n then Just $ mon { visible = True } else Nothing | Just HideMonitor <- fromMessage mess = return $ Just $ mon { visible = False } | Just (HideMonitorNamed n) <- fromMessage mess = return $ if name mon == n then Just $ mon { visible = False } else Nothing | Just Hide <- fromMessage mess = do unless (persistent mon) $ withMonitor (prop mon) () hide; return Nothing | otherwise = return Nothing -- | ManageHook which demanages monitor window and applies opacity settings. manageMonitor :: Monitor a -> ManageHook manageMonitor mon = propertyToQuery (prop mon) --> do w <- ask liftX $ setOpacity w $ opacity mon if persistent mon then doIgnore else doHideIgnore -- $hints -- - This module assumes that there is only one window satisfying property exists. -- -- - If your monitor is available on /all/ layouts, set -- 'persistent' to 'True' to avoid unnecessary -- flickering. You can still toggle monitor with a keybinding. -- -- - You can use several monitors with nested modifiers. Give them names --- to be able to toggle them independently. -- -- - You can display monitor only on specific workspaces with -- "XMonad.Layout.PerWorkspace". -- $todo -- - make Monitor remember the window it manages -- -- - specify position relative to the screen
markus1189/xmonad-contrib-710
XMonad/Layout/Monitor.hs
bsd-3-clause
6,244
0
15
1,483
992
560
432
67
2
{-# LANGUAGE PatternGuards, OverloadedStrings #-} {- Copyright (C) 2014 Jesse Rosenthal <[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.Readers.Docx Copyright : Copyright (C) 2014 Jesse Rosenthal License : GNU GPL, version 2 or above Maintainer : Jesse Rosenthal <[email protected]> Stability : alpha Portability : portable Conversion of Docx type (defined in Text.Pandoc.Readers.Docx.Parse) to 'Pandoc' document. -} {- Current state of implementation of Docx entities ([x] means implemented, [-] means partially implemented): * Blocks - [X] Para - [X] CodeBlock (styled with `SourceCode`) - [X] BlockQuote (styled with `Quote`, `BlockQuote`, or, optionally, indented) - [X] OrderedList - [X] BulletList - [X] DefinitionList (styled with adjacent `DefinitionTerm` and `Definition`) - [X] Header (styled with `Heading#`) - [ ] HorizontalRule - [-] Table (column widths and alignments not yet implemented) * Inlines - [X] Str - [X] Emph (From italics. `underline` currently read as span. In future, it might optionally be emph as well) - [X] Strong - [X] Strikeout - [X] Superscript - [X] Subscript - [X] SmallCaps - [ ] Quoted - [ ] Cite - [X] Code (styled with `VerbatimChar`) - [X] Space - [X] LineBreak (these are invisible in Word: entered with Shift-Return) - [ ] Math - [X] Link (links to an arbitrary bookmark create a span with the target as id and "anchor" class) - [-] Image (Links to path in archive. Future option for data-encoded URI likely.) - [X] Note (Footnotes and Endnotes are silently combined.) -} module Text.Pandoc.Readers.Docx ( readDocx ) where import Codec.Archive.Zip import Text.Pandoc.Definition import Text.Pandoc.Options import Text.Pandoc.Builder import Text.Pandoc.Walk import Text.Pandoc.Readers.Docx.Parse import Text.Pandoc.Readers.Docx.Lists import Text.Pandoc.Readers.Docx.Reducible import Text.Pandoc.Shared import Text.Pandoc.MediaBag (insertMedia, MediaBag) import Data.List (delete, (\\), intersect) import Data.Monoid import Text.TeXMath (writeTeX) import Data.Default (Default) import qualified Data.ByteString.Lazy as B import qualified Data.Map as M import Control.Monad.Reader import Control.Monad.State import Control.Applicative ((<$>)) import Data.Sequence (ViewL(..), viewl) import qualified Data.Sequence as Seq (null) import Text.Pandoc.Error import Text.Pandoc.Compat.Except readDocx :: ReaderOptions -> B.ByteString -> Either PandocError (Pandoc, MediaBag) readDocx opts bytes = case archiveToDocx (toArchive bytes) of Right docx -> (\(meta, blks, mediaBag) -> (Pandoc meta blks, mediaBag)) <$> (docxToOutput opts docx) Left _ -> Left (ParseFailure "couldn't parse docx file") data DState = DState { docxAnchorMap :: M.Map String String , docxMediaBag :: MediaBag , docxDropCap :: Inlines } instance Default DState where def = DState { docxAnchorMap = M.empty , docxMediaBag = mempty , docxDropCap = mempty } data DEnv = DEnv { docxOptions :: ReaderOptions , docxInHeaderBlock :: Bool } instance Default DEnv where def = DEnv def False type DocxContext = ExceptT PandocError (ReaderT DEnv (State DState)) evalDocxContext :: DocxContext a -> DEnv -> DState -> Either PandocError a evalDocxContext ctx env st = flip evalState st . flip runReaderT env . runExceptT $ ctx -- This is empty, but we put it in for future-proofing. spansToKeep :: [String] spansToKeep = [] divsToKeep :: [String] divsToKeep = ["list-item", "Definition", "DefinitionTerm"] metaStyles :: M.Map String String metaStyles = M.fromList [ ("Title", "title") , ("Subtitle", "subtitle") , ("Author", "author") , ("Date", "date") , ("Abstract", "abstract")] sepBodyParts :: [BodyPart] -> ([BodyPart], [BodyPart]) sepBodyParts = span (\bp -> (isMetaPar bp || isEmptyPar bp)) isMetaPar :: BodyPart -> Bool isMetaPar (Paragraph pPr _) = not $ null $ intersect (pStyle pPr) (M.keys metaStyles) isMetaPar _ = False isEmptyPar :: BodyPart -> Bool isEmptyPar (Paragraph _ parParts) = all isEmptyParPart parParts where isEmptyParPart (PlainRun (Run _ runElems)) = all isEmptyElem runElems isEmptyParPart _ = False isEmptyElem (TextRun s) = trim s == "" isEmptyElem _ = True isEmptyPar _ = False bodyPartsToMeta' :: [BodyPart] -> DocxContext (M.Map String MetaValue) bodyPartsToMeta' [] = return M.empty bodyPartsToMeta' (bp : bps) | (Paragraph pPr parParts) <- bp , (c : _)<- intersect (pStyle pPr) (M.keys metaStyles) , (Just metaField) <- M.lookup c metaStyles = do inlines <- concatReduce <$> mapM parPartToInlines parParts remaining <- bodyPartsToMeta' bps let f (MetaInlines ils) (MetaInlines ils') = MetaBlocks [Para ils, Para ils'] f (MetaInlines ils) (MetaBlocks blks) = MetaBlocks ((Para ils) : blks) f m (MetaList mv) = MetaList (m : mv) f m n = MetaList [m, n] return $ M.insertWith f metaField (MetaInlines (toList inlines)) remaining bodyPartsToMeta' (_ : bps) = bodyPartsToMeta' bps bodyPartsToMeta :: [BodyPart] -> DocxContext Meta bodyPartsToMeta bps = do mp <- bodyPartsToMeta' bps let mp' = case M.lookup "author" mp of Just mv -> M.insert "author" (fixAuthors mv) mp Nothing -> mp return $ Meta mp' fixAuthors :: MetaValue -> MetaValue fixAuthors (MetaBlocks blks) = MetaList $ map g $ filter f blks where f (Para _) = True f _ = False g (Para ils) = MetaInlines ils g _ = MetaInlines [] fixAuthors mv = mv codeStyles :: [String] codeStyles = ["VerbatimChar"] codeDivs :: [String] codeDivs = ["SourceCode"] runElemToInlines :: RunElem -> Inlines runElemToInlines (TextRun s) = text s runElemToInlines (LnBrk) = linebreak runElemToInlines (Tab) = space runElemToString :: RunElem -> String runElemToString (TextRun s) = s runElemToString (LnBrk) = ['\n'] runElemToString (Tab) = ['\t'] runToString :: Run -> String runToString (Run _ runElems) = concatMap runElemToString runElems runToString _ = "" parPartToString :: ParPart -> String parPartToString (PlainRun run) = runToString run parPartToString (InternalHyperLink _ runs) = concatMap runToString runs parPartToString (ExternalHyperLink _ runs) = concatMap runToString runs parPartToString _ = "" blacklistedCharStyles :: [String] blacklistedCharStyles = ["Hyperlink"] resolveDependentRunStyle :: RunStyle -> RunStyle resolveDependentRunStyle rPr | Just (s, _) <- rStyle rPr, s `elem` blacklistedCharStyles = rPr | Just (_, cs) <- rStyle rPr = let rPr' = resolveDependentRunStyle cs in RunStyle { isBold = case isBold rPr of Just bool -> Just bool Nothing -> isBold rPr' , isItalic = case isItalic rPr of Just bool -> Just bool Nothing -> isItalic rPr' , isSmallCaps = case isSmallCaps rPr of Just bool -> Just bool Nothing -> isSmallCaps rPr' , isStrike = case isStrike rPr of Just bool -> Just bool Nothing -> isStrike rPr' , rVertAlign = case rVertAlign rPr of Just valign -> Just valign Nothing -> rVertAlign rPr' , rUnderline = case rUnderline rPr of Just ulstyle -> Just ulstyle Nothing -> rUnderline rPr' , rStyle = rStyle rPr } | otherwise = rPr runStyleToTransform :: RunStyle -> (Inlines -> Inlines) runStyleToTransform rPr | Just (s, _) <- rStyle rPr , s `elem` spansToKeep = let rPr' = rPr{rStyle = Nothing} in (spanWith ("", [s], [])) . (runStyleToTransform rPr') | Just True <- isItalic rPr = emph . (runStyleToTransform rPr {isItalic = Nothing}) | Just True <- isBold rPr = strong . (runStyleToTransform rPr {isBold = Nothing}) | Just True <- isSmallCaps rPr = smallcaps . (runStyleToTransform rPr {isSmallCaps = Nothing}) | Just True <- isStrike rPr = strikeout . (runStyleToTransform rPr {isStrike = Nothing}) | Just SupScrpt <- rVertAlign rPr = superscript . (runStyleToTransform rPr {rVertAlign = Nothing}) | Just SubScrpt <- rVertAlign rPr = subscript . (runStyleToTransform rPr {rVertAlign = Nothing}) | Just "single" <- rUnderline rPr = emph . (runStyleToTransform rPr {rUnderline = Nothing}) | otherwise = id runToInlines :: Run -> DocxContext Inlines runToInlines (Run rs runElems) | Just (s, _) <- rStyle rs , s `elem` codeStyles = let rPr = resolveDependentRunStyle rs codeString = code $ concatMap runElemToString runElems in return $ case rVertAlign rPr of Just SupScrpt -> superscript codeString Just SubScrpt -> subscript codeString _ -> codeString | otherwise = do let ils = concatReduce (map runElemToInlines runElems) return $ (runStyleToTransform $ resolveDependentRunStyle rs) ils runToInlines (Footnote bps) = do blksList <- concatReduce <$> (mapM bodyPartToBlocks bps) return $ note blksList runToInlines (Endnote bps) = do blksList <- concatReduce <$> (mapM bodyPartToBlocks bps) return $ note blksList runToInlines (InlineDrawing fp bs) = do mediaBag <- gets docxMediaBag modify $ \s -> s { docxMediaBag = insertMedia fp Nothing bs mediaBag } return $ image fp "" "" parPartToInlines :: ParPart -> DocxContext Inlines parPartToInlines (PlainRun r) = runToInlines r parPartToInlines (Insertion _ author date runs) = do opts <- asks docxOptions case readerTrackChanges opts of AcceptChanges -> concatReduce <$> mapM runToInlines runs RejectChanges -> return mempty AllChanges -> do ils <- concatReduce <$> mapM runToInlines runs let attr = ("", ["insertion"], [("author", author), ("date", date)]) return $ spanWith attr ils parPartToInlines (Deletion _ author date runs) = do opts <- asks docxOptions case readerTrackChanges opts of AcceptChanges -> return mempty RejectChanges -> concatReduce <$> mapM runToInlines runs AllChanges -> do ils <- concatReduce <$> mapM runToInlines runs let attr = ("", ["deletion"], [("author", author), ("date", date)]) return $ spanWith attr ils parPartToInlines (BookMark _ anchor) | anchor `elem` dummyAnchors = return mempty parPartToInlines (BookMark _ anchor) = -- We record these, so we can make sure not to overwrite -- user-defined anchor links with header auto ids. do -- get whether we're in a header. inHdrBool <- asks docxInHeaderBlock -- Get the anchor map. anchorMap <- gets docxAnchorMap -- We don't want to rewrite if we're in a header, since we'll take -- care of that later, when we make the header anchor. If the -- bookmark were already in uniqueIdent form, this would lead to a -- duplication. Otherwise, we check to see if the id is already in -- there. Rewrite if necessary. This will have the possible effect -- of rewriting user-defined anchor links. However, since these -- are not defined in pandoc, it seems like a necessary evil to -- avoid an extra pass. let newAnchor = if not inHdrBool && anchor `elem` (M.elems anchorMap) then uniqueIdent [Str anchor] (M.elems anchorMap) else anchor unless inHdrBool (modify $ \s -> s { docxAnchorMap = M.insert anchor newAnchor anchorMap}) return $ spanWith (newAnchor, ["anchor"], []) mempty parPartToInlines (Drawing fp bs) = do mediaBag <- gets docxMediaBag modify $ \s -> s { docxMediaBag = insertMedia fp Nothing bs mediaBag } return $ image fp "" "" parPartToInlines (InternalHyperLink anchor runs) = do ils <- concatReduce <$> mapM runToInlines runs return $ link ('#' : anchor) "" ils parPartToInlines (ExternalHyperLink target runs) = do ils <- concatReduce <$> mapM runToInlines runs return $ link target "" ils parPartToInlines (PlainOMath exps) = do return $ math $ writeTeX exps isAnchorSpan :: Inline -> Bool isAnchorSpan (Span (_, classes, kvs) ils) = classes == ["anchor"] && null kvs && null ils isAnchorSpan _ = False dummyAnchors :: [String] dummyAnchors = ["_GoBack"] makeHeaderAnchor :: Blocks -> DocxContext Blocks makeHeaderAnchor bs = case viewl $ unMany bs of (x :< xs) -> do x' <- (makeHeaderAnchor' x) xs' <- (makeHeaderAnchor $ Many xs) return $ (singleton x') <> xs' EmptyL -> return mempty makeHeaderAnchor' :: Block -> DocxContext Block -- If there is an anchor already there (an anchor span in the header, -- to be exact), we rename and associate the new id with the old one. makeHeaderAnchor' (Header n (_, classes, kvs) ils) | (c:cs) <- filter isAnchorSpan ils , (Span (ident, ["anchor"], _) _) <- c = do hdrIDMap <- gets docxAnchorMap let newIdent = uniqueIdent ils (M.elems hdrIDMap) modify $ \s -> s {docxAnchorMap = M.insert ident newIdent hdrIDMap} return $ Header n (newIdent, classes, kvs) (ils \\ (c:cs)) -- Otherwise we just give it a name, and register that name (associate -- it with itself.) makeHeaderAnchor' (Header n (_, classes, kvs) ils) = do hdrIDMap <- gets docxAnchorMap let newIdent = uniqueIdent ils (M.elems hdrIDMap) modify $ \s -> s {docxAnchorMap = M.insert newIdent newIdent hdrIDMap} return $ Header n (newIdent, classes, kvs) ils makeHeaderAnchor' blk = return blk -- Rewrite a standalone paragraph block as a plain singleParaToPlain :: Blocks -> Blocks singleParaToPlain blks | (Para (ils) :< seeq) <- viewl $ unMany blks , Seq.null seeq = singleton $ Plain ils singleParaToPlain blks = blks cellToBlocks :: Cell -> DocxContext Blocks cellToBlocks (Cell bps) = do blks <- concatReduce <$> mapM bodyPartToBlocks bps return $ fromList $ blocksToDefinitions $ blocksToBullets $ toList blks rowToBlocksList :: Row -> DocxContext [Blocks] rowToBlocksList (Row cells) = do blksList <- mapM cellToBlocks cells return $ map singleParaToPlain blksList trimLineBreaks :: [Inline] -> [Inline] trimLineBreaks [] = [] trimLineBreaks (LineBreak : ils) = trimLineBreaks ils trimLineBreaks ils | (LineBreak : ils') <- reverse ils = trimLineBreaks (reverse ils') trimLineBreaks ils = ils parStyleToTransform :: ParagraphStyle -> (Blocks -> Blocks) parStyleToTransform pPr | (c:cs) <- pStyle pPr , c `elem` divsToKeep = let pPr' = pPr { pStyle = cs } in (divWith ("", [c], [])) . (parStyleToTransform pPr') | (c:cs) <- pStyle pPr, c `elem` listParagraphDivs = let pPr' = pPr { pStyle = cs, indentation = Nothing} in (divWith ("", [c], [])) . (parStyleToTransform pPr') | (_:cs) <- pStyle pPr , Just True <- pBlockQuote pPr = let pPr' = pPr { pStyle = cs } in blockQuote . (parStyleToTransform pPr') | (_:cs) <- pStyle pPr = let pPr' = pPr { pStyle = cs} in parStyleToTransform pPr' | null (pStyle pPr) , Just left <- indentation pPr >>= leftParIndent , Just hang <- indentation pPr >>= hangingParIndent = let pPr' = pPr { indentation = Nothing } in case (left - hang) > 0 of True -> blockQuote . (parStyleToTransform pPr') False -> parStyleToTransform pPr' | null (pStyle pPr), Just left <- indentation pPr >>= leftParIndent = let pPr' = pPr { indentation = Nothing } in case left > 0 of True -> blockQuote . (parStyleToTransform pPr') False -> parStyleToTransform pPr' parStyleToTransform _ = id bodyPartToBlocks :: BodyPart -> DocxContext Blocks bodyPartToBlocks (Paragraph pPr parparts) | not $ null $ codeDivs `intersect` (pStyle pPr) = return $ parStyleToTransform pPr $ codeBlock $ concatMap parPartToString parparts | Just (style, n) <- pHeading pPr = do ils <- local (\s-> s{docxInHeaderBlock=True}) $ (concatReduce <$> mapM parPartToInlines parparts) makeHeaderAnchor $ headerWith ("", delete style (pStyle pPr), []) n ils | otherwise = do ils <- concatReduce <$> mapM parPartToInlines parparts >>= (return . fromList . trimLineBreaks . normalizeSpaces . toList) dropIls <- gets docxDropCap let ils' = dropIls <> ils if dropCap pPr then do modify $ \s -> s { docxDropCap = ils' } return mempty else do modify $ \s -> s { docxDropCap = mempty } return $ case isNull ils' of True -> mempty _ -> parStyleToTransform pPr $ para ils' bodyPartToBlocks (ListItem pPr numId lvl levelInfo parparts) = do let kvs = case levelInfo of (_, fmt, txt, Just start) -> [ ("level", lvl) , ("num-id", numId) , ("format", fmt) , ("text", txt) , ("start", (show start)) ] (_, fmt, txt, Nothing) -> [ ("level", lvl) , ("num-id", numId) , ("format", fmt) , ("text", txt) ] blks <- bodyPartToBlocks (Paragraph pPr parparts) return $ divWith ("", ["list-item"], kvs) blks bodyPartToBlocks (Tbl _ _ _ []) = return $ para mempty bodyPartToBlocks (Tbl cap _ look (r:rs)) = do let caption = text cap (hdr, rows) = case firstRowFormatting look of True -> (Just r, rs) False -> (Nothing, r:rs) hdrCells <- case hdr of Just r' -> rowToBlocksList r' Nothing -> return [] cells <- mapM rowToBlocksList rows let size = case null hdrCells of True -> length $ head cells False -> length $ hdrCells -- -- The two following variables (horizontal column alignment and -- relative column widths) go to the default at the -- moment. Width information is in the TblGrid field of the Tbl, -- so should be possible. Alignment might be more difficult, -- since there doesn't seem to be a column entity in docx. alignments = replicate size AlignDefault widths = replicate size 0 :: [Double] return $ table caption (zip alignments widths) hdrCells cells bodyPartToBlocks (OMathPara e) = do return $ para $ displayMath (writeTeX e) -- replace targets with generated anchors. rewriteLink' :: Inline -> DocxContext Inline rewriteLink' l@(Link ils ('#':target, title)) = do anchorMap <- gets docxAnchorMap return $ case M.lookup target anchorMap of Just newTarget -> (Link ils ('#':newTarget, title)) Nothing -> l rewriteLink' il = return il rewriteLinks :: [Block] -> DocxContext [Block] rewriteLinks = mapM (walkM rewriteLink') bodyToOutput :: Body -> DocxContext (Meta, [Block], MediaBag) bodyToOutput (Body bps) = do let (metabps, blkbps) = sepBodyParts bps meta <- bodyPartsToMeta metabps blks <- concatReduce <$> mapM bodyPartToBlocks blkbps blks' <- rewriteLinks $ blocksToDefinitions $ blocksToBullets $ toList blks mediaBag <- gets docxMediaBag return $ (meta, blks', mediaBag) docxToOutput :: ReaderOptions -> Docx -> Either PandocError (Meta, [Block], MediaBag) docxToOutput opts (Docx (Document _ body)) = let dEnv = def { docxOptions = opts} in evalDocxContext (bodyToOutput body) dEnv def
gbataille/pandoc
src/Text/Pandoc/Readers/Docx.hs
gpl-2.0
20,401
0
17
5,120
5,830
2,974
2,856
401
7
{-# LANGUAGE RankNTypes #-} module ShouldFail where bar :: Num (forall a. a) => Int -> Int bar = error "urk"
shlevy/ghc
testsuite/tests/typecheck/should_fail/tcfail196.hs
bsd-3-clause
112
0
8
24
37
21
16
-1
-1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} -- | This module provides various simple ways to query and manipulate -- fundamental Futhark terms, such as types and values. The intent is to -- keep "Futhark.IRrsentation.AST.Syntax" simple, and put whatever -- embellishments we need here. This is an internal, desugared -- representation. module Futhark.IR.Prop ( module Futhark.IR.Prop.Reshape, module Futhark.IR.Prop.Rearrange, module Futhark.IR.Prop.Types, module Futhark.IR.Prop.Constants, module Futhark.IR.Prop.TypeOf, module Futhark.IR.Prop.Patterns, module Futhark.IR.Prop.Names, module Futhark.IR.RetType, -- * Built-in functions isBuiltInFunction, builtInFunctions, -- * Extra tools asBasicOp, safeExp, subExpVars, subExpVar, commutativeLambda, entryPointSize, defAux, stmCerts, certify, expExtTypesFromPat, attrsForAssert, lamIsBinOp, ASTConstraints, IsOp (..), ASTRep (..), ) where import Control.Monad import Data.List (elemIndex, find) import qualified Data.Map.Strict as M import Data.Maybe (isJust, mapMaybe) import qualified Data.Set as S import Futhark.IR.Pretty import Futhark.IR.Prop.Constants import Futhark.IR.Prop.Names import Futhark.IR.Prop.Patterns import Futhark.IR.Prop.Rearrange import Futhark.IR.Prop.Reshape import Futhark.IR.Prop.TypeOf import Futhark.IR.Prop.Types import Futhark.IR.RetType import Futhark.IR.Syntax import Futhark.Transform.Rename (Rename, Renameable) import Futhark.Transform.Substitute (Substitutable, Substitute) import Futhark.Util (maybeNth) import Futhark.Util.Pretty -- | @isBuiltInFunction k@ is 'True' if @k@ is an element of 'builtInFunctions'. isBuiltInFunction :: Name -> Bool isBuiltInFunction fnm = fnm `M.member` builtInFunctions -- | A map of all built-in functions and their types. builtInFunctions :: M.Map Name (PrimType, [PrimType]) builtInFunctions = M.fromList $ map namify $ M.toList primFuns where namify (k, (paramts, ret, _)) = (nameFromString k, (ret, paramts)) -- | If the expression is a t'BasicOp', return it, otherwise 'Nothing'. asBasicOp :: Exp rep -> Maybe BasicOp asBasicOp (BasicOp op) = Just op asBasicOp _ = Nothing -- | An expression is safe if it is always well-defined (assuming that -- any required certificates have been checked) in any context. For -- example, array indexing is not safe, as the index may be out of -- bounds. On the other hand, adding two numbers cannot fail. safeExp :: IsOp (Op rep) => Exp rep -> Bool safeExp (BasicOp op) = safeBasicOp op where safeBasicOp (BinOp (SDiv _ Safe) _ _) = True safeBasicOp (BinOp (SDivUp _ Safe) _ _) = True safeBasicOp (BinOp (SQuot _ Safe) _ _) = True safeBasicOp (BinOp (UDiv _ Safe) _ _) = True safeBasicOp (BinOp (UDivUp _ Safe) _ _) = True safeBasicOp (BinOp (SMod _ Safe) _ _) = True safeBasicOp (BinOp (SRem _ Safe) _ _) = True safeBasicOp (BinOp (UMod _ Safe) _ _) = True safeBasicOp (BinOp SDiv {} _ (Constant y)) = not $ zeroIsh y safeBasicOp (BinOp SDiv {} _ _) = False safeBasicOp (BinOp SDivUp {} _ (Constant y)) = not $ zeroIsh y safeBasicOp (BinOp SDivUp {} _ _) = False safeBasicOp (BinOp UDiv {} _ (Constant y)) = not $ zeroIsh y safeBasicOp (BinOp UDiv {} _ _) = False safeBasicOp (BinOp UDivUp {} _ (Constant y)) = not $ zeroIsh y safeBasicOp (BinOp UDivUp {} _ _) = False safeBasicOp (BinOp SMod {} _ (Constant y)) = not $ zeroIsh y safeBasicOp (BinOp SMod {} _ _) = False safeBasicOp (BinOp UMod {} _ (Constant y)) = not $ zeroIsh y safeBasicOp (BinOp UMod {} _ _) = False safeBasicOp (BinOp SQuot {} _ (Constant y)) = not $ zeroIsh y safeBasicOp (BinOp SQuot {} _ _) = False safeBasicOp (BinOp SRem {} _ (Constant y)) = not $ zeroIsh y safeBasicOp (BinOp SRem {} _ _) = False safeBasicOp (BinOp Pow {} _ (Constant y)) = not $ negativeIsh y safeBasicOp (BinOp Pow {} _ _) = False safeBasicOp ArrayLit {} = True safeBasicOp BinOp {} = True safeBasicOp SubExp {} = True safeBasicOp UnOp {} = True safeBasicOp CmpOp {} = True safeBasicOp ConvOp {} = True safeBasicOp Scratch {} = True safeBasicOp Concat {} = True safeBasicOp Reshape {} = True safeBasicOp Rearrange {} = True safeBasicOp Manifest {} = True safeBasicOp Iota {} = True safeBasicOp Replicate {} = True safeBasicOp Copy {} = True safeBasicOp _ = False safeExp (DoLoop _ _ body) = safeBody body safeExp (Apply fname _ _ _) = isBuiltInFunction fname safeExp (If _ tbranch fbranch _) = all (safeExp . stmExp) (bodyStms tbranch) && all (safeExp . stmExp) (bodyStms fbranch) safeExp WithAcc {} = True -- Although unlikely to matter. safeExp (Op op) = safeOp op safeBody :: IsOp (Op rep) => Body rep -> Bool safeBody = all (safeExp . stmExp) . bodyStms -- | Return the variable names used in 'Var' subexpressions. May contain -- duplicates. subExpVars :: [SubExp] -> [VName] subExpVars = mapMaybe subExpVar -- | If the t'SubExp' is a 'Var' return the variable name. subExpVar :: SubExp -> Maybe VName subExpVar (Var v) = Just v subExpVar Constant {} = Nothing -- | Does the given lambda represent a known commutative function? -- Based on pattern matching and checking whether the lambda -- represents a known arithmetic operator; don't expect anything -- clever here. commutativeLambda :: Lambda rep -> Bool commutativeLambda lam = let body = lambdaBody lam n2 = length (lambdaParams lam) `div` 2 (xps, yps) = splitAt n2 (lambdaParams lam) okComponent c = isJust $ find (okBinOp c) $ bodyStms body okBinOp (xp, yp, SubExpRes _ (Var r)) (Let (Pat [pe]) _ (BasicOp (BinOp op (Var x) (Var y)))) = patElemName pe == r && commutativeBinOp op && ( (x == paramName xp && y == paramName yp) || (y == paramName xp && x == paramName yp) ) okBinOp _ _ = False in n2 * 2 == length (lambdaParams lam) && n2 == length (bodyResult body) && all okComponent (zip3 xps yps $ bodyResult body) -- | How many value parameters are accepted by this entry point? This -- is used to determine which of the function parameters correspond to -- the parameters of the original function (they must all come at the -- end). entryPointSize :: EntryPointType -> Int entryPointSize (TypeOpaque _ _ x) = x entryPointSize (TypeUnsigned _) = 1 entryPointSize (TypeDirect _) = 1 -- | A 'StmAux' with empty 'Certs'. defAux :: dec -> StmAux dec defAux = StmAux mempty mempty -- | The certificates associated with a statement. stmCerts :: Stm rep -> Certs stmCerts = stmAuxCerts . stmAux -- | Add certificates to a statement. certify :: Certs -> Stm rep -> Stm rep certify cs1 (Let pat (StmAux cs2 attrs dec) e) = Let pat (StmAux (cs2 <> cs1) attrs dec) e -- | A handy shorthand for properties that we usually want to things -- we stuff into ASTs. type ASTConstraints a = (Eq a, Ord a, Show a, Rename a, Substitute a, FreeIn a, Pretty a) -- | A type class for operations. class (ASTConstraints op, TypedOp op) => IsOp op where -- | Like 'safeExp', but for arbitrary ops. safeOp :: op -> Bool -- | Should we try to hoist this out of branches? cheapOp :: op -> Bool instance IsOp () where safeOp () = True cheapOp () = True -- | Representation-specific attributes; also means the rep supports -- some basic facilities. class ( RepTypes rep, PrettyRep rep, Renameable rep, Substitutable rep, FreeDec (ExpDec rep), FreeIn (LetDec rep), FreeDec (BodyDec rep), FreeIn (FParamInfo rep), FreeIn (LParamInfo rep), FreeIn (RetType rep), FreeIn (BranchType rep), IsOp (Op rep) ) => ASTRep rep where -- | Given a pattern, construct the type of a body that would match -- it. An implementation for many representations would be -- 'expExtTypesFromPat'. expTypesFromPat :: (HasScope rep m, Monad m) => Pat (LetDec rep) -> m [BranchType rep] -- | Construct the type of an expression that would match the pattern. expExtTypesFromPat :: Typed dec => Pat dec -> [ExtType] expExtTypesFromPat pat = existentialiseExtTypes (patNames pat) $ staticShapes $ map patElemType $ patElems pat -- | Keep only those attributes that are relevant for 'Assert' -- expressions. attrsForAssert :: Attrs -> Attrs attrsForAssert (Attrs attrs) = Attrs $ S.filter attrForAssert attrs where attrForAssert = (== AttrComp "warn" ["safety_checks"]) -- | Horizontally fission a lambda that models a binary operator. lamIsBinOp :: ASTRep rep => Lambda rep -> Maybe [(BinOp, PrimType, VName, VName)] lamIsBinOp lam = mapM splitStm $ bodyResult $ lambdaBody lam where n = length $ lambdaReturnType lam splitStm (SubExpRes cs (Var res)) = do guard $ cs == mempty Let (Pat [pe]) _ (BasicOp (BinOp op (Var x) (Var y))) <- find (([res] ==) . patNames . stmPat) $ stmsToList $ bodyStms $ lambdaBody lam i <- Var res `elemIndex` map resSubExp (bodyResult (lambdaBody lam)) xp <- maybeNth i $ lambdaParams lam yp <- maybeNth (n + i) $ lambdaParams lam guard $ paramName xp == x guard $ paramName yp == y Prim t <- Just $ patElemType pe return (op, t, paramName xp, paramName yp) splitStm _ = Nothing
diku-dk/futhark
src/Futhark/IR/Prop.hs
isc
9,490
0
18
2,085
2,909
1,528
1,381
194
41
{-# LANGUAGE BangPatterns #-} module Stage.Boundary (setBoundary) where import Model import Data.Array.Repa as R import Control.Monad import Debug.Trace import Config import FieldElt -- | Apply boundary conditions to a velocity field. setBoundary :: Config -> VelocityField -> IO VelocityField setBoundary config f = let (width, _) = configModelSize config in (rebuild width f <=< setBoundary' width <=< grabBorders width) f -- | Takes the original VelocityField and the array of edges and replaces -- edge values with new values rebuild :: Int -> VelocityField -> VelocityField -> IO VelocityField rebuild width field edges = field `deepSeqArray` edges `deepSeqArray` do computeUnboxedP $ backpermuteDft field (rebuildPosMap width) edges {-# INLINE rebuild #-} rebuildPosMap :: Int -> DIM2 -> Maybe DIM2 rebuildPosMap !width (Z:.j:.i) | j == 0 = Just (Z:.0:.i) | j == width - 1 = Just (Z:.1:.i) | i == 0 = if j == 0 then Just (Z:. 0 :. 0) else if j == end then Just (Z:. 1 :. 0) else Just (Z:. 2 :. j) | i == width - 1 = if j == 0 then Just (Z:. 0 :. (width-1)) else if j == end then Just (Z:. 1 :. (width-1)) else Just (Z:. 3 :. j) | otherwise = Nothing where end = width - 1 {-# INLINE rebuildPosMap #-} -- | Grabs the border elements of the VelocityField and outputs them as -- one array, for ease of adding back into the original VelocityField later grabBorders :: Int -> VelocityField -> IO VelocityField grabBorders width f = f `deepSeqArray` do traceEventIO "Fluid: grabBorders" computeUnboxedP $ backpermute (Z:. 4 :. width) (edgeCases width) f {-# INLINE grabBorders #-} -- | Map a position in the edges array to what they were in the original -- array. edgeCases :: Int -> DIM2 -> DIM2 edgeCases width (Z:.j:.i) | j == 0 = (Z:.0 :.i) | j == 1 = (Z:.(width-1) :.i) | j == 2 = (Z:.i :.0) | j == 3 = (Z:.i :.(width-1)) | otherwise = error "Incorrect coordinate given in setBoundary" {-# INLINE edgeCases #-} setBoundary' :: Int -> VelocityField -> IO VelocityField setBoundary' width e = e `deepSeqArray` do traceEventIO "Fluid: setBoundary'" computeUnboxedP $ traverse e id (revBoundary width) {-# INLINE setBoundary' #-} -- | Based on position in edges array set the velocity accordingly revBoundary :: Int -> (DIM2 -> (Float,Float)) -> DIM2 -> (Float,Float) revBoundary width loc pos@(Z:.j:.i) | j == 0 = if i == 0 then grabCornerCase loc (Z:.2:.1) (Z:.0:.1) else if i == end then grabCornerCase loc (Z:.0:.(width-2)) (Z:.3:.1) else (-p1,p2) | j == 1 = if i == 0 then grabCornerCase loc (Z:.2:.(width-2)) (Z:.1:.1) else if i == end then grabCornerCase loc (Z:.1:.(width-2)) (Z:.3:.(width-2)) else (-p1,p2) | j == 2 = (p1,-p2) | j == 3 = (p1,-p2) | otherwise = error "Fluid: revBoundary" where (p1,p2) = loc pos end = width - 1 {-# INLINE revBoundary #-} -- | Corner cases are special and are calculated with this function grabCornerCase :: (DIM2 -> (Float, Float)) -> DIM2 -> DIM2 -> (Float, Float) grabCornerCase loc pos1 pos2 = (p1 * q1, p2 * q2) ~*~ 0.5 where (p1,p2) = loc pos1 (q1,q2) = loc pos2 {-# INLINE grabCornerCase #-}
gscalzo/HaskellTheHardWay
gloss-try/gloss-master/gloss-examples/raster/Fluid/src-repa/Stage/Boundary.hs
mit
3,628
0
12
1,121
1,231
649
582
77
5
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TypeFamilies #-} module Widgets.Tabs.Services ( panelServices ) where import Reflex.Dom import Commons import Widgets.Generation -- TODO: Add functionality to Panel Services panelServices :: ( Reflex t , DomBuilder t m , DomBuilderSpace m ~ GhcjsDomSpace , MonadIO m ) => m () panelServices = do el "div" $ do text "Select a remote service to run" void $ makeElementFromHtml def $(-- do -- qcss -- [cassius| -- .spKey -- padding: 2px -- text-align: right -- .spVal -- padding: 2px -- |] qhtml [hamlet| <table style="width: 95%"> <tr> <td style="width: 5%"> <a.btn.btn-flat.btn-red.waves-attach title="Refresh list of available services"> <span.icon.icon-lg>refresh <td style="width: 95%"> <select.form-control> |] ) elAttr "div" attrs $ el "table" blank -- TODO: For service parameters. where attrs = ("class" =: "form-group") <> ("id" =: "guiServiceParams")
achirkin/qua-view
src/Widgets/Tabs/Services.hs
mit
1,424
0
14
594
170
95
75
24
1
{-| Special Data Types used in the Game |-} module Types where -------------------------------------------------- import qualified Data.Set as S import Prelude hiding (Either (..)) import Coord -------------------------------------------------- {- Environment -} data Level = Level { lRank :: Int , lMoves :: Int , lStart :: Coord , lMax :: Coord , lWalls :: S.Set Coord , lGoals :: S.Set Coord , lBlocks :: S.Set Coord } data World = World { wRank :: Int , wPlayer :: Coord , wLevel :: Level , wLevels :: [Level] } {- Control Data -} data Input = Dir Direction | Exit data Direction = Up | Down | Left | Right -- | Convert a Direction to a Coordinate assuming -- a top left origin coordinate system. dirToCoord :: Direction -> Coord dirToCoord d = case d of Up -> Coord 0 (-1) Down -> Coord 0 1 Left -> Coord (-1) 0 Right -> Coord 1 0 -- Define some default data structures for convenience -- -- | Empty Level. emptyLevel = Level { lRank = 0 , lMoves = 0 , lStart = Coord 0 0 , lMax = Coord 0 0 , lWalls = S.empty , lGoals = S.empty , lBlocks = S.empty } -- | Empty World. emptyWorld = World { wRank = 0 , wPlayer = Coord 0 0 , wLevel = emptyLevel , wLevels = [emptyLevel] }
stuhacking/Sokoban
src/Types.hs
mit
1,695
0
10
748
347
209
138
38
4
module Main where import Dib import Dib.Builders.C import Dib.Target import Data.Maybe import Data.Monoid import qualified Data.List as L import qualified Data.Text as T data Configuration = Configuration { platform :: T.Text, buildType :: T.Text, exeExt :: T.Text, soExt :: T.Text, sanitizerFlags :: T.Text, buildFlags :: T.Text } mingw32Config = defaultGXXConfig { compiler = "x86_64-w64-mingw32-gcc", linker = "x86_64-w64-mingw32-g++ ", archiver = "i86_64-w64-mingw32-ar" } -- liblaminaFS targets liblaminaFSInfo config = (getCompiler $ platform config) { outputName = "liblaminaFS" <> soExt config, targetName = "laminaFS-" <> platform config <> "-" <> buildType config, srcDir = "src", commonCompileFlags = "-Wall -Wextra -Werror -fPIC " <> buildFlags config <> sanitizerFlags config, cCompileFlags = "--std=c11", cxxCompileFlags = "--std=c++17 -Wold-style-cast", linkFlags = "-shared -lpthread" <> sanitizerFlags config, outputLocation = ObjAndBinDirs ("obj/" <> platform config <> "-" <> buildType config) ("lib/" <> platform config <> "-" <> buildType config), includeDirs = ["src"] } liblaminaFS config = makeCTarget $ liblaminaFSInfo config cleanLamina config = makeCleanTarget $ liblaminaFSInfo config -- Test targets testsInfo config = (getCompiler $ platform config) { outputName = "test" <> exeExt config, targetName = "tests-" <> platform config <> "-" <> buildType config, srcDir = "tests", commonCompileFlags = "-Wall -Wextra -Werror " <> buildFlags config <> sanitizerFlags config, cCompileFlags = "--std=c11", cxxCompileFlags = "--std=c++17 -Wold-style-cast", linkFlags = "-L./lib/" <> platform config <> "-" <> buildType config <> " -llaminaFS -lstdc++ -lpthread" <> sanitizerFlags config, extraLinkDeps = ["lib/" <> platform config <> "-" <> buildType config <> "/liblaminaFS" <> soExt config], outputLocation = ObjAndBinDirs ("obj/" <> platform config <> "-" <> buildType config) ("bin/" <> platform config <> "-" <> buildType config), includeDirs = ["src", "tests"] } tests config = addDependency (makeCTarget $ testsInfo config) $ liblaminaFS config cleanTests config = makeCleanTarget $ testsInfo config -- Targets allTarget config = makePhonyTarget "all" [liblaminaFS config, tests config] targets config = [allTarget config, liblaminaFS config, cleanLamina config, tests config, cleanTests config] -- Configuration related functions getBuildPlatform d = handleArgResult $ makeArgDictLookupFuncChecked "PLATFORM" "local" ["local", "mingw32"] d getSanitizer d = handleArgResult $ makeArgDictLookupFuncChecked "SANITIZER" "" (map fst sanitizerMap) d getBuildType d = handleArgResult $ makeArgDictLookupFuncChecked "BUILD" "release" (map fst buildTypeMap) d getCompiler platform = if platform == "mingw32" then mingw32Config else defaultGXXConfig findInMap m s = snd.fromJust $ L.find (\(k, v) -> k == s) m sanitizerMap = [ ("undefined", " -fsanitize=undefined"), ("address", " -fsanitize=address"), ("thread", " -fsanitize=thread"), ("", "")] sanitizerToFlags = findInMap sanitizerMap buildTypeMap = [ ("debug", "-g "), ("release", "-g -O2 "), ("release-min", "-O2 ")] buildTypeToFlags = findInMap buildTypeMap handleArgResult (Left e) = error e handleArgResult (Right v) = v main = do argDict <- getArgDict let platform = T.pack $ getBuildPlatform argDict let buildType = getBuildType argDict let configuration = Configuration { platform = platform, buildType = T.pack buildType, exeExt = if platform == "mingw32" then ".exe" else "", soExt = if platform == "mingw32" then ".dll" else ".so", sanitizerFlags = sanitizerToFlags $ getSanitizer argDict, buildFlags = buildTypeToFlags buildType } dib $ targets configuration
blajzer/laminaFS
dib.hs
mit
3,781
0
13
623
1,073
579
494
76
3
module Huffman (encode, decode) where import qualified LHeap as L import qualified Data.Map as M type Code = [Char] data HT = Node Int HT HT | Leaf Char Int deriving (Show) instance Eq HT where (==) h1 h2 = frequency h1 == frequency h2 instance Ord HT where compare h1 h2 = compare (frequency h1) (frequency h2) frequency :: HT -> Int frequency (Leaf _ i) = i frequency (Node i _ _) = i mapFrequency :: String -> [(Char, Int)] mapFrequency xs = M.toList $ M.fromListWith (+) $ map (\x -> (x, 1)) xs toLHeap :: String -> L.LH HT toLHeap xs = L.fromList $ map (\(c, i) -> Leaf c i) $ mapFrequency xs mergeAll :: L.LH HT -> HT mergeAll h | L.size h == 1 = L.min' h | otherwise = mergeAll $ L.insert (Node (frequency x + frequency y) x y) newH where (x, y, newH) = L.deleteTwoMin h encode' :: String -> (HT, [Code]) encode' xs = (h, map (\x -> m M.! x) xs) where m = M.fromList . getCharCode $ h h = mergeAll . toLHeap $ xs getCharCode :: HT -> [(Char, Code)] getCharCode (Leaf c _) = [(c, [])] getCharCode (Node _ l r) = (applyPrefix '0' (getCharCode l)) ++ (applyPrefix '1' (getCharCode r)) applyPrefix :: Char -> [(Char, Code)] -> [(Char, Code)] applyPrefix c xs = map (\(ch, cd) -> (ch, c:cd)) xs encode :: String -> (HT, Code) encode xs = let (h, ys) = encode' xs in (h, concat ys) -- 1st HT = Original HuffmanTree -- 2nd HT = Actual Node we are in right now decode' :: HT -> HT -> Code -> String decode' _ (Leaf c _) [] = [c] decode' _ _ [] = "" decode' orgH (Leaf c _) xs = c:(decode' orgH orgH xs) decode' orgH (Node _ l r) (x:xs) = decode' orgH (if x == '0' then l else r) xs decode :: (HT, Code) -> String decode (h, cd) = decode' h h cd
NMouad21/HaskellSamples
Huffman.hs
mit
1,723
0
12
417
874
469
405
38
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Main where import qualified Data.ByteString.Char8 as Char import Data.FileEmbed import Database.PostgreSQL.Simple import Drifter.PostgreSQL import Drifter.Types import System.Environment main :: IO () main = do connStr <- getEnv "CONSTELLATION_DB" conn <- connectPostgreSQL (Char.pack connStr) res <- migrate (DBConnection conn) changes case res of Left er -> putStrLn er Right () -> putStrLn "Migration Complete" changes :: [Change Postgres] changes = [ Change "schema-constellation" Nothing (Script $(embedFile "drift/schema/constellation.sql")) ]
ClassyCoding/constellation-server
drift/Main.hs
mit
766
0
11
217
174
90
84
20
2
{-# LANGUAGE RecordWildCards #-} module GradientAscentDemo (runGradientAscentDemos) where import Ch05LogisticRegression.GradientAscent import Control.Monad import DataFiles import qualified Data.Vector.Storable as VS import qualified Data.Vector.Unboxed as VU import MLUtil import MLUtil ((|||)) import MLUtil.Graphics hiding ((|||), Vector) import Graphics.Rendering.Chart.Easy hiding (Matrix, Vector) waveform :: (Double -> Double) -> [Double] -> [(Double, Double)] waveform f xs = [ (x, f x) | x <- xs ] createSigmoidFigures :: IO () createSigmoidFigures = do renderChartSVG "sigmoid-fig5-1a.svg" defaultChartLabels { clTitle = Just "Figure 5.1a: Sigmoid" , clXAxisLabel = Just "x" , clYAxisLabel = Just "sigmoid(x)" } [ mkRPlot (line "sigmoid(x)" [waveform sigmoid [-5.0, -4.9 .. 5.0]]) ] renderChartSVG "sigmoid-fig5-1b.svg" defaultChartLabels { clTitle = Just "Figure 5.1b: Sigmoid (zoomed out)" , clXAxisLabel = Just "x" , clYAxisLabel = Just "sigmoid(x)" } [ mkRPlot (line "sigmoid(x)" [waveform sigmoid [-60.0, -59.0 .. 60.0]]) ] Just m@LabelledMatrix{..} <- getDataFileName "testSet.txt" >>= readLabelledMatrix let values = ones (rows lmValues, 1) ||| lmValues labels = col (map fromIntegral (VU.toList lmLabelIds)) r = gradAscent 0.001 500 values labels plots = (mkRPlot $ line "best-fit line" [waveform (bestFitLine r) [-3.0, -2.9 .. 3.0]]) : (colouredSeriesPlots m 0 1) renderChartSVG "sigmoid-fig5-4.svg" defaultChartLabels { clTitle = Just "Figure 5.4: Logistic regression best-fit line after gradient ascent" , clXAxisLabel = Just "x" , clYAxisLabel = Just "sigmoid(x)" } plots Just m@LabelledMatrix{..} <- getDataFileName "testSet.txt" >>= readLabelledMatrix let values = ones (rows lmValues, 1) ||| lmValues labels = col (map fromIntegral (VU.toList lmLabelIds)) r = stocGradAscent0 0.01 values labels plots = (mkRPlot $ line "best-fit line" [waveform (bestFitLine r) [-3.0, -2.9 .. 3.0]]) : (colouredSeriesPlots m 0 1) renderChartSVG "sigmoid-fig5-5.svg" defaultChartLabels { clTitle = Just "Figure 5.5: Stochastic gradient ascent best-fit line" , clXAxisLabel = Just "x" , clYAxisLabel = Just "y" } plots -- The performance-related failings of my implementation become apparent -- when trying to record the history: running to 500 iterations like Peter's -- sample is not really viable! -- TODO: Optimize! let (_, history) = stocGradAscent0History 0.01 50 values labels plots = map (\i -> mkRPlot $ line ("x" ++ show i) [zip (map fromIntegral [0 ..]) (map (`atIndex` i) history)]) [0 .. 2] renderChartSVG "sigmoid-fig5-6.svg" defaultChartLabels { clTitle = Just "Figure 5.6: Weights vs. iteration number" , clXAxisLabel = Just "Iteration" , clYAxisLabel = Just "Weights" } plots let values = ones (rows lmValues, 1) ||| lmValues labels = col (map fromIntegral (VU.toList lmLabelIds)) rowCount = rows values Just eiAction = choiceExtractIndices rowCount rowCount numIter = 150 eis <- foldM (\eis _ -> eiAction >>= \ei -> return $ ei : eis) [] [1 .. numIter] let r = stocGradAscent1 0.01 values labels eis plots = (mkRPlot $ line "best-fit line" [waveform (bestFitLine r) [-3.0, -2.9 .. 3.0]]) : (colouredSeriesPlots m 0 1) renderChartSVG "sigmoid-fig5-8.svg" defaultChartLabels { clTitle = Just "Figure 5.8: Improved stochastic gradient ascent best-fit line" , clXAxisLabel = Just "x" , clYAxisLabel = Just "y" } plots -- cf logRegres.plotBestFit bestFitLine :: Matrix -> Double -> Double bestFitLine weights x = let w0 = weights `atIndex` (0, 0) w1 = weights `atIndex` (1, 0) w2 = weights `atIndex` (2, 0) in ((-w0) - w1 * x) / w2 testGradAscent :: IO () testGradAscent = do Just LabelledMatrix{..} <- getDataFileName "testSet.txt" >>= readLabelledMatrix let values = ones (rows lmValues, 1) ||| lmValues labels = col (map fromIntegral (VU.toList lmLabelIds)) r = gradAscent 0.001 500 values labels print r testStocGradAscent :: IO () testStocGradAscent = do Just LabelledMatrix{..} <- getDataFileName "testSet.txt" >>= readLabelledMatrix let values = ones (rows lmValues, 1) ||| lmValues labels = col (map fromIntegral (VU.toList lmLabelIds)) r0 = stocGradAscent0 0.01 values labels rowCount = rows values Just eiAction = choiceExtractIndices rowCount rowCount numIter = 150 eis <- foldM (\eis _ -> eiAction >>= \ei -> return $ ei : eis) [] [1 .. numIter] let r1 = stocGradAscent1 0.01 values labels eis print r0 print r1 -- cf logRegres.colicTest -- I'm bored of this now -- This function doesn't work colicTest :: IO () colicTest = do Just trainingM <- getDataFileName "horseColicTraining.txt" >>= readLabelledMatrix let trainingValues = lmValues trainingM trainingLabels = col (map fromIntegral (VU.toList (lmLabelIds trainingM))) trainingRowCount = rows trainingValues Just eiAction = choiceExtractIndices trainingRowCount trainingRowCount eis <- foldM (\eis _ -> eiAction >>= \ei -> return $ ei : eis) [] [1 .. 500] let weights = flatten $ stocGradAscent1 0.01 trainingValues trainingLabels eis Just testM <- getDataFileName "horseColicTest.txt" >>= readLabelledMatrix let testValues = lmValues testM testLabels = VU.toList (lmLabelIds testM) testRows = toRows testValues (n, err) = foldr (\(testRow, testLabel) (n, err) -> let r = classifyVector testRow weights; err' = if r == testLabel then err else err + 1 in (n + 1, err')) (0, 0) (zip testRows testLabels) errorRate = (fromIntegral err) / (fromIntegral n) putStrLn $ "errorRate=" ++ show errorRate -- cf logRegres.classifyVector classifyVector :: Vector -> Vector -> Int classifyVector inX weights = let prob = sigmoid (sumElements (inX * weights)) in if prob > 0.5 then 1 else 0 runGradientAscentDemos :: IO () runGradientAscentDemos = do createSigmoidFigures testGradAscent testStocGradAscent colicTest
rcook/mlutil
ch05-logistic-regression/src/GradientAscentDemo.hs
mit
6,712
0
19
1,855
1,930
1,006
924
140
2
-- Master of Files -- http://www.codewars.com/kata/574bd867d277832448000adf module Codewars.Kata.Files (isAudio, isImage) where import Control.Arrow ((&&&)) import Data.Char (isLetter) import System.FilePath.Posix (takeExtension, takeBaseName) f exts = uncurry (&&) . ( uncurry (&&) . (all isLetter &&& not . null) . takeBaseName &&& (`elem` exts) . takeExtension ) isAudio :: FilePath -> Bool isAudio = f [".mp3", ".flac", ".alac", ".aac"] isImage :: FilePath -> Bool isImage = f [".jpg", ".jpeg", ".png", ".bmp", ".gif"]
gafiatulin/codewars
src/6 kyu/Files.hs
mit
529
0
14
76
175
105
70
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} -- | -- Module : Control.Monad.Prompt.Class -- Description : Typeclass for contexts with prompting ability. -- Copyright : (c) Justin Le 2015 -- License : MIT -- Maintainer : [email protected] -- Stability : unstable -- Portability : portable -- -- Provides a typeclass for 'Applicative' and 'Monad' types that give you -- the ability to, at any time, "prompt" with an @a@ and get a @b@ in -- response. The power of this instance is that each type gets to define -- its own way to deliver a response. -- -- This library provides instances for 'PromptT' from -- "Control.Monad.Prompt" and the monad transformers in /transformers/ and -- /mtl/. Feel free to create your own instances too. -- -- @ -- data Interactive a = Interactive ((String -> String) -> a) -- -- -- at any time, ask with a string to get a string -- instance MonadPrompt String String Interactive where -- prompt str = Interactive $ \f -> f str -- @ module Control.Monad.Prompt.Class ( MonadPrompt(..) , prompt' , prompts' ) where import Control.Monad.Trans.Class import Control.Monad.Trans.Error import Control.Monad.Trans.Except import Control.Monad.Trans.Maybe import Control.Monad.Trans.Reader import Prelude.Compat import qualified Control.Monad.Trans.RWS.Lazy as RWSL import qualified Control.Monad.Trans.RWS.Strict as RWSS import qualified Control.Monad.Trans.State.Lazy as SL import qualified Control.Monad.Trans.State.Strict as SS import qualified Control.Monad.Trans.Writer.Lazy as WL import qualified Control.Monad.Trans.Writer.Strict as WS -- | An 'Applicative' (and possibly 'Monad') where you can, at any time, -- "prompt" with an @a@ and receive a @b@ in response. -- -- Instances include 'PromptT' and any /transformers/ monad transformer -- over another 'MonadPrompt'. class Applicative m => MonadPrompt a b m | m -> a b where -- | "Prompt" with an @a@ for a @b@ in the context of the type. prompt :: a -- ^ prompting value -> m b prompt = prompts id -- | "Prompt" with an @a@ for a @b@ in the context of the type, and -- apply the given function to receive a @c@. prompts :: (b -> c) -- ^ mapping function -> a -- ^ prompting value -> m c prompts f = fmap f . prompt #if MIN_VERSION_base(4,7,0) {-# MINIMAL prompt | prompts #-} #endif -- | A version of 'prompt' strict on its prompting value. prompt' :: MonadPrompt a b m => a -> m b prompt' x = x `seq` prompt x -- | A version of 'prompts' strict on its prompting value. prompts' :: MonadPrompt a b m => (b -> c) -> a -> m c prompts' f x = x `seq` prompts f x instance (Monad m, MonadPrompt a b m) => MonadPrompt a b (ReaderT r m) where prompt = lift . prompt prompts f = lift . prompts f instance (Monad m, MonadPrompt a b m) => MonadPrompt a b (ExceptT e m) where prompt = lift . prompt prompts f = lift . prompts f #if MIN_VERSION_transformers(0,5,0) instance (Monad m, MonadPrompt a b m) => MonadPrompt a b (ErrorT e m) where #else instance (Error e, Monad m, MonadPrompt a b m) => MonadPrompt a b (ErrorT e m) where #endif prompt = lift . prompt prompts f = lift . prompts f instance (Monad m, MonadPrompt a b m) => MonadPrompt a b (SS.StateT s m) where prompt = lift . prompt prompts f = lift . prompts f instance (Monad m, MonadPrompt a b m) => MonadPrompt a b (SL.StateT s m) where prompt = lift . prompt prompts f = lift . prompts f instance (Monad m, MonadPrompt a b m, Monoid w) => MonadPrompt a b (WS.WriterT w m) where prompt = lift . prompt prompts f = lift . prompts f instance (Monad m, MonadPrompt a b m, Monoid w) => MonadPrompt a b (WL.WriterT w m) where prompt = lift . prompt prompts f = lift . prompts f instance (Monad m, MonadPrompt a b m, Monoid w) => MonadPrompt a b (RWSS.RWST r w s m) where prompt = lift . prompt prompts f = lift . prompts f instance (Monad m, MonadPrompt a b m, Monoid w) => MonadPrompt a b (RWSL.RWST r w s m) where prompt = lift . prompt prompts f = lift . prompts f instance (Monad m, MonadPrompt a b m) => MonadPrompt a b (MaybeT m) where prompt = lift . prompt prompts f = lift . prompts f
mstksg/prompt
src/Control/Monad/Prompt/Class.hs
mit
4,487
0
9
1,004
1,032
581
451
65
1
module UtilityTree( weightAllocation, budgetAllocation, resolveAllocation, quantityAllocation, buildUtilityTree, UtilityTree, MultiplicatorTree) where import qualified Data.Edison.Assoc.StandardMap as E import Libaddutil.BinTree import qualified Utility as U import Types import MarketTypes weightAllocation :: UtilityTree -> MultiplicatorTree weightAllocation = g . f budgetAllocation :: Price -> UtilityTree -> MarketPriceMap budgetAllocation b = resolveAllocation b . weightAllocation quantityAllocation :: MarketPriceMap -> MarketPriceMap -> MarketQuantityMap quantityAllocation prices budgets = E.mapWithKey func budgets where func k b = case E.lookupM k prices of Nothing -> 0 Just p -> b / p buildUtilityTree :: ProductName -> UtilityMap -> MarketPriceMap -> UtilityTree buildUtilityTree rootname utilities prices = let val = E.lookupM rootname utilities in case val of Nothing -> LeafR (rootname, E.lookup rootname prices) Just (UtilityInfo uf o1 o2) -> NodeR (rootname, uf) (buildUtilityTree o1 utilities prices) (buildUtilityTree o2 utilities prices) f :: UtilityTree -> MiddleTree f t@(NodeR (n, u) l r) = NodeR (n, u, p) (f l) (f r) where p = getPrice t f (LeafR np) = LeafR np f _ = error "Invalid utility tree: converting empty to price tree" -- Price of a node. Trivial for leaves. -- For inner nodes the prices of their children have to be resolved first. -- This is done by going further down the tree; leaves already have their -- prices, the inner nodes compute their own price by combining the prices -- of their children and the utility function. getPrice :: UtilityTree -> Price getPrice t@(NodeR (_, u) l r) = let (c1, c2) = getMultiplicators t p1 = getPrice l p2 = getPrice r in c1 * p1 + c2 * p2 getPrice (LeafR (_, p)) = p getPrice _ = error "Invalid utility tree: reading price from empty" getMultiplicators :: UtilityTree -> (Flt, Flt) getMultiplicators (NodeR (_, u) l r) = (c1, c2) where c1 = q1 / (q1 + q2) c2 = q2 / (q1 + q2) (q1, q2) = U.factors u p1 p2 1 p1 = getPrice l p2 = getPrice r getMultiplicators _ = error "Invalid utility tree: reading multiplicators from non-node" g :: MiddleTree -> MultiplicatorTree g t = go 1 t where go v (NodeR (n, u, _) l r) = Node (n, v) (go g1 l) (go g2 r) where g1 = v1 / (v1 + v2) g2 = v2 / (v1 + v2) (v1, v2) = U.factors u (get l) (get r) 1 go v (LeafR (n, _)) = Node (n, v) Empty Empty go _ EmptyR = Empty get :: MiddleTree -> Flt get (NodeR (_, _, p) _ _) = p get (LeafR (_, p)) = p get EmptyR = 0 -- Converts a final tree of only multiplicators to a map of quantities. -- The multiplicators are simply multiplied all the way down. resolveAllocation :: Flt -> MultiplicatorTree -> MarketPriceMap resolveAllocation m (Node (n, v) Empty Empty) = E.singleton n (m * v) resolveAllocation m (Node (_, v) l r) = resolveAllocation (m * v) l `E.union` resolveAllocation (m * v) r resolveAllocation _ Empty = E.empty
anttisalonen/economics
src/UtilityTree.hs
mit
3,236
0
13
854
1,034
553
481
66
3
module Problem59 where {-- Task description: Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65. For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message. Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable. Your task has been made easy, as the encryption key consists of three lower case characters. Using cipher1.txt (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text. --} import Data.Function (on) import System.IO import Data.Bits (xor) import Data.List (sortBy, transpose, maximumBy) import Control.Monad (liftM) import Data.Char (isLower, isAscii) import qualified Data.Map as M {- Cipher part -} charList :: String -- | ' ' is #1 Char in most languages ô.Ô charList = " etaoinshrdlucmwfygpbvkjzxq" xorChar :: Char -> Char -> Char xorChar a b = let a' = fromEnum a b' = fromEnum b in toEnum $ xor a' b' type CMap = M.Map Char Int getAlphabet :: String -> Alphabet getAlphabet = mkAlphabet . mkCMap where mkCMap :: String -> CMap mkCMap = foldl incChar startMap mkAlphabet :: CMap -> Alphabet mkAlphabet = reverse . fmap fst . sortBy (compare `on` snd) . M.assocs startMap :: CMap startMap = M.empty incChar :: CMap -> Char -> CMap incChar = flip (M.alter inc) where inc :: Maybe Int -> Maybe Int inc Nothing = Just 1 inc (Just x) = Just (x + 1) type Alphabet = String type Alphabets = [Alphabet] alphabets :: [String] -> Alphabets alphabets = fmap getAlphabet . transpose type Password = String crack :: Alphabets -> Password crack = fmap (fst . maximumBy (compare `on` snd) . helper) where helper :: Alphabet -> [(Char, Int)] helper a = do c <- charList let f = xorChar c let a' = fmap f a let a'' = filter isLower a' return (c, length a'') type Cipher = String decipher :: Cipher -> Password -> String decipher c p = zipWith xorChar c (cycle p) asciiSum :: String -> Int asciiSum = sum . fmap fromEnum -- | Search the best fitting Char in each alphabet - eq. the one with the most lowerChar's in it's encrypted part {- Initial functions -} load :: String -> [Int] load input = let s = init $ init input s' = '[':s `mappend` "]" in read s' stack :: [a] -> [[a]] stack x | length x >= 3 = take 3 x : stack (drop 3 x) | otherwise = [x] {- All that is below shall run inside the IO Monad -} file :: IO String file = readFile "p59_cipher1.txt" loadFile :: IO [Int] loadFile = fmap load file loadStack :: IO [String] loadStack = fmap (stack . fmap toEnum) loadFile main :: IO () main = do stack <- loadStack let password = crack $ alphabets stack let cipher = concat stack let clearText = decipher cipher password let sum = asciiSum $ filter isAscii clearText putStrLn $ "Password:\t" `mappend` password putStrLn $ "Cleartext:\n" `mappend` clearText putStrLn $ "Sum:\t" `mappend` show sum
runjak/projectEuler
src/Problem59.hs
mit
4,057
0
12
880
891
467
424
75
2
module STG.AST where -- The following is the definition of the STG language. type Var = String data Program = Program [Binding] deriving (Show, Eq) data Binding = Binding Var Lambda deriving (Show, Eq) data Lambda = Lambda [Var] UpdateFlag [Var] Expr deriving (Show, Eq) data UpdateFlag = U | N deriving (Show, Eq) data Expr = Let [Binding] Expr | LetRec [Binding] Expr | Case Expr Alts | Ap Var [Atom] | Constr Constr [Atom] | Prim Prim [Atom] | Literal Literal deriving (Show, Eq) type Constr = Int data Alts = Algebraic [AAlt] DefAlt | Primitive [PAlt] DefAlt deriving (Show, Eq) data AAlt = AAlt Constr [Var] Expr deriving (Show, Eq) data PAlt = PAlt Literal Expr deriving (Show, Eq) data DefAlt = DefBinding Var Expr | Default Expr deriving (Show, Eq) type Literal = Int data Prim = PrimAdd | PrimMul deriving (Show, Eq) data Atom = AtomVar Var | AtomLit Literal deriving (Show, Eq) mul :: Binding mul = Binding "mul" (Lambda [] N ["x", "y"] (Prim PrimMul [AtomVar "x", AtomVar "y"])) double :: Binding double = Binding "double" (Lambda [] N [] (Ap "mul" [AtomLit 2])) stgmain1 :: Binding stgmain1 = Binding "main" (Lambda [] N [] (Let [Binding "x" (Lambda [] N [] (Ap "double" [AtomLit 2])), Binding "y" (Lambda ["x"] N [] (Ap "double" [AtomVar "x"]))] (Ap "dumpInt" [AtomVar "y"]))) stgmodule1 :: Program stgmodule1 = Program [mul, double, stgmain1] stgmain2 :: Binding stgmain2 = Binding "main" (Lambda [] N [] (Let [Binding "x" (Lambda [] N [] (Ap "double" [AtomLit 0]))] (Case (Ap "x" []) (Primitive [PAlt 0 (Ap "dumpInt" [AtomLit 9000])] (DefBinding "z" (Ap "dumpInt" [AtomVar "z"])))))) stgmodule2 :: Program stgmodule2 = Program [mul, double, stgmain2] stgmain3 :: Binding stgmain3 = Binding "main" (Lambda [] N [] (Let [Binding "x" (Lambda [] N [] (Ap "double" [AtomLit 8])), Binding "y" (Lambda ["x"] N [] (Constr 0 [AtomVar "x"]))] (Case (Ap "y" []) (Algebraic [AAlt 0 ["foo"] (Ap "dumpInt" [AtomVar "foo"])] (Default (Ap "dumpInt" [AtomLit 1337])))))) stgmodule3 :: Program stgmodule3 = Program [mul, double, stgmain3]
tcsavage/lazy-compiler
src/STG/AST.hs
mit
2,193
0
19
499
989
532
457
44
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.RTCDTMFToneChangeEvent (newRTCDTMFToneChangeEvent, getTone, RTCDTMFToneChangeEvent(..), gTypeRTCDTMFToneChangeEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFToneChangeEvent Mozilla RTCDTMFToneChangeEvent documentation> newRTCDTMFToneChangeEvent :: (MonadDOM m, ToJSString type') => type' -> Maybe RTCDTMFToneChangeEventInit -> m RTCDTMFToneChangeEvent newRTCDTMFToneChangeEvent type' eventInitDict = liftDOM (RTCDTMFToneChangeEvent <$> new (jsg "RTCDTMFToneChangeEvent") [toJSVal type', toJSVal eventInitDict]) -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFToneChangeEvent.tone Mozilla RTCDTMFToneChangeEvent.tone documentation> getTone :: (MonadDOM m, FromJSString result) => RTCDTMFToneChangeEvent -> m result getTone self = liftDOM ((self ^. js "tone") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/RTCDTMFToneChangeEvent.hs
mit
1,917
0
10
320
432
268
164
32
1
module Plotly.REST ( createPlot , updatePlot ) where import Data.Aeson (ToJSON, decode', toJSON) import Control.Lens import Control.Monad (void) import Network.Wreq import qualified Data.Text as Text import Plotly.JSON createPlot :: String -> Registration -> IO (Maybe RegistryEntry) createPlot host reg = do r <- post (host ++ "/rest/plot") (toJSON reg) return $ decode' (r ^. responseBody) updatePlot :: ToJSON a => String -> RegistryEntry -> a -> IO () updatePlot host reg plot = do let url = host ++ (Text.unpack $ link reg) void $ put url (toJSON plot)
kosmoskatten/plotly-hs
plotly-hs-lib/src/Plotly/REST.hs
mit
578
0
13
109
221
116
105
17
1
module LinkedList ( LinkedList , datum , fromList , isNil , new , next , nil , reverseLinkedList , toList ) where data LinkedList a = Node { datum :: a, next :: LinkedList a } | NullNode fromList :: [a] -> LinkedList a fromList [] = NullNode fromList xs = Node (head xs) (fromList (tail xs)) isNil :: LinkedList a -> Bool isNil NullNode = True isNil _ = False new :: a -> LinkedList a -> LinkedList a new = Node nil :: LinkedList a nil = NullNode reverseLinkedList :: LinkedList a -> LinkedList a reverseLinkedList = fromList . reverse . toList toList :: LinkedList a -> [a] toList NullNode = [] toList (Node a l) = [a] ++ (toList l)
vaibhav276/exercism_haskell
simple-linked-list/src/LinkedList.hs
mit
711
0
9
200
264
142
122
27
1
{-# LANGUAGE ScopedTypeVariables #-} module Main where import System.IO.Strict (hGetContents) import System.IO hiding (hGetContents) import Database.HDBC import Database.HDBC.Sqlite3 import Text.Parsec.Prim (runPT, ParsecT, (<|>), try) import Text.Parsec.Char (string, char, anyChar, newline) import Text.Parsec.Combinator (many1, manyTill) import Text.Parsec.Error (ParseError) import Control.Monad.IO.Class (liftIO) import Data.Either (either) data Script = Comment String | EmptyLine | Sql String commentLine:: ParsecT String st IO Script commentLine = string "--" >> manyTill anyChar newline >>= return . Comment emptyLine :: ParsecT String st IO Script emptyLine = many1 newline >> return EmptyLine sqlOperator :: ParsecT String st IO Script sqlOperator = manyTill anyChar (char ';') >>= return . Sql sqlScript :: ParsecT String st IO [Script] sqlScript = many1 $ try commentLine <|> try emptyLine <|> try sqlOperator sqlStatemts :: IConnection a => a -> ParsecT String st IO [Statement] sqlStatemts conn = do cmds <- filter (not . null) . map unwrap <$> sqlScript -- liftIO $ sequence $ map putStrLn script liftIO . sequence $ prepare conn <$> cmds where unwrap (Sql s) = s unwrap _ = "" main = do conn <- connectSqlite3 "test.db" (script::Either ParseError [Statement]) <- withFile "D:\\git\\duo-memo\\doc\\sql\\duo-dicto_create.sql" ReadMode $ \handle-> do val <- hGetContents handle runPT (sqlStatemts conn) () "*.sql" val flip (either $ putStrLn . show) script $ \xs-> do sequence $ map (flip execute []) xs commit conn disconnect conn
erithion/duo-memo
doc/drafts/CreateSqlTables.hs
mit
1,972
0
15
648
543
284
259
41
2
-- Checks if a string is an integer of the regular expression (*, +) format in parenthesis: ((-)*(0123456789)+). module IsInteger where isInteger :: String -> Bool isInteger [] = False isInteger potentialInteger@(potentialSign : potentialRemainingDigits) | potentialSign == '-' = isInteger' potentialRemainingDigits | otherwise = isInteger' potentialInteger where isInteger' :: String -> Bool isInteger' [] = True isInteger' (potentialDigit : remainingPotentialDigits) = (potentialDigit `elem` "0123456789") && (isInteger' remainingPotentialDigits) {- GHCi> isInteger "-1" isInteger "0" isInteger "00" isInteger "" isInteger "+1" isInteger "A" -} -- True -- True -- True -- -- False -- False -- False
pascal-knodel/haskell-craft
Examples/· Recursion/· Primitive Recursion/Lists/IsInteger.hs
mit
741
0
9
135
130
72
58
10
2
module Paths_Life ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,1,0,0], versionTags = []} bindir, libdir, datadir, libexecdir :: FilePath bindir = "/Users/Adarsh/Library/Haskell/ghc-7.4.2/lib/Life-0.1.0.0/bin" libdir = "/Users/Adarsh/Library/Haskell/ghc-7.4.2/lib/Life-0.1.0.0/lib" datadir = "/Users/Adarsh/Library/Haskell/ghc-7.4.2/lib/Life-0.1.0.0/share" libexecdir = "/Users/Adarsh/Library/Haskell/ghc-7.4.2/lib/Life-0.1.0.0/libexec" getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath getBinDir = catchIO (getEnv "Life_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "Life_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "Life_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "Life_libexecdir") (\_ -> return libexecdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
asolanki/cs1501-final
dist/build/autogen/Paths_Life.hs
gpl-2.0
1,222
0
10
164
329
188
141
25
1
import Logfile import System.Environment dumpLogfile :: Logfile -> LogfilePtr -> IO () dumpLogfile lf ptr = case nextRecord lf ptr of Nothing -> return () Just (rec, nextPtr) -> (putStrLn $ show rec) >> dumpLogfile lf nextPtr main :: IO () main = do args <- getArgs case args of [path] -> do (log,startPtr) <- openLogfile path dumpLogfile log startPtr _ -> putStrLn "wanted a single argument, the path to dump"
sos22/ppres
ppres/driver/DumpLogfile.hs
gpl-2.0
498
0
13
158
162
79
83
14
2
-- SrcRegActList.hs -- -- Author: Yoshikuni Jujo <[email protected]> -- -- This file is part of regexpr library -- -- regexpr is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or any later version. -- -- regexpr is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANGY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this program. If not, see -- <http://www.gnu.org/licenses/>. module Hidden.SrcRegActList ( selfTest , plusesList , oneCharList , backSlashesList , parensesList , charClassList ) where import Hidden.RegexPRTypes ( RegexAction(..), reverseRegexAction ) import Data.Char ( isAlphaNum, isAlpha, isUpper, isLower, isDigit, isHexDigit, isSpace, isPrint, isControl ) import Hidden.Tools ( (&&&), (|||), isSymbol, isBit7On ) selfTest :: Char -> Bool selfTest = flip elem "\b\n\f\r\t !\"#%&',-/:;<=>@]_'~}" ||| isAlphaNum ||| isBit7On plusesList :: [ (String, RegexAction -> RegexAction) ] plusesList = [ ( "" , id ) , ( "*" , Repeat 0 Nothing ) , ( "*?", RepeatNotGreedy 0 Nothing ) , ( "+" , Repeat 1 Nothing ) , ( "+?", RepeatNotGreedy 1 Nothing ) , ( "?" , Repeat 0 $ Just 1 ) , ( "??", RepeatNotGreedy 0 $ Just 1 ) ] oneCharList :: [ (Char, RegexAction) ] oneCharList = [ ('.', Select (/='\n')) , ('$', RegexOr [EndOfInput] [Still [Select (=='\n')]]) , ('^', RegexOr [BeginningOfInput] [Still [Backword [Select (=='\n')]]]) ] backSlashesList :: [ (Char, RegexAction) ] backSlashesList = [ ( 'w', Select isWord ) , ( 'W', Select $ not . isWord ) , ( 's', Select (`elem` " \t\n\r\f") ) , ( 'S', Select (`notElem` " \t\n\r\f") ) , ( 'd', Select isDigit ) , ( 'D', Select (not . isDigit) ) , ( 'A', BeginningOfInput ) , ( 'Z', RegexOr [EndOfInput] [Still [Select (=='\n'), EndOfInput]] ) , ( 'z', EndOfInput ) , ( 'b', regexOr [ [ lookBehind [Select isWord], Still [selectNot isWord] ] , [ lookBehind [selectNot isWord], Still [Select isWord] ] , [ BeginningOfInput, Still [Select isWord] ] , [ lookBehind [Select isWord], EndOfInput ] ] ) , ( 'B', RegActNot [ regexOr [ [ lookBehind [Select isWord], Still [selectNot isWord] ] , [ lookBehind [selectNot isWord], Still [Select isWord] ] , [ BeginningOfInput, Still [Select isWord] ] , [ lookBehind [Select isWord], EndOfInput ] ] ] ) , ( 'G', PreMatchPoint ) ] parensesList :: [ (String, [RegexAction] -> RegexAction) ] parensesList = [ ( "?<=", Still . (:[]) . Backword . reverse . map reverseRegexAction ) , ( "?<!", Still . (:[]) . RegActNot . (:[]) . Backword . reverse . map reverseRegexAction ) , ( "?=", Still ) , ( "?!", Still . (:[]) . RegActNot ) , ( "?:", Parens ) , ( "?>", NoBacktrack ) , ( "$>", NoBacktrack ) ] charClassList :: [ (String, Char -> Bool) ] charClassList = [ ( "alnum" , isAlphaNum ) , ( "alpha" , isAlpha ) , ( "blank" , isSpace ) , ( "cntrl" , isControl ) , ( "digit" , isDigit ) , ( "graph" , isPrint &&& (not.) isSpace ) , ( "lower" , isLower ) , ( "print" , isPrint ) , ( "punct" , isSymbol ) , ( "space" , isSpace ) , ( "upper" , isUpper ) , ( "xdigit", isHexDigit ) ] isWord :: Char -> Bool isWord = isAlphaNum ||| (=='_') regexOr :: [[RegexAction]] -> RegexAction regexOr = head . foldr1 (\ra1 ra2 -> [RegexOr ra1 ra2]) lookBehind :: [RegexAction] -> RegexAction lookBehind ras = Still [Backword ras] selectNot :: (Char -> Bool) -> RegexAction selectNot s = Select (not . s)
YoshikuniJujo/regexpr
Hidden/SrcRegActList.hs
gpl-3.0
4,880
4
14
1,874
1,210
722
488
82
1
module QHaskell.Expression.Utils.TemplateHaskell ((===),unQ,stripNameSpace,trmEql) where import Prelude import QHaskell.ErrorMonad import Language.Haskell.TH.Syntax hiding (unQ) (===) :: Name -> Name -> Bool n1 === n2 = stripNameSpace n1 == stripNameSpace n2 unQ :: Q a -> a unQ = frmRgt. runQ stripNameSpace :: Name -> Name stripNameSpace (Name x _) = Name x NameS trmEql :: Q (TExp a) -> Q (TExp b) -> Bool trmEql m n = let m' = frmRgt (runQ (unTypeQ m)) n' = frmRgt (runQ (unTypeQ n)) in m' == n' instance Show (Q (TExp a)) where show q = let q' = frmRgt (runQ (unTypeQ q)) in show q' instance Quasi ErrM where qNewName = return . mkName qReport b = fail . if b then ("Error: " ++) else ("Warning: " ++) qRecover = fail "Not Allowed!" qReify = fail "Not Allowed!" qLookupName = fail "Not Allowed!" qReifyInstances = fail "Not Allowed!" qReifyRoles = fail "Not Allowed!" qReifyAnnotations = fail "Not Allowed!" qReifyModule = fail "Not Allowed!" qAddDependentFile = fail "Not Allowed!" qAddModFinalizer = fail "Not Allowed!" qAddTopDecls = fail "Not Allowed!" qLocation = fail "Not Allowed!" qRunIO = fail "Not Allowed!" qPutQ = fail "Not Allowed!" qGetQ = fail "Not Allowed!"
shayan-najd/QHaskell
QHaskell/Expression/Utils/TemplateHaskell.hs
gpl-3.0
1,432
0
14
449
437
228
209
36
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} -- | Provides parser for @$HOME/.netrc@ files -- -- The implemented grammar is approximately: -- -- > NETRC := (WS|<comment>)* (ENTRY (WS+ <comment>*)+)* ENTRY? -- > -- > ENTRY := 'machine' WS+ <value> WS+ ((account|username|password) WS+ <value>)* -- > | 'default' WS+ (('account'|'username'|'password') WS+ <value>)* -- > | 'macdef' <value> LF (<line> LF)* LF -- > -- > WS := (LF|SPC|TAB) -- > -- > <line> := !LF+ -- > <value> := !WS+ -- > <comment> := '#' !LF* LF -- -- As an extension to the @.netrc@-format as described in .e.g. -- <http://linux.die.net/man/5/netrc netrc(5)>, @#@-style comments are -- tolerated. Comments are currently only allowed before, between, -- and after @machine@\/@default@\/@macdef@ entries. Be aware though -- that such @#@-comment are not supported by all @.netrc@-aware -- applications, including @ftp(1)@. module Network.NetRc ( -- * Types NetRc(..) , NetRcHost(..) , NetRcMacDef(..) -- * Formatters , netRcToBuilder , netRcToByteString -- * Parsers , netRcParsec , parseNetRc -- * Utilities , readUserNetRc ) where import Control.Applicative import Control.DeepSeq import Control.Monad import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as LB import Data.Data import Data.Either (rights, lefts) import Data.List (intersperse, foldl') import Data.Monoid import GHC.Generics import System.Environment import System.IO.Error import qualified Text.Parsec as P import qualified Text.Parsec.ByteString as P -- | @machine@ and @default@ entries describe remote accounts -- -- __Invariant__: fields must not contain any @TAB@s, @SPACE@, or @LF@s. data NetRcHost = NetRcHost { nrhName :: !ByteString -- ^ Remote machine name (@""@ for @default@-entries) , nrhLogin :: !ByteString -- ^ @login@ property (@""@ if missing) , nrhPassword :: !ByteString -- ^ @password@ property (@""@ if missing) , nrhAccount :: !ByteString -- ^ @account@ property (@""@ if missing) , nrhMacros :: [NetRcMacDef] -- ^ associated @macdef@ entries } deriving (Eq,Ord,Show,Typeable,Data,Generic) instance NFData NetRcHost where rnf !_ = () -- | @macdef@ entries defining @ftp@ macros data NetRcMacDef = NetRcMacDef { nrmName :: !ByteString -- ^ Name of @macdef@ entry -- -- __Invariant__: must not contain any @TAB@s, @SPACE@, or @LF@s , nrmBody :: !ByteString -- ^ Raw @macdef@ body -- -- __Invariant__: must not contain null-lines, i.e. consecutive @LF@s } deriving (Eq,Ord,Show,Typeable,Data,Generic) instance NFData NetRcMacDef where rnf !_ = () -- | Represents (semantic) contents of a @.netrc@ file data NetRc = NetRc { nrHosts :: [NetRcHost] -- ^ @machine@\/@default@ entries -- -- __Note__: If it exists, the -- @default@ entry ought to be the -- last entry, otherwise it can cause -- later entries to become invisible -- for some implementations -- (e.g. @ftp(1)@) , nrMacros :: [NetRcMacDef] -- ^ Non-associated @macdef@ entries -- -- __Note__: @macdef@ entries not -- associated with host-entries are -- invisible to some applications -- (e.g. @ftp(1)@). } deriving (Eq,Ord,Show,Typeable,Data,Generic) instance NFData NetRc where rnf (NetRc ms ds) = ms `deepseq` ds `deepseq` () -- | Construct a 'ByteString' 'BB.Builder' netRcToBuilder :: NetRc -> BB.Builder netRcToBuilder (NetRc ms ds) = mconcat . intersperse nl $ map netRcMacDefToBuilder ds <> map netRcHostToBuilder ms where netRcHostToBuilder (NetRcHost {..}) = mconcat $ [ mline , prop "login" nrhLogin , prop "password" nrhPassword , prop "account" nrhAccount , nl ] <> (intersperse nl $ map netRcMacDefToBuilder nrhMacros) where mline | B.null nrhName = BB.byteString "default" | otherwise = BB.byteString "machine" <> spc <> BB.byteString nrhName prop lab val | B.null val = mempty | otherwise = spc <> BB.byteString lab <> spc <> BB.byteString val netRcMacDefToBuilder (NetRcMacDef {..}) = BB.byteString "macdef" <> spc <> BB.byteString nrmName <> (if B.null nrmBody then mempty else nl <> BB.byteString nrmBody) <> nl spc = BB.charUtf8 ' ' nl = BB.charUtf8 '\n' -- | Format 'NetRc' into a 'ByteString' -- -- This is currently just a convenience wrapper around 'netRcToBuilder' netRcToByteString :: NetRc -> ByteString #if MIN_VERSION_bytestring(0,10,0) netRcToByteString = LB.toStrict . BB.toLazyByteString . netRcToBuilder #else netRcToByteString = B.concat . LB.toChunks . BB.toLazyByteString . netRcToBuilder #endif -- | Convenience wrapper for 'netRcParsec' parser -- -- This is basically just -- -- @ -- 'parseNetRc' = 'P.parse' ('netRcParsec' <* 'P.eof') -- @ -- -- This wrapper is mostly useful for avoiding to have to import Parsec -- modules (and to build-depend explicitly on @parsec@). -- parseNetRc :: P.SourceName -> ByteString -> Either P.ParseError NetRc parseNetRc = P.parse (netRcParsec <* P.eof) -- | Reads and parses default @$HOME/.netrc@ -- -- Returns 'Nothing' if @$HOME@ variable undefined and/or if @.netrc@ if missing. -- Throws standard IO exceptions in case of other filesystem-errors. -- -- __Note__: This function performs no permission sanity-checking on -- the @.netrc@ file readUserNetRc :: IO (Maybe (Either P.ParseError NetRc)) readUserNetRc = do mhome <- lookupEnv "HOME" case mhome of Nothing -> return Nothing Just "" -> return Nothing Just ho -> do let fn = ho ++ "/.netrc" ret <- tryIOError (B.readFile fn) case ret of Left e | isDoesNotExistError e -> return Nothing | otherwise -> ioError e Right b -> return $! Just $! parseNetRc fn b #if !(MIN_VERSION_base(4,6,0)) where lookupEnv k = lookup k <$> getEnvironment #endif -- | "Text.Parsec.ByteString" 'P.Parser' for @.netrc@ grammar netRcParsec :: P.Parser NetRc netRcParsec = do entries <- uncurry NetRc . normEnts . splitEithers <$> (wsOrComments0 *> P.sepEndBy netrcEnt wsOrComments1) return entries where wsOrComments0 = P.skipMany comment >> P.skipMany (wsChars1 >> P.skipMany comment) wsOrComments1 = P.skipMany1 (wsChars1 >> P.skipMany comment) netrcEnt = (Left <$> hostEnt) <|> (Right <$> macDefEnt) normEnts [] = ([], []) normEnts (([], ms):es) = (normEnts' es, ms) normEnts es = (normEnts' es, []) normEnts' :: [([NetRcHost],[NetRcMacDef])] -> [NetRcHost] normEnts' [] = [] normEnts' (([], _):_) = error "netRcParsec internal error" normEnts' ((hs, ms):es) = init hs ++ ((last hs) { nrhMacros = ms } : normEnts' es) macDefEnt :: P.Parser NetRcMacDef macDefEnt = do void $ P.try (P.string "macdef") wsChars1 n <- tok P.<?> "macdef-name" P.skipMany (P.oneOf "\t ") lf bodyLines <- P.sepEndBy neline lf return $! NetRcMacDef n (BC.pack $ unlines bodyLines) where neline = P.many1 (P.noneOf "\n") hostEnt :: P.Parser NetRcHost hostEnt = do nam <- mac <|> def ps <- P.many (P.try (wsChars1 *> pval)) return $! foldl' setFld (NetRcHost nam "" "" "" []) ps where def = P.try (P.string "default") *> pure "" mac = do P.try (void $ P.string "machine") wsChars1 tok P.<?> "hostname" -- pval := ((account|username|password) WS+ <value>) pval = hlp "login" PValLogin <|> hlp "account" PValAccount <|> hlp "password" PValPassword where hlp tnam cons = P.try (P.string tnam) *> wsChars1 *> (cons <$> tok P.<?> (tnam ++ "-value")) setFld n (PValLogin v) = n { nrhLogin = v } setFld n (PValAccount v) = n { nrhAccount = v } setFld n (PValPassword v) = n { nrhPassword = v } tok :: P.Parser ByteString tok = BC.pack <$> P.many1 notWsChar P.<?> "token" data PVal = PValLogin !ByteString | PValAccount !ByteString | PValPassword !ByteString deriving Show lf, wsChar, wsChars1 :: P.Parser () lf = void (P.char '\n') P.<?> "line-feed" wsChar = void (P.oneOf "\t \n") wsChars1 = P.skipMany1 wsChar -- | Any 'Char' not parsed by 'wsChar' notWsChar :: P.Parser Char notWsChar = P.noneOf "\t \n" -- | Comments (where allowed) go till rest of line comment :: P.Parser () comment = (P.char '#' *> skipToEol) P.<?> "comment" -- | Consume/skip rest of line skipToEol :: P.Parser () skipToEol = P.skipMany notlf <* (lf <|> P.eof) where notlf = P.noneOf "\n" -- | Regroup lst of 'Either's into pair of lists splitEithers :: [Either l r] -> [([l], [r])] splitEithers = goL where goL [] = [] goL es = let (pfx,es') = span isLeft es in goR es' (lefts pfx) goR [] ls = [(ls,[])] goR es ls = let (pfx,es') = span isRight es in (ls,rights pfx) : goL es' isLeft (Left _) = True isLeft (Right _) = False isRight = not . isLeft
hvr/netrc
src/Network/NetRc.hs
gpl-3.0
9,959
0
18
2,762
2,264
1,218
1,046
177
5
-- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings where import ClassyPrelude.Yesod import Control.Exception as Ex (throw) import Data.Aeson (Result (..), fromJSON, withObject, (.!=), (.:?)) import Data.FileEmbed (embedFile) import Data.Yaml (decodeEither') import Database.Persist.Postgresql (PostgresConf) import Language.Haskell.TH.Syntax (Exp, Name, Q) import Network.Wai.Handler.Warp (HostPreference) import Yesod.Default.Config2 (applyEnvValue, configSettingsYml) import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload, widgetFileReload) -- | Runtime settings to configure this application. These settings can be -- loaded from various sources: defaults, environment variables, config files, -- theoretically even a database. data AppSettings = AppSettings { appStaticDir :: String -- ^ Directory from which to serve static files. , appDatabaseConf :: PostgresConf -- ^ Configuration settings for accessing the database. , appRoot :: Text -- ^ Base for all generated URLs. , appHost :: HostPreference -- ^ Host/interface the server should bind to. , appPort :: Int -- ^ Port to listen on , appIpFromHeader :: Bool -- ^ Get the IP address from the header when logging. Useful when sitting -- behind a reverse proxy. , appDetailedRequestLogging :: Bool -- ^ Use detailed request logging system , appShouldLogAll :: Bool -- ^ Should all log messages be displayed? , appReloadTemplates :: Bool -- ^ Use the reload version of templates , appMutableStatic :: Bool -- ^ Assume that files in the static dir may change after compilation , appSkipCombining :: Bool -- ^ Perform no stylesheet/script combining -- Example app-specific configuration values. , appCopyright :: Text -- ^ Copyright text to appear in the footer of the page , appAnalytics :: Maybe Text -- ^ Google Analytics code } instance FromJSON AppSettings where parseJSON = withObject "AppSettings" $ \o -> do let defaultDev = #if DEVELOPMENT True #else False #endif appStaticDir <- o .: "static-dir" appDatabaseConf <- o .: "database" appRoot <- o .: "approot" appHost <- fromString <$> o .: "host" appPort <- o .: "port" appIpFromHeader <- o .: "ip-from-header" appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev appShouldLogAll <- o .:? "should-log-all" .!= defaultDev appReloadTemplates <- o .:? "reload-templates" .!= defaultDev appMutableStatic <- o .:? "mutable-static" .!= defaultDev appSkipCombining <- o .:? "skip-combining" .!= defaultDev appCopyright <- o .: "copyright" appAnalytics <- o .:? "analytics" return AppSettings {..} -- | Settings for 'widgetFile', such as which template languages to support and -- default Hamlet settings. -- -- For more information on modifying behavior, see: -- -- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile widgetFileSettings :: WidgetFileSettings widgetFileSettings = def -- | How static files should be combined. combineSettings :: CombineSettings combineSettings = def -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = (if appReloadTemplates compileTimeAppSettings then widgetFileReload else widgetFileNoReload) widgetFileSettings -- | Raw bytes at compile time of @config/settings.yml@ configSettingsYmlBS :: ByteString configSettingsYmlBS = $(embedFile configSettingsYml) -- | @config/settings.yml@, parsed to a @Value@. configSettingsYmlValue :: Value configSettingsYmlValue = either Ex.throw id $ decodeEither' configSettingsYmlBS -- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@. compileTimeAppSettings :: AppSettings compileTimeAppSettings = case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of Error e -> error e Success settings -> settings -- The following two functions can be used to combine multiple CSS or JS files -- at compile time to decrease the number of http requests. -- Sample usage (inside a Widget): -- -- > $(combineStylesheets 'StaticR [style1_css, style2_css]) combineStylesheets :: Name -> [Route Static] -> Q Exp combineStylesheets = combineStylesheets' (appSkipCombining compileTimeAppSettings) combineSettings combineScripts :: Name -> [Route Static] -> Q Exp combineScripts = combineScripts' (appSkipCombining compileTimeAppSettings) combineSettings
Drezil/neat
Settings.hs
gpl-3.0
5,368
0
12
1,438
705
405
300
-1
-1
module Hed where import System.IO import System.Environment import StringUtil import FileMan import Data.Char (toUpper) import Data.Maybe import Control.Exception {- the structure of the document is - [[privious lines]] and these are reversed - [the current line] but this will be only one string - [[the lines after current line]] -} {- and the current line number -} {- so the document structure is:-} data Line = LineBuffer Int [Char] Char [Char] deriving (Show) data Document = Buffer Int [[Char]] [Char] [[Char]] deriving (Show) fillDocument :: String -> Document fillDocument input = Buffer 1 [] (head readin) (tail readin) where readin = lines input appendLine :: Document -> [Char] -> Document appendLine (Buffer 0 [] [] []) newline = Buffer 1 [] newline [] appendLine (Buffer lineNum prev cur post) newline = Buffer (lineNum + 1) (cur : prev) newline post insertLine :: Document -> [Char] -> Document insertLine (Buffer 0 [] [] []) newline = Buffer 1 [] newline [] insertLine (Buffer lineNum prev cur post) newline = Buffer lineNum prev newline (cur : post) deleteLine :: Document -> Document deleteLine (Buffer 0 _ _ _ ) = Buffer 0 [] [] [] deleteLine (Buffer _ [] _ post) = Buffer 1 [] (head post) (tail post) deleteLine (Buffer lineNum prev _ post) = Buffer (lineNum - 1) (tail prev) (head prev) post replaceLine :: Document -> String -> Document replaceLine (Buffer lineNum prev cur post) newline = Buffer lineNum prev newline post replaceSubLine :: Document -> [Char] -> [Char] -> Document replaceSubLine (Buffer lineNum prev cur post) replace withThis = Buffer lineNum prev (StringUtil.replaceFirstSubString replace withThis cur) post gotoLine :: Document -> Int -> Document gotoLine org@(Buffer lineNum prev cur post) newline | newline < 1 = gotoLine org 1 | lineNum > newline = gotoLine (Buffer (lineNum-1) (tail prev) (head prev) (cur:post)) newline | post == [] = org | lineNum < newline = gotoLine (Buffer (lineNum+1) (cur:prev) (head post) (tail post)) newline | otherwise = org allToString :: Document -> String allToString (Buffer 1 _ cur post) = unlines (cur:post) allToString doc = allToString $ gotoLine doc 1 partToString :: Document -> Int -> Int -> String partToString doc@(Buffer lineNum _ cur post) bgnng ndng | bgnng < 1 = partToString (gotoLine doc 1) 1 ndng | bgnng > ndng = partToString (gotoLine doc ndng) ndng bgnng | lineNum == bgnng = unlines $ cur : take (ndng-bgnng) post | otherwise = partToString (gotoLine doc bgnng) bgnng ndng executeCommand :: [Char] -> Document -> Document executeCommand [] doc = doc executeCommand command doc | abriv == 'd' = deleteLine doc | abriv == 'g' && args == 1 = gotoLine doc (((read.head.(drop 1).words) command)::Int ) | abriv == 'r' && args >= 1 = replaceLine doc stament | abriv == 'i' && args >= 1 = insertLine doc stament | abriv == 'a' && args >= 1 = appendLine doc stament | abriv == 's' && args == 2 = replaceSubLine doc ((head.words) stament) ((head.(drop 1).words) stament) | otherwise = doc where abriv = (head.head.words) command stament = ((tail.dropWhile (/=' ')).tail) command args = length.tail.words $ command getLineNum :: Document -> Int getLineNum (Buffer lineNum _ _ _) = lineNum promptLine doc@(Buffer lineNum _ _ _) = do putStr $ (show lineNum) ++ " > " hFlush stdout getLine insertMode :: IO Document -> IO Document insertMode input = do line <- putStr "I " >> input >>= promptLine case line of ".." -> input _ -> do doc <- input insertMode $ return $ appendLine doc line visualMode :: IO Document -> IO Document visualMode input = do doc <- input let line = getLineNum doc hSetBuffering stdin NoBuffering putStr $ "V " ++ (show line) ++ " > " putStr $partToString doc line line hFlush stdout hSetEcho stdin False command <- getChar hSetEcho stdin True case (command) of 'j' -> return (executeCommand ("g " ++ (show (line + 1))) doc) >>= visualMode.return 'k' -> return (executeCommand ("g " ++ (show (line - 1))) doc) >>= visualMode.return 'q' -> do hSetBuffering stdin LineBuffering input _ -> putStrLn "" >> visualMode input progLoop :: IO [Document] -> IO Document progLoop input = do command <- input >>= promptLine.head if command /= "" then case (head command) of 'Q' -> fmap head input 'V' -> input >>= (putStrLn.allToString.head) >> progLoop input 'v' -> catch ( do doc <-input let ltop = ((read.head.(drop 1).words) command) :: Int let lbot = ((read.head.(drop 2).words) command) :: Int putStrLn $ partToString (head doc) ltop lbot progLoop input ) (handleError (progLoop input)) '.' -> do { doc <- input; insertMode (fmap head input) >>= (\x -> (progLoop.return) $ x:doc) } 'n' -> do { doc <- input; visualMode (fmap head input) >>= (\x -> (progLoop.return) $ x:doc) } 'u' -> do doc <- input if ((length doc) > 1) then progLoop $ fmap tail input else progLoop input _ -> do doc <- input catch ( progLoop $ return $ (executeCommand command (head doc) : doc ) ) ( handleError (progLoop input) ) else progLoop input handleError :: IO a -> SomeException -> IO a handleError callback exception = (print.show) exception >> callback getFilename :: [a] -> Maybe a getFilename [] = Nothing getFilename (x:_) = Just x getFilename' :: [String] -> String getFilename' [] = "test.txt" getFilename' (x:_) = x textInput :: String -> IO String textInput x = do input <- getChar if (input == '\n') then return $ reverse x else do print $ reverse x textInput (input : x) main = do hSetBuffering stdin NoBuffering hSetBuffering stdin LineBuffering fileName <- getArgs >>= return.getFilename' print fileName progLoop $ readFileToBuffer fileName fillDocument >>= (\x -> return (x:[])) --print "saving test.txt" --(writeBufferToFile "test.txt").allToString --The document-- print "bye." --textInput "" --Now this is the proper way to implement ed in Haskell --main = getLine >> putStrLn "?" >> main
joshuaunderwood7/beeHive
Hed.hs
gpl-3.0
6,656
4
24
1,844
2,449
1,216
1,233
141
9
{-# LANGUAGE BangPatterns #-} ---------------------------------------------------------------------------------- -- | -- Module : Tct.Method.Bounds.Violations -- Copyright : (c) Martin Avanzini <[email protected]>, -- Georg Moser <[email protected]>, -- Andreas Schnabl <[email protected]> -- License : LGPL (see COPYING) -- Maintainer : Martin Avanzini <[email protected]>, -- Andreas Schnabl <[email protected]> -- Stability : unstable -- Portability : unportable -- -- This module implements constructs automata compatible with enriched systems, -- as employed in the bound processor. ---------------------------------------------------------------------------------- module Tct.Method.Bounds.Violations where import qualified Data.Set as Set import Control.Monad (liftM, foldM) import qualified Termlib.Rule as R import Termlib.Trs (Trs) import Termlib.Rule (Strictness(..)) import qualified Termlib.Trs as Trs import Tct.Processor (SolverM) import Tct.Method.Bounds.Automata import Tct.Method.Bounds.Violations.Find import Tct.Method.Bounds.Violations.Fix makeRuleCompatible :: R.Rule -> Enrichment -> Strictness -> WeakBoundedness -> Label -> Automaton -> Either Automaton Automaton makeRuleCompatible r !e !str !wb !ml !a = case null violations of True -> Right a False -> Left $ foldl fixViolation a violations where violations = Set.toList $ findViolations a e str wb ml r compatibleAutomaton :: SolverM m => Trs -> Trs -> Enrichment -> Automaton -> m Automaton compatibleAutomaton strict weak e a = eitherVal `liftM` (iter a (1 :: Int)) where iter a' i = do r' <- foldM (f i WeakRule $ maxlabel a') (Right a') wrs r <- foldM (f i StrictRule $ maxlabel a') r' srs case r of Left a'' -> iter a'' (i + 1) Right a'' -> return $ Right a'' f _ str ml a' rule = case a' of (Left a'') -> return $ Left $ eitherVal $ makeRuleCompatible rule e str wb ml a'' (Right a'') -> return $ makeRuleCompatible rule e str wb ml a'' -- where tl v = do debugMsg $ show $ (brackets $ text $ show i) <+> text "processing rule" <+> pprint rule $$ pprint (eitherVal v) -- return v eitherVal (Left v) = v eitherVal (Right v) = v srs = Trs.rules strict wrs = Trs.rules weak wb = if Trs.isCollapsing strict then WeakMayExceedBound else WeakMayNotExceedBound
mzini/TcT
source/Tct/Method/Bounds/Violations.hs
gpl-3.0
2,709
0
14
758
575
308
267
32
5
{-# 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.DeploymentManager.Deployments.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates a deployment and all of the resources described by the -- deployment manifest. -- -- /See:/ <https://cloud.google.com/deployment-manager/ Google Cloud Deployment Manager API Reference> for @deploymentmanager.deployments.update@. module Network.Google.Resource.DeploymentManager.Deployments.Update ( -- * REST Resource DeploymentsUpdateResource -- * Creating a Request , deploymentsUpdate , DeploymentsUpdate -- * Request Lenses , duCreatePolicy , duProject , duPayload , duDeletePolicy , duPreview , duDeployment ) where import Network.Google.DeploymentManager.Types import Network.Google.Prelude -- | A resource alias for @deploymentmanager.deployments.update@ method which the -- 'DeploymentsUpdate' request conforms to. type DeploymentsUpdateResource = "deploymentmanager" :> "v2" :> "projects" :> Capture "project" Text :> "global" :> "deployments" :> Capture "deployment" Text :> QueryParam "createPolicy" DeploymentsUpdateCreatePolicy :> QueryParam "deletePolicy" DeploymentsUpdateDeletePolicy :> QueryParam "preview" Bool :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Deployment :> Put '[JSON] Operation -- | Updates a deployment and all of the resources described by the -- deployment manifest. -- -- /See:/ 'deploymentsUpdate' smart constructor. data DeploymentsUpdate = DeploymentsUpdate' { _duCreatePolicy :: !DeploymentsUpdateCreatePolicy , _duProject :: !Text , _duPayload :: !Deployment , _duDeletePolicy :: !DeploymentsUpdateDeletePolicy , _duPreview :: !Bool , _duDeployment :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DeploymentsUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'duCreatePolicy' -- -- * 'duProject' -- -- * 'duPayload' -- -- * 'duDeletePolicy' -- -- * 'duPreview' -- -- * 'duDeployment' deploymentsUpdate :: Text -- ^ 'duProject' -> Deployment -- ^ 'duPayload' -> Text -- ^ 'duDeployment' -> DeploymentsUpdate deploymentsUpdate pDuProject_ pDuPayload_ pDuDeployment_ = DeploymentsUpdate' { _duCreatePolicy = CreateOrAcquire , _duProject = pDuProject_ , _duPayload = pDuPayload_ , _duDeletePolicy = DUDPDelete' , _duPreview = False , _duDeployment = pDuDeployment_ } -- | Sets the policy to use for creating new resources. duCreatePolicy :: Lens' DeploymentsUpdate DeploymentsUpdateCreatePolicy duCreatePolicy = lens _duCreatePolicy (\ s a -> s{_duCreatePolicy = a}) -- | The project ID for this request. duProject :: Lens' DeploymentsUpdate Text duProject = lens _duProject (\ s a -> s{_duProject = a}) -- | Multipart request metadata. duPayload :: Lens' DeploymentsUpdate Deployment duPayload = lens _duPayload (\ s a -> s{_duPayload = a}) -- | Sets the policy to use for deleting resources. duDeletePolicy :: Lens' DeploymentsUpdate DeploymentsUpdateDeletePolicy duDeletePolicy = lens _duDeletePolicy (\ s a -> s{_duDeletePolicy = a}) -- | If set to true, updates the deployment and creates and updates the -- \"shell\" resources but does not actually alter or instantiate these -- resources. This allows you to preview what your deployment will look -- like. You can use this intent to preview how an update would affect your -- deployment. You must provide a target.config with a configuration if -- this is set to true. After previewing a deployment, you can deploy your -- resources by making a request with the update() or you can -- cancelPreview() to remove the preview altogether. Note that the -- deployment will still exist after you cancel the preview and you must -- separately delete this deployment if you want to remove it. duPreview :: Lens' DeploymentsUpdate Bool duPreview = lens _duPreview (\ s a -> s{_duPreview = a}) -- | The name of the deployment for this request. duDeployment :: Lens' DeploymentsUpdate Text duDeployment = lens _duDeployment (\ s a -> s{_duDeployment = a}) instance GoogleRequest DeploymentsUpdate where type Rs DeploymentsUpdate = Operation type Scopes DeploymentsUpdate = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/ndev.cloudman"] requestClient DeploymentsUpdate'{..} = go _duProject _duDeployment (Just _duCreatePolicy) (Just _duDeletePolicy) (Just _duPreview) (Just AltJSON) _duPayload deploymentManagerService where go = buildClient (Proxy :: Proxy DeploymentsUpdateResource) mempty
rueshyna/gogol
gogol-deploymentmanager/gen/Network/Google/Resource/DeploymentManager/Deployments/Update.hs
mpl-2.0
5,818
0
19
1,417
701
416
285
111
1
-- -- Copyright 2017-2018 Azad Bolour -- Licensed under GNU Affero General Public License v3.0 - -- https://github.com/azadbolour/boardgame/blob/master/LICENSE.md -- {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE DisambiguateRecordFields #-} module BoardGame.Server.Service.GamePersisterJsonBridge ( mkBridge ) where import Control.Monad.IO.Class (liftIO) import qualified Data.Sequence as Sequence import Bolour.Util.VersionStamped (Version, VersionStamped, VersionStamped(VersionStamped)) import qualified Bolour.Util.VersionStamped as VersionStamped import BoardGame.Server.Domain.Player (Player, Player(Player)) import BoardGame.Server.Domain.Play (Play(WordPlay), BasePlay(..)) import qualified BoardGame.Server.Domain.Play as Play import qualified BoardGame.Server.Domain.Player as Player import BoardGame.Server.Service.GameData (GameData, GameData(GameData)) import qualified BoardGame.Server.Service.GameData as GameData import BoardGame.Server.Domain.GameBase (GameBase, GameBase(GameBase)) import qualified BoardGame.Server.Domain.GameBase as GameBase import BoardGame.Server.Domain.GameError (GameError) import BoardGame.Server.Service.TypeDefs (Result) import BoardGame.Server.Service.GamePersister (GamePersister, GamePersister(GamePersister)) import BoardGame.Server.Service.GameJsonPersister (GameJsonPersister, GameJsonPersister(GameJsonPersister)) import qualified BoardGame.Server.Service.GameJsonPersister as GameJsonPersister migrate :: GameJsonPersister -> Result () migrate GameJsonPersister {migrate = delegate} = delegate savePlayer :: GameJsonPersister -> Version -> Player -> Result () savePlayer GameJsonPersister {addPlayer = delegate} version player @ Player {playerId, name} = do let json = VersionStamped.encodeWithVersion version player delegate playerId name json findPlayerById :: GameJsonPersister -> String -> Result (Maybe Player) findPlayerById GameJsonPersister {findPlayerById = delegate} playerId = do maybeJson <- delegate playerId return $ maybeJson >>= VersionStamped.decodeAndExtract findPlayerByName :: GameJsonPersister -> String -> Result (Maybe Player) findPlayerByName GameJsonPersister {findPlayerByName = delegate} playerName = do maybeJson <- delegate playerName return $ maybeJson >>= VersionStamped.decodeAndExtract clearPlayers :: GameJsonPersister -> Result () clearPlayers GameJsonPersister {clearPlayers = delegate} = delegate addGame :: GameJsonPersister -> Version -> GameData -> Result () addGame GameJsonPersister {addGame = delegate} version gameData @ GameData {base} = do let GameBase {gameId, playerId} = base json = VersionStamped.encodeWithVersion version gameData delegate gameId playerId json updateGame :: GameJsonPersister -> Version -> GameData -> Result () updateGame GameJsonPersister {updateGame = delegate} version gameData @ GameData {base, plays} = do let GameBase {gameId} = base json = VersionStamped.encodeWithVersion version gameData delegate gameId json findGameById :: GameJsonPersister -> String -> Result (Maybe GameData) findGameById GameJsonPersister {findGameById = delegate} gameUid = do maybeJson <- delegate gameUid let maybeGameData = maybeJson >>= VersionStamped.decodeAndExtract return maybeGameData deleteGame :: GameJsonPersister -> String -> Result () deleteGame GameJsonPersister {deleteGame = delegate} = delegate clearGames :: GameJsonPersister -> Result () clearGames GameJsonPersister {clearGames = delegate} = delegate mkBridge :: GameJsonPersister -> Version -> GamePersister mkBridge jsonPersister version = GamePersister (migrate jsonPersister) (savePlayer jsonPersister version) (findPlayerById jsonPersister) (findPlayerByName jsonPersister) (clearPlayers jsonPersister) (addGame jsonPersister version) (updateGame jsonPersister version) (findGameById jsonPersister) (deleteGame jsonPersister) (clearGames jsonPersister)
azadbolour/boardgame
haskell-server/src/BoardGame/Server/Service/GamePersisterJsonBridge.hs
agpl-3.0
3,933
3
12
484
968
536
432
70
1
{-# LANGUAGE BangPatterns, FlexibleContexts, FlexibleInstances , ParallelListComp, TypeFamilies, TypeOperators #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | Contains functions to compute and manipulate histograms as well as some -- images transformations which are histogram-based. -- -- Every polymorphic function is specialised for histograms of 'Int32', 'Double' -- and 'Float'. Other types can be specialized as every polymorphic function is -- declared @INLINABLE@. module Vision.Histogram ( -- * Types & helpers Histogram (..), HistogramShape (..), ToHistogram (..) , index, linearIndex, map, assocs, pixToBin -- * Histogram computations , histogram, histogram2D, reduce, resize, cumulative, normalize -- * Images processing , equalizeImage -- * Histogram comparisons , compareCorrel, compareChi, compareIntersect, compareEMD ) where import Data.Int import Data.Vector.Storable (Vector, (!)) import qualified Data.Vector.Storable as V import Foreign.Storable (Storable) import Prelude hiding (map) import Vision.Image.Grey.Type (GreyPixel (..)) import Vision.Image.HSV.Type (HSVPixel (..)) import Vision.Image.RGBA.Type (RGBAPixel (..)) import Vision.Image.RGB.Type (RGBPixel (..)) import Vision.Image.Type (Pixel, MaskedImage, Image, ImagePixel, FunctorImage) import qualified Vision.Image.Type as I import Vision.Primitive ( Z (..), (:.) (..), Shape (..), DIM1, DIM3, DIM4, DIM5, ix1, ix3, ix4 ) -- There is no rule to simplify the conversion from Int32 to Double and Float -- when using realToFrac. Both conversions are using a temporary yet useless -- Rational value. {-# RULES "realToFrac/Int32->Double" realToFrac = fromIntegral :: Int32 -> Double "realToFrac/Int32->Float" realToFrac = fromIntegral :: Int32 -> Float #-} -- Types ----------------------------------------------------------------------- data Histogram sh a = Histogram { shape :: !sh , vector :: !(Vector a) -- ^ Values of the histogram in row-major order. } deriving (Eq, Ord, Show) -- | Subclass of 'Shape' which defines how to resize a shape so it will fit -- inside a resized histogram. class Shape sh => HistogramShape sh where -- | Given a number of bins of an histogram, reduces an index so it will be -- mapped to a bin. toBin :: sh -- ^ The number of bins we are mapping to. -> sh -- ^ The number of possible values of the original index. -> sh -- ^ The original index. -> sh -- ^ The index of the bin in the histogram. instance HistogramShape Z where toBin _ _ _ = Z {-# INLINE toBin #-} instance HistogramShape sh => HistogramShape (sh :. Int) where toBin !(shBins :. bins) !(shMaxBins :. maxBins) !(shIx :. ix) | bins == maxBins = inner :. ix | otherwise = inner :. (ix * bins `quot` maxBins) where inner = toBin shBins shMaxBins shIx {-# INLINE toBin #-} -- | This class defines how many dimensions a histogram will have and what will -- be the default number of bins. class (Pixel p, Shape (PixelValueSpace p)) => ToHistogram p where -- | Gives the value space of a pixel. Single-channel pixels will be 'DIM1' -- whereas three-channels pixels will be 'DIM3'. -- This is used to determine the rank of the generated histogram. type PixelValueSpace p -- | Converts a pixel to an index. pixToIndex :: p -> PixelValueSpace p -- | Returns the maximum number of different values an index can take for -- each dimension of the histogram (aka. the maximum index returned by -- 'pixToIndex' plus one). domainSize :: p -> PixelValueSpace p instance ToHistogram GreyPixel where type PixelValueSpace GreyPixel = DIM1 pixToIndex !(GreyPixel val) = ix1 $ int val {-# INLINE pixToIndex #-} domainSize _ = ix1 256 instance ToHistogram RGBAPixel where type PixelValueSpace RGBAPixel = DIM4 pixToIndex !(RGBAPixel r g b a) = ix4 (int r) (int g) (int b) (int a) {-# INLINE pixToIndex #-} domainSize _ = ix4 256 256 256 256 instance ToHistogram RGBPixel where type PixelValueSpace RGBPixel = DIM3 pixToIndex !(RGBPixel r g b) = ix3 (int r) (int g) (int b) {-# INLINE pixToIndex #-} domainSize _ = ix3 256 256 256 instance ToHistogram HSVPixel where type PixelValueSpace HSVPixel = DIM3 pixToIndex !(HSVPixel h s v) = ix3 (int h) (int s) (int v) {-# INLINE pixToIndex #-} domainSize _ = ix3 180 256 256 -- Functions ------------------------------------------------------------------- index :: (Shape sh, Storable a) => Histogram sh a -> sh -> a index !hist = linearIndex hist . toLinearIndex (shape hist) {-# INLINE index #-} -- | Returns the value at the index as if the histogram was a single dimension -- vector (row-major representation). linearIndex :: (Shape sh, Storable a) => Histogram sh a -> Int -> a linearIndex !hist = (!) (vector hist) {-# INLINE linearIndex #-} map :: (Storable a, Storable b) => (a -> b) -> Histogram sh a -> Histogram sh b map f !(Histogram sh vec) = Histogram sh (V.map f vec) {-# INLINE map #-} -- | Returns all index/value pairs from the histogram. assocs :: (Shape sh, Storable a) => Histogram sh a -> [(sh, a)] assocs !(Histogram sh vec) = [ (ix, v) | ix <- shapeList sh | v <- V.toList vec ] {-# INLINE assocs #-} -- | Given the number of bins of an histogram and a given pixel, returns the -- corresponding bin. pixToBin :: (HistogramShape (PixelValueSpace p), ToHistogram p) => PixelValueSpace p -> p -> PixelValueSpace p pixToBin size p = let !domain = domainSize p in toBin size domain $! pixToIndex p {-# INLINE pixToBin #-} -- | Computes an histogram from a (possibly) multi-channel image. -- -- If the size of the histogram is not given, there will be as many bins as the -- range of values of pixels of the original image (see 'domainSize'). -- -- If the size of the histogram is specified, every bin of a given dimension -- will be of the same size (uniform histogram). histogram :: ( MaskedImage i, ToHistogram (ImagePixel i), Storable a, Num a , HistogramShape (PixelValueSpace (ImagePixel i))) => Maybe (PixelValueSpace (ImagePixel i)) -> i -> Histogram (PixelValueSpace (ImagePixel i)) a histogram mSize img = let initial = V.replicate nBins 0 ones = V.replicate nPixs 1 ixs = V.map toIndex (I.values img) in Histogram size (V.accumulate_ (+) initial ixs ones) where !size = case mSize of Just s -> s Nothing -> domainSize (I.pixel img) !nChans = I.nChannels img !nPixs = shapeLength (I.shape img) * nChans !nBins = shapeLength size toIndex !p = toLinearIndex size $! case mSize of Just _ -> pixToBin size p Nothing -> pixToIndex p {-# INLINE toIndex #-} {-# INLINABLE histogram #-} -- | Similar to 'histogram' but adds two dimensions for the y and x-coordinates -- of the sampled points. This way, the histogram will map different regions of -- the original image. -- -- For example, an 'RGB' image will be mapped as -- @'Z' ':.' red channel ':.' green channel ':.' blue channel ':.' y region -- ':.' x region@. -- -- As there is no reason to create an histogram as large as the number of pixels -- of the image, a size is always needed. histogram2D :: ( Image i, ToHistogram (ImagePixel i), Storable a, Num a , HistogramShape (PixelValueSpace (ImagePixel i))) => (PixelValueSpace (ImagePixel i)) :. Int :. Int -> i -> Histogram ((PixelValueSpace (ImagePixel i)) :. Int :. Int) a histogram2D size img = let initial = V.replicate nBins 0 ones = V.replicate nPixs 1 imgIxs = V.iterateN nPixs (shapeSucc imgSize) shapeZero ixs = V.zipWith toIndex imgIxs (I.vector img) in Histogram size (V.accumulate_ (+) initial ixs ones) where !imgSize@(Z :. h :. w) = I.shape img !maxSize = domainSize (I.pixel img) :. h :. w !nChans = I.nChannels img !nPixs = shapeLength (I.shape img) * nChans !nBins = shapeLength size toIndex !(Z :. y :. x) !p = let !ix = (pixToIndex p) :. y :. x in toLinearIndex size $! toBin size maxSize ix {-# INLINE toIndex #-} {-# INLINABLE histogram2D #-} -- Reshaping ------------------------------------------------------------------- -- | Reduces a 2D histogram to its linear representation. See 'resize' for a -- reduction of the number of bins of an histogram. -- -- @'histogram' == 'reduce' . 'histogram2D'@ reduce :: (HistogramShape sh, Storable a, Num a) => Histogram (sh :. Int :. Int) a -> Histogram sh a reduce !(Histogram sh vec) = let !(sh' :. h :. w) = sh !len2D = h * w !vec' = V.unfoldrN (shapeLength sh') step vec step !rest = let (!channels, !rest') = V.splitAt len2D rest in Just (V.sum channels, rest') in Histogram sh' vec' {-# SPECIALIZE reduce :: Histogram DIM5 Int32 -> Histogram DIM3 Int32 , Histogram DIM5 Double -> Histogram DIM3 Double , Histogram DIM5 Float -> Histogram DIM3 Float , Histogram DIM3 Int32 -> Histogram DIM1 Int32 , Histogram DIM3 Double -> Histogram DIM1 Double , Histogram DIM3 Float -> Histogram DIM1 Float #-} {-# INLINABLE reduce #-} -- | Resizes an histogram to another index shape. See 'reduce' for a reduction -- of the number of dimensions of an histogram. resize :: (HistogramShape sh, Storable a, Num a) => sh -> Histogram sh a -> Histogram sh a resize !sh' (Histogram sh vec) = let initial = V.replicate (shapeLength sh') 0 -- TODO: In this scheme, indexes are computed for each bin of the -- original histogram. It's sub-optimal as some parts of those indexes -- (lower dimensions) don't change at each bin. reIndex = toLinearIndex sh' . toBin sh' sh . fromLinearIndex sh ixs = V.map reIndex $ V.enumFromN 0 (shapeLength sh) in Histogram sh' (V.accumulate_ (+) initial ixs vec) -- Normalisation --------------------------------------------------------------- -- | Computes the cumulative histogram of another single dimension histogram. -- -- @C(i) = SUM H(j)@ for each @j@ in @[0..i]@ where @C@ is the cumulative -- histogram, and @H@ the original histogram. cumulative :: (Storable a, Num a) => Histogram DIM1 a -> Histogram DIM1 a cumulative (Histogram sh vec) = Histogram sh (V.scanl1' (+) vec) {-# SPECIALIZE cumulative :: Histogram DIM1 Int32 -> Histogram DIM1 Int32 , Histogram DIM1 Double -> Histogram DIM1 Double , Histogram DIM1 Float -> Histogram DIM1 Float #-} {-# INLINABLE cumulative #-} -- | Normalizes the histogram so that the sum of the histogram bins is equal to -- the given value (normalisation by the @L1@ norm). -- -- This is useful to compare two histograms which have been computed from images -- with a different number of pixels. normalize :: (Storable a, Real a, Storable b, Fractional b) => b -> Histogram sh a -> Histogram sh b normalize norm !hist@(Histogram _ vec) = let !ratio = norm / realToFrac (V.sum vec) equalizeVal !val = realToFrac val * ratio {-# INLINE equalizeVal #-} in map equalizeVal hist {-# SPECIALIZE normalize :: Double -> Histogram sh Int32 -> Histogram sh Double , Float -> Histogram sh Int32 -> Histogram sh Float , Double -> Histogram sh Double -> Histogram sh Double , Float -> Histogram sh Double -> Histogram sh Float , Double -> Histogram sh Float -> Histogram sh Double , Float -> Histogram sh Float -> Histogram sh Float #-} {-# INLINABLE normalize #-} -- | Equalizes a single channel image by equalising its histogram. -- -- The algorithm equalizes the brightness and increases the contrast of the -- image by mapping each pixel values to the value at the index of the -- cumulative @L1@-normalized histogram : -- -- @N(x, y) = H(I(x, y))@ where @N@ is the equalized image, @I@ is the image and -- @H@ the cumulative of the histogram normalized over an @L1@ norm. -- -- See <https://en.wikipedia.org/wiki/Histogram_equalization>. equalizeImage :: ( FunctorImage i i, Integral (ImagePixel i) , ToHistogram (ImagePixel i) , PixelValueSpace (ImagePixel i) ~ DIM1) => i -> i equalizeImage img = I.map equalizePixel img where hist = histogram Nothing img :: Histogram DIM1 Int32 Z :. nBins = shape hist cumNormalized = cumulative $ normalize (double nBins) hist !cumNormalized' = map round cumNormalized :: Histogram DIM1 Int32 equalizePixel !val = fromIntegral $ cumNormalized' `index` ix1 (int val) {-# INLINE equalizePixel #-} {-# INLINABLE equalizeImage #-} -- Comparisons ----------------------------------------------------------------- -- | Computes the /Pearson\'s correlation coefficient/ between each -- corresponding bins of the two histograms. -- -- A value of 1 implies a perfect correlation, a value of -1 a perfect -- opposition and a value of 0 no correlation at all. -- -- @'compareCorrel' = SUM [ (H1(i) - µ(H1)) (H1(2) - µ(H2)) ] -- / ( SQRT [ SUM [ (H1(i) - µ(H1))^2 ] ] -- * SQRT [ SUM [ (H2(i) - µ(H2))^2 ] ] )@ -- -- Where @µ(H)@ is the average value of the histogram @H@. -- -- See <http://en.wikipedia.org/wiki/Pearson_correlation_coefficient>. compareCorrel :: (Shape sh, Storable a, Real a, Storable b, Eq b, Floating b) => Histogram sh a -> Histogram sh a -> b compareCorrel (Histogram sh1 vec1) (Histogram sh2 vec2) | sh1 /= sh2 = error "Histograms are not of equal size." | denominat == 0 = 1 | otherwise = numerat / denominat where numerat = V.sum $ V.zipWith (*) diff1 diff2 denominat = sqrt (V.sum (V.map square diff1)) * sqrt (V.sum (V.map square diff2)) diff1 = V.map (\v1 -> realToFrac v1 - avg1) vec1 diff2 = V.map (\v2 -> realToFrac v2 - avg2) vec2 (avg1, avg2) = (avg vec1, avg vec2) avg !vec = realToFrac (V.sum vec) / realToFrac (V.length vec) {-# SPECIALIZE compareCorrel :: Shape sh => Histogram sh Int32 -> Histogram sh Int32 -> Double , Shape sh => Histogram sh Int32 -> Histogram sh Int32 -> Float , Shape sh => Histogram sh Double -> Histogram sh Double -> Double , Shape sh => Histogram sh Double -> Histogram sh Double -> Float , Shape sh => Histogram sh Float -> Histogram sh Float -> Double , Shape sh => Histogram sh Float -> Histogram sh Float -> Float #-} {-# INLINABLE compareCorrel #-} -- | Computes the Chi-squared distance between two histograms. -- -- A value of 0 indicates a perfect match. -- -- @'compareChi' = SUM (d(i))@ for each indice @i@ of the histograms where -- @d(i) = 2 * ((H1(i) - H2(i))^2 / (H1(i) + H2(i)))@. compareChi :: (Shape sh, Storable a, Real a, Storable b, Fractional b) => Histogram sh a -> Histogram sh a -> b compareChi (Histogram sh1 vec1) (Histogram sh2 vec2) | sh1 /= sh2 = error "Histograms are not of equal size." | otherwise = (V.sum $ V.zipWith step vec1 vec2) * 2 where step !v1 !v2 = let !denom = v1 + v2 in if denom == 0 then 0 else realToFrac (square (v1 - v2)) / realToFrac denom {-# INLINE step #-} {-# SPECIALIZE compareChi :: Shape sh => Histogram sh Int32 -> Histogram sh Int32 -> Double , Shape sh => Histogram sh Int32 -> Histogram sh Int32 -> Float , Shape sh => Histogram sh Double -> Histogram sh Double -> Double , Shape sh => Histogram sh Double -> Histogram sh Double -> Float , Shape sh => Histogram sh Float -> Histogram sh Float -> Double , Shape sh => Histogram sh Float -> Histogram sh Float -> Float #-} {-# INLINABLE compareChi #-} -- | Computes the intersection of the two histograms. -- -- The higher the score is, the best the match is. -- -- @'compareIntersect' = SUM (min(H1(i), H2(i))@ for each indice @i@ of the -- histograms. compareIntersect :: (Shape sh, Storable a, Num a, Ord a) => Histogram sh a -> Histogram sh a -> a compareIntersect (Histogram sh1 vec1) (Histogram sh2 vec2) | sh1 /= sh2 = error "Histograms are not of equal size." | otherwise = V.sum $ V.zipWith min vec1 vec2 {-# SPECIALIZE compareIntersect :: Shape sh => Histogram sh Int32 -> Histogram sh Int32 -> Int32 , Shape sh => Histogram sh Double -> Histogram sh Double -> Double , Shape sh => Histogram sh Float -> Histogram sh Float -> Float #-} {-# INLINABLE compareIntersect #-} -- | Computed the /Earth mover's distance/ between two histograms. -- -- Current algorithm only supports histograms of one dimension. -- -- See <https://en.wikipedia.org/wiki/Earth_mover's_distance>. compareEMD :: (Num a, Storable a) => Histogram DIM1 a -> Histogram DIM1 a -> a compareEMD hist1@(Histogram sh1 _) hist2@(Histogram sh2 _) | sh1 /= sh2 = error "Histograms are not of equal size." | otherwise = let Histogram _ vec1 = cumulative hist1 Histogram _ vec2 = cumulative hist2 in V.sum $ V.zipWith (\v1 v2 -> abs (v1 - v2)) vec1 vec2 {-# SPECIALIZE compareEMD :: Histogram DIM1 Int32 -> Histogram DIM1 Int32 -> Int32 , Histogram DIM1 Double -> Histogram DIM1 Double -> Double , Histogram DIM1 Float -> Histogram DIM1 Float -> Float #-} {-# INLINABLE compareEMD #-} square :: Num a => a -> a square a = a * a double :: Integral a => a -> Double double= fromIntegral int :: Integral a => a -> Int int = fromIntegral
TomMD/friday
src/Vision/Histogram.hs
lgpl-3.0
17,942
1
15
4,447
3,575
1,874
1,701
242
3
module Function.TypeFooler where -- External Imports import Language.Haskell.Her.HaLay import Data.List.Split (splitOn) import Data.List (intercalate, elem, isSuffixOf, intersperse) import Text.ParserCombinators.Parsec (parse, manyTill, anyChar, try, string, manyTill) import Debug.Trace (trace) import System.IO -- Project Imports import GHCIProc import FileUtils (splitPath) import TokenUtils import ListUtils -- Either String String {-| Find the type of a variable by inserting a tactical type error -} findTypeOfVarAtTok :: FilePath -> FilePath -> Tok -> ([[Tok]], [[Tok]], [[Tok]]) -> String -> IO (Maybe String) findTypeOfVarAtTok ghci file tok (str, fn, end) vname = do case extractFunctionNameFromLine (head fn) of Nothing -> return Nothing Just fnName -> do let (filePath, fileName) = splitPath file nfn <- ensureFunctionHasType ghci fnName fn file let newFn = insertTacticalTypeError tok (typeFoolerCaller vname) nfn case newFn == fn of True -> return (Just "Couldnt insert type fooler") False -> do let newEnd = insertTypeFooler end let newFile = untokeniseArr (str ++ newFn ++ newEnd) writeFile file newFile response <- runCommandList ghci file [] writeFile file (tokssOut (str ++ fn ++ end)) case lookup (LOAD fileName) response of Nothing -> return Nothing Just loadErrResp -> do case parseTacticalTypeError errorStrings (readGhciError loadErrResp) of Nothing -> return Nothing Just mType -> return (Just mType) {-| Find the return type of a function by inserting a tactical type error -} findReturnTypeAtTok :: FilePath -> FilePath -> Tok -> ([[Tok]], [[Tok]], [[Tok]]) -> IO (Maybe String) findReturnTypeAtTok ghci file tok (str, fn, end) = do case extractFunctionNameFromLine (head fn) of Nothing -> return Nothing Just fnName -> do let (filePath, fileName) = splitPath file nfn <- ensureFunctionHasType ghci fnName fn file let newFn = insertTacticalTypeError tok typeFoolerReturnType nfn case newFn == fn of True -> return (Just "Couldnt insert type fooler") False -> do let newEnd = insertTypeFooler end let newFile = untokeniseArr (str ++ newFn ++ newEnd) writeFile file newFile response <- runCommandList ghci file [] writeFile file (tokssOut (str ++ fn ++ end)) case lookup (LOAD fileName) response of Nothing -> return Nothing Just loadErrResp -> do case parseTacticalTypeError errorStrings (readGhciError loadErrResp) of Nothing -> return Nothing Just mType -> return (Just mType) {-| insertTacticalTypeError will look for the line containing {-SPLIT-} and insert our type error onto the end of the file, deleting the existing right hand side of the binding if it exists -} insertTacticalTypeError :: Tok -> [Tok] -> [[Tok]] -> [[Tok]] insertTacticalTypeError tok er [] = [] insertTacticalTypeError tok er (t:ts) = case elemToken tok t of False -> t : insertTacticalTypeError tok er ts True -> scope t : ts where scope [] = [] scope ((L x lss) : ts) = case elemTokenArr tok lss of True -> (L x (insertTacticalTypeError tok er lss)) : ts False -> (L x lss) : scope ts scope ((B x rs) : ts) = case elemToken tok rs of True -> (B x rs) : insert ts False -> (B x rs) : scope ts scope ((T x rs) : ts) = case elemToken tok rs of True -> (T x rs) : insert ts False -> (T x rs) : scope ts scope ((Sym "=") : ts) = case elemOuter tok ts of True -> er False -> (Sym "=") : scope ts scope (t:ts) = case t == tok of True -> t : insert ts False -> t : scope ts insert [] = [] insert ((Sym "=") : ts) = er insert (t:ts) = t : insert ts elemOuter tok [] = False elemOuter tok (t:ts) = case t == tok of True -> True False -> elemOuter tok ts {-| Add Type Fooler will tag our BlackboxGHCITypeFooler class & plzTellMeTheTypeGHCI onto the end of the class -} insertTypeFooler :: [[Tok]] -> [[Tok]] insertTypeFooler tokens = tokens ++ typeFoolerDataType typeFoolerCaller :: String -> [Tok] typeFoolerCaller varName = head $ tokeniseString ("= plzTellMeTheTypeGHCI " ++ varName) typeFoolerReturnType :: [Tok] typeFoolerReturnType = head $ tokeniseString ("= BlackboxGHCITypeFooler") -- These are Strings GHCI wraps type errors in, -- Add more below to account for more errors, diffrent versions etc errorStrings :: [(String, String)] errorStrings = [ ("with actual type `", "'") , ("Couldn't match expected type `BlackboxGHCITypeFooler'\nwith actual type `", "'") , ("Couldn't match type `", "' with `BlackboxGHCITypeFooler'") , ("Couldn't match expected type `", "'\nwith actual type `BlackboxGHCITypeFooler'") , ("Couldn't match expected type `", "'with actual type `BlackboxGHCITypeFooler'") , ("Couldn't match expected type `", "' \nwith actual type `BlackboxGHCITypeFooler'") , ("Couldn't match expected type `", "' with actual type `BlackboxGHCITypeFooler'") , ("`","' is a rigid type variable bound by")] {-| Given a List of GHCi error strings and our tactical type error attempt to parse the expected type of the binding. Wrapped in Maybe to denote failure -} parseTacticalTypeError :: [(String, String)] -> String -> Maybe String parseTacticalTypeError [] err = Nothing parseTacticalTypeError ((s, e): es) err = case parse (parseBetween s e) ("parseTacticalTypeError:" ++ (s ++ "->" ++ e)) err of Left _ -> parseTacticalTypeError es err Right val -> case val == "BlackboxGHCITypeFooler" of -- Some types end up being swapped about True -> parseTacticalTypeError es err False -> Just val parseBetween s e = do { manyTill anyChar (try (string s)) ; manyTill anyChar (try (string e)) } {-| Make sure that the set of tokens for the function passed in contains a high level type line. If it doesn't attempt to get one from GHCI -} ensureFunctionHasType :: FilePath -> String -> [[Tok]] -> FilePath -> IO [[Tok]] ensureFunctionHasType ghci name tokens file = case head tokens of [] -> return [] xs -> case elemToken (Sym "::") xs of True -> return tokens False -> do fntype <- getFunctionTypeFromGHCI ghci file name case fntype of Nothing -> return tokens Just fntype -> do let typeTokens = ready "" fntype -- Need to check if the line doesnt end with this already return $ typeTokens ++ ([NL ("", 0)] : tokens) {-| Query GHCI for the type of a function -} getFunctionTypeFromGHCI :: FilePath -> FilePath -> String -> IO (Maybe String) getFunctionTypeFromGHCI ghci file name = do let cmd = TYPEINFO name resp <- runCommandList ghci file [cmd] case lookup cmd resp of Nothing -> return Nothing Just resp -> do return $ Just (readGhciOutput resp) typeFoolerDataType :: [[Tok]] typeFoolerDataType = tokeniseString $ unlines dt {-| Datatype used for type fooling -} dt :: [String] dt = [ "" , "{-# LANGUAGE ScopedTypeVariables #-}" , "data BlackboxGHCITypeFooler = BlackboxGHCITypeFooler" , "plzTellMeTheTypeGHCI :: BlackboxGHCITypeFooler -> a" , "plzTellMeTheTypeGHCI = undefined" , "" ]
DarrenMowat/blackbox
src/Function/TypeFooler.hs
unlicense
7,854
0
27
2,239
2,152
1,100
1,052
136
16
{-# LANGUAGE TypeFamilies #-} -- 3.1 Type-directed memoization -------------------------------- class Memo a where data Table a :: * -> * toTable :: (a -> w) -> Table a w fromTable :: Table a w -> (a -> w) instance Memo Bool where data Table Bool w = TBool w w toTable f = TBool (f True) (f False) fromTable (TBool x y) b = if b then x else y g :: Bool -> Integer g = fromTable (toTable f) factorial n | n < 1 = 1 | otherwise = n * factorial (n-1) fibonacci n | n < 2 = 1 | otherwise = fibonacci(n-1) + fibonacci(n-2) f True = factorial 30000 f False = fibonacci 30 -------------------- instance (Memo a, Memo b) => Memo (Either a b) where data Table (Either a b) w = TSum (Table a w) (Table b w) toTable f = TSum (toTable (f . Left)) (toTable (f . Right)) fromTable (TSum t _) (Left v) = fromTable t v fromTable (TSum _ t) (Right v) = fromTable t v f1 :: Either Bool Bool -> Integer f1 v = case v of Left x -> if x then factorial 30000 else factorial 30 Right x -> if x then fibonacci 30 else fibonacci 10 g1 = fromTable . toTable $ f1 -------------------- instance (Memo a, Memo b) => Memo (a,b) where newtype Table (a,b) w = TProduct (Table a (Table b w)) toTable f = TProduct (toTable (\x -> toTable (\y -> f (x,y)))) fromTable (TProduct t) (x,y) = fromTable (fromTable t x) y f2 :: (Bool,Bool) -> Integer f2 (True,True) = factorial 30000 f2 (True,False) = factorial 30 f2 (False,True) = fibonacci 30 f2 (False,False) = fibonacci 10 g2 = fromTable . toTable $ f2 -- 3.2 Memoization for recrusive types -------------------------------------- instance (Memo a) => Memo [a] where data Table [a] w = TList w (Table a (Table [a] w)) toTable f = TList (f []) (toTable (\x -> toTable (\xs -> f (x:xs)))) fromTable (TList t _) [] = t fromTable (TList _ t) (x:xs) = fromTable (fromTable t x) xs f3 :: [Bool] -> Integer f3 [] = -1 f3 [True,True,False] = fibonacci 20 f3 [True,False,True] = fibonacci 30 f3 [True,False,False] = fibonacci 35 f3 [False,True,True] = fibonacci 13 f3 [False,True,False] = fibonacci 23 f3 [False,False,True] = fibonacci 33 f3 [False,False,False] = fibonacci 33 g3 = fromTable . toTable $ f3 -- 3.3 Generic finite maps -------------------------- class Key k where data Map k :: * -> * empty :: Map k v lookp :: k -> Map k v -> Maybe v instance Key Bool where data Map Bool elt = MB (Maybe elt) (Maybe elt) empty = MB Nothing Nothing lookp False (MB mf _) = mf lookp True (MB _ mt) = mt -- 3.4 Session types and their duality -------------------------------------- data Stop = Done newtype In a b = In (a -> IO b) data Out a b = Out a (IO b) add_server :: In Int (In Int (Out Int Stop)) add_server = In $ \x -> return $ In $ \y -> do putStrLn "Thinking" return $ Out (x+y) (return Done) class Session a where type Dual a run :: a -> Dual a -> IO () instance (Session b) => Session (In a b) where type Dual (In a b) = Out a (Dual b) run (In f) (Out a d) = f a >>= \b -> d >>= \c -> run b c instance (Session b) => Session (Out a b) where type Dual (Out a b) = In a (Dual b) run (Out a d) (In f) = f a >>= \b -> d >>= \c -> run c b instance Session Stop where type Dual Stop = Stop run Done Done = return () add_client :: Out Int (Out Int (In Int Stop)) add_client = Out 3 $ return $ Out 4 $ do putStrLn "Waiting" return $ In $ \ z-> print z >> return Done test1 = run add_server add_client test2 = run add_client add_server neg_server :: In Int (Out Int Stop) neg_server = In $ \x -> do putStrLn "Thinking" return $ Out (-x) (return Done) instance (Session a, Session b) => Session (Either a b) where type Dual (Either a b) = (Dual a, Dual b) run (Left y) (x,_) = run y x run (Right y) (_,x) = run y x instance (Session a, Session b) => Session (a, b) where type Dual (a,b) = Either (Dual a) (Dual b) run (x,_) (Left y) = run x y run (_,x) (Right y) = run x y neg_client :: Out Int (In Int Stop) neg_client = Out 5 . (putStrLn "Waiting" >>) . return $ In $ \z -> print z >> return Done server :: (In Int (Out Int Stop), In Int (In Int (Out Int Stop))) server = (neg_server, add_server) client :: Either (Out Int (In Int Stop)) (Out Int (Out Int (In Int Stop))) client = Right add_client test3 = run server client >> run client server
egaburov/funstuff
Haskell/fun-with-types/memo.hs
apache-2.0
4,477
0
16
1,171
2,256
1,159
1,097
104
4
-- Input/Output (aka De-/serialization) for expressions {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE RankNTypes #-} module IO where import Data.Generics import Data.Tree import DataBase import DataExtension {- Let's serialize. In fact, let's "treealize". It should be noted that such conversion, expressiveness-wise, is like printing, which we covered before. Hence, let's use SYB to provides that operation in a generic manner. -} toTree :: Data x => x -> Tree String toTree x = Node (showConstr (toConstr x)) (gmapQ toTree x) {- We could try to use the magic of SYB to do the de-serialization. In fact, this is not straigthforward. (Solutions are appreciated, and should be sent directly to haskell-cafe.) Let us try to understand de-serialization (or de-treealization) as an "open" operation here. So let us apply the same class-based method as in the case of printing and evaluation; this approach fails, as we discuss below. -} class FromTree x where fromTree :: Tree String -> x instance FromTree Lit where fromTree (Node "Lit" [i]) = Lit (fromTree i) instance (Exp e, Exp e', FromTree e, FromTree e') => FromTree (Add e e') where fromTree (Node "Add" [x,y]) = Add (fromTree x) (fromTree y) instance (Exp e, FromTree e) => FromTree (Neg e) where fromTree (Node "Neg" [x]) = Neg (fromTree x) instance FromTree Int where fromTree (Node s []) = read s {- The problem with this apparently open and extensible solution is that we would need to know the precise type of the result of de-serialization for it to work on the grounds of the many instances shown. This is absolutely unrealistic. (Types represent shape of input in our model.) We need a way to combine all those cases operationally so that they are tried until one applies. The result of the operation can be of many different types though (literals, additions, etc.), and hence, we also need to exploit a form of polymorphism to express that result type. An attempt follows, but it fails, as we will discuss below. -} -- The homogenized type of all expressions data AnyExp = forall x. (Exp x, Show x) => AnyExp x instance Show AnyExp where show (AnyExp x) = show x -- Apply a polymorphic function on expressions applyToExp :: (forall x. (Exp x, Show x) => x -> y) -> AnyExp -> y applyToExp f (AnyExp x) = f x -- The conversion from trees to expressions tree2exp :: Tree String -> AnyExp tree2exp (Node "Lit" [i]) = AnyExp (Lit (fromTree i)) tree2exp (Node "Neg" [x]) = applyToExp (AnyExp . Neg) (tree2exp x) tree2exp (Node "Add" [x,y]) = applyToExp (applyToExp (\x' -> AnyExp . Add x') (tree2exp x)) (tree2exp y) {- One problem with this attempt is that it is actually no longer open (extensible). The given function takes a closed-world assumption on the served forms of trees (corresponding to known forms of expressions). This problem could be potentially solved by sort of chaining up "blocks" like the one above with the help of maybes. The bigger problem is the representation of the result. When we existentially quantify, we must also mention all type-class constraints that are needed perhaps. The type AnyExp mentions Exp as the only constraint. This leaves us virtually with no operation to be applied to the result of de-serialization. For instance, if we wanted to print the de-serialized expression, we better add a printing constraint to AnyExp--but how can we possibly anticipate all operations to be applied to the results of de-serialization? We call this the de-serialization problem: "Can we describe functionality for de-serialization in a modular fashion so that arbitrary functionality can be applied to the data, just as if the data was never serialized in the first place?" -}
egaburov/funstuff
Haskell/tytag/xproblem_src/samples/expressions/Haskell/OpenDatatype2/IO.hs
apache-2.0
3,906
0
11
846
565
294
271
33
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | Frame source module Haskus.System.Linux.Graphics.FrameSource ( -- * Frame source FrameSource(..) , addFrameSource , removeFrameSource , dirtyFrameSource -- * Pixel source , PixelSource(..) -- * Flip, Clip, Dirty , PageFlipFlag (..) , PageFlipFlags , DirtyAnnotation (..) , Clip (..) ) where import Haskus.System.Linux.ErrorCode import Haskus.System.Linux.Handle import Haskus.System.Linux.Graphics.PixelFormat import Haskus.System.Linux.Graphics.Entities import Haskus.System.Linux.Internals.Graphics import Haskus.Format.Binary.Vector as Vector import Haskus.Format.Binary.Word import Haskus.Format.Binary.Ptr import Haskus.Format.Binary.Storable import Haskus.Utils.Tuple import Haskus.Utils.Flow import Haskus.Utils.List (zip4) fromFrameSource :: FrameSource -> StructFrameBufferCommand fromFrameSource FrameSource{..} = s where g :: (Num a,Storable a) => (PixelSource -> a) -> Vector 4 a g f = Vector.fromFilledList 0 (fmap f frameSources) s = StructFrameBufferCommand (unEntityID frameID) frameWidth frameHeight framePixelFormat frameFlags (g surfaceHandle) (g surfacePitch) (g surfaceOffset) (g surfaceModifiers) toFrameSource :: StructFrameBufferCommand -> FrameSource toFrameSource StructFrameBufferCommand{..} = s where bufs = uncurry4 PixelSource <$> zip4 (Vector.toList fc2Handles) (Vector.toList fc2Pitches) (Vector.toList fc2Offsets) (Vector.toList fc2Modifiers) s = FrameSource (EntityID fc2FbId) fc2Width fc2Height fc2PixelFormat fc2Flags bufs -- | Create a framebuffer addFrameSource :: MonadInIO m => Handle -> Word32 -> Word32 -> PixelFormat -> FrameBufferFlags -> [PixelSource] -> FlowT '[ErrorCode] m FrameSource addFrameSource hdl width height fmt flags buffers = do let s = FrameSource (EntityID 0) width height fmt flags buffers ioctlAddFrameBuffer (fromFrameSource s) hdl ||> toFrameSource -- | Release a frame buffer removeFrameSource :: MonadInIO m => Handle -> FrameSource -> FlowT '[ErrorCode] m () removeFrameSource hdl fs = do void (ioctlRemoveFrameBuffer (unEntityID (frameID fs)) hdl) -- | Indicate dirty parts of a frame source dirtyFrameSource :: MonadInIO m => Handle -> FrameSource -> DirtyAnnotation -> FlowT '[ErrorCode] m () dirtyFrameSource hdl fs mode = do let (color,flags,clips) = case mode of Dirty cs -> (0,0,cs) DirtyCopy cs -> (0,1, concatMap (\(a,b) -> [a,b]) cs) DirtyFill c cs -> (c,2,cs) void $ withArray clips $ \clipPtr -> do let s = StructFrameBufferDirty { fdFbId = unEntityID (frameID fs) , fdFlags = flags , fdColor = color , fdNumClips = fromIntegral (length clips) , fdClipsPtr = fromIntegral (ptrToWordPtr clipPtr) } ioctlDirtyFrameBuffer s hdl
hsyl20/ViperVM
haskus-system/src/lib/Haskus/System/Linux/Graphics/FrameSource.hs
bsd-3-clause
3,117
0
18
744
833
459
374
67
3
-- | Server operations for items. module Game.LambdaHack.Server.ItemM ( registerItem, moveStashIfNeeded, randomResetTimeout, embedItemOnPos , prepareItemKind, rollItemAspect, rollAndRegisterItem , placeItemsInDungeon, embedItemsInDungeon, mapActorCStore_ #ifdef EXPOSE_INTERNAL -- * Internal operations , onlyRegisterItem, computeRndTimeout, createCaveItem, createEmbedItem #endif ) where import Prelude () import Game.LambdaHack.Core.Prelude import qualified Data.EnumMap.Strict as EM import qualified Data.EnumSet as ES import qualified Data.HashMap.Strict as HM import Game.LambdaHack.Atomic import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Item import qualified Game.LambdaHack.Common.ItemAspect as IA import Game.LambdaHack.Common.Kind import Game.LambdaHack.Common.Level import Game.LambdaHack.Common.MonadStateRead import Game.LambdaHack.Common.Point import qualified Game.LambdaHack.Common.PointArray as PointArray import Game.LambdaHack.Common.State import qualified Game.LambdaHack.Common.Tile as Tile import Game.LambdaHack.Common.Time import Game.LambdaHack.Common.Types import Game.LambdaHack.Content.CaveKind (citemFreq, citemNum) import Game.LambdaHack.Content.ItemKind (ItemKind) import qualified Game.LambdaHack.Content.ItemKind as IK import Game.LambdaHack.Content.TileKind (TileKind) import qualified Game.LambdaHack.Core.Dice as Dice import Game.LambdaHack.Core.Frequency import Game.LambdaHack.Core.Random import qualified Game.LambdaHack.Definition.Ability as Ability import Game.LambdaHack.Definition.Defs import Game.LambdaHack.Server.ItemRev import Game.LambdaHack.Server.MonadServer import Game.LambdaHack.Server.ServerOptions import Game.LambdaHack.Server.State onlyRegisterItem :: MonadServerAtomic m => ItemKnown -> m ItemId onlyRegisterItem itemKnown@(ItemKnown _ arItem _) = do itemRev <- getsServer sitemRev case HM.lookup itemKnown itemRev of Just iid -> return iid Nothing -> do icounter <- getsServer sicounter executedOnServer <- execUpdAtomicSer $ UpdDiscoverServer icounter arItem let !_A = assert executedOnServer () modifyServer $ \ser -> ser { sitemRev = HM.insert itemKnown icounter (sitemRev ser) , sicounter = succ icounter } return $! icounter registerItem :: MonadServerAtomic m => Bool -> ItemFullKit -> ItemKnown -> Container -> m ItemId registerItem verbose (itemFull@ItemFull{itemBase, itemKindId, itemKind}, kit) itemKnown@(ItemKnown _ arItem _) containerRaw = do container <- case containerRaw of CActor aid CEqp -> do b <- getsState $ getActorBody aid return $! if eqpFreeN b >= fst kit then containerRaw else CActor aid CStash _ -> return containerRaw iid <- onlyRegisterItem itemKnown let slore = IA.loreFromContainer arItem container modifyServer $ \ser -> ser {sgenerationAn = EM.adjust (EM.insertWith (+) iid (fst kit)) slore (sgenerationAn ser)} moveStash <- moveStashIfNeeded container mapM_ execUpdAtomic moveStash execUpdAtomic $ UpdCreateItem verbose iid itemBase kit container let worth = itemPrice (fst kit) itemKind case container of _ | worth == 0 -> return () CActor _ COrgan -> return () -- destroyed on drop CTrunk{} -> return () -- we assume any valuables in CEmbed can be dug out _ -> execUpdAtomic $ UpdAlterGold worth knowItems <- getsServer $ sknowItems . soptions when knowItems $ case container of CTrunk{} -> return () _ -> execUpdAtomic $ UpdDiscover container iid itemKindId arItem -- The first recharging period after creation is random, -- between 1 and 2 standard timeouts of the item. -- In this way we avoid many rattlesnakes rattling in unison. case container of CActor _ cstore | cstore `elem` [CEqp, COrgan] -> randomResetTimeout (fst kit) iid itemFull [] container _ -> return () return iid moveStashIfNeeded :: MonadStateRead m => Container -> m [UpdAtomic] moveStashIfNeeded c = case c of CActor aid CStash -> do b <- getsState $ getActorBody aid mstash <- getsState $ \s -> gstash $ sfactionD s EM.! bfid b case mstash of Just (lid, pos) -> do bagStash <- getsState $ getFloorBag lid pos return $! if EM.null bagStash then [ UpdLoseStashFaction False (bfid b) lid pos , UpdSpotStashFaction True (bfid b) (blid b) (bpos b) ] else [] Nothing -> return [UpdSpotStashFaction True (bfid b) (blid b) (bpos b)] _ -> return [] randomResetTimeout :: MonadServerAtomic m => Int -> ItemId -> ItemFull -> [ItemTimer] -> Container -> m () randomResetTimeout k iid itemFull beforeIt toC = do lid <- getsState $ lidFromC toC localTime <- getsState $ getLocalTime lid mrndTimeout <- rndToAction $ computeRndTimeout localTime itemFull -- The created or moved item set (not the items previously at destination) -- has its timeouts reset to a random value between timeout and twice timeout. -- This prevents micromanagement via swapping items in and out of eqp -- and via exact prediction of first timeout after equip. case mrndTimeout of Just rndT -> do bagAfter <- getsState $ getContainerBag toC let afterIt = case iid `EM.lookup` bagAfter of Nothing -> error $ "" `showFailure` (iid, bagAfter, toC) Just (_, it2) -> it2 resetIt = beforeIt ++ replicate k rndT when (afterIt /= resetIt) $ execUpdAtomic $ UpdTimeItem iid toC afterIt resetIt Nothing -> return () -- no @Timeout@ aspect; don't touch computeRndTimeout :: Time -> ItemFull -> Rnd (Maybe ItemTimer) computeRndTimeout localTime ItemFull{itemDisco=ItemDiscoFull itemAspect} = do let t = IA.aTimeout itemAspect if t > 0 then do rndT <- randomR0 t let rndTurns = timeDeltaScale (Delta timeTurn) (t + rndT) return $ Just $ createItemTimer localTime rndTurns else return Nothing computeRndTimeout _ _ = error "computeRndTimeout: server ignorant about an item" createCaveItem :: MonadServerAtomic m => Point -> LevelId -> m () createCaveItem pos lid = do COps{cocave} <- getsState scops Level{lkind, ldepth} <- getLevel lid let container = CFloor lid pos litemFreq = citemFreq $ okind cocave lkind -- Power depth of new items unaffected by number of spawned actors. freq <- prepareItemKind 0 ldepth litemFreq mIidEtc <- rollAndRegisterItem True ldepth freq container Nothing createKitItems lid pos mIidEtc createEmbedItem :: MonadServerAtomic m => LevelId -> Point -> GroupName ItemKind -> m () createEmbedItem lid pos grp = do Level{ldepth} <- getLevel lid let container = CEmbed lid pos -- Power depth of new items unaffected by number of spawned actors. freq <- prepareItemKind 0 ldepth [(grp, 1)] mIidEtc <- rollAndRegisterItem True ldepth freq container Nothing createKitItems lid pos mIidEtc -- Create, register and insert all initial kit items. createKitItems :: MonadServerAtomic m => LevelId -> Point -> Maybe (ItemId, ItemFullKit) -> m () createKitItems lid pos mIidEtc = case mIidEtc of Nothing -> error $ "" `showFailure` (lid, pos, mIidEtc) Just (_, (itemFull, _)) -> do cops <- getsState scops lvl@Level{ldepth} <- getLevel lid let ikit = IK.ikit $ itemKind itemFull nearbyPassable = take (20 + length ikit) $ nearbyPassablePoints cops lvl pos walkable p = Tile.isWalkable (coTileSpeedup cops) (lvl `at` p) good p = walkable p && p `EM.notMember` lfloor lvl kitPos = zip ikit $ filter good nearbyPassable ++ filter walkable nearbyPassable ++ repeat pos forM_ kitPos $ \((ikGrp, cstore), p) -> do let container = if cstore == CGround then CFloor lid p else CEmbed lid pos itemFreq = [(ikGrp, 1)] -- Power depth of new items unaffected by number of spawned actors. freq <- prepareItemKind 0 ldepth itemFreq mresult <- rollAndRegisterItem False ldepth freq container Nothing assert (isJust mresult) $ return () -- Tiles already placed, so it's possible to scatter companion items -- over walkable tiles. embedItemOnPos :: MonadServerAtomic m => LevelId -> Point -> ContentId TileKind -> m () embedItemOnPos lid pos tk = do COps{cotile} <- getsState scops let embedGroups = Tile.embeddedItems cotile tk mapM_ (createEmbedItem lid pos) embedGroups prepareItemKind :: MonadServerAtomic m => Int -> Dice.AbsDepth -> Freqs ItemKind -> m (Frequency (GroupName ItemKind, ContentId IK.ItemKind, ItemKind)) prepareItemKind lvlSpawned ldepth itemFreq = do cops <- getsState scops uniqueSet <- getsServer suniqueSet totalDepth <- getsState stotalDepth return $! newItemKind cops uniqueSet itemFreq ldepth totalDepth lvlSpawned rollItemAspect :: MonadServerAtomic m => Frequency (GroupName ItemKind, ContentId IK.ItemKind, ItemKind) -> Dice.AbsDepth -> m NewItem rollItemAspect freq ldepth = do cops <- getsState scops flavour <- getsServer sflavour discoRev <- getsServer sdiscoKindRev totalDepth <- getsState stotalDepth m2 <- rndToAction $ newItem cops freq flavour discoRev ldepth totalDepth case m2 of NewItem _ (ItemKnown _ arItem _) ItemFull{itemKindId} _ -> do when (IA.checkFlag Ability.Unique arItem) $ modifyServer $ \ser -> ser {suniqueSet = ES.insert itemKindId (suniqueSet ser)} NoNewItem -> return () return m2 rollAndRegisterItem :: MonadServerAtomic m => Bool -> Dice.AbsDepth -> Frequency (GroupName ItemKind, ContentId IK.ItemKind, ItemKind) -> Container -> Maybe Int -> m (Maybe (ItemId, ItemFullKit)) rollAndRegisterItem verbose ldepth freq container mk = do m2 <- rollItemAspect freq ldepth case m2 of NoNewItem -> return Nothing NewItem _ itemKnown itemFull kit -> do let f k = if k == 1 && null (snd kit) then quantSingle else (k, snd kit) !kit2 = maybe kit f mk iid <- registerItem verbose (itemFull, kit2) itemKnown container return $ Just (iid, (itemFull, kit2)) -- Tiles already placed, so it's possible to scatter over walkable tiles. placeItemsInDungeon :: forall m. MonadServerAtomic m => EM.EnumMap LevelId (EM.EnumMap FactionId Point) -> m () placeItemsInDungeon factionPositions = do COps{cocave, coTileSpeedup} <- getsState scops totalDepth <- getsState stotalDepth let initialItems (lid, lvl@Level{lkind, ldepth}) = do litemNum <- rndToAction $ castDice ldepth totalDepth (citemNum $ okind cocave lkind) let alPos = EM.elems $ EM.findWithDefault EM.empty lid factionPositions placeItems :: Int -> m () placeItems n | n == litemNum = return () placeItems !n = do Level{lfloor} <- getLevel lid -- Don't generate items around initial actors or in bunches. let distAndNotFloor !p _ = let f !k = chessDist p k > 4 in p `EM.notMember` lfloor && all f alPos mpos <- rndToAction $ findPosTry2 10 lvl (\_ !t -> Tile.isWalkable coTileSpeedup t && not (Tile.isNoItem coTileSpeedup t)) [ \_ !t -> Tile.isVeryOftenItem coTileSpeedup t , \_ !t -> Tile.isCommonItem coTileSpeedup t ] distAndNotFloor (replicate 10 distAndNotFloor) case mpos of Just pos -> do createCaveItem pos lid placeItems (n + 1) Nothing -> debugPossiblyPrint "Server: placeItemsInDungeon: failed to find positions" placeItems 0 dungeon <- getsState sdungeon -- Make sure items on easy levels are generated first, to avoid all -- artifacts on deep levels. let fromEasyToHard = sortBy (comparing (ldepth . snd)) $ EM.assocs dungeon mapM_ initialItems fromEasyToHard -- Tiles already placed, so it's possible to scatter companion items -- over walkable tiles. embedItemsInDungeon :: MonadServerAtomic m => m () embedItemsInDungeon = do let embedItemsOnLevel (lid, Level{ltile}) = PointArray.imapMA_ (embedItemOnPos lid) ltile dungeon <- getsState sdungeon -- Make sure items on easy levels are generated first, to avoid all -- artifacts on deep levels. let fromEasyToHard = sortBy (comparing (ldepth . snd)) $ EM.assocs dungeon mapM_ embedItemsOnLevel fromEasyToHard -- | Mapping over actor's items from a give store. mapActorCStore_ :: MonadServer m => CStore -> (ItemId -> ItemQuant -> m ()) -> Actor -> m () mapActorCStore_ cstore f b = do bag <- getsState $ getBodyStoreBag b cstore mapM_ (uncurry f) $ EM.assocs bag
LambdaHack/LambdaHack
engine-src/Game/LambdaHack/Server/ItemM.hs
bsd-3-clause
13,557
12
29
3,573
3,678
1,842
1,836
-1
-1
{-#LANGUAGE OverloadedStrings#-} {- Project name: Chromosome Min Zhang Date: Oct 13, 2015 Version: v.0.1.0 README: Annotate genes on sex chromosome -} import qualified Data.Text as T import qualified Data.Text.IO as TextIO import qualified Data.Char as C import Control.Applicative import qualified Data.List as L import Control.Monad (fmap) import Data.Ord (comparing) import Data.Function (on) import qualified Safe as S import qualified Data.Map as M import qualified Data.Maybe as Maybe import qualified Data.Foldable as F (all) import Data.Traversable (sequenceA) import qualified Data.Dates as Dates import qualified Data.ByteString.Lazy.Char8 as Bl import qualified System.IO as IO import System.Environment import System.Directory import MyText import MyTable import Util main = do [inputpath, outputpath] <- take 2 <$> getArgs input <- smartTable inputpath chromMap <- makeChromMap let result = map (\x->appendChrom x chromMap) input TextIO.writeFile outputpath (T.unlines $ map untab result) makeChromMap = do humanGeneDescription <- smartTable "/Applications/commandline/Homer/data/accession/human.description" let chromosome = map getChrom $ cols 8 humanGeneDescription let geneNames = cols 5 humanGeneDescription return $ M.fromList (zip geneNames chromosome) where getChrom x = if T.head x == 'X' || T.head x == 'Y' then T.take 1 x else "" appendChrom input chromMap = let chr = M.findWithDefault "" (head input) chromMap in input ++ [chr]
Min-/fourseq
src/utils/Chromosome.hs
bsd-3-clause
1,533
0
13
276
414
231
183
39
2
{- Problem 12 What is the value of the first triangle number to have over five hundred divisors? Result 76576500 0.74 s -} module Problem12 (solution) where import Data.List import Data.Numbers.Primes solution = head [triangle n | n <- [1..], triangleD n > 500] where -- Calculates the n-th triangle number triangle n = n * (n+1) `quot` 2 -- Number of divisors of the triangle number n*(n+1)/2. Uses the -- fact that n and (n+1) are coprime, so the divisor count is a -- homomorphism on them. triangleD n | even n = numDivisors (n `quot` 2) * numDivisors (n + 1) | otherwise = numDivisors n * numDivisors ((n + 1) `quot` 2) -- Number of divisors. -- Based on the fact that a number with prime factors of multi- -- plicities a1, a2, ... has (a1+1)(a2+1)... divisors. -- Equivalent to length.divisors, but performs way better. numDivisors = product . map (+1) . pfm -- pfm = prime factor multiplicities pfm = map length . group . primeFactors
quchen/HaskellEuler
src/Problem12.hs
bsd-3-clause
1,194
0
13
423
207
114
93
10
1
module Main ( main ) where import Control.Monad (forM_) import Data.Maybe (listToMaybe) import System.Directory ( canonicalizePath, getCurrentDirectory , makeRelativeToCurrentDirectory ) import System.Environment (getArgs) import System.FilePath ((</>)) import DirMetadata.Persist (persist, unpersist) import qualified DirMetadata as DM import qualified Data.Text as T import qualified Data.Text.IO as T main :: IO () main = do args <- getArgs case args of [] -> list [] ("add" : a) -> add a ("help" : _) -> usage ("ls" : a) -> list a ("lsd" : _) -> listDirs ("mv" : a) -> move a ("rm" : a) -> remove a ("usage" : _) -> usage _ -> usage getDir :: Maybe FilePath -> IO FilePath getDir (Just fp) = do dir <- makeRelativeToCurrentDirectory fp cd <- getCurrentDirectory canonicalizePath $ cd </> dir getDir Nothing = getCurrentDirectory list :: [String] -> IO () list args = do dir <- getDir $ listToMaybe args dm <- unpersist forM_ (zip [1 ..] $ DM.list dir dm) $ \(i, t) -> do putStr (show (i :: Int)) putStr ". " T.putStrLn t add :: [String] -> IO () add args = do t <- case args of [] -> fmap T.stripEnd T.getContents _ -> return $ T.unwords $ map T.pack args dir <- getDir Nothing persist . DM.add dir t =<< unpersist remove :: [String] -> IO () remove args = do let (d, is) = case args of [] -> (Nothing, []) (h : a) -> if isInt h then (Nothing, map read args) else (Just h, map read a) dir <- getDir d persist . DM.remove dir is =<< unpersist where isInt = not . null . (reads :: ReadS Int) move :: [String] -> IO () move args = do dm <- unpersist cur <- getDir Nothing case args of [] -> putStrLn "Operand needed" [d] -> do dir <- getDir (Just d) persist $ DM.moveAll cur dir dm _ -> do dir <- getDir (Just $ last args) let is = map read (init args) persist $ DM.move cur is dir dm listDirs :: IO () listDirs = unpersist >>= mapM_ putStrLn . DM.listDirs usage :: IO () usage = undefined
jaspervdj/dir-metadata
src/Main.hs
bsd-3-clause
2,335
0
17
801
913
462
451
72
9
{-# language CPP #-} -- No documentation found for Chapter "EnvironmentBlendMode" module OpenXR.Core10.Enums.EnvironmentBlendMode (EnvironmentBlendMode( ENVIRONMENT_BLEND_MODE_OPAQUE , ENVIRONMENT_BLEND_MODE_ADDITIVE , ENVIRONMENT_BLEND_MODE_ALPHA_BLEND , .. )) where import OpenXR.Internal.Utils (enumReadPrec) import OpenXR.Internal.Utils (enumShowsPrec) import GHC.Show (showsPrec) import OpenXR.Zero (Zero) import Foreign.Storable (Storable) import Data.Int (Int32) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) -- | XrEnvironmentBlendMode - Environment blend modes -- -- == Enumerant Descriptions -- -- = See Also -- -- 'OpenXR.Core10.DisplayTiming.FrameEndInfo', -- 'OpenXR.Extensions.XR_MSFT_secondary_view_configuration.SecondaryViewConfigurationLayerInfoMSFT', -- 'OpenXR.Core10.Device.enumerateEnvironmentBlendModes' newtype EnvironmentBlendMode = EnvironmentBlendMode Int32 deriving newtype (Eq, Ord, Storable, Zero) -- Note that the zero instance does not produce a valid value, passing 'zero' to Vulkan will result in an error -- | 'ENVIRONMENT_BLEND_MODE_OPAQUE'. The composition layers will be -- displayed with no view of the physical world behind them. The composited -- image will be interpreted as an RGB image, ignoring the composited alpha -- channel. This is the typical mode for VR experiences, although this mode -- can also be supported on devices that support video passthrough. pattern ENVIRONMENT_BLEND_MODE_OPAQUE = EnvironmentBlendMode 1 -- | 'ENVIRONMENT_BLEND_MODE_ADDITIVE'. The composition layers will be -- additively blended with the real world behind the display. The -- composited image will be interpreted as an RGB image, ignoring the -- composited alpha channel during the additive blending. This will cause -- black composited pixels to appear transparent. This is the typical mode -- for an AR experience on a see-through headset with an additive display, -- although this mode can also be supported on devices that support video -- passthrough. pattern ENVIRONMENT_BLEND_MODE_ADDITIVE = EnvironmentBlendMode 2 -- | 'ENVIRONMENT_BLEND_MODE_ALPHA_BLEND'. The composition layers will be -- alpha-blended with the real world behind the display. The composited -- image will be interpreted as an RGBA image, with the composited alpha -- channel determining each pixel’s level of blending with the real world -- behind the display. This is the typical mode for an AR experience on a -- phone or headset that supports video passthrough. pattern ENVIRONMENT_BLEND_MODE_ALPHA_BLEND = EnvironmentBlendMode 3 {-# complete ENVIRONMENT_BLEND_MODE_OPAQUE, ENVIRONMENT_BLEND_MODE_ADDITIVE, ENVIRONMENT_BLEND_MODE_ALPHA_BLEND :: EnvironmentBlendMode #-} conNameEnvironmentBlendMode :: String conNameEnvironmentBlendMode = "EnvironmentBlendMode" enumPrefixEnvironmentBlendMode :: String enumPrefixEnvironmentBlendMode = "ENVIRONMENT_BLEND_MODE_" showTableEnvironmentBlendMode :: [(EnvironmentBlendMode, String)] showTableEnvironmentBlendMode = [ (ENVIRONMENT_BLEND_MODE_OPAQUE , "OPAQUE") , (ENVIRONMENT_BLEND_MODE_ADDITIVE , "ADDITIVE") , (ENVIRONMENT_BLEND_MODE_ALPHA_BLEND, "ALPHA_BLEND") ] instance Show EnvironmentBlendMode where showsPrec = enumShowsPrec enumPrefixEnvironmentBlendMode showTableEnvironmentBlendMode conNameEnvironmentBlendMode (\(EnvironmentBlendMode x) -> x) (showsPrec 11) instance Read EnvironmentBlendMode where readPrec = enumReadPrec enumPrefixEnvironmentBlendMode showTableEnvironmentBlendMode conNameEnvironmentBlendMode EnvironmentBlendMode
expipiplus1/vulkan
openxr/src/OpenXR/Core10/Enums/EnvironmentBlendMode.hs
bsd-3-clause
4,057
1
10
924
340
213
127
-1
-1
{-# LANGUAGE NamedFieldPuns #-} module Text.Mediawiki.ParseTree where import ClassyPrelude import Data.Text (strip) import Data.Tree.NTree.TypeDefs (NTree(..)) import Text.XML.HXT.DOM.QualifiedName (QName) import Text.XML.HXT.DOM.TypeDefs (XmlTree, XmlTrees, XNode(..)) import Text.XML.HXT.PathFinder (hasLocalName, LocatedTree(..), number, Numbered, Path(..)) class LocatingUnpickle a where unpickleL :: LocatedTree -> Maybe a data TemplateArgument = TemplateArg { argName :: String , argValue :: [LocatedTree] } data TemplateInvocation = TemplateCall { templateName :: String , arguments :: [TemplateArgument] } eqStripped :: String -> Text -> Bool eqStripped s t = strip (pack $ toLower s) == t argument :: Text -> TemplateInvocation -> Maybe [LocatedTree] argument name TemplateCall { arguments } = argValue <$> find (\a -> eqStripped (argName a) name) arguments named :: String -> XmlTrees -> [Numbered XmlTree] named name = filter (maybe False (hasLocalName name) . elemName . snd) . number exactly1 :: [a] -> Maybe a exactly1 [x] = Just x exactly1 _ = Nothing named1 :: String -> XmlTrees -> Maybe (Int, XmlTree) named1 name = exactly1 . named name instance LocatingUnpickle TemplateArgument where unpickleL (LocatedTree argPath (NTree (XTag _ _) children)) = do (_, NTree _ [NTree (XText argName) _]) <- named1 "name" children (valueBranch, NTree _ valueTrees) <- named1 "value" children let toLocated branch tree = LocatedTree { path = Path $ branches argPath ++ [valueBranch, branch] , tree } return TemplateArg { argName , argValue = uncurry toLocated <$> number valueTrees } instance LocatingUnpickle TemplateInvocation where unpickleL (LocatedTree invocationPath (NTree (XTag _ _) children)) = do (_, NTree _ [NTree (XText title) _]) <- named1 "title" children let partElems = named "part" children tas <- mapM (unpickleL . uncurry toLocated) partElems return TemplateCall { templateName = title , arguments = tas } where toLocated branch tree = LocatedTree { path = Path $ snoc (branches invocationPath) branch , tree } unpickleL _ = Nothing elemName :: NTree XNode -> Maybe QName elemName (NTree (XTag n _) _) = Just n elemName _ = Nothing toWikitext :: XmlTree -> [Text] toWikitext (NTree (XText t) _) = [pack t] toWikitext (NTree (XEntityRef er) _) = ["&", pack er, ";"] toWikitext (NTree (XCmt cmt) _) = ["<!--", pack cmt, "-->"] toWikitext (NTree (XCdata t) _) = [pack t] toWikitext (NTree (XTag name _) children) | hasLocalName "template" name = "{{" : (toWikitext =<< children) ++ ["}}"] toWikitext (NTree (XTag name _) children) | hasLocalName "part" name = "|" : (toWikitext =<< children) toWikitext (NTree (XTag name _) children) | hasLocalName "ext" name = "<" : (toWikitext =<< children) toWikitext (NTree (XTag name _) children) | hasLocalName "inner" name = ">" : (toWikitext =<< children) toWikitext (NTree (XTag _ _) children) = toWikitext =<< children toWikitext (NTree _ _) = []
greenrd/wpfixcites
src/Text/Mediawiki/ParseTree.hs
bsd-3-clause
3,343
0
15
874
1,178
613
565
65
1
module Main where import Utils.TigerUtils main :: IO () main = do runFile
lialan/TigerCompiler
app/Main.hs
bsd-3-clause
78
0
6
17
27
15
12
5
1
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.HP.TextureLighting -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.HP.TextureLighting ( -- * Extension Support glGetHPTextureLighting, gl_HP_texture_lighting, -- * Enums pattern GL_TEXTURE_LIGHTING_MODE_HP, pattern GL_TEXTURE_POST_SPECULAR_HP, pattern GL_TEXTURE_PRE_SPECULAR_HP ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
haskell-opengl/OpenGLRaw
src/Graphics/GL/HP/TextureLighting.hs
bsd-3-clause
739
0
5
99
57
42
15
9
0
{-# LANGUAGE OverloadedStrings #-} module Day7 ( day7 , day7' ) where import Control.Applicative import Data.Attoparsec.Text import Data.Either import Data.List import qualified Data.Text as T import Shared.String import Shared.List {- Day 7: Internet Protocol Version 7 -} type IPV7 = (String, String) data IPInfo = HN String | SN String deriving (Show) isAbba :: String -> Bool isAbba = any (\(a,b,c,d) -> a == d && b == c && a /= b) . abbas where abbas = zip4 <*> drop 1 <*> drop 2 <*> drop 3 parseIP :: Parser IPV7 parseIP = concatIPInfos <$> many1 (parseHn <|> parseSn) where parseHn = HN <$> (char '[' *> many1 letter <* char ']') parseSn = SN <$> many1 letter concatIPInfos :: [IPInfo] -> IPV7 concatIPInfos = foldl parseI ([], []) where parseI (z1,z2) (HN s) = (z1, z2 ++ " " ++ s) parseI (z1,z2) (SN s) = (z1 ++ " " ++ s, z2) day7 :: IO () day7 = do input <- T.lines . T.pack <$> readFile "resources/day7.txt" let results = rights $ map (parseOnly parseIP) input print $ countF (True ==) $ (\(sn,hn) -> isAbba sn && not (isAbba hn)) <$> results {- Part Two -} day7' :: IO () day7' = do input <- T.lines . T.pack <$> readFile "resources/day7.txt" let results = rights $ map (parseOnly parseIP) input print $ countF (True ==) $ (\(sn,hn) -> (any (checkHn hn) (zipSn sn))) <$> results where zipSn = zip3 <*> drop 1 <*> drop 2 checkHn h (a,b,c) = a == c && a /= b && substring [b, a, b] h
Rydgel/advent-of-code-2016
src/Day7.hs
bsd-3-clause
1,535
0
14
406
652
349
303
36
2
module Paths_wordfreq ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,1,0,0], versionTags = []} bindir, libdir, datadir, libexecdir :: FilePath bindir = "/Users/Dave/Desktop/hm/.virthualenv/cabal/bin" libdir = "/Users/Dave/Desktop/hm/.virthualenv/cabal/lib/wordfreq-0.1.0.0/ghc-7.4.1" datadir = "/Users/Dave/Desktop/hm/.virthualenv/cabal/share/wordfreq-0.1.0.0" libexecdir = "/Users/Dave/Desktop/hm/.virthualenv/cabal/libexec" getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath getBinDir = catchIO (getEnv "wordfreq_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "wordfreq_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "wordfreq_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "wordfreq_libexecdir") (\_ -> return libexecdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
dmjio/wordfreq
dist/build/autogen/Paths_wordfreq.hs
bsd-3-clause
1,226
0
10
164
329
188
141
25
1
module Omnisharp.Utils (toPascelCase) where import Data.Char toPascelCase :: String -> String toPascelCase [] = [] toPascelCase (x : xs) = toUpper x : xs
alistair/omnisharp-hs
src/Omnisharp/Utils.hs
bsd-3-clause
157
0
7
27
59
32
27
5
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE BangPatterns #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Compat.Graph -- Copyright : (c) Edward Z. Yang 2016 -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- A data type representing directed graphs, backed by "Data.Graph". -- It is strict in the node type. -- -- This is an alternative interface to "Data.Graph". In this interface, -- nodes (identified by the 'IsNode' type class) are associated with a -- key and record the keys of their neighbors. This interface is more -- convenient than 'Data.Graph.Graph', which requires vertices to be -- explicitly handled by integer indexes. -- -- The current implementation has somewhat peculiar performance -- characteristics. The asymptotics of all map-like operations mirror -- their counterparts in "Data.Map". However, to perform a graph -- operation, we first must build the "Data.Graph" representation, an -- operation that takes /O(V + E log V)/. However, this operation can -- be amortized across all queries on that particular graph. -- -- Some nodes may be broken, i.e., refer to neighbors which are not -- stored in the graph. In our graph algorithms, we transparently -- ignore such edges; however, you can easily query for the broken -- vertices of a graph using 'broken' (and should, e.g., to ensure that -- a closure of a graph is well-formed.) It's possible to take a closed -- subset of a broken graph and get a well-formed graph. -- ----------------------------------------------------------------------------- module Distribution.Compat.Graph ( -- * Graph type Graph, IsNode(..), -- * Query null, size, lookup, -- * Construction empty, insert, deleteKey, deleteLookup, -- * Combine unionLeft, unionRight, -- * Graph algorithms stronglyConnComp, SCC(..), cycles, broken, closure, revClosure, topSort, revTopSort, -- * Conversions -- ** Maps toMap, -- ** Lists fromList, toList, keys, -- ** Graphs toGraph, -- * Node type Node(..), nodeValue, ) where import qualified Prelude as Prelude import Prelude hiding (lookup, null) import Data.Graph (SCC(..)) import qualified Data.Graph as G import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Array as Array import Data.Array ((!)) import qualified Data.Tree as Tree import Data.Either (partitionEithers) import Data.Typeable (Typeable) import qualified Data.Foldable as Foldable import Control.DeepSeq (NFData(..)) import Distribution.Compat.Binary (Binary(..)) -- | A graph of nodes @a@. The nodes are expected to have instance -- of class 'IsNode'. data Graph a = Graph { graphMap :: !(Map (Key a) a), -- Lazily cached graph representation graphForward :: G.Graph, graphAdjoint :: G.Graph, graphVertexToNode :: G.Vertex -> a, graphKeyToVertex :: Key a -> Maybe G.Vertex, graphBroken :: [(a, [Key a])] } deriving (Typeable) -- NB: Not a Functor! (or Traversable), because you need -- to restrict Key a ~ Key b. We provide our own mapping -- functions. -- General strategy is most operations are deferred to the -- Map representation. instance Show a => Show (Graph a) where show = show . toList instance (IsNode a, Read a) => Read (Graph a) where readsPrec d s = map (\(a,r) -> (fromList a, r)) (readsPrec d s) instance (IsNode a, Binary a) => Binary (Graph a) where put x = put (toList x) get = fmap fromList get instance (Eq (Key a), Eq a) => Eq (Graph a) where g1 == g2 = graphMap g1 == graphMap g2 instance Foldable.Foldable Graph where fold = Foldable.fold . graphMap foldr f z = Foldable.foldr f z . graphMap foldl f z = Foldable.foldl f z . graphMap foldMap f = Foldable.foldMap f . graphMap #ifdef MIN_VERSION_base #if MIN_VERSION_base(4,6,0) foldl' f z = Foldable.foldl' f z . graphMap foldr' f z = Foldable.foldr' f z . graphMap #endif #if MIN_VERSION_base(4,8,0) length = Foldable.length . graphMap null = Foldable.null . graphMap toList = Foldable.toList . graphMap elem x = Foldable.elem x . graphMap maximum = Foldable.maximum . graphMap minimum = Foldable.minimum . graphMap sum = Foldable.sum . graphMap product = Foldable.product . graphMap #endif #endif instance (NFData a, NFData (Key a)) => NFData (Graph a) where rnf Graph { graphMap = m, graphForward = gf, graphAdjoint = ga, graphVertexToNode = vtn, graphKeyToVertex = ktv, graphBroken = b } = gf `seq` ga `seq` vtn `seq` ktv `seq` b `seq` rnf m -- TODO: Data instance? -- | The 'IsNode' class is used for datatypes which represent directed -- graph nodes. A node of type @a@ is associated with some unique key of -- type @'Key' a@; given a node we can determine its key ('nodeKey') -- and the keys of its neighbors ('nodeNeighbors'). class Ord (Key a) => IsNode a where type Key a :: * nodeKey :: a -> Key a nodeNeighbors :: a -> [Key a] -- | A simple, trivial data type which admits an 'IsNode' instance. data Node k a = N a k [k] deriving (Show, Eq) -- | Get the value from a 'Node'. nodeValue :: Node k a -> a nodeValue (N a _ _) = a instance Functor (Node k) where fmap f (N a k ks) = N (f a) k ks instance Ord k => IsNode (Node k a) where type Key (Node k a) = k nodeKey (N _ k _) = k nodeNeighbors (N _ _ ks) = ks -- TODO: Maybe introduce a typeclass for items which just -- keys (so, Key associated type, and nodeKey method). But -- I didn't need it here, so I didn't introduce it. -- Query -- | /O(1)/. Is the graph empty? null :: Graph a -> Bool null = Map.null . toMap -- | /O(1)/. The number of nodes in the graph. size :: Graph a -> Int size = Map.size . toMap -- | /O(log V)/. Lookup the node at a key in the graph. lookup :: IsNode a => Key a -> Graph a -> Maybe a lookup k g = Map.lookup k (toMap g) -- Construction -- | /O(1)/. The empty graph. empty :: IsNode a => Graph a empty = fromMap Map.empty -- | /O(log V)/. Insert a node into a graph. insert :: IsNode a => a -> Graph a -> Graph a insert !n g = fromMap (Map.insert (nodeKey n) n (toMap g)) -- | /O(log V)/. Delete the node at a key from the graph. deleteKey :: IsNode a => Key a -> Graph a -> Graph a deleteKey k g = fromMap (Map.delete k (toMap g)) -- | /O(log V)/. Lookup and delete. This function returns the deleted -- value if it existed. deleteLookup :: IsNode a => Key a -> Graph a -> (Maybe a, Graph a) deleteLookup k g = let (r, m') = Map.updateLookupWithKey (\_ _ -> Nothing) k (toMap g) in (r, fromMap m') -- Combining -- | /O(V + V')/. Right-biased union, preferring entries -- from the second map when conflicts occur. -- @'nodeKey' x = 'nodeKey' (f x)@. unionRight :: IsNode a => Graph a -> Graph a -> Graph a unionRight g g' = fromMap (Map.union (toMap g') (toMap g)) -- | /O(V + V')/. Left-biased union, preferring entries from -- the first map when conflicts occur. unionLeft :: IsNode a => Graph a -> Graph a -> Graph a unionLeft = flip unionRight -- Graph-like operations -- | /Ω(V + E)/. Compute the strongly connected components of a graph. -- Requires amortized construction of graph. stronglyConnComp :: Graph a -> [SCC a] stronglyConnComp g = map decode forest where forest = G.scc (graphForward g) decode (Tree.Node v []) | mentions_itself v = CyclicSCC [graphVertexToNode g v] | otherwise = AcyclicSCC (graphVertexToNode g v) decode other = CyclicSCC (dec other []) where dec (Tree.Node v ts) vs = graphVertexToNode g v : foldr dec vs ts mentions_itself v = v `elem` (graphForward g ! v) -- Implementation copied from 'stronglyConnCompR' in 'Data.Graph'. -- | /Ω(V + E)/. Compute the cycles of a graph. -- Requires amortized construction of graph. cycles :: Graph a -> [[a]] cycles g = [ vs | CyclicSCC vs <- stronglyConnComp g ] -- | /O(1)/. Return a list of nodes paired with their broken -- neighbors (i.e., neighbor keys which are not in the graph). -- Requires amortized construction of graph. broken :: Graph a -> [(a, [Key a])] broken g = graphBroken g -- | Compute the subgraph which is the closure of some set of keys. -- Returns @Nothing@ if one (or more) keys are not present in -- the graph. -- Requires amortized construction of graph. closure :: Graph a -> [Key a] -> Maybe [a] closure g ks = do vs <- mapM (graphKeyToVertex g) ks return (decodeVertexForest g (G.dfs (graphForward g) vs)) -- | Compute the reverse closure of a graph from some set -- of keys. Returns @Nothing@ if one (or more) keys are not present in -- the graph. -- Requires amortized construction of graph. revClosure :: Graph a -> [Key a] -> Maybe [a] revClosure g ks = do vs <- mapM (graphKeyToVertex g) ks return (decodeVertexForest g (G.dfs (graphAdjoint g) vs)) flattenForest :: Tree.Forest a -> [a] flattenForest = concatMap Tree.flatten decodeVertexForest :: Graph a -> Tree.Forest G.Vertex -> [a] decodeVertexForest g = map (graphVertexToNode g) . flattenForest -- | Topologically sort the nodes of a graph. -- Requires amortized construction of graph. topSort :: Graph a -> [a] topSort g = map (graphVertexToNode g) $ G.topSort (graphForward g) -- | Reverse topologically sort the nodes of a graph. -- Requires amortized construction of graph. revTopSort :: Graph a -> [a] revTopSort g = map (graphVertexToNode g) $ G.topSort (graphAdjoint g) -- Conversions -- | /O(1)/. Convert a map from keys to nodes into a graph. -- The map must satisfy the invariant that -- @'fromMap' m == 'fromList' ('Data.Map.elems' m)@; -- if you can't fulfill this invariant use @'fromList' ('Data.Map.elems' m)@ -- instead. The values of the map are assumed to already -- be in WHNF. fromMap :: IsNode a => Map (Key a) a -> Graph a fromMap m = Graph { graphMap = m -- These are lazily computed! , graphForward = g , graphAdjoint = G.transposeG g , graphVertexToNode = vertex_to_node , graphKeyToVertex = key_to_vertex , graphBroken = broke } where try_key_to_vertex k = maybe (Left k) Right (key_to_vertex k) (brokenEdges, edges) = unzip $ [ partitionEithers (map try_key_to_vertex (nodeNeighbors n)) | n <- ns ] broke = filter (not . Prelude.null . snd) (zip ns brokenEdges) g = Array.listArray bounds edges ns = Map.elems m -- sorted ascending vertices = zip (map nodeKey ns) [0..] vertex_map = Map.fromAscList vertices key_to_vertex k = Map.lookup k vertex_map vertex_to_node vertex = nodeTable ! vertex nodeTable = Array.listArray bounds ns bounds = (0, Map.size m - 1) -- | /O(V log V)/. Convert a list of nodes into a graph. fromList :: IsNode a => [a] -> Graph a fromList ns = fromMap . Map.fromList . map (\n -> n `seq` (nodeKey n, n)) $ ns -- Map-like operations -- | /O(V)/. Convert a graph into a list of nodes. toList :: Graph a -> [a] toList g = Map.elems (toMap g) -- | /O(V)/. Convert a graph into a list of keys. keys :: Graph a -> [Key a] keys g = Map.keys (toMap g) -- | /O(1)/. Convert a graph into a map from keys to nodes. -- The resulting map @m@ is guaranteed to have the property that -- @'Prelude.all' (\(k,n) -> k == 'nodeKey' n) ('Data.Map.toList' m)@. toMap :: Graph a -> Map (Key a) a toMap = graphMap -- Graph-like operations -- | /O(1)/. Convert a graph into a 'Data.Graph.Graph'. -- Requires amortized construction of graph. toGraph :: Graph a -> (G.Graph, G.Vertex -> a, Key a -> Maybe G.Vertex) toGraph g = (graphForward g, graphVertexToNode g, graphKeyToVertex g)
kolmodin/cabal
Cabal/Distribution/Compat/Graph.hs
bsd-3-clause
12,109
0
13
2,780
2,858
1,553
1,305
180
2
{-# LANGUAGE RecordWildCards #-} module HPack.Cache (Cache, newCache, addElem) where import qualified Data.Map as M import qualified Data.List as L -- | Keep a cache of elements of a maximum size. When the maximum is -- exceeded, indicate which elements should be deleted. data Cache a = Cache { maxSize :: Int -- ^ Maximum number of elements that should be in the -- cache at any one time , priority :: Integer -- ^ Priority of the last inserted element -- (this grows unbounded) , elements :: M.Map a Integer -- ^ Elements of the cache. |elements| < maxSize } newCache :: Int -> Cache a newCache maxSize = Cache maxSize 0 M.empty -- | Add an element to the cache. If maxSize is exceeded, addElem :: Ord a => a -> Cache a -> (Cache a, [a]) addElem item Cache{..} = if M.size elems < maxSize then (mkCache elems, []) else (mkCache (M.fromList keepElems), map fst dropElems) where elems = M.insert item priority elements mkCache = Cache maxSize (priority - 1) sorted = L.sortOn snd (M.assocs elems) (keepElems, dropElems) = splitAt (maxSize `quot` 3 * 2) sorted
markflorisson/hpack
src/HPack/Cache.hs
bsd-3-clause
1,218
0
10
346
290
163
127
21
2
module Language.NyFl.Term ( -- * Data types Term (..) ) where -- | Term data Term a = Int Int | Bool Bool | Var a | Op (Term a) (Term a) | Fn a (Term a) | Ap (Term a) (Term a) deriving (Eq, Show)
nobsun/nyfl
src/Language/NyFl/Term.hs
bsd-3-clause
276
0
8
126
100
58
42
9
0
----------------------------------------------------------------------------- -- | -- Module : Data.OrgMode.Parse.Attoparsec.Time -- Copyright : © 2014 Parnell Springmeyer -- License : All Rights Reserved -- Maintainer : Parnell Springmeyer <[email protected]> -- Stability : stable -- -- Parsing combinators for org-mode active and inactive timestamps. ---------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Data.OrgMode.Parse.Attoparsec.Time where import Control.Applicative (pure, some, (*>), (<$>), (<*), (<*>), (<|>)) import Control.Monad (liftM) import qualified Data.Attoparsec.ByteString as AB import Data.Attoparsec.Text as T import Data.Attoparsec.Types as TP (Parser) import Data.Attoparsec.Combinator as TP import qualified Data.ByteString.Char8 as BS import Data.HashMap.Strict (HashMap, fromList) import Data.Maybe (listToMaybe) import Data.Text as Text (Text, pack, unpack, unwords) import Data.Thyme.Format (buildTime, timeParser) import Data.Thyme.LocalTime (Hours, Minutes) import Prelude hiding (concat, null, takeWhile, unwords, words) import System.Locale (defaultTimeLocale) import Data.OrgMode.Parse.Types -- | Parse a planning line. -- -- Plannings inhabit a heading section and are formatted as a keyword -- and a timestamp. There can be more than one, but they are all on -- the same line e.g: -- -- > DEADLINE: <2015-05-10 17:00> CLOSED: <2015-04-1612:00> parsePlannings :: TP.Parser Text (HashMap PlanningKeyword Timestamp) parsePlannings = fromList <$> (many' (skipSpace *> planning <* skipSpace)) where planning :: TP.Parser Text (PlanningKeyword, Timestamp) planning = (,) <$> pType <* char ':' <*> (skipSpace *> parseTimestamp) pType = choice [string "SCHEDULED" *> pure SCHEDULED ,string "DEADLINE" *> pure DEADLINE ,string "CLOSED" *> pure CLOSED ] -- | Parse a clock line. -- -- A heading's section contains one line per clock entry. Clocks may -- have a timestamp, a duration, both, or neither e.g.: -- -- > CLOCK: [2014-12-10 Fri 2:30]--[2014-12-10 Fri 10:30] => 08:00 parseClock :: TP.Parser Text (Maybe Timestamp, Maybe Duration) parseClock = (,) <$> (skipSpace *> string "CLOCK: " *> ts) <*> dur where ts = option Nothing (Just <$> parseTimestamp) dur = option Nothing (Just <$> (string " => " *> skipSpace *> parseHM)) -- | Parse a timestamp. -- -- Timestamps may be timepoints or timeranges, and they indicate -- whether they are active or closed by using angle or square brackets -- respectively. -- -- Time ranges are formatted by infixing two timepoints with a double -- hyphen, @--@; or, by appending two @hh:mm@ timestamps together in a -- single timepoint with one hyphen @-@. -- -- Each timepoint includes an optional repeater flag and an optional -- delay flag. parseTimestamp :: TP.Parser Text Timestamp parseTimestamp = do (ts1, tsb1, act) <- transformBracketedDateTime <$> parseBracketedDateTime -- Such ew, so gross, much clean, very needed blk2 <- liftM (maybe Nothing (Just . transformBracketedDateTime)) optionalBracketedDateTime -- TODO: this is grody, I'd like to refactor this truth table logic -- and make the transformations chainable and composable as opposed -- to depending on case matching blocks. - Parnell case (tsb1, blk2) of (Nothing, Nothing) -> return (Timestamp ts1 act Nothing) (Nothing, Just (ts2, Nothing, _)) -> return (Timestamp ts1 act (Just ts2)) (Nothing, Just _) -> fail "Illegal time range in second timerange timestamp" (Just (h',m'), Nothing) -> return (Timestamp ts1 act (Just $ ts1 {hourMinute = Just (h',m') ,repeater = Nothing ,delay = Nothing})) (Just _, Just _) -> fail "Illegal mix of time range and timestamp range" where optionalBracketedDateTime = option Nothing (Just <$> (string "--" *> parseBracketedDateTime)) type Weekday = Text data BracketedDateTime = BracketedDateTime { datePart :: YearMonthDay , dayNamePart :: Maybe Weekday , timePart :: Maybe TimePart , repeat :: Maybe Repeater , delayPart :: Maybe Delay , isActive :: Bool } deriving (Show, Eq) -- | Parse a single time part. -- -- > [2015-03-27 Fri 10:20 +4h] -- -- Returns: -- -- - The basic timestamp -- - Whether there was a time interval in place of a single time -- (this will be handled upstream by parseTimestamp) -- - Whether the time is active or inactive parseBracketedDateTime :: TP.Parser Text BracketedDateTime parseBracketedDateTime = do openingBracket <- char '<' <|> char '[' brkDateTime <- BracketedDateTime <$> parseDate <* skipSpace <*> optionalParse parseDay <*> optionalParse parseTime' <*> maybeListParse parseRepeater <*> maybeListParse parseDelay <*> pure (activeBracket openingBracket) closingBracket <- char '>' <|> char ']' finally brkDateTime openingBracket closingBracket where optionalParse p = option Nothing (Just <$> p) <* skipSpace maybeListParse p = listToMaybe <$> many' p <* skipSpace activeBracket = (=='<') finally bkd ob cb | complementaryBracket ob /= cb = fail "Mismatched timestamp brackets" | otherwise = return bkd complementaryBracket '<' = '>' complementaryBracket '[' = ']' complementaryBracket x = x -- TODO: this function is also grody but it's better than having this -- logic in the primary parseBracketedDateTime function. - Parnell transformBracketedDateTime :: BracketedDateTime -> (DateTime, Maybe (Hours, Minutes), Bool) transformBracketedDateTime (BracketedDateTime dp dn tp rp dly act) = case tp of Just (TimePart (Left (h,m))) -> ( DateTime (YMD' dp) dn (Just (h,m)) rp dly , Nothing , act) Just (TimePart (Right (t1, t2))) -> ( DateTime (YMD' dp) dn (Just t1) rp dly , Just t2 , act) Nothing -> ( DateTime (YMD' dp) dn Nothing rp dly , Nothing , act) -- | Parse a day name in the same way as org-mode does. parseDay :: TP.Parser Text Text parseDay = pack <$> some (TP.satisfyElem isDayChar) where isDayChar :: Char -> Bool isDayChar = (`notElem` nonDayChars) nonDayChars :: String nonDayChars = "]+0123456789>\r\n -" -- The above syntax is based on [^]+0-9>\r\n -]+ -- a part of regexp named org-ts-regexp0 -- in org.el . type AbsoluteTime = (Hours, Minutes) type TimestampRange = (AbsoluteTime, AbsoluteTime) newtype TimePart = TimePart (Either AbsoluteTime TimestampRange) deriving (Eq, Ord, Show) -- | Parse the time-of-day part of a time part, as a single point or a -- time range. parseTime' :: TP.Parser Text TimePart parseTime' = TimePart <$> choice [ Right <$> ((,) <$> parseHM <* char '-' <*> parseHM) , Left <$> parseHM ] -- | Parse the YYYY-MM-DD part of a time part. parseDate :: TP.Parser Text YearMonthDay parseDate = consumeDate >>= either failure success . dateParse where failure e = fail . unpack $ unwords ["Failure parsing date: ", pack e] success t = return $ buildTime t consumeDate = manyTill anyChar (char ' ') dateParse = AB.parseOnly dpCombinator . BS.pack dpCombinator = timeParser defaultTimeLocale "%Y-%m-%d" -- | Parse a single @HH:MM@ point. parseHM :: TP.Parser Text (Hours, Minutes) parseHM = (,) <$> decimal <* char ':' <*> decimal -- | Parse the Timeunit part of a delay or repeater flag. parseTimeUnit :: TP.Parser Text TimeUnit parseTimeUnit = choice [ char 'h' *> pure UnitHour , char 'd' *> pure UnitDay , char 'w' *> pure UnitWeek , char 'm' *> pure UnitMonth , char 'y' *> pure UnitYear ] -- | Parse a repeater flag, e.g. @.+4w@, or @++1y@. parseRepeater :: TP.Parser Text Repeater parseRepeater = Repeater <$> choice[ string "++" *> pure RepeatCumulate , char '+' *> pure RepeatCatchUp , string ".+" *> pure RepeatRestart ] <*> decimal <*> parseTimeUnit -- | Parse a delay flag, e.g. @--1d@ or @-2w@. parseDelay :: TP.Parser Text Delay parseDelay = Delay <$> choice [ string "--" *> pure DelayFirst , char '-' *> pure DelayAll ] <*> decimal <*> parseTimeUnit
nushio3/orgmode-parse
src/Data/OrgMode/Parse/Attoparsec/Time.hs
bsd-3-clause
9,107
0
18
2,549
1,882
1,037
845
145
5
{-# LANGUAGE RecordWildCards #-} module JSONLog ( jsonLogs , parseLogP , IndexedJLTimedEvent (..) , runParseLogs ) where import Data.Attoparsec.Text (Parser, parseOnly, takeTill) import Pipes import Pipes.ByteString (fromHandle) import Pipes.Interleave (interleave) import qualified Pipes.Prelude as P import System.Directory (listDirectory) import System.FilePath ((</>)) import Pos.Infra.Util.JsonLog.Events (JLEvent, JLTimedEvent (..)) import Types import Universum import Util.Aeson (parseJSONP) import Util.Safe (runWithFiles) jsonLogs :: FilePath -> IO [(Text, FilePath)] jsonLogs logDir = do files <- listDirectory logDir return $ map (second (logDir </>)) $ mapMaybe f files where f :: FilePath -> Maybe (Text, FilePath) f logFile = case parseOnly nodeIndexParser $ toText logFile of Right name -> Just (name, logFile) Left _ -> Nothing nodeIndexParser :: Parser Text nodeIndexParser = takeTill (== '.') <* ".json" parseLogP :: MonadIO m => Handle -> Producer JLTimedEvent m () parseLogP h = fromHandle h >-> parseJSONP data IndexedJLTimedEvent = IndexedJLTimedEvent { ijlNode :: !NodeId , ijlTimestamp :: !Timestamp , ijlEvent :: !JLEvent } instance Eq IndexedJLTimedEvent where (==) = (==) `on` ijlTimestamp instance Ord IndexedJLTimedEvent where compare = compare `on` ijlTimestamp runParseLogs :: FilePath -> (Producer IndexedJLTimedEvent IO () -> IO r) -> IO r runParseLogs logDir f = do xs <- jsonLogs logDir runWithFiles xs ReadMode $ \ys -> f $ interleave (map (uncurry producer) ys) where producer :: NodeId -> Handle -> Producer IndexedJLTimedEvent IO () producer n h = parseLogP h >-> P.map (\JLTimedEvent{..} -> IndexedJLTimedEvent { ijlNode = n , ijlTimestamp = fromIntegral jlTimestamp , ijlEvent = jlEvent })
input-output-hk/pos-haskell-prototype
tools/post-mortem/src/JSONLog.hs
mit
2,064
0
14
577
588
322
266
53
2
{-| Copyright : (c) 2015 Javran Cheng License : MIT Maintainer : [email protected] Stability : unstable Portability : non-portable (requires X11) Compiling-related functions -} module XMonad.Util.EntryHelper.Compile ( defaultCompile , defaultPostCompile , postCompileCheckLog , compileUsingShell , withFileLock , withLock ) where import Data.Functor import Control.Applicative import Control.Monad import System.IO import System.Posix.Process import System.Process import Control.Exception.Extensible import System.Exit import System.FilePath import System.Directory import Data.List import System.Posix.User import XMonad.Util.EntryHelper.File import XMonad.Util.EntryHelper.Util -- | the default compiling action. -- checks whether any of the sources files under @"~\/.xmonad\/"@ -- is newer than the binary and recompiles XMonad if so. defaultCompile :: Bool -> IO ExitCode defaultCompile force = do b <- isSourceNewer if force || b then do bin <- binPath <$> getXMonadPaths let cmd = "ghc --make xmonad.hs -i -ilib -fforce-recomp -o " ++ bin compileUsingShell cmd else return ExitSuccess -- | the default post-compiling action. -- same as @postCompileCheckLog errlog@ -- where @errlog@ is the default error log location -- (usually @"~\/.xmonad\/xmonad.errors"@) -- see also: 'postCompileCheckLog' defaultPostCompile :: ExitCode -> IO () defaultPostCompile e = join (postCompileCheckLog <$> getXMonadLog <*> pure e) -- | a post-compiling action. -- @postCompileCheckLog fp ec@ -- first checks the 'ExitCode' given, if it is not equal to 'ExitSuccess', -- prints out error log to stderr and pops up a message -- containing the error log. -- the error log is indicated by @fpath@ postCompileCheckLog :: FilePath -> ExitCode -> IO () postCompileCheckLog _ ExitSuccess = return () postCompileCheckLog fpath st@(ExitFailure _) = do ghcErr <- readFile fpath let msg = unlines $ [ "Error detected while loading xmonad configuration file(s)" ] ++ lines (if null ghcErr then show st else ghcErr) ++ ["","Please check the file for errors."] hPutStrLn stderr msg void $ forkProcess $ executeFile "xmessage" True ["-default", "okay", msg] Nothing -- | @compileUsingShell cmd@ spawns a new process to run a shell command -- (shell expansion is applied). -- The working directory of the shell command is @"~\/.xmonad\/"@, and -- the process' stdout and stdout are redirected to @"~\/.xmonad\/xmonad.errors"@ compileUsingShell :: String -> IO ExitCode compileUsingShell cmd = do -- please make sure "installSignalHandlers" hasn't been executed -- or has been undone by "uninstallSignalHandlers" -- see also: https://ghc.haskell.org/trac/ghc/ticket/5212 dir <- getXMonadDir compileLogPath <- getXMonadLog hNullInput <- openFile "/dev/null" ReadMode hCompileLog <- openFile compileLogPath WriteMode hSetBuffering hCompileLog NoBuffering let cp = (shell cmd) { cwd = Just dir , std_in = UseHandle hNullInput , std_out = UseHandle hCompileLog , std_err = UseHandle hCompileLog } -- std_out and std_err are closed automatically -- so we don't need to take care of them. (_,_,_,ph) <- createProcess cp waitForProcess ph -- | @withLock def action@ is the same as @withFileLock fpath def action@ with -- @fpath@ being @"xmonad.${USERNAME}.lock"@ under your temporary directory. -- Wrapping an action with more than one @withLock@ will not work. -- -- See also: `withFileLock`, 'getTemporaryDirectory', 'getEffectiveUserName' withLock :: a -> IO a -> IO a withLock def action = do tmpDir <- getTemporaryDirectory -- https://ghc.haskell.org/trac/ghc/ticket/1487 -- avoid using "getLoginName" here usr <- getEffectiveUserName let lockFile = tmpDir </> intercalate "." ["xmonad",usr,"lock"] withFileLock lockFile def action -- | prevents an IO action from parallel execution by using a lock file. -- @withFileLock fpath def action@ checks whether the file indicated by @fpath@ -- exists. And: -- -- * returns @def@ if the file exists. -- * creates @fpath@, executes the action, and deletes @fpath@ when the action -- has completed. If @action@ has failed, @def@ will be returned instead. -- -- Note that: -- -- * the action will be protected by 'safeIO', meaning the lock file will be deleted -- regardless of any error. -- * No check on @fpath@ will be done by this function. Please make sure the lock file -- does not exist. -- * please prevent wrapping the action with same file lock multiple times, -- in which case the action will never be executed. withFileLock :: FilePath -> a -> IO a -> IO a withFileLock fPath def action = do lock <- doesFileExist fPath if lock then skipCompile else doCompile where skipCompile = do putStrLn $ "Lock file " ++ fPath ++ " found, aborting ..." putStrLn "Delete lock file to continue." return def doCompile = bracket_ (writeFile fPath "") (removeFile fPath) (safeIO def action)
Javran/xmonad-entryhelper
src/XMonad/Util/EntryHelper/Compile.hs
mit
5,320
0
15
1,231
766
411
355
76
2
-- | Maintainer: Jelmer Vernooij <[email protected]> -- module Propellor.Property.Munin ( hostListFragment, hostListFragment', nodePort, nodeInstalled, nodeRestarted, nodeConfPath, masterInstalled, masterRestarted, masterConfPath, ) where import Propellor import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.Service as Service nodePort :: Integer nodePort = 4949 nodeInstalled :: Property DebianLike nodeInstalled = Apt.serviceInstalledRunning "munin-node" nodeRestarted :: Property DebianLike nodeRestarted = Service.restarted "munin-node" nodeConfPath :: FilePath nodeConfPath = "/etc/munin/munin-node.conf" masterInstalled :: Property DebianLike masterInstalled = Apt.serviceInstalledRunning "munin" masterRestarted :: Property DebianLike masterRestarted = Service.restarted "munin" masterConfPath :: FilePath masterConfPath = "/etc/munin/munin.conf" -- | Create the host list fragment for master config. -- Takes an optional override list for hosts that are accessible on a non-standard host/port. -- TODO(jelmer): Only do this on hosts where munin is present (in other words, with Munin.installedNode) hostListFragment' :: [Host] -> [(HostName, (IPAddr, Port))] -> [String] hostListFragment' hs os = concatMap muninHost hs where muninHost :: Host -> [String] muninHost h = [ "[" ++ (hostName h) ++ "]" , " address " ++ maybe (hostName h) (val . fst) (hOverride h) ] ++ (maybe [] (\x -> [" port " ++ (val $ snd x)]) (hOverride h)) ++ [""] hOverride :: Host -> Maybe (IPAddr, Port) hOverride h = lookup (hostName h) os -- | Create the host list fragment for master config. hostListFragment :: [Host] -> [String] hostListFragment hs = hostListFragment' hs []
ArchiveTeam/glowing-computing-machine
src/Propellor/Property/Munin.hs
bsd-2-clause
1,735
20
17
266
428
241
187
37
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.ModuleName -- Copyright : Duncan Coutts 2008 -- -- Maintainer : [email protected] -- Portability : portable -- -- Data type for Haskell module names. {- All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Isaac Jones nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Distribution.ModuleName ( ModuleName, fromString, components, toFilePath, main, simple, ) where import Distribution.Text ( Text(..) ) import qualified Distribution.Compat.ReadP as Parse import qualified Text.PrettyPrint as Disp import qualified Data.Char as Char ( isAlphaNum, isUpper ) import System.FilePath ( pathSeparator ) import Data.List ( intersperse ) -- | A valid Haskell module name. -- newtype ModuleName = ModuleName [String] deriving (Eq, Ord, Read, Show) instance Text ModuleName where disp (ModuleName ms) = Disp.hcat (intersperse (Disp.char '.') (map Disp.text ms)) parse = do ms <- Parse.sepBy1 component (Parse.char '.') return (ModuleName ms) where component = do c <- Parse.satisfy Char.isUpper cs <- Parse.munch validModuleChar return (c:cs) validModuleChar :: Char -> Bool validModuleChar c = Char.isAlphaNum c || c == '_' || c == '\'' validModuleComponent :: String -> Bool validModuleComponent [] = False validModuleComponent (c:cs) = Char.isUpper c && all validModuleChar cs {-# DEPRECATED simple "use ModuleName.fromString instead" #-} simple :: String -> ModuleName simple str = ModuleName [str] -- | Construct a 'ModuleName' from a valid module name 'String'. -- -- This is just a convenience function intended for valid module strings. It is -- an error if it is used with a string that is not a valid module name. If you -- are parsing user input then use 'Distribution.Text.simpleParse' instead. -- fromString :: String -> ModuleName fromString string | all validModuleComponent components' = ModuleName components' | otherwise = error badName where components' = split string badName = "ModuleName.fromString: invalid module name " ++ show string split cs = case break (=='.') cs of (chunk,[]) -> chunk : [] (chunk,_:rest) -> chunk : split rest -- | The module name @Main@. -- main :: ModuleName main = ModuleName ["Main"] -- | The individual components of a hierarchical module name. For example -- -- > components (fromString "A.B.C") = ["A", "B", "C"] -- components :: ModuleName -> [String] components (ModuleName ms) = ms -- | Convert a module name to a file path, but without any file extension. -- For example: -- -- > toFilePath (fromString "A.B.C") = "A/B/C" -- toFilePath :: ModuleName -> FilePath toFilePath = concat . intersperse [pathSeparator] . components
IreneKnapp/Faction
libfaction/Distribution/ModuleName.hs
bsd-3-clause
4,332
0
14
919
601
332
269
53
2
foo x = case (odd x) of True -> "Odd" False -> "Even"
mpickering/ghc-exactprint
tests/examples/ghc710/B.hs
bsd-3-clause
80
0
7
39
31
15
16
3
2
module Settings.Packages.IntegerGmp (integerGmpPackageArgs) where import Base import Expression import Oracles.Setting import Rules.Gmp -- TODO: Is this needed? -- ifeq "$(GMP_PREFER_FRAMEWORK)" "YES" -- libraries/integer-gmp_CONFIGURE_OPTS += --with-gmp-framework-preferred -- endif integerGmpPackageArgs :: Args integerGmpPackageArgs = package integerGmp ? do path <- expr gmpBuildPath let includeGmp = "-I" ++ path -/- "include" gmpIncludeDir <- getSetting GmpIncludeDir gmpLibDir <- getSetting GmpLibDir mconcat [ builder Cc ? arg includeGmp , builder GhcCabal ? mconcat [ (null gmpIncludeDir && null gmpLibDir) ? arg "--configure-option=--with-intree-gmp" , arg ("--configure-option=CFLAGS=" ++ includeGmp) , arg ("--gcc-options=" ++ includeGmp) ] ]
bgamari/shaking-up-ghc
src/Settings/Packages/IntegerGmp.hs
bsd-3-clause
864
0
16
198
177
90
87
17
1
module Aws.Sqs.Core where import Aws.Core import Aws.S3.Core (LocationConstraint, locationUsClassic, locationUsWest, locationUsWest2, locationApSouthEast, locationApNorthEast, locationEu) import qualified Blaze.ByteString.Builder as Blaze import qualified Blaze.ByteString.Builder.Char8 as Blaze8 import qualified Control.Exception as C import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Resource (MonadThrow, throwM) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Data.Conduit (($$+-)) import Data.IORef import Data.List import Data.Maybe import Data.Monoid import Data.Ord import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding as TE import Data.Time import Data.Typeable import qualified Network.HTTP.Conduit as HTTP import qualified Network.HTTP.Types as HTTP import System.Locale import qualified Text.XML as XML import Text.XML.Cursor (($/)) import qualified Text.XML.Cursor as Cu type ErrorCode = T.Text data SqsError = SqsError { sqsStatusCode :: HTTP.Status , sqsErrorCode :: ErrorCode , sqsErrorType :: T.Text , sqsErrorMessage :: T.Text , sqsErrorDetail :: Maybe T.Text , sqsErrorMetadata :: Maybe SqsMetadata } | SqsXmlError { sqsXmlErrorMessage :: T.Text , sqsXmlErrorMetadata :: Maybe SqsMetadata } deriving (Show, Typeable) instance C.Exception SqsError data SqsMetadata = SqsMetadata { sqsMAmzId2 :: Maybe T.Text , sqsMRequestId :: Maybe T.Text } deriving (Show) instance Loggable SqsMetadata where toLogText (SqsMetadata id2 rid) = "SQS: request ID=" `mappend` fromMaybe "<none>" rid `mappend` ", x-amz-id-2=" `mappend` fromMaybe "<none>" id2 instance Monoid SqsMetadata where mempty = SqsMetadata Nothing Nothing SqsMetadata a1 r1 `mappend` SqsMetadata a2 r2 = SqsMetadata (a1 `mplus` a2) (r1 `mplus` r2) data SqsAuthorization = SqsAuthorizationHeader | SqsAuthorizationQuery deriving (Show) data Endpoint = Endpoint { endpointHost :: B.ByteString , endpointDefaultLocationConstraint :: LocationConstraint , endpointAllowedLocationConstraints :: [LocationConstraint] } deriving (Show) data SqsConfiguration qt = SqsConfiguration { sqsProtocol :: Protocol , sqsEndpoint :: Endpoint , sqsPort :: Int , sqsUseUri :: Bool , sqsDefaultExpiry :: NominalDiffTime } deriving (Show) instance DefaultServiceConfiguration (SqsConfiguration NormalQuery) where defServiceConfig = sqs HTTPS sqsEndpointUsClassic False debugServiceConfig = sqs HTTP sqsEndpointUsClassic False instance DefaultServiceConfiguration (SqsConfiguration UriOnlyQuery) where defServiceConfig = sqs HTTPS sqsEndpointUsClassic True debugServiceConfig = sqs HTTP sqsEndpointUsClassic True sqsEndpointUsClassic :: Endpoint sqsEndpointUsClassic = Endpoint { endpointHost = "queue.amazonaws.com" , endpointDefaultLocationConstraint = locationUsClassic , endpointAllowedLocationConstraints = [locationUsClassic , locationUsWest , locationEu , locationApSouthEast , locationApNorthEast] } sqsEndpointUsWest :: Endpoint sqsEndpointUsWest = Endpoint { endpointHost = "us-west-1.queue.amazonaws.com" , endpointDefaultLocationConstraint = locationUsWest , endpointAllowedLocationConstraints = [locationUsWest] } sqsEndpointUsWest2 :: Endpoint sqsEndpointUsWest2 = Endpoint { endpointHost = "us-west-2.queue.amazonaws.com" , endpointDefaultLocationConstraint = locationUsWest2 , endpointAllowedLocationConstraints = [locationUsWest2] } sqsEndpointEu :: Endpoint sqsEndpointEu = Endpoint { endpointHost = "eu-west-1.queue.amazonaws.com" , endpointDefaultLocationConstraint = locationEu , endpointAllowedLocationConstraints = [locationEu] } sqsEndpointApSouthEast :: Endpoint sqsEndpointApSouthEast = Endpoint { endpointHost = "ap-southeast-1.queue.amazonaws.com" , endpointDefaultLocationConstraint = locationApSouthEast , endpointAllowedLocationConstraints = [locationApSouthEast] } sqsEndpointApNorthEast :: Endpoint sqsEndpointApNorthEast = Endpoint { endpointHost = "sqs.ap-northeast-1.amazonaws.com" , endpointDefaultLocationConstraint = locationApNorthEast , endpointAllowedLocationConstraints = [locationApNorthEast] } sqs :: Protocol -> Endpoint -> Bool -> SqsConfiguration qt sqs protocol endpoint uri = SqsConfiguration { sqsProtocol = protocol , sqsEndpoint = endpoint , sqsPort = defaultPort protocol , sqsUseUri = uri , sqsDefaultExpiry = 15*60 } data SqsQuery = SqsQuery{ sqsQueueName :: Maybe QueueName, sqsQuery :: HTTP.Query } sqsSignQuery :: SqsQuery -> SqsConfiguration qt -> SignatureData -> SignedQuery sqsSignQuery SqsQuery{..} SqsConfiguration{..} SignatureData{..} = SignedQuery { sqMethod = method , sqProtocol = sqsProtocol , sqHost = endpointHost sqsEndpoint , sqPort = sqsPort , sqPath = path , sqQuery = signedQuery , sqDate = Just signatureTime , sqAuthorization = Nothing , sqBody = Nothing , sqStringToSign = stringToSign , sqContentType = Nothing , sqContentMd5 = Nothing , sqAmzHeaders = [] , sqOtherHeaders = [] } where method = PostQuery path = case sqsQueueName of Just x -> TE.encodeUtf8 $ printQueueName x Nothing -> "/" expandedQuery = sortBy (comparing fst) ( sqsQuery ++ [ ("AWSAccessKeyId", Just(accessKeyID signatureCredentials)), ("Expires", Just(BC.pack expiresString)), ("SignatureMethod", Just("HmacSHA256")), ("SignatureVersion",Just("2")), ("Version",Just("2012-11-05"))] ++ maybe [] (\tok -> [("SecurityToken", Just tok)]) (iamToken signatureCredentials)) expires = AbsoluteExpires $ sqsDefaultExpiry `addUTCTime` signatureTime expiresString = formatTime defaultTimeLocale "%FT%TZ" (fromAbsoluteTimeInfo expires) sig = signature signatureCredentials HmacSHA256 stringToSign stringToSign = Blaze.toByteString . mconcat . intersperse (Blaze8.fromChar '\n') . concat $ [[Blaze.copyByteString $ httpMethod method] , [Blaze.copyByteString $ endpointHost sqsEndpoint] , [Blaze.copyByteString path] , [Blaze.copyByteString $ HTTP.renderQuery False expandedQuery ]] signedQuery = expandedQuery ++ (HTTP.simpleQueryToQuery $ makeAuthQuery) makeAuthQuery = [("Signature", sig)] sqsResponseConsumer :: HTTPResponseConsumer a -> IORef SqsMetadata -> HTTPResponseConsumer a sqsResponseConsumer inner metadata resp = do let headerString = fmap T.decodeUtf8 . flip lookup (HTTP.responseHeaders resp) let amzId2 = headerString "x-amz-id-2" let requestId = headerString "x-amz-request-id" let m = SqsMetadata { sqsMAmzId2 = amzId2, sqsMRequestId = requestId } liftIO $ tellMetadataRef metadata m if HTTP.responseStatus resp >= HTTP.status400 then sqsErrorResponseConsumer resp else inner resp sqsXmlResponseConsumer :: (Cu.Cursor -> Response SqsMetadata a) -> IORef SqsMetadata -> HTTPResponseConsumer a sqsXmlResponseConsumer parse metadataRef = sqsResponseConsumer (xmlCursorConsumer parse metadataRef) metadataRef sqsErrorResponseConsumer :: HTTPResponseConsumer a sqsErrorResponseConsumer resp = do doc <- HTTP.responseBody resp $$+- XML.sinkDoc XML.def let cursor = Cu.fromDocument doc liftIO $ case parseError cursor of Right err -> throwM err Left otherErr -> throwM otherErr where parseError :: Cu.Cursor -> Either C.SomeException SqsError parseError root = do cursor <- force "Missing Error" $ root $/ Cu.laxElement "Error" code <- force "Missing error Code" $ cursor $/ elContent "Code" message <- force "Missing error Message" $ cursor $/ elContent "Message" errorType <- force "Missing error Type" $ cursor $/ elContent "Type" let detail = listToMaybe $ cursor $/ elContent "Detail" return SqsError { sqsStatusCode = HTTP.responseStatus resp , sqsErrorCode = code , sqsErrorMessage = message , sqsErrorType = errorType , sqsErrorDetail = detail , sqsErrorMetadata = Nothing } data QueueName = QueueName{ qName :: T.Text, qAccountNumber :: T.Text } deriving(Show, Read, Eq, Ord) printQueueName :: QueueName -> T.Text printQueueName queue = T.concat ["/", (qAccountNumber queue), "/", (qName queue), "/"] data QueueAttribute = QueueAll | ApproximateNumberOfMessages | ApproximateNumberOfMessagesNotVisible | VisibilityTimeout | CreatedTimestamp | LastModifiedTimestamp | Policy | MaximumMessageSize | MessageRetentionPeriod | QueueArn deriving(Show, Enum, Eq) data MessageAttribute = MessageAll -- ^ all values | SenderId -- ^ the AWS account number (or the IP address, if anonymous access is -- allowed) of the sender | SentTimestamp -- ^ the time when the message was sent (epoch time in milliseconds) | ApproximateReceiveCount -- ^ the number of times a message has been received but not deleted | ApproximateFirstReceiveTimestamp -- ^ the time when the message was first received (epoch time in -- milliseconds) deriving(Show,Read,Eq,Ord,Enum,Bounded) data SqsPermission = PermissionAll | PermissionSendMessage | PermissionReceiveMessage | PermissionDeleteMessage | PermissionChangeMessageVisibility | PermissionGetQueueAttributes deriving (Show, Enum, Eq) parseQueueAttribute :: MonadThrow m => T.Text -> m QueueAttribute parseQueueAttribute "ApproximateNumberOfMessages" = return ApproximateNumberOfMessages parseQueueAttribute "ApproximateNumberOfMessagesNotVisible" = return ApproximateNumberOfMessagesNotVisible parseQueueAttribute "VisibilityTimeout" = return VisibilityTimeout parseQueueAttribute "CreatedTimestamp" = return CreatedTimestamp parseQueueAttribute "LastModifiedTimestamp" = return LastModifiedTimestamp parseQueueAttribute "Policy" = return Policy parseQueueAttribute "MaximumMessageSize" = return MaximumMessageSize parseQueueAttribute "MessageRetentionPeriod" = return MessageRetentionPeriod parseQueueAttribute "QueueArn" = return QueueArn parseQueueAttribute x = throwM $ XmlException ( "Invalid Attribute Name. " ++ show x) printQueueAttribute :: QueueAttribute -> T.Text printQueueAttribute QueueAll = "All" printQueueAttribute ApproximateNumberOfMessages = "ApproximateNumberOfMessages" printQueueAttribute ApproximateNumberOfMessagesNotVisible = "ApproximateNumberOfMessagesNotVisible" printQueueAttribute VisibilityTimeout = "VisibilityTimeout" printQueueAttribute CreatedTimestamp = "CreatedTimestamp" printQueueAttribute LastModifiedTimestamp = "LastModifiedTimestamp" printQueueAttribute Policy = "Policy" printQueueAttribute MaximumMessageSize = "MaximumMessageSize" printQueueAttribute MessageRetentionPeriod = "MessageRetentionPeriod" printQueueAttribute QueueArn = "QueueArn" parseMessageAttribute :: MonadThrow m => T.Text -> m MessageAttribute parseMessageAttribute "SenderId" = return SenderId parseMessageAttribute "SentTimestamp" = return SentTimestamp parseMessageAttribute "ApproximateReceiveCount" = return ApproximateReceiveCount parseMessageAttribute "ApproximateFirstReceiveTimestamp" = return ApproximateFirstReceiveTimestamp parseMessageAttribute x = throwM $ XmlException ( "Invalid Attribute Name. " ++ show x) printMessageAttribute :: MessageAttribute -> T.Text printMessageAttribute MessageAll = "All" printMessageAttribute SenderId = "SenderId" printMessageAttribute SentTimestamp = "SentTimestamp" printMessageAttribute ApproximateReceiveCount = "ApproximateReceiveCount" printMessageAttribute ApproximateFirstReceiveTimestamp = "ApproximateFirstReceiveTimestamp" printPermission :: SqsPermission -> T.Text printPermission PermissionAll = "*" printPermission PermissionSendMessage = "SendMessage" printPermission PermissionReceiveMessage = "ReceiveMessage" printPermission PermissionDeleteMessage = "DeleteMessage" printPermission PermissionChangeMessageVisibility = "ChangeMessageVisibility" printPermission PermissionGetQueueAttributes = "GetQueueAttributes" newtype ReceiptHandle = ReceiptHandle T.Text deriving(Show, Read, Eq, Ord) newtype MessageId = MessageId T.Text deriving(Show, Read, Eq, Ord) printReceiptHandle :: ReceiptHandle -> T.Text printReceiptHandle (ReceiptHandle handle) = handle
fpco/aws
Aws/Sqs/Core.hs
bsd-3-clause
13,954
0
16
3,532
2,724
1,504
1,220
-1
-1
module Strings.Reverse.Data where import Autolib.Size import Autolib.ToDoc data Exp a = Reverse ( Exp a ) | Plus ( Exp a ) ( Exp a ) | Empty | Item a instance ToDoc a => ToDoc ( Exp a ) where toDoc x = case x of Reverse y -> parens (toDoc y) <> text "^R" Plus y z -> toDoc y <+> toDoc z Empty -> empty Item i -> toDoc i instance ToDoc a => Show ( Exp a ) where show = render . toDoc instance Size ( Exp a ) where size x = 1 + case x of Reverse y -> size y Plus y z -> size y + size z _ -> 0 make :: [a] -> [Int] -> Exp a make items [] = Empty make items [x] = Item $ items !! (x `mod` length items) make items (x : y : []) = Plus ( make items [x] ) ( make items [y] ) make items (x : xs) = case odd x of False -> let k = x `div` 2 ( pre, post ) = splitAt ( 1 + k `mod` (length xs -1) ) xs in Plus ( make items pre ) ( make items post ) True -> Reverse ( make_no_r items xs ) make_no_r items [] = Empty make_no_r items [x] = Item $ items !! (x `mod` length items) make_no_r items (x : y : []) = Plus ( make items [x] ) ( make items [y] ) make_no_r items (k : xs) = let ( pre, post ) = splitAt ( 1 + k `mod` (length xs -1) ) xs in Plus ( make items pre ) ( make items post ) original :: Exp a -> [a] original x = case x of Reverse y -> original y Plus y z -> original y ++ original z Empty -> [] Item i -> [i] semantics :: Exp a -> [a] semantics x = case x of Reverse y -> reverse $ semantics y Plus y z -> semantics y ++ semantics z Empty -> [] Item i -> [i]
Erdwolf/autotool-bonn
src/Strings/Reverse/Data.hs
gpl-2.0
1,659
0
17
558
841
423
418
47
4
module RnHsDoc ( rnHsDoc, rnLHsDoc, rnMbLHsDoc ) where import GhcPrelude import TcRnTypes import HsSyn import SrcLoc rnMbLHsDoc :: Maybe LHsDocString -> RnM (Maybe LHsDocString) rnMbLHsDoc mb_doc = case mb_doc of Just doc -> do doc' <- rnLHsDoc doc return (Just doc') Nothing -> return Nothing rnLHsDoc :: LHsDocString -> RnM LHsDocString rnLHsDoc (L pos doc) = do doc' <- rnHsDoc doc return (L pos doc') rnHsDoc :: HsDocString -> RnM HsDocString rnHsDoc (HsDocString s) = return (HsDocString s)
ezyang/ghc
compiler/rename/RnHsDoc.hs
bsd-3-clause
520
0
12
102
187
92
95
17
2
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Typeable.Internal -- Copyright : (c) The University of Glasgow, CWI 2001--2011 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- The representations of the types TyCon and TypeRep, and the -- function mkTyCon which is used by derived instances of Typeable to -- construct a TyCon. -- ----------------------------------------------------------------------------- module Data.Typeable.Internal ( Proxy (..), TypeRep(..), Fingerprint(..), typeOf, typeOf1, typeOf2, typeOf3, typeOf4, typeOf5, typeOf6, typeOf7, Typeable1, Typeable2, Typeable3, Typeable4, Typeable5, Typeable6, Typeable7, TyCon(..), typeRep, mkTyCon, mkTyCon3, mkTyConApp, mkAppTy, typeRepTyCon, Typeable(..), mkFunTy, splitTyConApp, funResultTy, typeRepArgs, showsTypeRep, tyConString, listTc, funTc ) where import GHC.Base import GHC.Word import GHC.Show import GHC.Read ( Read ) import Data.Proxy import GHC.Num import GHC.Real -- import GHC.IORef -- import GHC.IOArray -- import GHC.MVar import GHC.ST ( ST, STret ) import GHC.STRef ( STRef ) import GHC.Ptr ( Ptr, FunPtr ) -- import GHC.Stable import GHC.Arr ( Array, STArray, Ix ) import GHC.TypeLits ( Nat, Symbol, KnownNat, KnownSymbol, natVal', symbolVal' ) import Data.Type.Coercion import Data.Type.Equality import Text.ParserCombinators.ReadP ( ReadP ) import Text.Read.Lex ( Lexeme, Number ) import Text.ParserCombinators.ReadPrec ( ReadPrec ) import GHC.Float ( FFFormat, RealFloat, Floating ) import Data.Bits ( Bits, FiniteBits ) import GHC.Enum ( Bounded, Enum ) import GHC.Fingerprint.Type import {-# SOURCE #-} GHC.Fingerprint -- loop: GHC.Fingerprint -> Foreign.Ptr -> Data.Typeable -- Better to break the loop here, because we want non-SOURCE imports -- of Data.Typeable as much as possible so we can optimise the derived -- instances. -- | A concrete representation of a (monomorphic) type. 'TypeRep' -- supports reasonably efficient equality. data TypeRep = TypeRep {-# UNPACK #-} !Fingerprint TyCon [TypeRep] -- Compare keys for equality instance Eq TypeRep where (TypeRep k1 _ _) == (TypeRep k2 _ _) = k1 == k2 instance Ord TypeRep where (TypeRep k1 _ _) <= (TypeRep k2 _ _) = k1 <= k2 -- | An abstract representation of a type constructor. 'TyCon' objects can -- be built using 'mkTyCon'. data TyCon = TyCon { tyConHash :: {-# UNPACK #-} !Fingerprint, tyConPackage :: String, -- ^ @since 4.5.0.0 tyConModule :: String, -- ^ @since 4.5.0.0 tyConName :: String -- ^ @since 4.5.0.0 } instance Eq TyCon where (TyCon t1 _ _ _) == (TyCon t2 _ _ _) = t1 == t2 instance Ord TyCon where (TyCon k1 _ _ _) <= (TyCon k2 _ _ _) = k1 <= k2 ----------------- Construction -------------------- #include "MachDeps.h" -- mkTyCon is an internal function to make it easier for GHC to -- generate derived instances. GHC precomputes the MD5 hash for the -- TyCon and passes it as two separate 64-bit values to mkTyCon. The -- TyCon for a derived Typeable instance will end up being statically -- allocated. #if WORD_SIZE_IN_BITS < 64 mkTyCon :: Word64# -> Word64# -> String -> String -> String -> TyCon #else mkTyCon :: Word# -> Word# -> String -> String -> String -> TyCon #endif mkTyCon high# low# pkg modl name = TyCon (Fingerprint (W64# high#) (W64# low#)) pkg modl name -- | Applies a type constructor to a sequence of types mkTyConApp :: TyCon -> [TypeRep] -> TypeRep mkTyConApp tc@(TyCon tc_k _ _ _) [] = TypeRep tc_k tc [] -- optimisation: all derived Typeable instances -- end up here, and it helps generate smaller -- code for derived Typeable. mkTyConApp tc@(TyCon tc_k _ _ _) args = TypeRep (fingerprintFingerprints (tc_k : arg_ks)) tc args where arg_ks = [k | TypeRep k _ _ <- args] -- | A special case of 'mkTyConApp', which applies the function -- type constructor to a pair of types. mkFunTy :: TypeRep -> TypeRep -> TypeRep mkFunTy f a = mkTyConApp funTc [f,a] -- | Splits a type constructor application splitTyConApp :: TypeRep -> (TyCon,[TypeRep]) splitTyConApp (TypeRep _ tc trs) = (tc,trs) -- | Applies a type to a function type. Returns: @'Just' u@ if the -- first argument represents a function of type @t -> u@ and the -- second argument represents a function of type @t@. Otherwise, -- returns 'Nothing'. funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep funResultTy trFun trArg = case splitTyConApp trFun of (tc, [t1,t2]) | tc == funTc && t1 == trArg -> Just t2 _ -> Nothing -- | Adds a TypeRep argument to a TypeRep. mkAppTy :: TypeRep -> TypeRep -> TypeRep mkAppTy (TypeRep _ tc trs) arg_tr = mkTyConApp tc (trs ++ [arg_tr]) -- Notice that we call mkTyConApp to construct the fingerprint from tc and -- the arg fingerprints. Simply combining the current fingerprint with -- the new one won't give the same answer, but of course we want to -- ensure that a TypeRep of the same shape has the same fingerprint! -- See Trac #5962 -- | Builds a 'TyCon' object representing a type constructor. An -- implementation of "Data.Typeable" should ensure that the following holds: -- -- > A==A' ^ B==B' ^ C==C' ==> mkTyCon A B C == mkTyCon A' B' C' -- -- mkTyCon3 :: String -- ^ package name -> String -- ^ module name -> String -- ^ the name of the type constructor -> TyCon -- ^ A unique 'TyCon' object mkTyCon3 pkg modl name = TyCon (fingerprintString (pkg ++ (' ':modl) ++ (' ':name))) pkg modl name ----------------- Observation --------------------- -- | Observe the type constructor of a type representation typeRepTyCon :: TypeRep -> TyCon typeRepTyCon (TypeRep _ tc _) = tc -- | Observe the argument types of a type representation typeRepArgs :: TypeRep -> [TypeRep] typeRepArgs (TypeRep _ _ args) = args -- | Observe string encoding of a type representation {-# DEPRECATED tyConString "renamed to 'tyConName'; 'tyConModule' and 'tyConPackage' are also available." #-} -- deprecated in 7.4 tyConString :: TyCon -> String tyConString = tyConName ------------------------------------------------------------- -- -- The Typeable class and friends -- ------------------------------------------------------------- -- | The class 'Typeable' allows a concrete representation of a type to -- be calculated. class Typeable a where typeRep# :: Proxy# a -> TypeRep -- | Takes a value of type @a@ and returns a concrete representation -- of that type. -- -- @since 4.7.0.0 typeRep :: forall proxy a. Typeable a => proxy a -> TypeRep typeRep _ = typeRep# (proxy# :: Proxy# a) {-# INLINE typeRep #-} -- Keeping backwards-compatibility typeOf :: forall a. Typeable a => a -> TypeRep typeOf _ = typeRep (Proxy :: Proxy a) typeOf1 :: forall t (a :: *). Typeable t => t a -> TypeRep typeOf1 _ = typeRep (Proxy :: Proxy t) typeOf2 :: forall t (a :: *) (b :: *). Typeable t => t a b -> TypeRep typeOf2 _ = typeRep (Proxy :: Proxy t) typeOf3 :: forall t (a :: *) (b :: *) (c :: *). Typeable t => t a b c -> TypeRep typeOf3 _ = typeRep (Proxy :: Proxy t) typeOf4 :: forall t (a :: *) (b :: *) (c :: *) (d :: *). Typeable t => t a b c d -> TypeRep typeOf4 _ = typeRep (Proxy :: Proxy t) typeOf5 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *). Typeable t => t a b c d e -> TypeRep typeOf5 _ = typeRep (Proxy :: Proxy t) typeOf6 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *). Typeable t => t a b c d e f -> TypeRep typeOf6 _ = typeRep (Proxy :: Proxy t) typeOf7 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *) (g :: *). Typeable t => t a b c d e f g -> TypeRep typeOf7 _ = typeRep (Proxy :: Proxy t) type Typeable1 (a :: * -> *) = Typeable a type Typeable2 (a :: * -> * -> *) = Typeable a type Typeable3 (a :: * -> * -> * -> *) = Typeable a type Typeable4 (a :: * -> * -> * -> * -> *) = Typeable a type Typeable5 (a :: * -> * -> * -> * -> * -> *) = Typeable a type Typeable6 (a :: * -> * -> * -> * -> * -> * -> *) = Typeable a type Typeable7 (a :: * -> * -> * -> * -> * -> * -> * -> *) = Typeable a {-# DEPRECATED Typeable1 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable2 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable3 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable4 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable5 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable6 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable7 "renamed to 'Typeable'" #-} -- deprecated in 7.8 -- | Kind-polymorphic Typeable instance for type application instance (Typeable s, Typeable a) => Typeable (s a) where -- See Note [The apparent incoherence of Typable] typeRep# = \_ -> rep -- Note [Memoising typeOf] where !ty1 = typeRep# (proxy# :: Proxy# s) !ty2 = typeRep# (proxy# :: Proxy# a) !rep = ty1 `mkAppTy` ty2 {- Note [Memoising typeOf] ~~~~~~~~~~~~~~~~~~~~~~~~~~ See #3245, #9203 IMPORTANT: we don't want to recalculate the TypeRep once per call with the proxy argument. This is what went wrong in #3245 and #9203. So we help GHC by manually keeping the 'rep' *outside* the lambda. -} ----------------- Showing TypeReps -------------------- instance Show TypeRep where showsPrec p (TypeRep _ tycon tys) = case tys of [] -> showsPrec p tycon [x] | tycon == listTc -> showChar '[' . shows x . showChar ']' [a,r] | tycon == funTc -> showParen (p > 8) $ showsPrec 9 a . showString " -> " . showsPrec 8 r xs | isTupleTyCon tycon -> showTuple xs | otherwise -> showParen (p > 9) $ showsPrec p tycon . showChar ' ' . showArgs (showChar ' ') tys showsTypeRep :: TypeRep -> ShowS showsTypeRep = shows instance Show TyCon where showsPrec _ t = showString (tyConName t) isTupleTyCon :: TyCon -> Bool isTupleTyCon (TyCon _ _ _ ('(':',':_)) = True isTupleTyCon _ = False -- Some (Show.TypeRep) helpers: showArgs :: Show a => ShowS -> [a] -> ShowS showArgs _ [] = id showArgs _ [a] = showsPrec 10 a showArgs sep (a:as) = showsPrec 10 a . sep . showArgs sep as showTuple :: [TypeRep] -> ShowS showTuple args = showChar '(' . showArgs (showChar ',') args . showChar ')' listTc :: TyCon listTc = typeRepTyCon (typeOf [()]) funTc :: TyCon funTc = typeRepTyCon (typeRep (Proxy :: Proxy (->))) ------------------------------------------------------------- -- -- Instances of the Typeable classes for Prelude types -- ------------------------------------------------------------- deriving instance Typeable () deriving instance Typeable [] deriving instance Typeable Maybe deriving instance Typeable Ratio deriving instance Typeable (->) deriving instance Typeable IO deriving instance Typeable Array deriving instance Typeable ST deriving instance Typeable STret deriving instance Typeable STRef deriving instance Typeable STArray deriving instance Typeable (,) deriving instance Typeable (,,) deriving instance Typeable (,,,) deriving instance Typeable (,,,,) deriving instance Typeable (,,,,,) deriving instance Typeable (,,,,,,) deriving instance Typeable Ptr deriving instance Typeable FunPtr ------------------------------------------------------- -- -- Generate Typeable instances for standard datatypes -- ------------------------------------------------------- deriving instance Typeable Bool deriving instance Typeable Char deriving instance Typeable Float deriving instance Typeable Double deriving instance Typeable Int deriving instance Typeable Word deriving instance Typeable Integer deriving instance Typeable Ordering deriving instance Typeable Word8 deriving instance Typeable Word16 deriving instance Typeable Word32 deriving instance Typeable Word64 deriving instance Typeable TyCon deriving instance Typeable TypeRep deriving instance Typeable Fingerprint deriving instance Typeable RealWorld deriving instance Typeable Proxy deriving instance Typeable KProxy deriving instance Typeable (:~:) deriving instance Typeable Coercion deriving instance Typeable ReadP deriving instance Typeable Lexeme deriving instance Typeable Number deriving instance Typeable ReadPrec deriving instance Typeable FFFormat ------------------------------------------------------- -- -- Generate Typeable instances for standard classes -- ------------------------------------------------------- deriving instance Typeable (~) deriving instance Typeable Coercible deriving instance Typeable TestEquality deriving instance Typeable TestCoercion deriving instance Typeable Eq deriving instance Typeable Ord deriving instance Typeable Bits deriving instance Typeable FiniteBits deriving instance Typeable Num deriving instance Typeable Real deriving instance Typeable Integral deriving instance Typeable Fractional deriving instance Typeable RealFrac deriving instance Typeable Floating deriving instance Typeable RealFloat deriving instance Typeable Bounded deriving instance Typeable Enum deriving instance Typeable Ix deriving instance Typeable Show deriving instance Typeable Read deriving instance Typeable Alternative deriving instance Typeable Applicative deriving instance Typeable Functor deriving instance Typeable Monad deriving instance Typeable MonadPlus deriving instance Typeable Monoid deriving instance Typeable Typeable -------------------------------------------------------------------------------- -- Instances for type literals {- Note [Potential Collisions in `Nat` and `Symbol` instances] Kinds resulting from lifted types have finitely many type-constructors. This is not the case for `Nat` and `Symbol`, which both contain *infinitely* many type constructors (e.g., `Nat` has 0, 1, 2, 3, etc.). One might think that this would increase the chance of hash-collisions in the type but this is not the case because the fingerprint stored in a `TypeRep` identifies the whole *type* and not just the type constructor. This is why the chance of collisions for `Nat` and `Symbol` is not any worse than it is for other lifted types with infinitely many inhabitants. Indeed, `Nat` is isomorphic to (lifted) `[()]` and `Symbol` is isomorphic to `[Char]`. -} {- Note [The apparent incoherence of Typable] See Trac #9242 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The reason we have INCOHERENT on Typeable (n:Nat) and Typeable (s:Symbol) because we also have an instance Typable (f a). Now suppose we have [Wanted] Typeable (a :: Nat) we should pick the (x::Nat) instance, even though the instance matching rules would worry that 'a' might later be instantiated to (f b), for some f and b. But we type theorists know that there are no type constructors f of kind blah -> Nat, so this can never happen and it's safe to pick the second instance. -} instance {-# INCOHERENT #-} KnownNat n => Typeable (n :: Nat) where -- See Note [The apparent incoherence of Typable] -- See #9203 for an explanation of why this is written as `\_ -> rep`. typeRep# = \_ -> rep where rep = mkTyConApp tc [] tc = TyCon { tyConHash = fingerprintString (mk pack modu nm) , tyConPackage = pack , tyConModule = modu , tyConName = nm } pack = "base" modu = "GHC.TypeLits" nm = show (natVal' (proxy# :: Proxy# n)) mk a b c = a ++ " " ++ b ++ " " ++ c instance {-# INCOHERENT #-} KnownSymbol s => Typeable (s :: Symbol) where -- See Note [The apparent incoherence of Typable] -- See #9203 for an explanation of why this is written as `\_ -> rep`. typeRep# = \_ -> rep where rep = mkTyConApp tc [] tc = TyCon { tyConHash = fingerprintString (mk pack modu nm) , tyConPackage = pack , tyConModule = modu , tyConName = nm } pack = "base" modu = "GHC.TypeLits" nm = show (symbolVal' (proxy# :: Proxy# s)) mk a b c = a ++ " " ++ b ++ " " ++ c
green-haskell/ghc
libraries/base/Data/Typeable/Internal.hs
bsd-3-clause
16,938
0
15
3,690
3,622
2,027
1,595
-1
-1
{-# LANGUAGE ExistentialQuantification, DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Language.C.Data.Error -- Copyright : (c) 2008 Benedikt Huber, Manuel M. T. Chakravarty -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : ghc -- -- Base type for errors occurring in parsing, analysing and pretty-printing. -- With ideas from Simon Marlow's -- "An extensible dynamically-typed hierarchy of execeptions [2006]" ----------------------------------------------------------------------------- module Language.C.Data.Error ( -- * Severity Level ErrorLevel(..), isHardError, -- * Error class Error(..), errorPos, errorLevel, errorMsgs, -- * Error 'supertype' CError(..), -- * Infos attached to errors ErrorInfo(..),showError,showErrorInfo,mkErrorInfo, -- * Default error types UnsupportedFeature, unsupportedFeature, unsupportedFeature_, UserError, userErr, -- * Raising internal errors internalErr, ) where import Data.Typeable import Data.Generics import Language.C.Data.Node import Language.C.Data.Position -- | Error levels (severity) data ErrorLevel = LevelWarn | LevelError | LevelFatal deriving (Eq, Ord) instance Show ErrorLevel where show LevelWarn = "WARNING" show LevelError = "ERROR" show LevelFatal = "FATAL ERROR" -- | return @True@ when the given error makes it impossible to continue -- analysis or compilation. isHardError :: (Error ex) => ex -> Bool isHardError = ( > LevelWarn) . errorLevel -- | information attached to every error in Language.C data ErrorInfo = ErrorInfo ErrorLevel Position [String] deriving Typeable -- to facilitate newtype deriving instance Show ErrorInfo where show = showErrorInfo "error" instance Error ErrorInfo where errorInfo = id changeErrorLevel (ErrorInfo _ pos msgs) lvl' = ErrorInfo lvl' pos msgs mkErrorInfo :: ErrorLevel -> String -> NodeInfo -> ErrorInfo mkErrorInfo lvl msg node = ErrorInfo lvl (posOfNode node) (lines msg) -- | `supertype' of all errors data CError = forall err. (Error err) => CError err deriving Typeable -- | errors in Language.C are instance of 'Error' class (Typeable e, Show e) => Error e where -- | obtain source location etc. of an error errorInfo :: e -> ErrorInfo -- | wrap error in 'CError' toError :: e -> CError -- | try to cast a generic 'CError' to the specific error type fromError :: CError -> (Maybe e) -- | modify the error level changeErrorLevel :: e -> ErrorLevel -> e -- default implementation fromError (CError e) = cast e toError = CError changeErrorLevel e lvl = if errorLevel e == lvl then e else error $ "changeErrorLevel: not possible for " ++ show e instance Show CError where show (CError e) = show e instance Error CError where errorInfo (CError err) = errorInfo err toError = id fromError = Just changeErrorLevel (CError e) = CError . changeErrorLevel e -- | position of an @Error@ errorPos :: (Error e) => e -> Position errorPos = ( \(ErrorInfo _ pos _) -> pos ) . errorInfo -- | severity level of an @Error@ errorLevel :: (Error e) => e -> ErrorLevel errorLevel = ( \(ErrorInfo lvl _ _) -> lvl ) . errorInfo -- | message lines of an @Error@ errorMsgs :: (Error e) => e -> [String] errorMsgs = ( \(ErrorInfo _ _ msgs) -> msgs ) . errorInfo -- | error raised if a operation requires an unsupported or not yet implemented feature. data UnsupportedFeature = UnsupportedFeature String Position deriving Typeable instance Error UnsupportedFeature where errorInfo (UnsupportedFeature msg pos) = ErrorInfo LevelError pos (lines msg) instance Show UnsupportedFeature where show = showError "Unsupported Feature" unsupportedFeature :: (Pos a) => String -> a -> UnsupportedFeature unsupportedFeature msg a = UnsupportedFeature msg (posOf a) unsupportedFeature_ :: String -> UnsupportedFeature unsupportedFeature_ msg = UnsupportedFeature msg internalPos -- | unspecified error raised by the user (in case the user does not want to define -- her own error types). newtype UserError = UserError ErrorInfo deriving Typeable instance Error UserError where errorInfo (UserError info) = info instance Show UserError where show = showError "User Error" userErr :: String -> UserError userErr msg = UserError (ErrorInfo LevelError internalPos (lines msg)) -- other errors to be defined elsewhere showError :: (Error e) => String -> e -> String showError short_msg = showErrorInfo short_msg . errorInfo -- | converts an error into a string using a fixed format -- -- * either the lines of the long error message or the short message has to be non-empty -- -- * the format is -- -- > <fname>:<row>: (column <col>) [<err lvl>] -- > >>> <line_1> -- > <line_2> -- > ... -- > <line_n> showErrorInfo :: String -> ErrorInfo -> String showErrorInfo short_msg (ErrorInfo level pos msgs) = header ++ showMsgLines (if null short_msg then msgs else short_msg:msgs) where header = showPos pos ++ "[" ++ show level ++ "]" showPos p | isSourcePos p = (posFile p) ++ ":" ++ show (posRow pos) ++ ": " ++ "(column " ++ show (posColumn pos) ++ ") " | otherwise = show p ++ ":: " showMsgLines [] = internalErr "No short message or error message provided." showMsgLines (x:xs) = indent ++ ">>> " ++ x ++ "\n" ++ unlines (map (indent++) xs) -- internal errors internalErrPrefix :: String internalErrPrefix = unlines [ "Language.C : Internal Error" , "This is propably a bug, and should be reported at "++ "http://www.sivity.net/projects/language.c/newticket"] -- | raise a fatal internal error; message may have multiple lines internalErr :: String -> a internalErr msg = error (internalErrPrefix ++ "\n" ++ indentLines msg ++ "\n") indent :: String indent = " " indentLines :: String -> String indentLines = unlines . map (indent++) . lines
vincenthz/language-c
src/Language/C/Data/Error.hs
bsd-3-clause
6,254
0
15
1,410
1,314
724
590
94
3
{-# Language FlexibleInstances #-} {-# Language TypeSynonymInstances #-} module Pretty ( ppconstraint, ppconstraints, ppdecl, ppenv, ppexpr, ppscheme, ppsubst, ppsignature, pptype ) where import Env import Type import Syntax import Infer import Text.PrettyPrint import qualified Data.Map as Map parensIf :: Bool -> Doc -> Doc parensIf True = parens parensIf False = id class Pretty p where ppr :: Int -> p -> Doc instance Pretty Name where ppr _ x = text x instance Pretty TVar where ppr _ (TV x) = text x instance Pretty Type where ppr p (TArr a b) = (parensIf (isArrow a) (ppr p a)) <+> text "->" <+> ppr p b where isArrow TArr{} = True isArrow _ = False ppr p (TVar a) = ppr p a ppr _ (TCon a) = text a instance Pretty Scheme where ppr p (Forall [] t) = ppr p t ppr p (Forall ts t) = text "forall" <+> hcat (punctuate space (map (ppr p) ts)) <> text "." <+> ppr p t instance Pretty Binop where ppr _ Add = text "+" ppr _ Sub = text "-" ppr _ Mul = text "*" ppr _ Eql = text "==" instance Pretty Expr where ppr p (Var a) = ppr p a ppr p (App a b) = parensIf (p > 0) $ ppr (p+1) a <+> ppr p b ppr p (Lam a b) = text "\\" <> ppr p a <+> text "->" <+> ppr p b ppr p (Let a b c) = text "let" <> ppr p a <+> text "=" <+> ppr p b <+> text "in" <+> ppr p c ppr p (Lit a) = ppr p a ppr p (Op o a b) = parensIf (p>0) $ ppr p a <+> ppr p o <+> ppr p b ppr p (Fix a) = parensIf (p>0) $ text "fix" <> ppr p a ppr p (If a b c) = text "if" <> ppr p a <+> text "then" <+> ppr p b <+> text "else" <+> ppr p c instance Pretty Lit where ppr _ (LInt i) = integer i ppr _ (LBool True) = text "True" ppr _ (LBool False) = text "False" instance Pretty Constraint where ppr p (a, b) = (ppr p a) <+> text " ~ " <+> (ppr p b) instance Pretty [Constraint] where ppr p cs = vcat (punctuate space (map (ppr p) cs)) instance Pretty Subst where ppr p (Subst s) = vcat (punctuate space (map pprSub $ Map.toList s)) where pprSub (a, b) = ppr 0 a <+> text "~" <+> ppr 0 b instance Show TypeError where show (UnificationFail a b) = concat ["Cannot unify types: \n\t", pptype a, "\nwith \n\t", pptype b] show (InfiniteType (TV a) b) = concat ["Cannot construct the infinite type: ", a, " = ", pptype b] show (Ambigious cs) = concat ["Cannot not match expected type: '" ++ pptype a ++ "' with actual type: '" ++ pptype b ++ "'\n" | (a,b) <- cs] show (UnboundVariable a) = "Not in scope: " ++ a ppscheme :: Scheme -> String ppscheme = render . ppr 0 pptype :: Type -> String pptype = render . ppr 0 ppexpr :: Expr -> String ppexpr = render . ppr 0 ppsignature :: (String, Scheme) -> String ppsignature (a, b) = a ++ " : " ++ ppscheme b ppdecl :: (String, Expr) -> String ppdecl (a, b) = "let " ++ a ++ " = " ++ ppexpr b ppenv :: Env -> [String] ppenv (TypeEnv env) = map ppsignature $ Map.toList env ppconstraint :: Constraint -> String ppconstraint = render . ppr 0 ppconstraints :: [Constraint] -> String ppconstraints = render . ppr 0 ppsubst :: Subst -> String ppsubst = render . ppr 0
yupferris/write-you-a-haskell
chapter7/poly_constraints/src/Pretty.hs
mit
3,106
0
15
782
1,479
738
741
90
1
module B5(myFringe,sumSquares)where import D5 hiding (sumSquares, fringe,myFringe) import D5 (fringe) import C5 hiding () myFringe:: Tree a -> [a] myFringe (Leaf x ) = [x] myFringe (Branch left right) = myFringe right sumSquares (x:xs)= x^2 + sumSquares xs sumSquares [] =0
kmate/HaRe
old/testing/moveDefBtwMods/B5_TokOut.hs
bsd-3-clause
284
0
7
51
129
72
57
9
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module T16183 where import Data.Kind $([d| type F1 = (Maybe :: Type -> Type) Int type F2 = (Int :: Type) -> (Int :: Type) type family F3 a where F3 (a :: Type) = Int newtype F4 = MkF4 (Int :: Type) |])
sdiehl/ghc
testsuite/tests/th/T16183.hs
bsd-3-clause
293
0
6
80
22
15
7
-1
-1
-- In this example, add data constructor 'Leaf' to the export list. module C4(Tree(Leaf)) where data Tree a = Leaf a | Branch (Tree a) (Tree a) sumTree:: (Num a) => Tree a -> a sumTree (Leaf x ) = x sumTree (Branch left right) = sumTree left + sumTree right myFringe:: Tree a -> [a] myFringe (Leaf x ) = [x] myFringe (Branch left right) = myFringe left class SameOrNot a where isSame :: a -> a -> Bool isNotSame :: a -> a -> Bool instance SameOrNot Int where isSame a b = a == b isNotSame a b = a /= b
kmate/HaRe
old/testing/addToExport/C4_TokOut.hs
bsd-3-clause
530
0
8
132
226
118
108
16
1
module PFE_HTML where import Prelude hiding(putStrLn,writeFile) --import Maybe(fromJust) import Control.Monad(when,unless) --import HsName(ModuleName(Module)) --import ScopeModule(scopeModule) import ConvRefsTypes(simplifyRefsTypes') import HLex2html(hlex2html') import HsLexerPass1(line,column) -- hmm import PFE0(findFile,newerThan,getCurrentModuleGraph,allModules,checkProject,moduleInfoPath) import PFE2(getModuleTime) import PFE3(parseSourceFile'') import PathUtils(normf) import DirUtils(getModificationTimeMaybe,optCreateDirectory) --import FileUtils(updateFile) import AbstractIO --import MUtils import PrettyPrint(pp) toHtmlFiles outDir srcURL modHTML optms = do ms <- maybe allModules return optms dir <- checkProject unless (null ms) $ optCreateDirectory (outDir dir) mapM_ (module2html dir) ms where module2html dir m = do let out_path = outDir dir++htmlFile m t_mod <- getModuleTime m t_html <- getModificationTimeMaybe out_path when (t_mod `newerThan` t_html) $ -- hmm!! do putStrLn $ "Updating: "++out_path writeFile out_path =<< file2html srcURL m file2html srcURL m = do path <- findFile m g <- getCurrentModuleGraph (ts,(_,rs0)) <- parseSourceFile'' path let rs = simplifyRefsTypes' rs0 ffm = (path,[(normf f,m)|(f,(m,_))<-g]) return (modHTML m (hlex2html' srcURL ffm (rs,ts))) -------------------------------------------------------------------------------- htmlFile m = moduleInfoPath m++".html" htmlDir dir = dir++"html/" --htmlPath m dir = htmldir dir++htmlFile m wwwDir dir = dir++"www/" --wwwPath m dir = wwwdir dir++htmlFile m --------------------------------------------------------------------------------
kmate/HaRe
old/tools/pfe/PFE_HTML.hs
bsd-3-clause
1,736
21
15
269
344
219
125
35
1
import Test.Cabal.Prelude main = cabalTest $ do fails $ cabal "new-build" ["q"]
mydaum/cabal
cabal-testsuite/PackageTests/NewBuild/T3978/cabal.test.hs
bsd-3-clause
84
0
10
16
31
16
15
3
1
module Exp where import Control.Monad import Parser -- import lecture18.example02 data Exp = Lit Int | Exp :+: Exp | Exp :*: Exp deriving (Eq, Show) evalExp :: Exp -> Int evalExp (Lit n) = n evalExp ( e :+: f) = evalExp e + evalExp f evalExp ( e :*: f) = evalExp e * evalExp f parseExp :: Parser Exp parseExp = parseLit `mplus` parseAdd `mplus` parseMul where parseLit = do { n <- parseInt; -- parse an integer 'n' return (Lit n) -- return Lit n } parseAdd = do { token '('; -- parse ( d <- parseExp; -- parse an Exp d token '+'; -- parse + e <- parseExp; -- parse an Exp e token ')'; -- parse ) return (d :+: e) } parseMul = do { token '('; -- parse ( d <- parseExp; -- parse an Exp d token '*'; -- parse * e <- parseExp; -- parse an Exp e token ')'; -- parse ) return (d :*: e) } -- expressions can be nested, recursion handling that
abhishekkr/tutorials_as_code
talks-articles/languages-n-runtimes/haskell/PhilipWadler-UniversityOfEdinburgh-2011/lecture18.example02.hs
mit
1,391
0
11
733
301
163
138
30
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE InstanceSigs #-} module Logic ( Logic(..), bFunctionMap) where import Data.Map as M hiding (map, foldl, (!)) import Data.Maybe import Data.Monoid import Data.List hiding (and) import Data.Array import Data.Char import Cat import Ref import Value import Sheet -- For Boolean calculations data Logic e = LVal Bool | And e e | Or e e | LGT e e | LLT e e | LEQ e e | Xor e e | BRef (Sheet e) Ref | BFunc String [e] deriving (Show) -- |It's a functor instance Functor Logic where fmap f (LVal x) = LVal x fmap f (And x y) = And (f x) (f y) fmap f (Or x y) = Or (f x) (f y) fmap f (Xor x y) = Xor (f x) (f y) fmap f (LGT x y) = LGT (f x) (f y) fmap f (LLT x y) = LLT (f x) (f y) fmap f (LEQ x y) = LEQ (f x) (f y) fmap f (BFunc s ps) = BFunc s (map f ps) -- |And we can evaluate it instance Monad m => Eval Logic m where evalAlg :: Logic (m Value) -> m Value evalAlg (LVal x) = return $ B x evalAlg (And x y) = x >>= \n -> y >>= \m -> return $ vand n m evalAlg (Or x y) = x >>= \n -> y >>= \m -> return $ vor n m evalAlg (Xor x y) = x >>= \n -> y >>= \m -> return $ vxor n m evalAlg (LGT x y) = x >>= \n -> y >>= \m -> return $ vgt n m evalAlg (LLT x y) = x >>= \n -> y >>= \m -> return $ vlt n m evalAlg (LEQ x y) = x >>= \n -> y >>= \m -> return $ veq n m evalAlg (BFunc s ps) = do pss <- sequence ps let ff = M.lookup (map toUpper s) bFunctionMap return $ maybe (E "No such function") (\f -> f pss) ff -- |Look up a function bFunctionMap :: Map String ([Value]->Value) bFunctionMap = fromList [ ("NOT", vnot) ] -- | A boolean spreadsheet function vnot::[Value]->Value vnot [] = B True vnot ((B x):[]) = B $ not x vnot _ = E "Only one parameter, please"
b1g3ar5/Spreadsheet
Logic.hs
mit
1,986
0
13
645
939
490
449
63
1
{-# LANGUAGE OverloadedStrings #-} -- This examples requires you to: cabal install cookie -- and: cabal install blaze-html module Sessions where import Control.Applicative ((<$>)) import qualified Data.Binary.Builder as B import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import Data.Text.Lazy (Text) import qualified Data.Text.Lazy.Encoding as T import Web.Cookie import Web.Scotty makeCookie :: BS.ByteString -> BS.ByteString -> SetCookie makeCookie n v = def { setCookieName = n, setCookieValue = v } renderSetCookie' :: SetCookie -> Text renderSetCookie' = T.decodeUtf8 . B.toLazyByteString . renderSetCookie setCookie :: BS.ByteString -> BS.ByteString -> ActionM () setCookie n v = setHeader "Set-Cookie" (renderSetCookie' (makeCookie n v)) getCookies' :: ActionM (Maybe CookiesText) getCookies' = fmap (parseCookiesText . lazyToStrict . T.encodeUtf8) <$> header "Cookie" where lazyToStrict = BS.concat . BSL.toChunks
hw-hello-world/okta-signin-widget
haskell-scotty/app/Sessions.hs
mit
1,048
0
9
214
251
146
105
20
1
module Y2018.M11.D21.Exercise where {-- From @fermatslibrary https://twitter.com/fermatslibrary/status/1061619809669074946 "A curious identity involving π and e:" 1 / (π² + 1) + 1 / (4π² + 1) + 1 / (9π² + 1) + 1 / (16π² + 1) + ... = 1 / (e² - 1) How many terms do you have to go out for that equation to be accurate within 0.1? 0.01? 0.001? 0.0001? --} pie :: Int -> Double pie nterms = undefined -- pie returns the value of the sum of the first n π² terms minus the e term
geophf/1HaskellADay
exercises/HAD/Y2018/M11/D21/Exercise.hs
mit
494
0
5
101
27
17
10
3
1
module Universe.Camera ( ) where data Camera coordSys d = Camera coordSys (Maybe (d, d))
fehu/hgt
core-universe/src/Universe/Camera.hs
mit
95
0
9
21
34
21
13
2
0
{-# LANGUAGE TypeFamilies, FlexibleContexts #-} {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable, DeriveDataTypeable, UndecidableInstances #-} {-# LANGUAGE TupleSections #-} module Data.Map.Vector (MapVector(..)) where import Prelude hiding (foldr) import Data.Foldable import Data.Traversable import Data.Data import Control.Applicative import Control.Arrow import Data.AdditiveGroup import Data.VectorSpace import Data.Basis import Data.Map (Map) import qualified Data.Map as Map -- TODO: Clean up overlong >>> examples. -- | Note: '<*>' in the 'Applicative' instance operates under /intersection/. i.e.: -- -- >>> (MapVector $ Map.fromList [("x", id)]) <*> (MapVector $ Map.fromList [("y", 3)]) -- MapVector (fromList []) -- -- Use the 'Applicative' instance for elementwise operations: -- -- >>> liftA2 (*) (MapVector $ Map.fromList [("x", 2), ("y", 3)]) (MapVector $ Map.fromList [("x", 5),("y", 7)]) -- MapVector (fromList [("x",10),("y",21)]) -- -- >>> liftA2 (*) (MapVector $ Map.fromList [("x", 2), ("y", 3)]) (MapVector $ Map.fromList [("y", 7)]) -- MapVector (fromList [("y",21)]) -- -- '*^' in the 'VectorSpace' instance multiplies by the scalar of v. Nesting MapVectors preserves -- the scalar type, e.g. @Scalar (MapVector k (MapVector k' v))@ = @Scalar v@. -- -- >>> 2 *^ (ConstantMap $ MapVector $ Map.fromList [("x", 3 :: Int), ("y", 5)]) -- ConstantMap (MapVector (fromList [("x",6),("y",10)])) -- -- Finally, '<.>' in 'InnerSpace' is the dot-product operator. Again, it operates under intersection. -- -- >>> (MapVector $ Map.fromList [("x", 2 :: Int), ("y", 3)]) <.> (MapVector $ Map.fromList [("x", 5),("y", 7)]) -- 31 -- -- >>> (pure . MapVector $ Map.fromList [("x", 2 :: Int), ("y", 3)]) <.> (MapVector $ Map.fromList [("a", pure (5::Int))]) -- 25 -- -- Addition with '^+^' operates under union. data MapVector k v = MapVector (Map k v) | ConstantMap v -- ^ An infinite-dimensional vector with the same value on all dimensions deriving (Eq, Functor, Show, Read, Foldable, Traversable, Typeable, Data) instance Semigroup (MapVector k v) where (<>) a b = a <> b -- | Respects the inner 'Monoid', unlike 'Map'. instance (Ord k, Monoid v) => Monoid (MapVector k v) where mempty = pure mempty --mappend = liftA2 mappend instance (Ord k) => Applicative (MapVector k) where pure = ConstantMap (ConstantMap f) <*> (ConstantMap v) = ConstantMap $ f v (ConstantMap f) <*> (MapVector vs) = MapVector $ f <$> vs (MapVector fs) <*> (ConstantMap v) = MapVector $ ($ v) <$> fs (MapVector fs) <*> (MapVector vs) = MapVector $ Map.intersectionWith ($) fs vs {-# INLINABLE (<*>) #-} instance (AdditiveGroup v, Ord k) => AdditiveGroup (MapVector k v) where zeroV = MapVector Map.empty negateV = fmap negateV (ConstantMap v) ^+^ (ConstantMap v') = ConstantMap $ v ^+^ v' (ConstantMap v) ^+^ (MapVector vs) = MapVector $ (v ^+^) <$> vs (MapVector vs) ^+^ (ConstantMap v) = MapVector $ (^+^ v) <$> vs (MapVector vs) ^+^ (MapVector vs') = MapVector $ Map.unionWith (^+^) vs vs' {-# INLINABLE (^+^) #-} instance (Ord k, VectorSpace v) => VectorSpace (MapVector k v) where type Scalar (MapVector k v) = Scalar v -- therefore Scalar (MapVector k (Mapvector k' v)) -- = Scalar v s *^ v = (s *^) <$> v {-# INLINABLE (*^) #-} instance (Ord k, VectorSpace v, InnerSpace v, AdditiveGroup (Scalar v)) => InnerSpace (MapVector k v) where (ConstantMap v) <.> (ConstantMap v') = v <.> v' (ConstantMap v) <.> (MapVector vs) = foldl' (^+^) zeroV $ (v <.>) <$> vs (MapVector vs) <.> (ConstantMap v) = foldl' (^+^) zeroV $ (<.> v) <$> vs (MapVector vs) <.> (MapVector vs') = foldl' (^+^) zeroV $ Map.intersectionWith (<.>) vs vs' {-# INLINABLE (<.>) #-} instance (Ord k, HasBasis v, AdditiveGroup (Scalar v)) => HasBasis (MapVector k v) where type Basis (MapVector k v) = (k, Basis v) basisValue (k, v) = MapVector $ Map.fromList $ (k, basisValue v):[] decompose (MapVector vs) = Map.toList (decompose<$>vs) >>= \(k,vs) -> first(k,)<$>vs decompose (ConstantMap _) = error "decompose: not defined for ConstantMap.\ \ Use decompose', which works properly on infinite-dimensional spaces." -- Note that it would be possible to properly implement 'decompose' under -- the additional constraint that the keys are enumerable. See e.g. the -- @universe-base@ package. decompose' (MapVector vs) (k,bv) = case Map.lookup k vs of Nothing -> zeroV Just v -> decompose' v bv decompose' (ConstantMap c) (_,bv) = decompose' c bv
conklech/vector-space-map
src/Data/Map/Vector.hs
mit
4,757
0
10
1,035
1,139
616
523
54
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} module LLVM.Pretty ( ppllvm, ) where import Prelude hiding ((<$>)) import GHC.Word import LLVM.Typed import LLVM.AST import LLVM.AST.Global import LLVM.AST.Type import LLVM.AST.Attribute import qualified LLVM.AST.Linkage as L import qualified LLVM.AST.Visibility as V import qualified LLVM.AST.CallingConvention as CC import qualified LLVM.AST.Constant as C import qualified LLVM.AST.FloatingPointPredicate as FP import qualified LLVM.AST.IntegerPredicate as IP import qualified LLVM.AST.AddrSpace as AS import qualified LLVM.AST.Float as F import LLVM.AST.ParameterAttribute as PA import LLVM.AST.FunctionAttribute as FA import Data.String import Text.Printf import Data.Text.Lazy (Text, pack, unpack) import Text.PrettyPrint.Leijen.Text import Data.Char (chr, ord, isAscii, isControl, isLetter, isDigit) import Data.List (intersperse) import Data.Maybe (isJust) import Numeric (showHex) ------------------------------------------------------------------------------- -- Utils ------------------------------------------------------------------------------- parensIf :: Bool -> Doc -> Doc parensIf True = parens parensIf False = id commas :: [Doc] -> Doc commas = hsep . punctuate (char ',') colons :: [Doc] -> Doc colons = hcat . intersperse (char ':') hlinecat :: [Doc] -> Doc hlinecat = vcat . intersperse softbreak wrapbraces :: Doc -> Doc -> Doc wrapbraces leadIn x = (leadIn <> char '{') <$> x <$> char '}' spacedbraces :: Doc -> Doc spacedbraces x = char '{' <+> x <+> char '}' local :: Doc -> Doc local a = "%" <> a global :: Doc -> Doc global a = "@" <> a label :: Doc -> Doc label a = "label" <+> "%" <> a cma :: Doc -> Doc -> Doc -- <,> does not work :( a `cma` b = a <> "," <+> b ------------------------------------------------------------------------------- -- Classes ------------------------------------------------------------------------------- class PP p where pp :: p -> Doc ppMaybe (Just x) = pp x ppMaybe Nothing = empty instance PP Word32 where pp x = int (fromIntegral x) instance PP Word64 where pp x = int (fromIntegral x) instance PP Integer where pp = integer instance PP Name where pp (Name []) = dquotes empty pp (Name name@(first:_)) | isFirst first && all isRest name = text (pack name) | otherwise = dquotes . hcat . map escape $ name where isFirst c = isLetter c || c == '-' || c == '_' isRest c = isDigit c || isFirst c pp (UnName x) = int (fromIntegral x) instance PP Parameter where pp (Parameter ty (UnName _) attrs) = pp ty <+> pp attrs pp (Parameter ty name attrs) = pp ty <+> pp attrs <+> local (pp name) instance PP [ParameterAttribute] where pp x = hsep $ fmap pp x instance PP ([Parameter], Bool) where pp (params, False) = commas (fmap pp params) instance PP (Operand, [ParameterAttribute]) where pp (op, attrs) = pp (typeOf op) <+> pp attrs <+> pp op instance PP UnnamedAddr where pp LocalAddr = "local_unnamed_addr" pp GlobalAddr = "unnamed_addr" instance PP Type where pp (IntegerType width) = "i" <> pp width pp (FloatingPointType 16 IEEE) = "half" pp (FloatingPointType 32 IEEE) = "float" pp (FloatingPointType 64 IEEE) = "double" pp (FloatingPointType width IEEE) = "fp" <> pp width pp (FloatingPointType width DoubleExtended) = "x86_fp" <> pp width pp (FloatingPointType width PairOfFloats) = "ppc_fp" <> pp width pp VoidType = "void" pp (PointerType ref addr) = pp ref <> "*" pp ft@(FunctionType {..}) = pp resultType <+> ppFunctionArgumentTypes ft pp (VectorType {..}) = "<" <> pp nVectorElements <+> "x" <+> pp elementType <> ">" pp (StructureType {..}) = if isPacked then "<{" <> (commas $ fmap pp elementTypes ) <> "}>" else "{" <> (commas $ fmap pp elementTypes ) <> "}" pp (ArrayType {..}) = brackets $ pp nArrayElements <+> "x" <+> pp elementType pp (NamedTypeReference name) = "%" <> pp name instance PP Global where pp (Function {..}) = case basicBlocks of [] -> ("declare" <+> pp linkage <+> pp callingConvention <+> pp returnAttributes <+> pp returnType <+> global (pp name) <> ppParams (pp . typeOf) parameters <+> pp functionAttributes <+> align <+> gcName) -- single unnamed block is special cased, and won't parse otherwise... yeah good times [b@(BasicBlock (UnName _) _ _)] -> ("define" <+> pp linkage <+> pp callingConvention <+> pp returnAttributes <+> pp returnType <+> global (pp name) <> ppParams pp parameters <+> pp functionAttributes <+> align <+> gcName) `wrapbraces` (indent 2 $ ppSingleBlock b) bs -> ("define" <+> pp linkage <+> pp callingConvention <+> pp returnAttributes <+> pp returnType <+> global (pp name) <> ppParams pp parameters <+> pp functionAttributes <+> align <+> gcName) `wrapbraces` (vcat $ fmap pp bs) where align | alignment == 0 = empty | otherwise = "align" <+> pp alignment gcName = maybe empty (\n -> "gc" <+> dquotes (text $ pack n)) garbageCollectorName pp (GlobalVariable {..}) = global (pp name) <+> "=" <+> ppLinkage hasInitializer linkage <+> ppMaybe unnamedAddr <+> kind <+> pp type' <+> ppMaybe initializer <> ppAlign alignment where hasInitializer = isJust initializer kind | isConstant = "constant" | otherwise = "global" pp (GlobalAlias {..}) = global (pp name) <+> "=" <+> pp linkage <+> ppMaybe unnamedAddr <+> "alias" <+> pp typ `cma` ppTyped aliasee where PointerType typ _ = type' instance PP Definition where pp (GlobalDefinition x) = pp x pp (TypeDefinition nm ty) = local (pp nm) <+> "=" <+> "type" <+> maybe "opaque" pp ty pp (FunctionAttributes gid attrs) = "attributes" <+> pp gid <+> "=" <+> braces (hsep (fmap pp attrs)) pp (NamedMetadataDefinition nm meta) = text (pack nm) pp (MetadataNodeDefinition node meta) = pp node instance PP FunctionAttribute where pp x = case x of NoReturn -> "noreturn" NoUnwind -> "nounwind" FA.ReadNone -> "readnone" FA.ReadOnly -> "readonly" FA.WriteOnly -> "writeonly" NoInline -> "noinline" AlwaysInline -> "alwaysinline" MinimizeSize -> "minimizesize" OptimizeForSize -> "optimizeforsize" OptimizeNone -> "optimizenone" SafeStack -> "safestack" StackProtect -> "ssp" StackProtectReq -> "sspreq" StackProtectStrong -> "sspstrong" NoRedZone -> "noredzone" NoImplicitFloat -> "noimplicitfloat" Naked -> "naked" InlineHint -> "inlinehint" StackAlignment n -> "stackalign" ReturnsTwice -> "returns_twice" UWTable -> "uwtable" NonLazyBind -> "nonlazybind" Builtin -> "builtin" NoBuiltin -> "nobuiltin" Cold -> "cold" JumpTable -> "TODO" NoDuplicate -> "noduplicate" SanitizeAddress -> "sanitize_address" SanitizeThread -> "sanitize_thread" SanitizeMemory -> "sanitize_memory" StringAttribute k v -> dquotes (text (pack k)) <> "=" <> dquotes (text (pack v)) instance PP ParameterAttribute where pp x = case x of ZeroExt -> "zeroext" SignExt -> "signext" InReg -> "inreg" SRet -> "sret" Alignment word -> "align" <+> pp word NoAlias -> "noalias" ByVal -> "byval" NoCapture -> "nocapture" Nest -> "nest" PA.ReadNone -> "TODO" PA.ReadOnly -> "TODO" PA.WriteOnly -> "TODO" InAlloca -> "inalloca" NonNull -> "nonnull" Dereferenceable word -> "dereferenceable" <> parens (pp word) DereferenceableOrNull word -> "dereferenceable_or_null" <> parens (pp word) Returned -> "returned" SwiftSelf -> "swiftself" SwiftError -> "swifterror" instance PP CC.CallingConvention where pp x = case x of CC.Numbered word -> "cc" <+> pp word CC.C -> "ccc" CC.Fast -> "fastcc" CC.Cold -> "coldcc" CC.GHC -> "cc 10" CC.HiPE -> "cc 11" CC.WebKit_JS -> "webkit_jscc" CC.AnyReg -> "anyregcc" CC.PreserveMost -> "preserve_mostcc" CC.PreserveAll -> "preserve_allcc" CC.X86_StdCall -> "cc 64" CC.X86_FastCall -> "cc 65" CC.ARM_APCS -> "cc 66" CC.ARM_AAPCS -> "cc 67" CC.ARM_AAPCS_VFP -> "cc 68" CC.MSP430_INTR -> "cc 69" CC.X86_ThisCall -> "cc 70" CC.PTX_Kernel -> "cc 71" CC.PTX_Device -> "cc 72" CC.SPIR_FUNC -> "cc 75" CC.SPIR_KERNEL -> "cc 76" CC.Intel_OCL_BI -> "cc 77" CC.X86_64_SysV -> "cc 78" CC.X86_64_Win64 -> "cc 79" instance PP L.Linkage where pp = ppLinkage False ppLinkage omitExternal x = case x of L.External | omitExternal -> empty | otherwise -> "external" L.Private -> "private" L.Internal -> "internal" L.ExternWeak -> "extern_weak" instance PP MetadataNodeID where pp (MetadataNodeID x) = "#" <> int (fromIntegral x) instance PP GroupID where pp (GroupID x) = "#" <> int (fromIntegral x) instance PP BasicBlock where pp (BasicBlock nm instrs term) = pp nm <> ":" <$> indent 2 (vcat $ (fmap pp instrs) ++ [pp term]) instance PP Terminator where pp (Br dest meta) = "br" <+> label (pp dest) pp (Ret val meta) = "ret" <+> maybe "void" ppTyped val pp (CondBr cond tdest fdest meta) = "br" <+> ppTyped cond `cma` label (pp tdest) `cma` label (pp fdest) pp (Switch {..}) = "switch" <+> ppTyped operand0' `cma` label (pp defaultDest) <+> brackets (hsep [ ppTyped v `cma` label (pp l) | (v,l) <- dests ]) pp x = error (show x) instance PP Instruction where pp x = case x of Add {..} -> "add" <+> ppTyped operand0 `cma` pp operand1 Sub {..} -> "sub" <+> ppTyped operand0 `cma` pp operand1 Mul {..} -> "mul" <+> ppTyped operand0 `cma` pp operand1 Shl {..} -> "shl" <+> ppTyped operand0 `cma` pp operand1 AShr {..} -> "ashr" <+> ppTyped operand0 `cma` pp operand1 And {..} -> "and" <+> ppTyped operand0 `cma` pp operand1 Or {..} -> "or" <+> ppTyped operand0 `cma` pp operand1 Xor {..} -> "xor" <+> ppTyped operand0 `cma` pp operand1 SDiv {..} -> "sdiv" <+> ppTyped operand0 `cma` pp operand1 UDiv {..} -> "udiv" <+> ppTyped operand0 `cma` pp operand1 SRem {..} -> "srem" <+> ppTyped operand0 `cma` pp operand1 URem {..} -> "urem" <+> ppTyped operand0 `cma` pp operand1 FAdd {..} -> "fadd" <+> ppTyped operand0 `cma` pp operand1 FSub {..} -> "fsub" <+> ppTyped operand0 `cma` pp operand1 FMul {..} -> "fmul" <+> ppTyped operand0 `cma` pp operand1 FCmp {..} -> "fcmp" <+> pp fpPredicate <+> ppTyped operand0 `cma` pp operand1 Alloca {..} -> "alloca" <+> pp allocatedType <> num <> ppAlign alignment where num = case numElements of Nothing -> empty Just o -> "," <+> ppTyped o Store {..} -> "store" <+> ppTyped value `cma` ppTyped address <> ppAlign alignment Load {..} -> "load" <+> pp argTy `cma` ppTyped address <> ppAlign alignment where PointerType argTy _ = typeOf address Phi {..} -> "phi" <+> pp type' <+> commas (fmap phiIncoming incomingValues) ICmp {..} -> "icmp" <+> pp iPredicate <+> ppTyped operand0 `cma` pp operand1 Call {..} -> ppCall x Select {..} -> "select" <+> pp condition' <+> pp trueValue <+> pp falseValue SExt {..} -> "sext" <+> ppTyped operand0 <+> "to" <+> pp type' ZExt {..} -> "zext" <+> ppTyped operand0 <+> "to" <+> pp type' Trunc {..} -> "trunc" <+> ppTyped operand0 <+> "to" <+> pp type' GetElementPtr {..} -> "getelementptr" <+> bounds inBounds <+> commas (pp argTy : fmap ppTyped (address:indices)) where PointerType argTy _ = typeOf address ExtractValue {..} -> "extractvalue" <+> commas (ppTyped aggregate : fmap pp indices') BitCast {..} -> "bitcast" <+> ppTyped operand0 <+> "to" <+> pp type' PtrToInt {..} -> "ptrtoint" <+> ppTyped operand0 <+> "to" <+> pp type' IntToPtr {..} -> "inttoptr" <+> ppTyped operand0 <+> "to" <+> pp type' x -> error (show x) where bounds True = "inbounds" bounds False = empty instance PP CallableOperand where pp (Left asm) = error "CallableOperand" pp (Right op) = pp op instance PP [Either GroupID FunctionAttribute] where pp x = hsep $ fmap pp x instance PP (Either GroupID FunctionAttribute) where pp (Left gid) = pp gid pp (Right fattr) = pp fattr instance PP Operand where pp (LocalReference _ nm) = local (pp nm) pp (ConstantOperand con) = pp con instance PP C.Constant where pp (C.Int width val) = pp val pp (C.Float (F.Double val)) = text $ pack $ printf "%6.6e" val pp (C.Float (F.Single val)) = text $ pack $ printf "%6.6e" val pp (C.GlobalReference ty nm) = "@" <> pp nm pp (C.Struct _ _ elems) = spacedbraces $ commas $ fmap ppTyped elems pp (C.Null {}) = "null" pp (C.Undef {}) = "undef" pp C.Array {..} | memberType == (IntegerType 8) = "c" <> (dquotes $ hcat [ppIntAsChar val | C.Int _ val <- memberValues]) | otherwise = brackets $ commas $ fmap ppTyped memberValues pp C.GetElementPtr {..} = "getelementptr" <+> bounds inBounds <+> parens (commas (pp argTy : fmap ppTyped (address:indices))) where PointerType argTy _ = typeOf address bounds True = "inbounds" bounds False = empty pp C.BitCast {..} = "bitcast" <+> parens (ppTyped operand0 <+> "to" <+> pp type') pp C.PtrToInt {..} = "ptrtoint" <+> parens (ppTyped operand0 <+> "to" <+> pp type') pp C.IntToPtr {..} = "inttoptr" <+> parens (ppTyped operand0 <+> "to" <+> pp type') pp x = error (show x) instance PP a => PP (Named a) where pp (nm := a) = "%" <> pp nm <+> "=" <+> pp a pp (Do a) = pp a instance PP Module where pp Module {..} = let header = printf "; ModuleID = '%s'" moduleName in hlinecat (fromString header : (fmap pp moduleDefinitions)) instance PP FP.FloatingPointPredicate where pp op = case op of FP.False -> "false" FP.OEQ -> "oeq" FP.OGT -> "ogt" FP.OGE -> "oge" FP.OLT -> "olt" FP.OLE -> "ole" FP.ONE -> "one" FP.ORD -> "ord" FP.UEQ -> "ueq" FP.UGT -> "ugt" FP.UGE -> "uge" FP.ULT -> "ult" FP.ULE -> "ule" FP.UNE -> "une" FP.UNO -> "uno" FP.True -> "true" instance PP IP.IntegerPredicate where pp op = case op of IP.EQ -> "eq" IP.NE -> "ne" IP.UGT -> "ugt" IP.UGE -> "uge" IP.ULT -> "ult" IP.ULE -> "ule" IP.SGT -> "sgt" IP.SGE -> "sge" IP.SLT -> "slt" IP.SLE -> "sle" ------------------------------------------------------------------------------- -- Special Case Hacks ------------------------------------------------------------------------------- escape :: Char -> Doc escape '"' = "\\22" escape '\\' = "\\\\" escape c = if isAscii c && not (isControl c) then char c else "\\" <> hex c where hex :: Char -> Doc hex = pad0 . ($ []) . showHex . ord pad0 :: String -> Doc pad0 [] = "00" pad0 [x] = "0" <> char x pad0 xs = text (pack xs) ppIntAsChar :: Integral a => a -> Doc ppIntAsChar = escape . chr . fromIntegral ppAlign :: Word32 -> Doc ppAlign x | x == 0 = empty | otherwise = ", align" <+> pp x -- print an operand and its type ppTyped :: (PP a, Typed a) => a -> Doc ppTyped a = pp (typeOf a) <+> pp a ppCommaTyped :: (PP a, Typed a) => a -> Doc ppCommaTyped a = pp (typeOf a) `cma` pp a phiIncoming :: (Operand, Name) -> Doc phiIncoming (op, nm) = brackets (pp op `cma` (local (pp nm))) ppParams :: (a -> Doc) -> ([a], Bool) -> Doc ppParams ppParam (ps, varrg) = parens . commas $ fmap ppParam ps ++ vargs where vargs = if varrg then ["..."] else [] ppFunctionArgumentTypes :: Type -> Doc ppFunctionArgumentTypes FunctionType {..} = ppParams pp (argumentTypes, isVarArg) ppCall :: Instruction -> Doc ppCall Call { function = Right f,..} = tail <+> "call" <+> pp callingConvention <+> pp returnAttributes <+> pp resultType <+> ftype <+> pp f <> parens (commas $ fmap pp arguments) <+> pp functionAttributes where (functionType@FunctionType {..}) = referencedType (typeOf f) ftype = if isVarArg then ppFunctionArgumentTypes functionType else empty referencedType (PointerType t _) = referencedType t referencedType t = t tail = case tailCallKind of Just Tail -> "tail" Just MustTail -> "musttail" Nothing -> empty ppCall x = error (show x) ppSingleBlock :: BasicBlock -> Doc ppSingleBlock (BasicBlock nm instrs term) = (vcat $ (fmap pp instrs) ++ [pp term]) ppllvm :: Module -> Text ppllvm = displayT . renderPretty 0.4 100 . pp
vjoki/llvm-hs-pretty
src/LLVM/Pretty.hs
mit
17,601
0
20
4,755
6,161
3,085
3,076
394
5
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MagicHash #-} module Shapes.Linear.ValueInfos where import GHC.Prim import GHC.Types (Double(..)) import Shapes.Linear.Template (ValueInfo(..)) doubleInfo :: ValueInfo doubleInfo = ValueInfo { _valueN = ''Double# , _valueWrap = 'D# , _valueBoxed = ''Double , _valueAdd = '(+##) , _valueSub = '(-##) , _valueMul = '(*##) , _valueDiv = '(/##) , _valueNeg = 'negateDouble# , _valueEq = '(==##) , _valueNeq = '(/=##) , _valueLeq = '(<=##) , _valueGeq = '(>=##) , _valueGt = '(>##) , _valueLt = '(<##) }
ublubu/shapes
shapes-math/src/Shapes/Linear/ValueInfos.hs
mit
871
0
7
408
175
126
49
21
1
main = do putStrLn "Entre com x e y: " line <- getLine let x = read line line <- getLine let y = read line putStrLn $ "Média = " ++ show ( (x+y)/2 )
folivetti/PI-UFABC
AULA_01/Haskell/Media.hs
mit
193
0
12
79
78
35
43
7
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Database.PostgreSQL.Simple.Util (withTransactionRolledBack) import Test.Hspec (around_, hspec) import AppContext (getContext, getDbConn) import qualified IndexControllerSpec import qualified OAuthLoginSpec import qualified ProjectSpec import qualified ProjectsControllerSpec import qualified SessionSpec import qualified UserSpec import qualified UsersControllerSpec main :: IO () main = do appContext <- getContext "test" let conn = getDbConn appContext hspec $ around_ (withTransactionRolledBack conn) $ do IndexControllerSpec.spec OAuthLoginSpec.spec appContext ProjectSpec.spec appContext ProjectsControllerSpec.spec appContext SessionSpec.spec UserSpec.spec appContext UsersControllerSpec.spec appContext
robertjlooby/scotty-story-board
test/Spec.hs
mit
872
0
11
176
176
93
83
24
1
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-} module MegaHAL.CBits where import Foreign.Ptr import Foreign.C.Types import Foreign.C.String -- Context data MHStruct type MHContext = Ptr MHStruct -- Initialisation -- -- CONTEXT *megahal_initialize(char *errorfilename, char *statusfilename, char *dir); foreign import ccall "wrapper.h megahal_initialize" m_initialize :: CString -> CString -> CString -> IO MHContext -- Unclear, but i think initial greetings, don't need i think -- char *megahal_initial_greeting(CONTEXT *context); foreign import ccall "wrapper.h megahal_initial_greeting" m_initial_greeting :: MHContext -> IO CString -- Reply and learn -- -- Logging (int log) -- bool - 0 = no log, 1 = log -- -- Output (char *) -- User is responsible for freeing this memory -- -- Input (char *input *prmpt) -- Assuming its a \0 terminated C string -- -- char *megahal_do_reply(CONTEXT *context, char *input, int32_t log); foreign import ccall "wrapper.h megahal_do_reply" m_do_reply :: MHContext -> CString -> CInt -> IO CString -- Input for learning with no reply generation -- void megahal_learn_no_reply(CONTEXT *context, char *input, int32_t log); foreign import ccall "wrapper.h megahal_learn_no_reply" m_learn_no_reply :: MHContext -> CString -> CInt -> IO () -- Exit -- TODO: consider ForeignPtr -- void megahal_cleanup(CONTEXT *context); foreign import ccall "wrapper.h megahal_cleanup" m_cleanup :: MHContext -> IO ()
pharaun/MegaHAL
src/MegaHAL/CBits.hs
gpl-2.0
1,471
0
10
227
182
110
72
-1
-1
module Algorithms where import Geometry import Chemistry import Data.List -- Warping Atoms bondRepulsion :: [Vector] -> [Vector] -> Int -> [Vector] bondRepulsion _ [] _ = [] bondRepulsion _ free 0 = free bondRepulsion fixed free n = bondRepulsion fixed (map (repel (fixed ++ free)) free) (n - 1) where repel vs v = (v + sum forces) `scaleTo` (norm v) where forces = map (repulsion v) (delete v vs) repulsion v u = v - u `scaleTo` (100 / (angleBetween v u)^2) warpAtom :: Atom -> [(Int, Vector)] -> Atom warpAtom (Atom p e q h bs) ivs = let (ibs1, ibs2, fixed, free) = separate (zip [0..] bs) ivs ibs1' = zipWith (\(i, BondSite os bt u rx) v -> (i, BondSite os bt v (alignTo v u rx))) ibs1 fixed ibs2' = zipWith (\(i, BondSite os bt u rx) v -> (i, BondSite os bt v (alignTo v u rx))) ibs2 (bondRepulsion fixed free 1000) in Atom p e q h (regroup ibs1' ibs2') where separate (ib@(i, b):ibs) ivs = let (ibs1, ibs2, fixed, free) = separate ibs ivs v = direction b in case lookup i ivs of Just v -> (ib:ibs1, ibs2, v:fixed, free) _ -> ( ibs1, ib:ibs2, fixed, v:free) separate _ _ = ([],[],[],[]) regroup xs@((i1,b1):ibs1) ys@((i2,b2):ibs2) = if i1 < i2 then b1 : regroup ibs1 ys else b2 : regroup xs ibs2 regroup ibs1 [] = map snd ibs1 regroup [] ibs2 = map snd ibs2
herngyi/hmol
Algorithms.hs
gpl-3.0
1,493
4
19
476
724
386
338
30
6
-- Haskell Music Player, client for the MPD (Music Player Daemon) -- Copyright (C) 2011 Ivan Vitjuk <[email protected]> -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. module Playlist ( Data, Playlist.init, setup, update, ) where import qualified Network.MPD.Core as MPDC import Graphics.UI.Gtk import Graphics.UI.Gtk.Glade import Data.IORef import Data.Maybe (fromMaybe) import qualified Network.MPD as MPD import qualified Util as U import qualified GuiData as GD data ListStoreEntry = ListStoreEntry { songIsCurrent :: Bool, songArtist :: String, songName :: String, songLength :: String } type ListStoreType = ListStore ListStoreEntry data Data = PLData { model :: ListStoreType } process :: Data -> Int -> Int -> [MPD.Song] -> IO () process st songIdx currentSong [] = return () process st songIdx currentSong (x:xs) = do let tags = MPD.sgTags x listStoreAppend (model st) $ ListStoreEntry (songIdx == currentSong) (U.showTag tags MPD.Artist) (U.showTag tags MPD.Title) (U.prettyTime $ MPD.sgLength x) process st (songIdx+1) currentSong xs playListChanged :: MPD.Status -> MPD.Status -> Bool playListChanged cur prev = (MPD.stPlaylistVersion cur) > (MPD.stPlaylistVersion prev) || (MPD.stSongPos cur) /= (MPD.stSongPos prev) update :: GD.GuiDataRef -> IO () update gdref = do gd <- readIORef gdref let currentSong = fromMaybe 0 (MPD.stSongPos (GD.currentStatus gd)) if playListChanged (GD.currentStatus gd) (GD.prevStatus gd) then do listStoreClear (model (GD.plist gd)) MPDC.withMPDPersistent (GD.mpd gd) (MPD.playlistInfo Nothing) >>= do U.processResponse $ process (GD.plist gd) 0 currentSong else return () init :: GladeXML -> IO Data init xml = do model <- listStoreNew [] view <- xmlGetWidget xml castToTreeView "currentPlaylist" treeViewSetModel view model treeViewSetHeadersVisible view True treeViewSetRulesHint view True artistCol <- treeViewColumnNew trackCol <- treeViewColumnNew timeCol <- treeViewColumnNew renderer <- cellRendererTextNew treeViewColumnSetTitle artistCol "Artist" treeViewColumnSetTitle trackCol "Track" treeViewColumnSetTitle timeCol "Length" treeViewColumnPackStart artistCol renderer True treeViewColumnPackStart trackCol renderer True treeViewColumnPackStart timeCol renderer True cellLayoutSetAttributes artistCol renderer model $ \row -> [ cellText := songArtist row , cellTextWeight := if (songIsCurrent row) then 1000 else 500 ] cellLayoutSetAttributes trackCol renderer model $ \row -> [ cellText := songName row ] cellLayoutSetAttributes timeCol renderer model $ \row -> [ cellText := songLength row ] treeViewAppendColumn view artistCol treeViewAppendColumn view trackCol treeViewAppendColumn view timeCol return $ PLData model setup :: GD.GuiDataRef -> GladeXML -> IO () setup gdref xml = do gd <- readIORef gdref view <- xmlGetWidget xml castToTreeView "currentPlaylist" onRowActivated view (\path col -> do MPDC.withMPDPersistent (GD.mpd gd) (MPD.play (Just (path !! 0))) return ()) return ()
ivitjuk/Haskell-Music-Player
src/Playlist.hs
gpl-3.0
3,936
0
18
900
990
495
495
79
2
{-# LANGUAGE DeriveDataTypeable#-} module Events where import Text.Parsec hiding (Error) import qualified PupEventsServer as Server import System.Environment import qualified Data.Time.Clock as Time import qualified Data.Time.Calendar as Cal import qualified Text.JSON.Parsec as JSONP import qualified Text.JSON import Text.JSON.Generic hiding (Error) import Text.JSON.Types -- |Put your event models here data Event = -- Client -> Server Login Username | Logout Username | GameJoin Game | GameLeave Game | GameNew Username | MouseMove Integer Integer -- Server -> Client | GameState [Ball] | GameStart Game | GameEnd Game -- Server <-> Client | GameList [Game] -- Errors | Error ErrorCode deriving (Eq, Typeable, Data, Show) data ErrorCode = AlreadyRegistered | UserExists | NotLoggedIn | GenericError deriving (Eq, Typeable, Data, Show) data Game = Game { gameUuid :: UUID , gameAlive :: Maybe [Username] , gameDead :: Maybe [Username] , gameStatus :: Maybe GameStatus , gameDifficulty :: Maybe Integer , gameStarted :: Maybe Time.UTCTime , gameEnded :: Maybe Time.UTCTime } deriving (Eq, Typeable, Data, Show) instance Show Time.UTCTime where show time = "Day: " ++ show (Cal.toModifiedJulianDay $ Time.utctDay time) ++ " Time: " ++ show (Time.utctDayTime time) data GameStatus = Created | InProgress | Ended deriving (Eq, Typeable, Data, Show) data Ball = Ball { ballUsername :: Maybe Username , ballPosition :: Maybe (Float, Float) } deriving (Eq, Typeable, Data, Show) newtype Username = Username String deriving (Eq, Typeable, Data, Show) newtype UUID = UUID String deriving (Eq, Typeable, Data, Show) -------------------- -- Generic Events -- -------------------- parseEvent :: Parsec String () Event parseEvent = do parsed <- JSONP.p_js_object let event = case fromJSON (JSObject parsed) of Text.JSON.Ok x -> x Text.JSON.Error m -> error m return event unparseEvent :: Event -> String unparseEvent e = encodeJSON e ++ "\0\0" -- |This is a list of the event parsers to be used when trying to parse messages. If you don't add your event parsers to this list they won't get called! parsers = [parseEvent] --parsers = map try [mouseMove, login, logout, gameNew, gameJoin, gameStart -- , gameAdvance , gameEnd, playerCollision -- , alreadyRegistered, userExists, gamesList -- , gamesRequest] -- |Returns the specified Event's priority level lookupPriority :: Event -> Int lookupPriority (MouseMove _ _ ) = 0 lookupPriority (Login _ ) = 2 lookupPriority (Logout _ ) = 2 lookupPriority (GameNew _ ) = 2 lookupPriority (GameJoin _ ) = 1 lookupPriority (GameLeave _ ) = 1 lookupPriority (GameStart _ ) = 2 lookupPriority (GameState _ ) = 0 lookupPriority (GameEnd _ ) = 1 --lookupPriority (AlreadyRegistered) = 2 lookupPriority (GameList _ ) = 2 lookupPriority (Error _ ) = 2 -- |Returns the function used to "unhandle" an Event, that is convert -- it to a string. lookupUnHandler :: Event -> (Event -> String) lookupUnHandler e = unparseEvent --lookupUnHandler (MouseMove _ _ ) = unMouseMove --lookupUnHandler (Login _ ) = unLogin --lookupUnHandler (Logout ) = unLogout --lookupUnHandler (GameNew _ ) = unGameNew --lookupUnHandler (GameJoin _ _ ) = unGameJoin --lookupUnHandler (GameLeave _ _ ) = unGameLeave --lookupUnHandler (GameStart _ ) = unGameStart --lookupUnHandler (GameAdvance _ ) = unGameAdvance --lookupUnHandler (GameEnd _ ) = unGameEnd --lookupUnHandler (PlayerCollision _ _ ) = unPlayerCollision --lookupUnHandler (AlreadyRegistered) = unAlreadyRegistered --lookupUnHandler (UserExists _ ) = unUserExists --lookupUnHandler (GamesRequest) = unGamesRequest --lookupUnHandler (GamesList _ ) = unGamesList ------------------------ -- Old Event handlers -- ------------------------ --------------- -- GamesList -- --------------- --gamesList :: Parsec String () Event --gamesList = -- do parsed <- JSONP.p_js_object -- let games = case fromJSON (JSObject parsed) of -- Text.JSON.Ok x -> x -- Text.JSON.Error m -> error m -- return games --unGamesList :: Event -> String --unGamesList e@(GamesList _ ) = "GamesList\0" ++ encodeJSON e ++ "\0\0" ------------------ -- GamesRequest -- ------------------ --gamesRequest :: Parsec String () Event --gamesRequest = -- do string "GamesRequest" -- string "\0\0" -- return GamesRequest --unGamesRequest :: Event -> String --unGamesRequest GamesRequest = "GamesRequest" ++ "\0\0" ----------------------- -- AlreadyRegistered -- ----------------------- --alreadyRegistered :: Parsec String () Event --alreadyRegistered = -- do string "AlreadyRegistered" -- string "\0\0" -- return AlreadyRegistered --unAlreadyRegistered :: Event -> String --unAlreadyRegistered AlreadyRegistered = "AlreadyRegistered" ++ "\0\0" ---------------- -- UserExists -- ---------------- --userExists :: Parsec String () Event --userExists = -- do string "UserExists" -- char '\0' -- username <- many $ alphaNum -- string "\0\0" -- return (UserExists $ Username username) --unUserExists :: Event -> String --unUserExists (UserExists (Username user)) = -- "UserExists\0" ++ user ++ "\0\0" --------------- -- GameLeave -- --------------- --gameLeave :: Parsec String () Event --gameLeave = -- do string "GameLeave" -- char '\0' -- player <- manyTill alphaNum (char '\0') -- game <- manyTill (alphaNum <|> char '-') (string "\0\0") -- return $ GameLeave (Username player) -- (Game (UUID game) Nothing Nothing Nothing Nothing Nothing Nothing) --unGameLeave :: Event -> String --unGameLeave (GameLeave player game) = -- "GameLeave\0" ++ show player ++ show game ++ "\0\0" --------------------- -- PlayerCollision -- --------------------- --playerCollision :: Parsec String () Event --playerCollision = -- do string "PlayerCollision" -- char '\0' -- game <- manyTill (alphaNum <|> char '-') (char '\0') -- players <- manyTill (manyTill (char '\0') alphaNum) (string "\0\0") -- return $ PlayerCollision (Game (UUID game) Nothing Nothing Nothing Nothing Nothing Nothing) $ map (Username) players --unPlayerCollision :: Event -> String --unPlayerCollision (PlayerCollision game players) = -- "PlayerCollision\0" ++ show game ++ "\0" ++ -- concatMap ((flip (++)) "\0" . show) players ++ "\0\0" ------------- -- GameEnd -- --------------- --gameEnd :: Parsec String () Event --gameEnd = -- do string "GameEnd" -- char '\0' -- game <- manyTill (alphaNum <|> char '-') (string "\0\0") -- return $ GameEnd (Game (UUID game) Nothing Nothing Nothing Nothing Nothing Nothing) --unGameEnd :: Event -> String --unGameEnd (GameEnd game) = -- "GameEnd\0" ++ show game ++ "\0\0" ------------------- ---- GameAdvance -- ------------------- --gameAdvance :: Parsec String () Event --gameAdvance = -- do string "GameAdvance" -- char '\0' -- game <- manyTill (alphaNum <|> char '-') (string "\0\0") -- return $ GameAdvance (Game (UUID game) Nothing Nothing Nothing Nothing Nothing Nothing) --unGameAdvance :: Event -> String --unGameAdvance (GameAdvance game) = -- "GameAdvance\0" ++ show game ++ "\0\0" ----------------- ---- GameStart -- ----------------- --gameStart :: Parsec String () Event --gameStart = -- do string "GameStart" -- char '\0' -- game <- manyTill (alphaNum <|> char '-') (string "\0\0") -- return $ GameStart (Game (UUID game) Nothing Nothing Nothing Nothing Nothing Nothing) --unGameStart :: Event -> String --unGameStart (GameStart game) = -- "GameStart\0" ++ show game ++ "\0\0" ---------------- ---- GameJoin -- ---------------- --gameJoin :: Parsec String () Event --gameJoin = -- do string "GameJoin" -- char '\0' -- player <- manyTill alphaNum (char '\0') -- game <- manyTill (alphaNum <|> char '-') (string "\0\0") -- return $ GameJoin (Username player) (Game (UUID game) Nothing Nothing Nothing Nothing Nothing Nothing) --unGameJoin :: Event -> String --unGameJoin (GameJoin player game) = -- "GameJoin\0" ++ show player ++ show game ++ "\0\0" --------------- ---- GameNew -- --------------- --gameNew :: Parsec String () Event --gameNew = -- do string "GameNew" -- char '\0' -- players <- manyTill (manyTill (char '\0') alphaNum) (string "\0\0") -- return $ GameNew $ map (Username) players --unGameNew :: Event -> String --unGameNew (GameNew players) = -- "GameNew\0" ++ concatMap ((flip (++)) "\0" . show) players ++ "\0\0" ----------------- ---- MouseMove -- ----------------- --mouseMove :: Parsec String () Event --mouseMove = -- do string "MouseMove" -- char '\0' -- p1 <- many $ oneOf "0123456789-+e." -- char '\0' -- p2 <- many $ oneOf "0123456789-+e." -- string "\0\0" -- return (MouseMove (read p1) (read p2)) --unMouseMove :: Event -> String --unMouseMove (MouseMove p1 p2) = -- "MouseMove\0" ++ (show p1) ++ '\0':(show p2) ++ "\0\0" ------------- ---- Login -- ------------- --login :: Parsec String () Event --login = -- do string "Login" -- char '\0' -- username <- many $ alphaNum -- string "\0\0" -- return (Login $ Username username) --unLogin :: Event -> String --unLogin (Login (Username user)) = -- "Login\0" ++ user ++ "\0\0" -------------- ---- Logout -- -------------- --logout :: Parsec String () Event --logout = -- do string "Logout" -- string "\0\0" -- return (Logout) --unLogout :: Event -> String --unLogout (Logout) = -- "Logout" ++ "\0\0"
RocketPuppy/PupCollide
Events/Events.hs
gpl-3.0
9,975
0
14
2,217
1,004
645
359
73
2
{-| Module : Interface.AST Description : Defines the abstract syntax tree used in syntax analysis. This is already simplified from the parse tree. Copyright : 2014, Jonas Cleve 2015, Tay Phuong Ho 2016, Philip Schmiel License : GPL-3 -} module Interface.AST ( ASTPart (..), AST, Command (..), Expression (..), BoolExpression (..), Address (..), walkAST ) where import Prelude ( Show, Eq, String, Bool (..), show, (++) ) import qualified Prelude ( Double, Char ) import Data.Int ( Int64 ) import Interface.Token ( MathOp, RelOp, LogOp, Type ) -- | The type of an AST is just a command. type AST = Command -- | A Command consists of either of the following: data Command = NONE | Output Expression -- ^ output something | Read Address -- ^ read something into a -- variable | Return Expression -- $ return something | Skip -- ^ a no operation | Sequence Command Command -- ^ execute both commands in -- order | IfThen BoolExpression Command -- ^ execute the command only if -- the expression yields true | IfThenElse BoolExpression Command Command -- ^ execute the first command -- on yielding true, the second -- command otherwise | While BoolExpression Command -- ^ repeatedly execute the -- command as long as the -- expression yields true | Assign Address Expression -- ^ assign the value of the -- expression to an identifier | ArrayAlloc Type Expression Address -- $ allocate dynamically an array -- expression to an array element | Declaration Type String | Set Address Address Expression -- set operation | Environment Command -- $ push and pop environment | Function Type String Command Command -- $ Type signature and code | LabelEnvironment String Command | Accepts Address Address -- set an acceptor for an object. deriving (Show, Eq) -- | An arithmetic expression. data Expression = Calculation MathOp Expression Expression -- ^ Calculate with mathematical -- operator: @expr1 mathop -- expr2@ | Negate Expression -- ^ Unary negation: @-expr@ | Integer Int64 -- $ Integer | Double Prelude.Double -- $ Double-precision floating-point number | Parameters Expression Expression | Parameter Expression | Character Prelude.Char -- Character | Reference String String -- Reference | Void -- void value | ToClass String -- wrap a label environment to a class | Variable Address deriving (Show, Eq) -- | A boolean expression. data BoolExpression = LogOp LogOp BoolExpression BoolExpression -- ^ Calculate with logical -- operator: @bexpr1 logop -- bexpr2@ | Comparison RelOp Expression Expression -- ^ Compare two expressions: -- @expr1 relop expr2@ | Not BoolExpression -- ^ Unary negation: @¬bexpr@ | Boolean Bool | Eof -- ^ End of input predicate deriving (Show, Eq) data Address = Identifier String | Label String String | FunctionCall Address Expression | FromArray Address Expression | Structure Address Address deriving (Show, Eq) data VarInfo = Scalar | Array deriving (Show, Eq) -- | Walk the whole AST calling the appropriate function for each tree element. walkAST :: (Command -> Command) -> (Expression -> Expression) -> (BoolExpression -> BoolExpression) -> AST -> AST walkAST tc te tb = walkC where walkC :: Command -> Command walkC (Output e) = tc (Output (walkE e)) walkC c@(Read _) = tc c walkC (Return e) = tc (Return (walkE e)) -- $ added walkC Skip = tc Skip walkC (Sequence c1 c2) = tc (Sequence (walkC c1) (walkC c2)) walkC (IfThen b c) = tc (IfThen (walkB b) (walkC c)) walkC (IfThenElse b c1 c2) = tc (IfThenElse (walkB b) (walkC c1) (walkC c2)) walkC (While b c) = tc (While (walkB b) (walkC c)) walkC (Assign i e) = tc (Assign i (walkE e)) walkC (Declaration t i) = tc (Declaration t i) -- $ added walkC (ArrayAlloc t e i) = tc (ArrayAlloc t (walkE e) i) -- $ added walkC (Environment c) = tc (Environment (walkC c)) -- $ added walkC (Function t id p c) = tc (Function t id (walkC p) (walkC c)) -- $ added walkC (LabelEnvironment i p) = tc (LabelEnvironment i (walkC p)) walkC (NONE) = NONE walkC (Set addr id e) = tc (Set addr id (walkE e)) walkC (Accepts obj hand) = tc (Accepts obj hand) walkE :: Expression -> Expression walkE (Calculation op e1 e2) = te (Calculation op (walkE e1) (walkE e2)) walkE (Negate e) = te (Negate (walkE e)) walkE (Parameters p1 p2) = te (Parameters (walkE p1) (walkE p2)) -- $ added walkE (Parameter e) = te (Parameter (walkE e)) walkE (ToClass s) = te (ToClass s) walkE (Void) = te (Void) walkE e = te e walkB :: BoolExpression -> BoolExpression walkB (LogOp op b1 b2) = tb (LogOp op (walkB b1) (walkB b2)) walkB (Comparison op e1 e2) = tb (Comparison op (walkE e1) (walkE e2)) walkB (Not b) = tb (Not (walkB b)) walkB b = tb b -- | A class to output the different parts of an AST. class ASTPart a where -- | Similar to 'show' but used explicitly for the AST. A string -- representation of the respective instance(s). showASTPart :: a -> String -- | The AST command is output-able. instance ASTPart Command where showASTPart (NONE) = "none" showASTPart (Output _) = "output" showASTPart (Return _) = "return" -- $ added showASTPart (Read _) = "read" showASTPart (Skip) = "skip" showASTPart (Sequence _ _) = ";" showASTPart (IfThen _ _) = "if _ then _" showASTPart (IfThenElse _ _ _) = "if _ then _ else _" showASTPart (While _ _) = "while _ do _" showASTPart (Assign _ _) = ":=" showASTPart (Declaration t _) = show t ++ " _" -- $ added showASTPart (ArrayAlloc t _ _) = show t ++ "[_] _" -- $ added showASTPart (Environment _) = "push scope" -- $ added showASTPart (Function _ _ _ _) = "function _ (_) {_}" -- $ added showASTPart (LabelEnvironment i _) = "labels "++i++"{_}" showASTPart (Set _ _ _) = "_ . _ <- _" showASTPart (Accepts _ _) = "_ accepts _" -- | The AST expression is output-able. instance ASTPart Expression where showASTPart (Calculation op _ _) = show op showASTPart (Negate _) = "-" showASTPart (Parameters _ _) = ";" -- $ added showASTPart (Parameter _) = "_" showASTPart (Integer n) = show n -- $ modified showASTPart (Double n) = show n -- $ added showASTPart (Character c) = "'"++(show c)++"'" showASTPart (ToClass _) = "toClass _" showASTPart (Void) = "void" showASTPart (Reference _ _) = "_:_" showASTPart (Variable _) = "var _" -- | The AST boolean expression is output-able. instance ASTPart BoolExpression where showASTPart (LogOp op _ _) = show op showASTPart (Comparison op _ _) = show op showASTPart (Not _) = "not" showASTPart (Boolean True) = "true" showASTPart (Boolean False) = "false" showASTPart Eof = "eof"
Potregon/while
src/Interface/AST.hs
gpl-3.0
8,298
0
11
3,022
2,052
1,093
959
145
26
{-# LANGUAGE DeriveFunctor #-} module TagFS.File ( File(..), FSTree(..), makeFSTrees ) where import Prelude hiding (filter) import qualified Prelude as P import Data.List hiding (filter) import Data.Function import Data.Ord import Data.Maybe import Control.Arrow -- | A file of the real file system. newtype File = File { getPath :: [FilePath] } deriving (Eq, Ord, Show, Read) data FSTree a = Leaf String a | Branch String [FSTree a] deriving (Eq, Show, Functor) filter :: (a -> Bool) -> FSTree a -> Maybe (FSTree a) filter f l@(Leaf _ a) = if f a then Just l else Nothing filter f (Branch s l) = case mapMaybe (filter f) l of [] -> Nothing xs -> Just $ Branch s xs groupHeadBy :: Eq b => (a -> (b, c)) -> [a] -> [(b, [c])] groupHeadBy f = map (fst.head &&& map snd) . groupBy ((==) `on` fst) . map f makeFSTrees :: [File] -> [FSTree File] makeFSTrees fs = go . map (getPath &&& id) $ sortBy (comparing getPath) fs where go l = uncurry helper =<< groupHeadBy (\(p,f) -> (head p, (tail p, f))) l helper _ [] = [] helper x pf = case span (\(a,_) -> null a) pf of (lf, bf) -> let leafs = map (Leaf x . snd) lf in if null bf then leafs else Branch x (go bf) : leafs
ffwng/tagfs
TagFS/File.hs
gpl-3.0
1,183
10
17
249
600
326
274
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.IAM.Types -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. module Network.AWS.IAM.Types ( -- * Service IAM -- ** Error , RESTError -- ** XML , ns -- * ManagedPolicyDetail , ManagedPolicyDetail , managedPolicyDetail , mpdArn , mpdAttachmentCount , mpdCreateDate , mpdDefaultVersionId , mpdDescription , mpdIsAttachable , mpdPath , mpdPolicyId , mpdPolicyName , mpdPolicyVersionList , mpdUpdateDate -- * PolicyRole , PolicyRole , policyRole , prRoleName -- * AssignmentStatusType , AssignmentStatusType (..) -- * PasswordPolicy , PasswordPolicy , passwordPolicy , ppAllowUsersToChangePassword , ppExpirePasswords , ppHardExpiry , ppMaxPasswordAge , ppMinimumPasswordLength , ppPasswordReusePrevention , ppRequireLowercaseCharacters , ppRequireNumbers , ppRequireSymbols , ppRequireUppercaseCharacters -- * Group , Group , group , gArn , gCreateDate , gGroupId , gGroupName , gPath -- * AttachedPolicy , AttachedPolicy , attachedPolicy , apPolicyArn , apPolicyName -- * MFADevice , MFADevice , mfadevice , mfadEnableDate , mfadSerialNumber , mfadUserName -- * PolicyVersion , PolicyVersion , policyVersion , pvCreateDate , pvDocument , pvIsDefaultVersion , pvVersionId -- * InstanceProfile , InstanceProfile , instanceProfile , ipArn , ipCreateDate , ipInstanceProfileId , ipInstanceProfileName , ipPath , ipRoles -- * RoleDetail , RoleDetail , roleDetail , rdArn , rdAssumeRolePolicyDocument , rdAttachedManagedPolicies , rdCreateDate , rdInstanceProfileList , rdPath , rdRoleId , rdRoleName , rdRolePolicyList -- * ReportFormatType , ReportFormatType (..) -- * ServerCertificateMetadata , ServerCertificateMetadata , serverCertificateMetadata , scmArn , scmExpiration , scmPath , scmServerCertificateId , scmServerCertificateName , scmUploadDate -- * OpenIDConnectProviderListEntry , OpenIDConnectProviderListEntry , openIDConnectProviderListEntry , oidcpleArn -- * LoginProfile , LoginProfile , loginProfile , lpCreateDate , lpPasswordResetRequired , lpUserName -- * EntityType , EntityType (..) -- * SummaryKeyType , SummaryKeyType (..) -- * GroupDetail , GroupDetail , groupDetail , gdArn , gdAttachedManagedPolicies , gdCreateDate , gdGroupId , gdGroupName , gdGroupPolicyList , gdPath -- * ReportStateType , ReportStateType (..) -- * User , User , user , uArn , uCreateDate , uPasswordLastUsed , uPath , uUserId , uUserName -- * PolicyDetail , PolicyDetail , policyDetail , pdPolicyDocument , pdPolicyName -- * StatusType , StatusType (..) -- * SAMLProviderListEntry , SAMLProviderListEntry , samlproviderListEntry , samlpleArn , samlpleCreateDate , samlpleValidUntil -- * Role , Role , role , rArn , rAssumeRolePolicyDocument , rCreateDate , rPath , rRoleId , rRoleName -- * PolicyGroup , PolicyGroup , policyGroup , pgGroupName -- * PolicyScopeType , PolicyScopeType (..) -- * UserDetail , UserDetail , userDetail , udArn , udAttachedManagedPolicies , udCreateDate , udGroupList , udPath , udUserId , udUserName , udUserPolicyList -- * Policy , Policy , policy , pArn , pAttachmentCount , pCreateDate , pDefaultVersionId , pDescription , pIsAttachable , pPath , pPolicyId , pPolicyName , pUpdateDate -- * ServerCertificate , ServerCertificate , serverCertificate , scCertificateBody , scCertificateChain , scServerCertificateMetadata -- * AccessKey , AccessKey , accessKey , akAccessKeyId , akCreateDate , akSecretAccessKey , akStatus , akUserName -- * VirtualMFADevice , VirtualMFADevice , virtualMFADevice , vmfadBase32StringSeed , vmfadEnableDate , vmfadQRCodePNG , vmfadSerialNumber , vmfadUser -- * SigningCertificate , SigningCertificate , signingCertificate , sc1CertificateBody , sc1CertificateId , sc1Status , sc1UploadDate , sc1UserName -- * AccessKeyMetadata , AccessKeyMetadata , accessKeyMetadata , akmAccessKeyId , akmCreateDate , akmStatus , akmUserName -- * PolicyUser , PolicyUser , policyUser , puUserName ) where import Network.AWS.Prelude import Network.AWS.Signing import qualified GHC.Exts -- | Version @2010-05-08@ of the Amazon Identity and Access Management service. data IAM instance AWSService IAM where type Sg IAM = V4 type Er IAM = RESTError service = service' where service' :: Service IAM service' = Service { _svcAbbrev = "IAM" , _svcPrefix = "iam" , _svcVersion = "2010-05-08" , _svcTargetPrefix = Nothing , _svcJSONVersion = Nothing , _svcHandle = handle , _svcRetry = retry } handle :: Status -> Maybe (LazyByteString -> ServiceError RESTError) handle = restError statusSuccess service' retry :: Retry IAM retry = Exponential { _retryBase = 0.05 , _retryGrowth = 2 , _retryAttempts = 5 , _retryCheck = check } check :: Status -> RESTError -> Bool check (statusCode -> s) (awsErrorCode -> e) | s == 400 && "Throttling" == e = True -- Throttling | s == 500 = True -- General Server Error | s == 509 = True -- Limit Exceeded | s == 503 = True -- Service Unavailable | otherwise = False ns :: Text ns = "https://iam.amazonaws.com/doc/2010-05-08/" {-# INLINE ns #-} data ManagedPolicyDetail = ManagedPolicyDetail { _mpdArn :: Maybe Text , _mpdAttachmentCount :: Maybe Int , _mpdCreateDate :: Maybe ISO8601 , _mpdDefaultVersionId :: Maybe Text , _mpdDescription :: Maybe Text , _mpdIsAttachable :: Maybe Bool , _mpdPath :: Maybe Text , _mpdPolicyId :: Maybe Text , _mpdPolicyName :: Maybe Text , _mpdPolicyVersionList :: List "member" PolicyVersion , _mpdUpdateDate :: Maybe ISO8601 } deriving (Eq, Read, Show) -- | 'ManagedPolicyDetail' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'mpdArn' @::@ 'Maybe' 'Text' -- -- * 'mpdAttachmentCount' @::@ 'Maybe' 'Int' -- -- * 'mpdCreateDate' @::@ 'Maybe' 'UTCTime' -- -- * 'mpdDefaultVersionId' @::@ 'Maybe' 'Text' -- -- * 'mpdDescription' @::@ 'Maybe' 'Text' -- -- * 'mpdIsAttachable' @::@ 'Maybe' 'Bool' -- -- * 'mpdPath' @::@ 'Maybe' 'Text' -- -- * 'mpdPolicyId' @::@ 'Maybe' 'Text' -- -- * 'mpdPolicyName' @::@ 'Maybe' 'Text' -- -- * 'mpdPolicyVersionList' @::@ ['PolicyVersion'] -- -- * 'mpdUpdateDate' @::@ 'Maybe' 'UTCTime' -- managedPolicyDetail :: ManagedPolicyDetail managedPolicyDetail = ManagedPolicyDetail { _mpdPolicyName = Nothing , _mpdPolicyId = Nothing , _mpdArn = Nothing , _mpdPath = Nothing , _mpdDefaultVersionId = Nothing , _mpdAttachmentCount = Nothing , _mpdIsAttachable = Nothing , _mpdDescription = Nothing , _mpdCreateDate = Nothing , _mpdUpdateDate = Nothing , _mpdPolicyVersionList = mempty } mpdArn :: Lens' ManagedPolicyDetail (Maybe Text) mpdArn = lens _mpdArn (\s a -> s { _mpdArn = a }) -- | The number of principal entities (users, groups, and roles) that the policy -- is attached to. mpdAttachmentCount :: Lens' ManagedPolicyDetail (Maybe Int) mpdAttachmentCount = lens _mpdAttachmentCount (\s a -> s { _mpdAttachmentCount = a }) -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the policy was created. mpdCreateDate :: Lens' ManagedPolicyDetail (Maybe UTCTime) mpdCreateDate = lens _mpdCreateDate (\s a -> s { _mpdCreateDate = a }) . mapping _Time -- | The identifier for the version of the policy that is set as the default -- (operative) version. -- -- For more information about policy versions, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html Versioning for ManagedPolicies> in the /Using IAM/ guide. mpdDefaultVersionId :: Lens' ManagedPolicyDetail (Maybe Text) mpdDefaultVersionId = lens _mpdDefaultVersionId (\s a -> s { _mpdDefaultVersionId = a }) -- | A friendly description of the policy. mpdDescription :: Lens' ManagedPolicyDetail (Maybe Text) mpdDescription = lens _mpdDescription (\s a -> s { _mpdDescription = a }) -- | Specifies whether the policy can be attached to an IAM user, group, or role. mpdIsAttachable :: Lens' ManagedPolicyDetail (Maybe Bool) mpdIsAttachable = lens _mpdIsAttachable (\s a -> s { _mpdIsAttachable = a }) -- | The path to the policy. -- -- For more information about paths, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. mpdPath :: Lens' ManagedPolicyDetail (Maybe Text) mpdPath = lens _mpdPath (\s a -> s { _mpdPath = a }) -- | The stable and unique string identifying the policy. -- -- For more information about IDs, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. mpdPolicyId :: Lens' ManagedPolicyDetail (Maybe Text) mpdPolicyId = lens _mpdPolicyId (\s a -> s { _mpdPolicyId = a }) -- | The friendly name (not ARN) identifying the policy. mpdPolicyName :: Lens' ManagedPolicyDetail (Maybe Text) mpdPolicyName = lens _mpdPolicyName (\s a -> s { _mpdPolicyName = a }) -- | A list containing information about the versions of the policy. mpdPolicyVersionList :: Lens' ManagedPolicyDetail [PolicyVersion] mpdPolicyVersionList = lens _mpdPolicyVersionList (\s a -> s { _mpdPolicyVersionList = a }) . _List -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the policy was last -- updated. -- -- When a policy has only one version, this field contains the date and time -- when the policy was created. When a policy has more than one version, this -- field contains the date and time when the most recent policy version was -- created. mpdUpdateDate :: Lens' ManagedPolicyDetail (Maybe UTCTime) mpdUpdateDate = lens _mpdUpdateDate (\s a -> s { _mpdUpdateDate = a }) . mapping _Time instance FromXML ManagedPolicyDetail where parseXML x = ManagedPolicyDetail <$> x .@? "Arn" <*> x .@? "AttachmentCount" <*> x .@? "CreateDate" <*> x .@? "DefaultVersionId" <*> x .@? "Description" <*> x .@? "IsAttachable" <*> x .@? "Path" <*> x .@? "PolicyId" <*> x .@? "PolicyName" <*> x .@? "PolicyVersionList" .!@ mempty <*> x .@? "UpdateDate" instance ToQuery ManagedPolicyDetail where toQuery ManagedPolicyDetail{..} = mconcat [ "Arn" =? _mpdArn , "AttachmentCount" =? _mpdAttachmentCount , "CreateDate" =? _mpdCreateDate , "DefaultVersionId" =? _mpdDefaultVersionId , "Description" =? _mpdDescription , "IsAttachable" =? _mpdIsAttachable , "Path" =? _mpdPath , "PolicyId" =? _mpdPolicyId , "PolicyName" =? _mpdPolicyName , "PolicyVersionList" =? _mpdPolicyVersionList , "UpdateDate" =? _mpdUpdateDate ] newtype PolicyRole = PolicyRole { _prRoleName :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'PolicyRole' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'prRoleName' @::@ 'Maybe' 'Text' -- policyRole :: PolicyRole policyRole = PolicyRole { _prRoleName = Nothing } -- | The name (friendly name, not ARN) identifying the role. prRoleName :: Lens' PolicyRole (Maybe Text) prRoleName = lens _prRoleName (\s a -> s { _prRoleName = a }) instance FromXML PolicyRole where parseXML x = PolicyRole <$> x .@? "RoleName" instance ToQuery PolicyRole where toQuery PolicyRole{..} = mconcat [ "RoleName" =? _prRoleName ] data AssignmentStatusType = Any -- ^ Any | Assigned -- ^ Assigned | Unassigned -- ^ Unassigned deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable AssignmentStatusType instance FromText AssignmentStatusType where parser = takeLowerText >>= \case "any" -> pure Any "assigned" -> pure Assigned "unassigned" -> pure Unassigned e -> fail $ "Failure parsing AssignmentStatusType from " ++ show e instance ToText AssignmentStatusType where toText = \case Any -> "Any" Assigned -> "Assigned" Unassigned -> "Unassigned" instance ToByteString AssignmentStatusType instance ToHeader AssignmentStatusType instance ToQuery AssignmentStatusType instance FromXML AssignmentStatusType where parseXML = parseXMLText "AssignmentStatusType" data PasswordPolicy = PasswordPolicy { _ppAllowUsersToChangePassword :: Maybe Bool , _ppExpirePasswords :: Maybe Bool , _ppHardExpiry :: Maybe Bool , _ppMaxPasswordAge :: Maybe Nat , _ppMinimumPasswordLength :: Maybe Nat , _ppPasswordReusePrevention :: Maybe Nat , _ppRequireLowercaseCharacters :: Maybe Bool , _ppRequireNumbers :: Maybe Bool , _ppRequireSymbols :: Maybe Bool , _ppRequireUppercaseCharacters :: Maybe Bool } deriving (Eq, Ord, Read, Show) -- | 'PasswordPolicy' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ppAllowUsersToChangePassword' @::@ 'Maybe' 'Bool' -- -- * 'ppExpirePasswords' @::@ 'Maybe' 'Bool' -- -- * 'ppHardExpiry' @::@ 'Maybe' 'Bool' -- -- * 'ppMaxPasswordAge' @::@ 'Maybe' 'Natural' -- -- * 'ppMinimumPasswordLength' @::@ 'Maybe' 'Natural' -- -- * 'ppPasswordReusePrevention' @::@ 'Maybe' 'Natural' -- -- * 'ppRequireLowercaseCharacters' @::@ 'Maybe' 'Bool' -- -- * 'ppRequireNumbers' @::@ 'Maybe' 'Bool' -- -- * 'ppRequireSymbols' @::@ 'Maybe' 'Bool' -- -- * 'ppRequireUppercaseCharacters' @::@ 'Maybe' 'Bool' -- passwordPolicy :: PasswordPolicy passwordPolicy = PasswordPolicy { _ppMinimumPasswordLength = Nothing , _ppRequireSymbols = Nothing , _ppRequireNumbers = Nothing , _ppRequireUppercaseCharacters = Nothing , _ppRequireLowercaseCharacters = Nothing , _ppAllowUsersToChangePassword = Nothing , _ppExpirePasswords = Nothing , _ppMaxPasswordAge = Nothing , _ppPasswordReusePrevention = Nothing , _ppHardExpiry = Nothing } -- | Specifies whether IAM users are allowed to change their own password. ppAllowUsersToChangePassword :: Lens' PasswordPolicy (Maybe Bool) ppAllowUsersToChangePassword = lens _ppAllowUsersToChangePassword (\s a -> s { _ppAllowUsersToChangePassword = a }) -- | Specifies whether IAM users are required to change their password after a -- specified number of days. ppExpirePasswords :: Lens' PasswordPolicy (Maybe Bool) ppExpirePasswords = lens _ppExpirePasswords (\s a -> s { _ppExpirePasswords = a }) -- | Specifies whether IAM users are prevented from setting a new password after -- their password has expired. ppHardExpiry :: Lens' PasswordPolicy (Maybe Bool) ppHardExpiry = lens _ppHardExpiry (\s a -> s { _ppHardExpiry = a }) -- | The number of days that an IAM user password is valid. ppMaxPasswordAge :: Lens' PasswordPolicy (Maybe Natural) ppMaxPasswordAge = lens _ppMaxPasswordAge (\s a -> s { _ppMaxPasswordAge = a }) . mapping _Nat -- | Minimum length to require for IAM user passwords. ppMinimumPasswordLength :: Lens' PasswordPolicy (Maybe Natural) ppMinimumPasswordLength = lens _ppMinimumPasswordLength (\s a -> s { _ppMinimumPasswordLength = a }) . mapping _Nat -- | Specifies the number of previous passwords that IAM users are prevented from -- reusing. ppPasswordReusePrevention :: Lens' PasswordPolicy (Maybe Natural) ppPasswordReusePrevention = lens _ppPasswordReusePrevention (\s a -> s { _ppPasswordReusePrevention = a }) . mapping _Nat -- | Specifies whether to require lowercase characters for IAM user passwords. ppRequireLowercaseCharacters :: Lens' PasswordPolicy (Maybe Bool) ppRequireLowercaseCharacters = lens _ppRequireLowercaseCharacters (\s a -> s { _ppRequireLowercaseCharacters = a }) -- | Specifies whether to require numbers for IAM user passwords. ppRequireNumbers :: Lens' PasswordPolicy (Maybe Bool) ppRequireNumbers = lens _ppRequireNumbers (\s a -> s { _ppRequireNumbers = a }) -- | Specifies whether to require symbols for IAM user passwords. ppRequireSymbols :: Lens' PasswordPolicy (Maybe Bool) ppRequireSymbols = lens _ppRequireSymbols (\s a -> s { _ppRequireSymbols = a }) -- | Specifies whether to require uppercase characters for IAM user passwords. ppRequireUppercaseCharacters :: Lens' PasswordPolicy (Maybe Bool) ppRequireUppercaseCharacters = lens _ppRequireUppercaseCharacters (\s a -> s { _ppRequireUppercaseCharacters = a }) instance FromXML PasswordPolicy where parseXML x = PasswordPolicy <$> x .@? "AllowUsersToChangePassword" <*> x .@? "ExpirePasswords" <*> x .@? "HardExpiry" <*> x .@? "MaxPasswordAge" <*> x .@? "MinimumPasswordLength" <*> x .@? "PasswordReusePrevention" <*> x .@? "RequireLowercaseCharacters" <*> x .@? "RequireNumbers" <*> x .@? "RequireSymbols" <*> x .@? "RequireUppercaseCharacters" instance ToQuery PasswordPolicy where toQuery PasswordPolicy{..} = mconcat [ "AllowUsersToChangePassword" =? _ppAllowUsersToChangePassword , "ExpirePasswords" =? _ppExpirePasswords , "HardExpiry" =? _ppHardExpiry , "MaxPasswordAge" =? _ppMaxPasswordAge , "MinimumPasswordLength" =? _ppMinimumPasswordLength , "PasswordReusePrevention" =? _ppPasswordReusePrevention , "RequireLowercaseCharacters" =? _ppRequireLowercaseCharacters , "RequireNumbers" =? _ppRequireNumbers , "RequireSymbols" =? _ppRequireSymbols , "RequireUppercaseCharacters" =? _ppRequireUppercaseCharacters ] data Group = Group { _gArn :: Text , _gCreateDate :: ISO8601 , _gGroupId :: Text , _gGroupName :: Text , _gPath :: Text } deriving (Eq, Ord, Read, Show) -- | 'Group' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gArn' @::@ 'Text' -- -- * 'gCreateDate' @::@ 'UTCTime' -- -- * 'gGroupId' @::@ 'Text' -- -- * 'gGroupName' @::@ 'Text' -- -- * 'gPath' @::@ 'Text' -- group :: Text -- ^ 'gPath' -> Text -- ^ 'gGroupName' -> Text -- ^ 'gGroupId' -> Text -- ^ 'gArn' -> UTCTime -- ^ 'gCreateDate' -> Group group p1 p2 p3 p4 p5 = Group { _gPath = p1 , _gGroupName = p2 , _gGroupId = p3 , _gArn = p4 , _gCreateDate = withIso _Time (const id) p5 } -- | The Amazon Resource Name (ARN) specifying the group. For more information -- about ARNs and how to use them in policies, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /UsingIAM/ guide. gArn :: Lens' Group Text gArn = lens _gArn (\s a -> s { _gArn = a }) -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the group was created. gCreateDate :: Lens' Group UTCTime gCreateDate = lens _gCreateDate (\s a -> s { _gCreateDate = a }) . _Time -- | The stable and unique string identifying the group. For more information -- about IDs, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. gGroupId :: Lens' Group Text gGroupId = lens _gGroupId (\s a -> s { _gGroupId = a }) -- | The friendly name that identifies the group. gGroupName :: Lens' Group Text gGroupName = lens _gGroupName (\s a -> s { _gGroupName = a }) -- | The path to the group. For more information about paths, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. gPath :: Lens' Group Text gPath = lens _gPath (\s a -> s { _gPath = a }) instance FromXML Group where parseXML x = Group <$> x .@ "Arn" <*> x .@ "CreateDate" <*> x .@ "GroupId" <*> x .@ "GroupName" <*> x .@ "Path" instance ToQuery Group where toQuery Group{..} = mconcat [ "Arn" =? _gArn , "CreateDate" =? _gCreateDate , "GroupId" =? _gGroupId , "GroupName" =? _gGroupName , "Path" =? _gPath ] data AttachedPolicy = AttachedPolicy { _apPolicyArn :: Maybe Text , _apPolicyName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'AttachedPolicy' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'apPolicyArn' @::@ 'Maybe' 'Text' -- -- * 'apPolicyName' @::@ 'Maybe' 'Text' -- attachedPolicy :: AttachedPolicy attachedPolicy = AttachedPolicy { _apPolicyName = Nothing , _apPolicyArn = Nothing } apPolicyArn :: Lens' AttachedPolicy (Maybe Text) apPolicyArn = lens _apPolicyArn (\s a -> s { _apPolicyArn = a }) -- | The friendly name of the attached policy. apPolicyName :: Lens' AttachedPolicy (Maybe Text) apPolicyName = lens _apPolicyName (\s a -> s { _apPolicyName = a }) instance FromXML AttachedPolicy where parseXML x = AttachedPolicy <$> x .@? "PolicyArn" <*> x .@? "PolicyName" instance ToQuery AttachedPolicy where toQuery AttachedPolicy{..} = mconcat [ "PolicyArn" =? _apPolicyArn , "PolicyName" =? _apPolicyName ] data MFADevice = MFADevice { _mfadEnableDate :: ISO8601 , _mfadSerialNumber :: Text , _mfadUserName :: Text } deriving (Eq, Ord, Read, Show) -- | 'MFADevice' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'mfadEnableDate' @::@ 'UTCTime' -- -- * 'mfadSerialNumber' @::@ 'Text' -- -- * 'mfadUserName' @::@ 'Text' -- mfadevice :: Text -- ^ 'mfadUserName' -> Text -- ^ 'mfadSerialNumber' -> UTCTime -- ^ 'mfadEnableDate' -> MFADevice mfadevice p1 p2 p3 = MFADevice { _mfadUserName = p1 , _mfadSerialNumber = p2 , _mfadEnableDate = withIso _Time (const id) p3 } -- | The date when the MFA device was enabled for the user. mfadEnableDate :: Lens' MFADevice UTCTime mfadEnableDate = lens _mfadEnableDate (\s a -> s { _mfadEnableDate = a }) . _Time -- | The serial number that uniquely identifies the MFA device. For virtual MFA -- devices, the serial number is the device ARN. mfadSerialNumber :: Lens' MFADevice Text mfadSerialNumber = lens _mfadSerialNumber (\s a -> s { _mfadSerialNumber = a }) -- | The user with whom the MFA device is associated. mfadUserName :: Lens' MFADevice Text mfadUserName = lens _mfadUserName (\s a -> s { _mfadUserName = a }) instance FromXML MFADevice where parseXML x = MFADevice <$> x .@ "EnableDate" <*> x .@ "SerialNumber" <*> x .@ "UserName" instance ToQuery MFADevice where toQuery MFADevice{..} = mconcat [ "EnableDate" =? _mfadEnableDate , "SerialNumber" =? _mfadSerialNumber , "UserName" =? _mfadUserName ] data PolicyVersion = PolicyVersion { _pvCreateDate :: Maybe ISO8601 , _pvDocument :: Maybe Text , _pvIsDefaultVersion :: Maybe Bool , _pvVersionId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'PolicyVersion' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pvCreateDate' @::@ 'Maybe' 'UTCTime' -- -- * 'pvDocument' @::@ 'Maybe' 'Text' -- -- * 'pvIsDefaultVersion' @::@ 'Maybe' 'Bool' -- -- * 'pvVersionId' @::@ 'Maybe' 'Text' -- policyVersion :: PolicyVersion policyVersion = PolicyVersion { _pvDocument = Nothing , _pvVersionId = Nothing , _pvIsDefaultVersion = Nothing , _pvCreateDate = Nothing } -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the policy version was -- created. pvCreateDate :: Lens' PolicyVersion (Maybe UTCTime) pvCreateDate = lens _pvCreateDate (\s a -> s { _pvCreateDate = a }) . mapping _Time -- | The policy document. -- -- The policy document is returned in the response to the 'GetPolicyVersion' -- operation. It is not included in the response to the 'ListPolicyVersions' or 'GetAccountAuthorizationDetails' operations. pvDocument :: Lens' PolicyVersion (Maybe Text) pvDocument = lens _pvDocument (\s a -> s { _pvDocument = a }) -- | Specifies whether the policy version is set as the policy's default version. pvIsDefaultVersion :: Lens' PolicyVersion (Maybe Bool) pvIsDefaultVersion = lens _pvIsDefaultVersion (\s a -> s { _pvIsDefaultVersion = a }) -- | The identifier for the policy version. -- -- Policy version identifiers always begin with 'v' (always lowercase). When a -- policy is created, the first policy version is 'v1'. pvVersionId :: Lens' PolicyVersion (Maybe Text) pvVersionId = lens _pvVersionId (\s a -> s { _pvVersionId = a }) instance FromXML PolicyVersion where parseXML x = PolicyVersion <$> x .@? "CreateDate" <*> x .@? "Document" <*> x .@? "IsDefaultVersion" <*> x .@? "VersionId" instance ToQuery PolicyVersion where toQuery PolicyVersion{..} = mconcat [ "CreateDate" =? _pvCreateDate , "Document" =? _pvDocument , "IsDefaultVersion" =? _pvIsDefaultVersion , "VersionId" =? _pvVersionId ] data InstanceProfile = InstanceProfile { _ipArn :: Text , _ipCreateDate :: ISO8601 , _ipInstanceProfileId :: Text , _ipInstanceProfileName :: Text , _ipPath :: Text , _ipRoles :: List "member" Role } deriving (Eq, Read, Show) -- | 'InstanceProfile' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ipArn' @::@ 'Text' -- -- * 'ipCreateDate' @::@ 'UTCTime' -- -- * 'ipInstanceProfileId' @::@ 'Text' -- -- * 'ipInstanceProfileName' @::@ 'Text' -- -- * 'ipPath' @::@ 'Text' -- -- * 'ipRoles' @::@ ['Role'] -- instanceProfile :: Text -- ^ 'ipPath' -> Text -- ^ 'ipInstanceProfileName' -> Text -- ^ 'ipInstanceProfileId' -> Text -- ^ 'ipArn' -> UTCTime -- ^ 'ipCreateDate' -> InstanceProfile instanceProfile p1 p2 p3 p4 p5 = InstanceProfile { _ipPath = p1 , _ipInstanceProfileName = p2 , _ipInstanceProfileId = p3 , _ipArn = p4 , _ipCreateDate = withIso _Time (const id) p5 , _ipRoles = mempty } -- | The Amazon Resource Name (ARN) specifying the instance profile. For more -- information about ARNs and how to use them in policies, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. ipArn :: Lens' InstanceProfile Text ipArn = lens _ipArn (\s a -> s { _ipArn = a }) -- | The date when the instance profile was created. ipCreateDate :: Lens' InstanceProfile UTCTime ipCreateDate = lens _ipCreateDate (\s a -> s { _ipCreateDate = a }) . _Time -- | The stable and unique string identifying the instance profile. For more -- information about IDs, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. ipInstanceProfileId :: Lens' InstanceProfile Text ipInstanceProfileId = lens _ipInstanceProfileId (\s a -> s { _ipInstanceProfileId = a }) -- | The name identifying the instance profile. ipInstanceProfileName :: Lens' InstanceProfile Text ipInstanceProfileName = lens _ipInstanceProfileName (\s a -> s { _ipInstanceProfileName = a }) -- | The path to the instance profile. For more information about paths, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAMIdentifiers> in the /Using IAM/ guide. ipPath :: Lens' InstanceProfile Text ipPath = lens _ipPath (\s a -> s { _ipPath = a }) -- | The role associated with the instance profile. ipRoles :: Lens' InstanceProfile [Role] ipRoles = lens _ipRoles (\s a -> s { _ipRoles = a }) . _List instance FromXML InstanceProfile where parseXML x = InstanceProfile <$> x .@ "Arn" <*> x .@ "CreateDate" <*> x .@ "InstanceProfileId" <*> x .@ "InstanceProfileName" <*> x .@ "Path" <*> x .@? "Roles" .!@ mempty instance ToQuery InstanceProfile where toQuery InstanceProfile{..} = mconcat [ "Arn" =? _ipArn , "CreateDate" =? _ipCreateDate , "InstanceProfileId" =? _ipInstanceProfileId , "InstanceProfileName" =? _ipInstanceProfileName , "Path" =? _ipPath , "Roles" =? _ipRoles ] data RoleDetail = RoleDetail { _rdArn :: Maybe Text , _rdAssumeRolePolicyDocument :: Maybe Text , _rdAttachedManagedPolicies :: List "member" AttachedPolicy , _rdCreateDate :: Maybe ISO8601 , _rdInstanceProfileList :: List "member" InstanceProfile , _rdPath :: Maybe Text , _rdRoleId :: Maybe Text , _rdRoleName :: Maybe Text , _rdRolePolicyList :: List "member" PolicyDetail } deriving (Eq, Read, Show) -- | 'RoleDetail' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rdArn' @::@ 'Maybe' 'Text' -- -- * 'rdAssumeRolePolicyDocument' @::@ 'Maybe' 'Text' -- -- * 'rdAttachedManagedPolicies' @::@ ['AttachedPolicy'] -- -- * 'rdCreateDate' @::@ 'Maybe' 'UTCTime' -- -- * 'rdInstanceProfileList' @::@ ['InstanceProfile'] -- -- * 'rdPath' @::@ 'Maybe' 'Text' -- -- * 'rdRoleId' @::@ 'Maybe' 'Text' -- -- * 'rdRoleName' @::@ 'Maybe' 'Text' -- -- * 'rdRolePolicyList' @::@ ['PolicyDetail'] -- roleDetail :: RoleDetail roleDetail = RoleDetail { _rdPath = Nothing , _rdRoleName = Nothing , _rdRoleId = Nothing , _rdArn = Nothing , _rdCreateDate = Nothing , _rdAssumeRolePolicyDocument = Nothing , _rdInstanceProfileList = mempty , _rdRolePolicyList = mempty , _rdAttachedManagedPolicies = mempty } rdArn :: Lens' RoleDetail (Maybe Text) rdArn = lens _rdArn (\s a -> s { _rdArn = a }) -- | The trust policy that grants permission to assume the role. -- -- The returned policy is URL-encoded according to <http://www.faqs.org/rfcs/rfc3986.html RFC 3986>. rdAssumeRolePolicyDocument :: Lens' RoleDetail (Maybe Text) rdAssumeRolePolicyDocument = lens _rdAssumeRolePolicyDocument (\s a -> s { _rdAssumeRolePolicyDocument = a }) -- | A list of managed policies attached to the role. These policies are the -- role's access (permissions) policies. rdAttachedManagedPolicies :: Lens' RoleDetail [AttachedPolicy] rdAttachedManagedPolicies = lens _rdAttachedManagedPolicies (\s a -> s { _rdAttachedManagedPolicies = a }) . _List -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the role was created. rdCreateDate :: Lens' RoleDetail (Maybe UTCTime) rdCreateDate = lens _rdCreateDate (\s a -> s { _rdCreateDate = a }) . mapping _Time rdInstanceProfileList :: Lens' RoleDetail [InstanceProfile] rdInstanceProfileList = lens _rdInstanceProfileList (\s a -> s { _rdInstanceProfileList = a }) . _List -- | The path to the role. For more information about paths, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. rdPath :: Lens' RoleDetail (Maybe Text) rdPath = lens _rdPath (\s a -> s { _rdPath = a }) -- | The stable and unique string identifying the role. For more information about -- IDs, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. rdRoleId :: Lens' RoleDetail (Maybe Text) rdRoleId = lens _rdRoleId (\s a -> s { _rdRoleId = a }) -- | The friendly name that identifies the role. rdRoleName :: Lens' RoleDetail (Maybe Text) rdRoleName = lens _rdRoleName (\s a -> s { _rdRoleName = a }) -- | A list of inline policies embedded in the role. These policies are the role's -- access (permissions) policies. rdRolePolicyList :: Lens' RoleDetail [PolicyDetail] rdRolePolicyList = lens _rdRolePolicyList (\s a -> s { _rdRolePolicyList = a }) . _List instance FromXML RoleDetail where parseXML x = RoleDetail <$> x .@? "Arn" <*> x .@? "AssumeRolePolicyDocument" <*> x .@? "AttachedManagedPolicies" .!@ mempty <*> x .@? "CreateDate" <*> x .@? "InstanceProfileList" .!@ mempty <*> x .@? "Path" <*> x .@? "RoleId" <*> x .@? "RoleName" <*> x .@? "RolePolicyList" .!@ mempty instance ToQuery RoleDetail where toQuery RoleDetail{..} = mconcat [ "Arn" =? _rdArn , "AssumeRolePolicyDocument" =? _rdAssumeRolePolicyDocument , "AttachedManagedPolicies" =? _rdAttachedManagedPolicies , "CreateDate" =? _rdCreateDate , "InstanceProfileList" =? _rdInstanceProfileList , "Path" =? _rdPath , "RoleId" =? _rdRoleId , "RoleName" =? _rdRoleName , "RolePolicyList" =? _rdRolePolicyList ] data ReportFormatType = TextCsv -- ^ text/csv deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ReportFormatType instance FromText ReportFormatType where parser = takeLowerText >>= \case "text/csv" -> pure TextCsv e -> fail $ "Failure parsing ReportFormatType from " ++ show e instance ToText ReportFormatType where toText TextCsv = "text/csv" instance ToByteString ReportFormatType instance ToHeader ReportFormatType instance ToQuery ReportFormatType instance FromXML ReportFormatType where parseXML = parseXMLText "ReportFormatType" data ServerCertificateMetadata = ServerCertificateMetadata { _scmArn :: Text , _scmExpiration :: Maybe ISO8601 , _scmPath :: Text , _scmServerCertificateId :: Text , _scmServerCertificateName :: Text , _scmUploadDate :: Maybe ISO8601 } deriving (Eq, Ord, Read, Show) -- | 'ServerCertificateMetadata' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'scmArn' @::@ 'Text' -- -- * 'scmExpiration' @::@ 'Maybe' 'UTCTime' -- -- * 'scmPath' @::@ 'Text' -- -- * 'scmServerCertificateId' @::@ 'Text' -- -- * 'scmServerCertificateName' @::@ 'Text' -- -- * 'scmUploadDate' @::@ 'Maybe' 'UTCTime' -- serverCertificateMetadata :: Text -- ^ 'scmPath' -> Text -- ^ 'scmServerCertificateName' -> Text -- ^ 'scmServerCertificateId' -> Text -- ^ 'scmArn' -> ServerCertificateMetadata serverCertificateMetadata p1 p2 p3 p4 = ServerCertificateMetadata { _scmPath = p1 , _scmServerCertificateName = p2 , _scmServerCertificateId = p3 , _scmArn = p4 , _scmUploadDate = Nothing , _scmExpiration = Nothing } -- | The Amazon Resource Name (ARN) specifying the server certificate. For more -- information about ARNs and how to use them in policies, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. scmArn :: Lens' ServerCertificateMetadata Text scmArn = lens _scmArn (\s a -> s { _scmArn = a }) -- | The date on which the certificate is set to expire. scmExpiration :: Lens' ServerCertificateMetadata (Maybe UTCTime) scmExpiration = lens _scmExpiration (\s a -> s { _scmExpiration = a }) . mapping _Time -- | The path to the server certificate. For more information about paths, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. scmPath :: Lens' ServerCertificateMetadata Text scmPath = lens _scmPath (\s a -> s { _scmPath = a }) -- | The stable and unique string identifying the server certificate. For more -- information about IDs, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. scmServerCertificateId :: Lens' ServerCertificateMetadata Text scmServerCertificateId = lens _scmServerCertificateId (\s a -> s { _scmServerCertificateId = a }) -- | The name that identifies the server certificate. scmServerCertificateName :: Lens' ServerCertificateMetadata Text scmServerCertificateName = lens _scmServerCertificateName (\s a -> s { _scmServerCertificateName = a }) -- | The date when the server certificate was uploaded. scmUploadDate :: Lens' ServerCertificateMetadata (Maybe UTCTime) scmUploadDate = lens _scmUploadDate (\s a -> s { _scmUploadDate = a }) . mapping _Time instance FromXML ServerCertificateMetadata where parseXML x = ServerCertificateMetadata <$> x .@ "Arn" <*> x .@? "Expiration" <*> x .@ "Path" <*> x .@ "ServerCertificateId" <*> x .@ "ServerCertificateName" <*> x .@? "UploadDate" instance ToQuery ServerCertificateMetadata where toQuery ServerCertificateMetadata{..} = mconcat [ "Arn" =? _scmArn , "Expiration" =? _scmExpiration , "Path" =? _scmPath , "ServerCertificateId" =? _scmServerCertificateId , "ServerCertificateName" =? _scmServerCertificateName , "UploadDate" =? _scmUploadDate ] newtype OpenIDConnectProviderListEntry = OpenIDConnectProviderListEntry { _oidcpleArn :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'OpenIDConnectProviderListEntry' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'oidcpleArn' @::@ 'Maybe' 'Text' -- openIDConnectProviderListEntry :: OpenIDConnectProviderListEntry openIDConnectProviderListEntry = OpenIDConnectProviderListEntry { _oidcpleArn = Nothing } oidcpleArn :: Lens' OpenIDConnectProviderListEntry (Maybe Text) oidcpleArn = lens _oidcpleArn (\s a -> s { _oidcpleArn = a }) instance FromXML OpenIDConnectProviderListEntry where parseXML x = OpenIDConnectProviderListEntry <$> x .@? "Arn" instance ToQuery OpenIDConnectProviderListEntry where toQuery OpenIDConnectProviderListEntry{..} = mconcat [ "Arn" =? _oidcpleArn ] data LoginProfile = LoginProfile { _lpCreateDate :: ISO8601 , _lpPasswordResetRequired :: Maybe Bool , _lpUserName :: Text } deriving (Eq, Ord, Read, Show) -- | 'LoginProfile' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lpCreateDate' @::@ 'UTCTime' -- -- * 'lpPasswordResetRequired' @::@ 'Maybe' 'Bool' -- -- * 'lpUserName' @::@ 'Text' -- loginProfile :: Text -- ^ 'lpUserName' -> UTCTime -- ^ 'lpCreateDate' -> LoginProfile loginProfile p1 p2 = LoginProfile { _lpUserName = p1 , _lpCreateDate = withIso _Time (const id) p2 , _lpPasswordResetRequired = Nothing } -- | The date when the password for the user was created. lpCreateDate :: Lens' LoginProfile UTCTime lpCreateDate = lens _lpCreateDate (\s a -> s { _lpCreateDate = a }) . _Time -- | Specifies whether the user is required to set a new password on next sign-in. lpPasswordResetRequired :: Lens' LoginProfile (Maybe Bool) lpPasswordResetRequired = lens _lpPasswordResetRequired (\s a -> s { _lpPasswordResetRequired = a }) -- | The name of the user, which can be used for signing in to the AWS Management -- Console. lpUserName :: Lens' LoginProfile Text lpUserName = lens _lpUserName (\s a -> s { _lpUserName = a }) instance FromXML LoginProfile where parseXML x = LoginProfile <$> x .@ "CreateDate" <*> x .@? "PasswordResetRequired" <*> x .@ "UserName" instance ToQuery LoginProfile where toQuery LoginProfile{..} = mconcat [ "CreateDate" =? _lpCreateDate , "PasswordResetRequired" =? _lpPasswordResetRequired , "UserName" =? _lpUserName ] data EntityType = ETAWSManagedPolicy -- ^ AWSManagedPolicy | ETGroup -- ^ Group | ETLocalManagedPolicy -- ^ LocalManagedPolicy | ETRole -- ^ Role | ETUser -- ^ User deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable EntityType instance FromText EntityType where parser = takeLowerText >>= \case "awsmanagedpolicy" -> pure ETAWSManagedPolicy "group" -> pure ETGroup "localmanagedpolicy" -> pure ETLocalManagedPolicy "role" -> pure ETRole "user" -> pure ETUser e -> fail $ "Failure parsing EntityType from " ++ show e instance ToText EntityType where toText = \case ETAWSManagedPolicy -> "AWSManagedPolicy" ETGroup -> "Group" ETLocalManagedPolicy -> "LocalManagedPolicy" ETRole -> "Role" ETUser -> "User" instance ToByteString EntityType instance ToHeader EntityType instance ToQuery EntityType instance FromXML EntityType where parseXML = parseXMLText "EntityType" data SummaryKeyType = AccessKeysPerUserQuota -- ^ AccessKeysPerUserQuota | AccountAccessKeysPresent -- ^ AccountAccessKeysPresent | AccountMFAEnabled -- ^ AccountMFAEnabled | AccountSigningCertificatesPresent -- ^ AccountSigningCertificatesPresent | AttachedPoliciesPerGroupQuota -- ^ AttachedPoliciesPerGroupQuota | AttachedPoliciesPerRoleQuota -- ^ AttachedPoliciesPerRoleQuota | AttachedPoliciesPerUserQuota -- ^ AttachedPoliciesPerUserQuota | GroupPolicySizeQuota -- ^ GroupPolicySizeQuota | Groups -- ^ Groups | GroupsPerUserQuota -- ^ GroupsPerUserQuota | GroupsQuota -- ^ GroupsQuota | MFADevices -- ^ MFADevices | MFADevicesInUse -- ^ MFADevicesInUse | Policies -- ^ Policies | PoliciesQuota -- ^ PoliciesQuota | PolicySizeQuota -- ^ PolicySizeQuota | PolicyVersionsInUse -- ^ PolicyVersionsInUse | PolicyVersionsInUseQuota -- ^ PolicyVersionsInUseQuota | ServerCertificates -- ^ ServerCertificates | ServerCertificatesQuota -- ^ ServerCertificatesQuota | SigningCertificatesPerUserQuota -- ^ SigningCertificatesPerUserQuota | UserPolicySizeQuota -- ^ UserPolicySizeQuota | Users -- ^ Users | UsersQuota -- ^ UsersQuota | VersionsPerPolicyQuota -- ^ VersionsPerPolicyQuota deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable SummaryKeyType instance FromText SummaryKeyType where parser = takeLowerText >>= \case "accesskeysperuserquota" -> pure AccessKeysPerUserQuota "accountaccesskeyspresent" -> pure AccountAccessKeysPresent "accountmfaenabled" -> pure AccountMFAEnabled "accountsigningcertificatespresent" -> pure AccountSigningCertificatesPresent "attachedpoliciespergroupquota" -> pure AttachedPoliciesPerGroupQuota "attachedpoliciesperrolequota" -> pure AttachedPoliciesPerRoleQuota "attachedpoliciesperuserquota" -> pure AttachedPoliciesPerUserQuota "grouppolicysizequota" -> pure GroupPolicySizeQuota "groups" -> pure Groups "groupsperuserquota" -> pure GroupsPerUserQuota "groupsquota" -> pure GroupsQuota "mfadevices" -> pure MFADevices "mfadevicesinuse" -> pure MFADevicesInUse "policies" -> pure Policies "policiesquota" -> pure PoliciesQuota "policysizequota" -> pure PolicySizeQuota "policyversionsinuse" -> pure PolicyVersionsInUse "policyversionsinusequota" -> pure PolicyVersionsInUseQuota "servercertificates" -> pure ServerCertificates "servercertificatesquota" -> pure ServerCertificatesQuota "signingcertificatesperuserquota" -> pure SigningCertificatesPerUserQuota "userpolicysizequota" -> pure UserPolicySizeQuota "users" -> pure Users "usersquota" -> pure UsersQuota "versionsperpolicyquota" -> pure VersionsPerPolicyQuota e -> fail $ "Failure parsing SummaryKeyType from " ++ show e instance ToText SummaryKeyType where toText = \case AccessKeysPerUserQuota -> "AccessKeysPerUserQuota" AccountAccessKeysPresent -> "AccountAccessKeysPresent" AccountMFAEnabled -> "AccountMFAEnabled" AccountSigningCertificatesPresent -> "AccountSigningCertificatesPresent" AttachedPoliciesPerGroupQuota -> "AttachedPoliciesPerGroupQuota" AttachedPoliciesPerRoleQuota -> "AttachedPoliciesPerRoleQuota" AttachedPoliciesPerUserQuota -> "AttachedPoliciesPerUserQuota" GroupPolicySizeQuota -> "GroupPolicySizeQuota" Groups -> "Groups" GroupsPerUserQuota -> "GroupsPerUserQuota" GroupsQuota -> "GroupsQuota" MFADevices -> "MFADevices" MFADevicesInUse -> "MFADevicesInUse" Policies -> "Policies" PoliciesQuota -> "PoliciesQuota" PolicySizeQuota -> "PolicySizeQuota" PolicyVersionsInUse -> "PolicyVersionsInUse" PolicyVersionsInUseQuota -> "PolicyVersionsInUseQuota" ServerCertificates -> "ServerCertificates" ServerCertificatesQuota -> "ServerCertificatesQuota" SigningCertificatesPerUserQuota -> "SigningCertificatesPerUserQuota" UserPolicySizeQuota -> "UserPolicySizeQuota" Users -> "Users" UsersQuota -> "UsersQuota" VersionsPerPolicyQuota -> "VersionsPerPolicyQuota" instance ToByteString SummaryKeyType instance ToHeader SummaryKeyType instance ToQuery SummaryKeyType instance FromXML SummaryKeyType where parseXML = parseXMLText "SummaryKeyType" data GroupDetail = GroupDetail { _gdArn :: Maybe Text , _gdAttachedManagedPolicies :: List "member" AttachedPolicy , _gdCreateDate :: Maybe ISO8601 , _gdGroupId :: Maybe Text , _gdGroupName :: Maybe Text , _gdGroupPolicyList :: List "member" PolicyDetail , _gdPath :: Maybe Text } deriving (Eq, Read, Show) -- | 'GroupDetail' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gdArn' @::@ 'Maybe' 'Text' -- -- * 'gdAttachedManagedPolicies' @::@ ['AttachedPolicy'] -- -- * 'gdCreateDate' @::@ 'Maybe' 'UTCTime' -- -- * 'gdGroupId' @::@ 'Maybe' 'Text' -- -- * 'gdGroupName' @::@ 'Maybe' 'Text' -- -- * 'gdGroupPolicyList' @::@ ['PolicyDetail'] -- -- * 'gdPath' @::@ 'Maybe' 'Text' -- groupDetail :: GroupDetail groupDetail = GroupDetail { _gdPath = Nothing , _gdGroupName = Nothing , _gdGroupId = Nothing , _gdArn = Nothing , _gdCreateDate = Nothing , _gdGroupPolicyList = mempty , _gdAttachedManagedPolicies = mempty } gdArn :: Lens' GroupDetail (Maybe Text) gdArn = lens _gdArn (\s a -> s { _gdArn = a }) -- | A list of the managed policies attached to the group. gdAttachedManagedPolicies :: Lens' GroupDetail [AttachedPolicy] gdAttachedManagedPolicies = lens _gdAttachedManagedPolicies (\s a -> s { _gdAttachedManagedPolicies = a }) . _List -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the group was created. gdCreateDate :: Lens' GroupDetail (Maybe UTCTime) gdCreateDate = lens _gdCreateDate (\s a -> s { _gdCreateDate = a }) . mapping _Time -- | The stable and unique string identifying the group. For more information -- about IDs, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. gdGroupId :: Lens' GroupDetail (Maybe Text) gdGroupId = lens _gdGroupId (\s a -> s { _gdGroupId = a }) -- | The friendly name that identifies the group. gdGroupName :: Lens' GroupDetail (Maybe Text) gdGroupName = lens _gdGroupName (\s a -> s { _gdGroupName = a }) -- | A list of the inline policies embedded in the group. gdGroupPolicyList :: Lens' GroupDetail [PolicyDetail] gdGroupPolicyList = lens _gdGroupPolicyList (\s a -> s { _gdGroupPolicyList = a }) . _List -- | The path to the group. For more information about paths, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. gdPath :: Lens' GroupDetail (Maybe Text) gdPath = lens _gdPath (\s a -> s { _gdPath = a }) instance FromXML GroupDetail where parseXML x = GroupDetail <$> x .@? "Arn" <*> x .@? "AttachedManagedPolicies" .!@ mempty <*> x .@? "CreateDate" <*> x .@? "GroupId" <*> x .@? "GroupName" <*> x .@? "GroupPolicyList" .!@ mempty <*> x .@? "Path" instance ToQuery GroupDetail where toQuery GroupDetail{..} = mconcat [ "Arn" =? _gdArn , "AttachedManagedPolicies" =? _gdAttachedManagedPolicies , "CreateDate" =? _gdCreateDate , "GroupId" =? _gdGroupId , "GroupName" =? _gdGroupName , "GroupPolicyList" =? _gdGroupPolicyList , "Path" =? _gdPath ] data ReportStateType = Complete -- ^ COMPLETE | Inprogress -- ^ INPROGRESS | Started -- ^ STARTED deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ReportStateType instance FromText ReportStateType where parser = takeLowerText >>= \case "complete" -> pure Complete "inprogress" -> pure Inprogress "started" -> pure Started e -> fail $ "Failure parsing ReportStateType from " ++ show e instance ToText ReportStateType where toText = \case Complete -> "COMPLETE" Inprogress -> "INPROGRESS" Started -> "STARTED" instance ToByteString ReportStateType instance ToHeader ReportStateType instance ToQuery ReportStateType instance FromXML ReportStateType where parseXML = parseXMLText "ReportStateType" data User = User { _uArn :: Text , _uCreateDate :: ISO8601 , _uPasswordLastUsed :: Maybe ISO8601 , _uPath :: Text , _uUserId :: Text , _uUserName :: Text } deriving (Eq, Ord, Read, Show) -- | 'User' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'uArn' @::@ 'Text' -- -- * 'uCreateDate' @::@ 'UTCTime' -- -- * 'uPasswordLastUsed' @::@ 'Maybe' 'UTCTime' -- -- * 'uPath' @::@ 'Text' -- -- * 'uUserId' @::@ 'Text' -- -- * 'uUserName' @::@ 'Text' -- user :: Text -- ^ 'uPath' -> Text -- ^ 'uUserName' -> Text -- ^ 'uUserId' -> Text -- ^ 'uArn' -> UTCTime -- ^ 'uCreateDate' -> User user p1 p2 p3 p4 p5 = User { _uPath = p1 , _uUserName = p2 , _uUserId = p3 , _uArn = p4 , _uCreateDate = withIso _Time (const id) p5 , _uPasswordLastUsed = Nothing } -- | The Amazon Resource Name (ARN) that identifies the user. For more information -- about ARNs and how to use ARNs in policies, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /UsingIAM/ guide. uArn :: Lens' User Text uArn = lens _uArn (\s a -> s { _uArn = a }) -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the user was created. uCreateDate :: Lens' User UTCTime uCreateDate = lens _uCreateDate (\s a -> s { _uCreateDate = a }) . _Time -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the user's password was -- last used to sign in to an AWS website. For a list of AWS websites that -- capture a user's last sign-in time, see the <http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html Credential Reports> topic in the /Using IAM/ guide. If a password is used more than once in a five-minute span, only the -- first use is returned in this field. When the user does not have a password, -- this field is null (not present). When a user's password exists but has never -- been used, or when there is no sign-in data associated with the user, this -- field is null (not present). -- -- This value is returned only in the 'GetUser' and 'ListUsers' actions. uPasswordLastUsed :: Lens' User (Maybe UTCTime) uPasswordLastUsed = lens _uPasswordLastUsed (\s a -> s { _uPasswordLastUsed = a }) . mapping _Time -- | The path to the user. For more information about paths, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. uPath :: Lens' User Text uPath = lens _uPath (\s a -> s { _uPath = a }) -- | The stable and unique string identifying the user. For more information about -- IDs, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. uUserId :: Lens' User Text uUserId = lens _uUserId (\s a -> s { _uUserId = a }) -- | The friendly name identifying the user. uUserName :: Lens' User Text uUserName = lens _uUserName (\s a -> s { _uUserName = a }) instance FromXML User where parseXML x = User <$> x .@ "Arn" <*> x .@ "CreateDate" <*> x .@? "PasswordLastUsed" <*> x .@ "Path" <*> x .@ "UserId" <*> x .@ "UserName" instance ToQuery User where toQuery User{..} = mconcat [ "Arn" =? _uArn , "CreateDate" =? _uCreateDate , "PasswordLastUsed" =? _uPasswordLastUsed , "Path" =? _uPath , "UserId" =? _uUserId , "UserName" =? _uUserName ] data PolicyDetail = PolicyDetail { _pdPolicyDocument :: Maybe Text , _pdPolicyName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'PolicyDetail' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pdPolicyDocument' @::@ 'Maybe' 'Text' -- -- * 'pdPolicyName' @::@ 'Maybe' 'Text' -- policyDetail :: PolicyDetail policyDetail = PolicyDetail { _pdPolicyName = Nothing , _pdPolicyDocument = Nothing } -- | The policy document. -- -- The returned policy is URL-encoded according to <http://www.faqs.org/rfcs/rfc3986.html RFC 3986>. pdPolicyDocument :: Lens' PolicyDetail (Maybe Text) pdPolicyDocument = lens _pdPolicyDocument (\s a -> s { _pdPolicyDocument = a }) -- | The name of the policy. pdPolicyName :: Lens' PolicyDetail (Maybe Text) pdPolicyName = lens _pdPolicyName (\s a -> s { _pdPolicyName = a }) instance FromXML PolicyDetail where parseXML x = PolicyDetail <$> x .@? "PolicyDocument" <*> x .@? "PolicyName" instance ToQuery PolicyDetail where toQuery PolicyDetail{..} = mconcat [ "PolicyDocument" =? _pdPolicyDocument , "PolicyName" =? _pdPolicyName ] data StatusType = Active -- ^ Active | Inactive -- ^ Inactive deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable StatusType instance FromText StatusType where parser = takeLowerText >>= \case "active" -> pure Active "inactive" -> pure Inactive e -> fail $ "Failure parsing StatusType from " ++ show e instance ToText StatusType where toText = \case Active -> "Active" Inactive -> "Inactive" instance ToByteString StatusType instance ToHeader StatusType instance ToQuery StatusType instance FromXML StatusType where parseXML = parseXMLText "StatusType" data SAMLProviderListEntry = SAMLProviderListEntry { _samlpleArn :: Maybe Text , _samlpleCreateDate :: Maybe ISO8601 , _samlpleValidUntil :: Maybe ISO8601 } deriving (Eq, Ord, Read, Show) -- | 'SAMLProviderListEntry' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'samlpleArn' @::@ 'Maybe' 'Text' -- -- * 'samlpleCreateDate' @::@ 'Maybe' 'UTCTime' -- -- * 'samlpleValidUntil' @::@ 'Maybe' 'UTCTime' -- samlproviderListEntry :: SAMLProviderListEntry samlproviderListEntry = SAMLProviderListEntry { _samlpleArn = Nothing , _samlpleValidUntil = Nothing , _samlpleCreateDate = Nothing } -- | The Amazon Resource Name (ARN) of the SAML provider. samlpleArn :: Lens' SAMLProviderListEntry (Maybe Text) samlpleArn = lens _samlpleArn (\s a -> s { _samlpleArn = a }) -- | The date and time when the SAML provider was created. samlpleCreateDate :: Lens' SAMLProviderListEntry (Maybe UTCTime) samlpleCreateDate = lens _samlpleCreateDate (\s a -> s { _samlpleCreateDate = a }) . mapping _Time -- | The expiration date and time for the SAML provider. samlpleValidUntil :: Lens' SAMLProviderListEntry (Maybe UTCTime) samlpleValidUntil = lens _samlpleValidUntil (\s a -> s { _samlpleValidUntil = a }) . mapping _Time instance FromXML SAMLProviderListEntry where parseXML x = SAMLProviderListEntry <$> x .@? "Arn" <*> x .@? "CreateDate" <*> x .@? "ValidUntil" instance ToQuery SAMLProviderListEntry where toQuery SAMLProviderListEntry{..} = mconcat [ "Arn" =? _samlpleArn , "CreateDate" =? _samlpleCreateDate , "ValidUntil" =? _samlpleValidUntil ] data Role = Role { _rArn :: Text , _rAssumeRolePolicyDocument :: Maybe Text , _rCreateDate :: ISO8601 , _rPath :: Text , _rRoleId :: Text , _rRoleName :: Text } deriving (Eq, Ord, Read, Show) -- | 'Role' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rArn' @::@ 'Text' -- -- * 'rAssumeRolePolicyDocument' @::@ 'Maybe' 'Text' -- -- * 'rCreateDate' @::@ 'UTCTime' -- -- * 'rPath' @::@ 'Text' -- -- * 'rRoleId' @::@ 'Text' -- -- * 'rRoleName' @::@ 'Text' -- role :: Text -- ^ 'rPath' -> Text -- ^ 'rRoleName' -> Text -- ^ 'rRoleId' -> Text -- ^ 'rArn' -> UTCTime -- ^ 'rCreateDate' -> Role role p1 p2 p3 p4 p5 = Role { _rPath = p1 , _rRoleName = p2 , _rRoleId = p3 , _rArn = p4 , _rCreateDate = withIso _Time (const id) p5 , _rAssumeRolePolicyDocument = Nothing } -- | The Amazon Resource Name (ARN) specifying the role. For more information -- about ARNs and how to use them in policies, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /UsingIAM/ guide. rArn :: Lens' Role Text rArn = lens _rArn (\s a -> s { _rArn = a }) -- | The policy that grants an entity permission to assume the role. -- -- The returned policy is URL-encoded according to <http://www.faqs.org/rfcs/rfc3986.html RFC 3986>. rAssumeRolePolicyDocument :: Lens' Role (Maybe Text) rAssumeRolePolicyDocument = lens _rAssumeRolePolicyDocument (\s a -> s { _rAssumeRolePolicyDocument = a }) -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the role was created. rCreateDate :: Lens' Role UTCTime rCreateDate = lens _rCreateDate (\s a -> s { _rCreateDate = a }) . _Time -- | The path to the role. For more information about paths, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. rPath :: Lens' Role Text rPath = lens _rPath (\s a -> s { _rPath = a }) -- | The stable and unique string identifying the role. For more information -- about IDs, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. rRoleId :: Lens' Role Text rRoleId = lens _rRoleId (\s a -> s { _rRoleId = a }) -- | The friendly name that identifies the role. rRoleName :: Lens' Role Text rRoleName = lens _rRoleName (\s a -> s { _rRoleName = a }) instance FromXML Role where parseXML x = Role <$> x .@ "Arn" <*> x .@? "AssumeRolePolicyDocument" <*> x .@ "CreateDate" <*> x .@ "Path" <*> x .@ "RoleId" <*> x .@ "RoleName" instance ToQuery Role where toQuery Role{..} = mconcat [ "Arn" =? _rArn , "AssumeRolePolicyDocument" =? _rAssumeRolePolicyDocument , "CreateDate" =? _rCreateDate , "Path" =? _rPath , "RoleId" =? _rRoleId , "RoleName" =? _rRoleName ] newtype PolicyGroup = PolicyGroup { _pgGroupName :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'PolicyGroup' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pgGroupName' @::@ 'Maybe' 'Text' -- policyGroup :: PolicyGroup policyGroup = PolicyGroup { _pgGroupName = Nothing } -- | The name (friendly name, not ARN) identifying the group. pgGroupName :: Lens' PolicyGroup (Maybe Text) pgGroupName = lens _pgGroupName (\s a -> s { _pgGroupName = a }) instance FromXML PolicyGroup where parseXML x = PolicyGroup <$> x .@? "GroupName" instance ToQuery PolicyGroup where toQuery PolicyGroup{..} = mconcat [ "GroupName" =? _pgGroupName ] data PolicyScopeType = All -- ^ All | Aws -- ^ AWS | Local -- ^ Local deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable PolicyScopeType instance FromText PolicyScopeType where parser = takeLowerText >>= \case "all" -> pure All "aws" -> pure Aws "local" -> pure Local e -> fail $ "Failure parsing PolicyScopeType from " ++ show e instance ToText PolicyScopeType where toText = \case All -> "All" Aws -> "AWS" Local -> "Local" instance ToByteString PolicyScopeType instance ToHeader PolicyScopeType instance ToQuery PolicyScopeType instance FromXML PolicyScopeType where parseXML = parseXMLText "PolicyScopeType" data UserDetail = UserDetail { _udArn :: Maybe Text , _udAttachedManagedPolicies :: List "member" AttachedPolicy , _udCreateDate :: Maybe ISO8601 , _udGroupList :: List "member" Text , _udPath :: Maybe Text , _udUserId :: Maybe Text , _udUserName :: Maybe Text , _udUserPolicyList :: List "member" PolicyDetail } deriving (Eq, Read, Show) -- | 'UserDetail' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'udArn' @::@ 'Maybe' 'Text' -- -- * 'udAttachedManagedPolicies' @::@ ['AttachedPolicy'] -- -- * 'udCreateDate' @::@ 'Maybe' 'UTCTime' -- -- * 'udGroupList' @::@ ['Text'] -- -- * 'udPath' @::@ 'Maybe' 'Text' -- -- * 'udUserId' @::@ 'Maybe' 'Text' -- -- * 'udUserName' @::@ 'Maybe' 'Text' -- -- * 'udUserPolicyList' @::@ ['PolicyDetail'] -- userDetail :: UserDetail userDetail = UserDetail { _udPath = Nothing , _udUserName = Nothing , _udUserId = Nothing , _udArn = Nothing , _udCreateDate = Nothing , _udUserPolicyList = mempty , _udGroupList = mempty , _udAttachedManagedPolicies = mempty } udArn :: Lens' UserDetail (Maybe Text) udArn = lens _udArn (\s a -> s { _udArn = a }) -- | A list of the managed policies attached to the user. udAttachedManagedPolicies :: Lens' UserDetail [AttachedPolicy] udAttachedManagedPolicies = lens _udAttachedManagedPolicies (\s a -> s { _udAttachedManagedPolicies = a }) . _List -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the user was created. udCreateDate :: Lens' UserDetail (Maybe UTCTime) udCreateDate = lens _udCreateDate (\s a -> s { _udCreateDate = a }) . mapping _Time -- | A list of IAM groups that the user is in. udGroupList :: Lens' UserDetail [Text] udGroupList = lens _udGroupList (\s a -> s { _udGroupList = a }) . _List -- | The path to the user. For more information about paths, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. udPath :: Lens' UserDetail (Maybe Text) udPath = lens _udPath (\s a -> s { _udPath = a }) -- | The stable and unique string identifying the user. For more information about -- IDs, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. udUserId :: Lens' UserDetail (Maybe Text) udUserId = lens _udUserId (\s a -> s { _udUserId = a }) -- | The friendly name identifying the user. udUserName :: Lens' UserDetail (Maybe Text) udUserName = lens _udUserName (\s a -> s { _udUserName = a }) -- | A list of the inline policies embedded in the user. udUserPolicyList :: Lens' UserDetail [PolicyDetail] udUserPolicyList = lens _udUserPolicyList (\s a -> s { _udUserPolicyList = a }) . _List instance FromXML UserDetail where parseXML x = UserDetail <$> x .@? "Arn" <*> x .@? "AttachedManagedPolicies" .!@ mempty <*> x .@? "CreateDate" <*> x .@? "GroupList" .!@ mempty <*> x .@? "Path" <*> x .@? "UserId" <*> x .@? "UserName" <*> x .@? "UserPolicyList" .!@ mempty instance ToQuery UserDetail where toQuery UserDetail{..} = mconcat [ "Arn" =? _udArn , "AttachedManagedPolicies" =? _udAttachedManagedPolicies , "CreateDate" =? _udCreateDate , "GroupList" =? _udGroupList , "Path" =? _udPath , "UserId" =? _udUserId , "UserName" =? _udUserName , "UserPolicyList" =? _udUserPolicyList ] data Policy = Policy { _pArn :: Maybe Text , _pAttachmentCount :: Maybe Int , _pCreateDate :: Maybe ISO8601 , _pDefaultVersionId :: Maybe Text , _pDescription :: Maybe Text , _pIsAttachable :: Maybe Bool , _pPath :: Maybe Text , _pPolicyId :: Maybe Text , _pPolicyName :: Maybe Text , _pUpdateDate :: Maybe ISO8601 } deriving (Eq, Ord, Read, Show) -- | 'Policy' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pArn' @::@ 'Maybe' 'Text' -- -- * 'pAttachmentCount' @::@ 'Maybe' 'Int' -- -- * 'pCreateDate' @::@ 'Maybe' 'UTCTime' -- -- * 'pDefaultVersionId' @::@ 'Maybe' 'Text' -- -- * 'pDescription' @::@ 'Maybe' 'Text' -- -- * 'pIsAttachable' @::@ 'Maybe' 'Bool' -- -- * 'pPath' @::@ 'Maybe' 'Text' -- -- * 'pPolicyId' @::@ 'Maybe' 'Text' -- -- * 'pPolicyName' @::@ 'Maybe' 'Text' -- -- * 'pUpdateDate' @::@ 'Maybe' 'UTCTime' -- policy :: Policy policy = Policy { _pPolicyName = Nothing , _pPolicyId = Nothing , _pArn = Nothing , _pPath = Nothing , _pDefaultVersionId = Nothing , _pAttachmentCount = Nothing , _pIsAttachable = Nothing , _pDescription = Nothing , _pCreateDate = Nothing , _pUpdateDate = Nothing } pArn :: Lens' Policy (Maybe Text) pArn = lens _pArn (\s a -> s { _pArn = a }) -- | The number of entities (users, groups, and roles) that the policy is attached -- to. pAttachmentCount :: Lens' Policy (Maybe Int) pAttachmentCount = lens _pAttachmentCount (\s a -> s { _pAttachmentCount = a }) -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the policy was created. pCreateDate :: Lens' Policy (Maybe UTCTime) pCreateDate = lens _pCreateDate (\s a -> s { _pCreateDate = a }) . mapping _Time -- | The identifier for the version of the policy that is set as the default -- version. pDefaultVersionId :: Lens' Policy (Maybe Text) pDefaultVersionId = lens _pDefaultVersionId (\s a -> s { _pDefaultVersionId = a }) -- | A friendly description of the policy. -- -- This element is included in the response to the 'GetPolicy' operation. It is -- not included in the response to the 'ListPolicies' operation. pDescription :: Lens' Policy (Maybe Text) pDescription = lens _pDescription (\s a -> s { _pDescription = a }) -- | Specifies whether the policy can be attached to an IAM user, group, or role. pIsAttachable :: Lens' Policy (Maybe Bool) pIsAttachable = lens _pIsAttachable (\s a -> s { _pIsAttachable = a }) -- | The path to the policy. -- -- For more information about paths, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. pPath :: Lens' Policy (Maybe Text) pPath = lens _pPath (\s a -> s { _pPath = a }) -- | The stable and unique string identifying the policy. -- -- For more information about IDs, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> in the /Using IAM/ guide. pPolicyId :: Lens' Policy (Maybe Text) pPolicyId = lens _pPolicyId (\s a -> s { _pPolicyId = a }) -- | The friendly name (not ARN) identifying the policy. pPolicyName :: Lens' Policy (Maybe Text) pPolicyName = lens _pPolicyName (\s a -> s { _pPolicyName = a }) -- | The date and time, in <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the policy was last -- updated. -- -- When a policy has only one version, this field contains the date and time -- when the policy was created. When a policy has more than one version, this -- field contains the date and time when the most recent policy version was -- created. pUpdateDate :: Lens' Policy (Maybe UTCTime) pUpdateDate = lens _pUpdateDate (\s a -> s { _pUpdateDate = a }) . mapping _Time instance FromXML Policy where parseXML x = Policy <$> x .@? "Arn" <*> x .@? "AttachmentCount" <*> x .@? "CreateDate" <*> x .@? "DefaultVersionId" <*> x .@? "Description" <*> x .@? "IsAttachable" <*> x .@? "Path" <*> x .@? "PolicyId" <*> x .@? "PolicyName" <*> x .@? "UpdateDate" instance ToQuery Policy where toQuery Policy{..} = mconcat [ "Arn" =? _pArn , "AttachmentCount" =? _pAttachmentCount , "CreateDate" =? _pCreateDate , "DefaultVersionId" =? _pDefaultVersionId , "Description" =? _pDescription , "IsAttachable" =? _pIsAttachable , "Path" =? _pPath , "PolicyId" =? _pPolicyId , "PolicyName" =? _pPolicyName , "UpdateDate" =? _pUpdateDate ] data ServerCertificate = ServerCertificate { _scCertificateBody :: Text , _scCertificateChain :: Maybe Text , _scServerCertificateMetadata :: ServerCertificateMetadata } deriving (Eq, Read, Show) -- | 'ServerCertificate' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'scCertificateBody' @::@ 'Text' -- -- * 'scCertificateChain' @::@ 'Maybe' 'Text' -- -- * 'scServerCertificateMetadata' @::@ 'ServerCertificateMetadata' -- serverCertificate :: ServerCertificateMetadata -- ^ 'scServerCertificateMetadata' -> Text -- ^ 'scCertificateBody' -> ServerCertificate serverCertificate p1 p2 = ServerCertificate { _scServerCertificateMetadata = p1 , _scCertificateBody = p2 , _scCertificateChain = Nothing } -- | The contents of the public key certificate. scCertificateBody :: Lens' ServerCertificate Text scCertificateBody = lens _scCertificateBody (\s a -> s { _scCertificateBody = a }) -- | The contents of the public key certificate chain. scCertificateChain :: Lens' ServerCertificate (Maybe Text) scCertificateChain = lens _scCertificateChain (\s a -> s { _scCertificateChain = a }) -- | The meta information of the server certificate, such as its name, path, ID, -- and ARN. scServerCertificateMetadata :: Lens' ServerCertificate ServerCertificateMetadata scServerCertificateMetadata = lens _scServerCertificateMetadata (\s a -> s { _scServerCertificateMetadata = a }) instance FromXML ServerCertificate where parseXML x = ServerCertificate <$> x .@ "CertificateBody" <*> x .@? "CertificateChain" <*> x .@ "ServerCertificateMetadata" instance ToQuery ServerCertificate where toQuery ServerCertificate{..} = mconcat [ "CertificateBody" =? _scCertificateBody , "CertificateChain" =? _scCertificateChain , "ServerCertificateMetadata" =? _scServerCertificateMetadata ] data AccessKey = AccessKey { _akAccessKeyId :: Text , _akCreateDate :: Maybe ISO8601 , _akSecretAccessKey :: Sensitive Text , _akStatus :: StatusType , _akUserName :: Text } deriving (Eq, Read, Show) -- | 'AccessKey' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'akAccessKeyId' @::@ 'Text' -- -- * 'akCreateDate' @::@ 'Maybe' 'UTCTime' -- -- * 'akSecretAccessKey' @::@ 'Text' -- -- * 'akStatus' @::@ 'StatusType' -- -- * 'akUserName' @::@ 'Text' -- accessKey :: Text -- ^ 'akUserName' -> Text -- ^ 'akAccessKeyId' -> StatusType -- ^ 'akStatus' -> Text -- ^ 'akSecretAccessKey' -> AccessKey accessKey p1 p2 p3 p4 = AccessKey { _akUserName = p1 , _akAccessKeyId = p2 , _akStatus = p3 , _akSecretAccessKey = withIso _Sensitive (const id) p4 , _akCreateDate = Nothing } -- | The ID for this access key. akAccessKeyId :: Lens' AccessKey Text akAccessKeyId = lens _akAccessKeyId (\s a -> s { _akAccessKeyId = a }) -- | The date when the access key was created. akCreateDate :: Lens' AccessKey (Maybe UTCTime) akCreateDate = lens _akCreateDate (\s a -> s { _akCreateDate = a }) . mapping _Time -- | The secret key used to sign requests. akSecretAccessKey :: Lens' AccessKey Text akSecretAccessKey = lens _akSecretAccessKey (\s a -> s { _akSecretAccessKey = a }) . _Sensitive -- | The status of the access key. 'Active' means the key is valid for API calls, -- while 'Inactive' means it is not. akStatus :: Lens' AccessKey StatusType akStatus = lens _akStatus (\s a -> s { _akStatus = a }) -- | The name of the IAM user that the access key is associated with. akUserName :: Lens' AccessKey Text akUserName = lens _akUserName (\s a -> s { _akUserName = a }) instance FromXML AccessKey where parseXML x = AccessKey <$> x .@ "AccessKeyId" <*> x .@? "CreateDate" <*> x .@ "SecretAccessKey" <*> x .@ "Status" <*> x .@ "UserName" instance ToQuery AccessKey where toQuery AccessKey{..} = mconcat [ "AccessKeyId" =? _akAccessKeyId , "CreateDate" =? _akCreateDate , "SecretAccessKey" =? _akSecretAccessKey , "Status" =? _akStatus , "UserName" =? _akUserName ] data VirtualMFADevice = VirtualMFADevice { _vmfadBase32StringSeed :: Maybe Base64 , _vmfadEnableDate :: Maybe ISO8601 , _vmfadQRCodePNG :: Maybe Base64 , _vmfadSerialNumber :: Text , _vmfadUser :: Maybe User } deriving (Eq, Read, Show) -- | 'VirtualMFADevice' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vmfadBase32StringSeed' @::@ 'Maybe' 'Base64' -- -- * 'vmfadEnableDate' @::@ 'Maybe' 'UTCTime' -- -- * 'vmfadQRCodePNG' @::@ 'Maybe' 'Base64' -- -- * 'vmfadSerialNumber' @::@ 'Text' -- -- * 'vmfadUser' @::@ 'Maybe' 'User' -- virtualMFADevice :: Text -- ^ 'vmfadSerialNumber' -> VirtualMFADevice virtualMFADevice p1 = VirtualMFADevice { _vmfadSerialNumber = p1 , _vmfadBase32StringSeed = Nothing , _vmfadQRCodePNG = Nothing , _vmfadUser = Nothing , _vmfadEnableDate = Nothing } -- | The Base32 seed defined as specified in <http://www.ietf.org/rfc/rfc3548.txt RFC3548>. The 'Base32StringSeed' is -- Base64-encoded. vmfadBase32StringSeed :: Lens' VirtualMFADevice (Maybe Base64) vmfadBase32StringSeed = lens _vmfadBase32StringSeed (\s a -> s { _vmfadBase32StringSeed = a }) -- | The date and time on which the virtual MFA device was enabled. vmfadEnableDate :: Lens' VirtualMFADevice (Maybe UTCTime) vmfadEnableDate = lens _vmfadEnableDate (\s a -> s { _vmfadEnableDate = a }) . mapping _Time -- | A QR code PNG image that encodes 'otpauth://totp/$virtualMFADeviceName@$AccountName?secret=$Base32String' where '$virtualMFADeviceName' is one of the create call arguments, 'AccountName' -- is the user name if set (otherwise, the account ID otherwise), and 'Base32String' is the seed in Base32 format. The 'Base32String' value is Base64-encoded. vmfadQRCodePNG :: Lens' VirtualMFADevice (Maybe Base64) vmfadQRCodePNG = lens _vmfadQRCodePNG (\s a -> s { _vmfadQRCodePNG = a }) -- | The serial number associated with 'VirtualMFADevice'. vmfadSerialNumber :: Lens' VirtualMFADevice Text vmfadSerialNumber = lens _vmfadSerialNumber (\s a -> s { _vmfadSerialNumber = a }) vmfadUser :: Lens' VirtualMFADevice (Maybe User) vmfadUser = lens _vmfadUser (\s a -> s { _vmfadUser = a }) instance FromXML VirtualMFADevice where parseXML x = VirtualMFADevice <$> x .@? "Base32StringSeed" <*> x .@? "EnableDate" <*> x .@? "QRCodePNG" <*> x .@ "SerialNumber" <*> x .@? "User" instance ToQuery VirtualMFADevice where toQuery VirtualMFADevice{..} = mconcat [ "Base32StringSeed" =? _vmfadBase32StringSeed , "EnableDate" =? _vmfadEnableDate , "QRCodePNG" =? _vmfadQRCodePNG , "SerialNumber" =? _vmfadSerialNumber , "User" =? _vmfadUser ] data SigningCertificate = SigningCertificate { _sc1CertificateBody :: Text , _sc1CertificateId :: Text , _sc1Status :: StatusType , _sc1UploadDate :: Maybe ISO8601 , _sc1UserName :: Text } deriving (Eq, Read, Show) -- | 'SigningCertificate' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'sc1CertificateBody' @::@ 'Text' -- -- * 'sc1CertificateId' @::@ 'Text' -- -- * 'sc1Status' @::@ 'StatusType' -- -- * 'sc1UploadDate' @::@ 'Maybe' 'UTCTime' -- -- * 'sc1UserName' @::@ 'Text' -- signingCertificate :: Text -- ^ 'sc1UserName' -> Text -- ^ 'sc1CertificateId' -> Text -- ^ 'sc1CertificateBody' -> StatusType -- ^ 'sc1Status' -> SigningCertificate signingCertificate p1 p2 p3 p4 = SigningCertificate { _sc1UserName = p1 , _sc1CertificateId = p2 , _sc1CertificateBody = p3 , _sc1Status = p4 , _sc1UploadDate = Nothing } -- | The contents of the signing certificate. sc1CertificateBody :: Lens' SigningCertificate Text sc1CertificateBody = lens _sc1CertificateBody (\s a -> s { _sc1CertificateBody = a }) -- | The ID for the signing certificate. sc1CertificateId :: Lens' SigningCertificate Text sc1CertificateId = lens _sc1CertificateId (\s a -> s { _sc1CertificateId = a }) -- | The status of the signing certificate. 'Active' means the key is valid for API -- calls, while 'Inactive' means it is not. sc1Status :: Lens' SigningCertificate StatusType sc1Status = lens _sc1Status (\s a -> s { _sc1Status = a }) -- | The date when the signing certificate was uploaded. sc1UploadDate :: Lens' SigningCertificate (Maybe UTCTime) sc1UploadDate = lens _sc1UploadDate (\s a -> s { _sc1UploadDate = a }) . mapping _Time -- | The name of the user the signing certificate is associated with. sc1UserName :: Lens' SigningCertificate Text sc1UserName = lens _sc1UserName (\s a -> s { _sc1UserName = a }) instance FromXML SigningCertificate where parseXML x = SigningCertificate <$> x .@ "CertificateBody" <*> x .@ "CertificateId" <*> x .@ "Status" <*> x .@? "UploadDate" <*> x .@ "UserName" instance ToQuery SigningCertificate where toQuery SigningCertificate{..} = mconcat [ "CertificateBody" =? _sc1CertificateBody , "CertificateId" =? _sc1CertificateId , "Status" =? _sc1Status , "UploadDate" =? _sc1UploadDate , "UserName" =? _sc1UserName ] data AccessKeyMetadata = AccessKeyMetadata { _akmAccessKeyId :: Maybe Text , _akmCreateDate :: Maybe ISO8601 , _akmStatus :: Maybe StatusType , _akmUserName :: Maybe Text } deriving (Eq, Read, Show) -- | 'AccessKeyMetadata' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'akmAccessKeyId' @::@ 'Maybe' 'Text' -- -- * 'akmCreateDate' @::@ 'Maybe' 'UTCTime' -- -- * 'akmStatus' @::@ 'Maybe' 'StatusType' -- -- * 'akmUserName' @::@ 'Maybe' 'Text' -- accessKeyMetadata :: AccessKeyMetadata accessKeyMetadata = AccessKeyMetadata { _akmUserName = Nothing , _akmAccessKeyId = Nothing , _akmStatus = Nothing , _akmCreateDate = Nothing } -- | The ID for this access key. akmAccessKeyId :: Lens' AccessKeyMetadata (Maybe Text) akmAccessKeyId = lens _akmAccessKeyId (\s a -> s { _akmAccessKeyId = a }) -- | The date when the access key was created. akmCreateDate :: Lens' AccessKeyMetadata (Maybe UTCTime) akmCreateDate = lens _akmCreateDate (\s a -> s { _akmCreateDate = a }) . mapping _Time -- | The status of the access key. 'Active' means the key is valid for API calls; 'Inactive' means it is not. akmStatus :: Lens' AccessKeyMetadata (Maybe StatusType) akmStatus = lens _akmStatus (\s a -> s { _akmStatus = a }) -- | The name of the IAM user that the key is associated with. akmUserName :: Lens' AccessKeyMetadata (Maybe Text) akmUserName = lens _akmUserName (\s a -> s { _akmUserName = a }) instance FromXML AccessKeyMetadata where parseXML x = AccessKeyMetadata <$> x .@? "AccessKeyId" <*> x .@? "CreateDate" <*> x .@? "Status" <*> x .@? "UserName" instance ToQuery AccessKeyMetadata where toQuery AccessKeyMetadata{..} = mconcat [ "AccessKeyId" =? _akmAccessKeyId , "CreateDate" =? _akmCreateDate , "Status" =? _akmStatus , "UserName" =? _akmUserName ] newtype PolicyUser = PolicyUser { _puUserName :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'PolicyUser' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'puUserName' @::@ 'Maybe' 'Text' -- policyUser :: PolicyUser policyUser = PolicyUser { _puUserName = Nothing } -- | The name (friendly name, not ARN) identifying the user. puUserName :: Lens' PolicyUser (Maybe Text) puUserName = lens _puUserName (\s a -> s { _puUserName = a }) instance FromXML PolicyUser where parseXML x = PolicyUser <$> x .@? "UserName" instance ToQuery PolicyUser where toQuery PolicyUser{..} = mconcat [ "UserName" =? _puUserName ]
kim/amazonka
amazonka-iam/gen/Network/AWS/IAM/Types.hs
mpl-2.0
86,686
0
28
22,551
14,933
8,488
6,445
-1
-1
module System.Delta.FRPUtils where import Control.Concurrent import Control.Monad import FRP.Sodium data Ticker a = Ticker{ tickerInterval :: Int , tickerEvent :: Event a , tickerTerminate :: IO () } periodical :: Int -- ^ Milliseconds -> a -- ^ Item that is sent periodically -> IO (Ticker a) periodical ms v = do (e,push) <- sync $ newEvent tId <- forkIO . forever $ do threadDelay $ 1000 * ms sync $ push v return $ Ticker ms e (killThread tId)
kryoxide/delta
src/main/delta/System/Delta/FRPUtils.hs
lgpl-3.0
565
0
12
197
165
87
78
16
1
{- Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} program = drawingOf(circle(f(-10))) f(t)|t<-8 = t + 10 |otherwise = t + 8
google/codeworld
codeworld-compiler/test/testcases/accidentalPatternGuard/source.hs
apache-2.0
689
0
11
133
65
32
33
3
1
module ToiletPaper.A260112Spec (main, spec) where import Test.Hspec import ToiletPaper.A260112 (a260112) main :: IO () main = hspec spec spec :: Spec spec = describe "A260112" $ it "correctly computes the first 20 elements" $ take 20 (map a260112 [0..]) `shouldBe` expectedValue where expectedValue = [0,1,2,3,2,3,4,5,3,4,5,6,4,5,6,7,3,4,5,6]
peterokagey/haskellOEIS
test/ToiletPaper/A260112Spec.hs
apache-2.0
357
0
10
59
160
95
65
10
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {- Copyright 2017 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Main where import Compile import Control.Applicative import Control.Monad import Control.Monad.Trans import Data.Aeson import qualified Data.ByteString as B import Data.ByteString.Builder (toLazyByteString) import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as LB import qualified Data.Text as T import qualified Data.Text.IO as T import HIndent (reformat) import HIndent.Types (defaultConfig) import Snap.Core import Snap.Http.Server (quickHttpServe) import Snap.Util.FileServe import System.Directory import System.FilePath import Collaboration import Comment import DataUtil import Folder import qualified Funblocks as FB import Model import SnapUtil main :: IO () main = do hasClientId <- doesFileExist "web/clientId.txt" unless hasClientId $ do putStrLn "WARNING: Missing web/clientId.txt" putStrLn "User logins will not function properly!" clientId <- case hasClientId of True -> do txt <- T.readFile "web/clientId.txt" return (ClientId (Just (T.strip txt))) False -> return (ClientId Nothing) quickHttpServe $ (processBody >> site clientId) <|> site clientId site :: ClientId -> Snap () site clientId = route ([ ("compile", compileHandler), ("loadSource", loadSourceHandler), ("run", runHandler), ("runJS", runHandler), ("runMsg", runMessageHandler), ("haskell", serveFile "web/env.html"), ("indent", indentHandler) ] ++ (collabRoutes clientId) ++ (commentRoutes clientId) ++ (folderRoutes clientId) ++ (FB.funblockRoutes $ currToFB clientId)) <|> serveDirectory "web" where currToFB clientId' = case clientId' of ClientId a -> FB.ClientId a compileHandler :: Snap () compileHandler = do mode <- getBuildMode Just source <- getParam "source" let programId = sourceToProgramId source deployId = sourceToDeployId source success <- liftIO $ do ensureProgramDir mode programId B.writeFile (buildRootDir mode </> sourceFile programId) source writeDeployLink mode deployId programId compileIfNeeded mode programId unless success $ modifyResponse $ setResponseCode 500 modifyResponse $ setContentType "text/plain" let result = CompileResult (unProgramId programId) (unDeployId deployId) writeLBS (encode result) loadSourceHandler :: Snap () loadSourceHandler = do mode <- getBuildMode programId <- getHashParam False mode modifyResponse $ setContentType "text/x-haskell" serveFile (buildRootDir mode </> sourceFile programId) runHandler :: Snap () runHandler = do mode <- getBuildMode programId <- getHashParam True mode liftIO $ compileIfNeeded mode programId modifyResponse $ setContentType "text/javascript" serveFile (buildRootDir mode </> targetFile programId) runMessageHandler :: Snap () runMessageHandler = do mode <- getBuildMode programId <- getHashParam False mode modifyResponse $ setContentType "text/plain" serveFile (buildRootDir mode </> resultFile programId) indentHandler :: Snap () indentHandler = do Just source <- getParam "source" case reformat defaultConfig Nothing source of Left err -> do modifyResponse $ setResponseCode 500 . setContentType "text/plain" writeLBS $ LB.fromStrict $ BC.pack err Right res -> do modifyResponse $ setContentType "text/x-haskell" writeLBS $ toLazyByteString res compileIfNeeded :: BuildMode -> ProgramId -> IO Bool compileIfNeeded mode programId = do hasResult <- doesFileExist (buildRootDir mode </> resultFile programId) hasTarget <- doesFileExist (buildRootDir mode </> targetFile programId) if hasResult then return hasTarget else compileSource FullBuild (buildRootDir mode </> sourceFile programId) (buildRootDir mode </> targetFile programId) (buildRootDir mode </> resultFile programId) (getMode mode) getMode :: BuildMode -> String getMode (BuildMode m) = m
parvmor/codeworld
codeworld-server/src/Main.hs
apache-2.0
5,052
0
20
1,289
1,136
563
573
116
2
<?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="da-DK"> <title>HTTPS Info Add-on</title> <maps> <homeID>httpsinfo</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
secdec/zap-extensions
addOns/httpsInfo/src/main/javahelp/org/zaproxy/zap/extension/httpsinfo/resources/help_da_DK/helpset_da_DK.hs
apache-2.0
968
77
67
157
413
209
204
-1
-1
module SandboxPath where import Data.Maybe import Data.Traversable (traverse) import Control.Applicative ((<$>)) import System.Directory import System.FilePath import Data.List import Data.Char -- From ghc-mod mightExist :: FilePath -> IO (Maybe FilePath) mightExist f = do exists <- doesFileExist f return $ if exists then (Just f) else (Nothing) -- | Get path to sandbox config file getSandboxDb :: IO (Maybe FilePath) getSandboxDb = do currentDir <- getCurrentDirectory config <- traverse readFile =<< mightExist (currentDir </> "cabal.sandbox.config") return $ (extractSandboxDbDir =<< config) -- | Extract the sandbox package db directory from the cabal.sandbox.config file. -- Exception is thrown if the sandbox config file is broken. extractSandboxDbDir :: String -> Maybe FilePath extractSandboxDbDir conf = extractValue <$> parse conf where key = "package-db:" keyLen = length key parse = listToMaybe . filter (key `isPrefixOf`) . lines extractValue = dropWhileEnd isSpace . dropWhile isSpace . drop keyLen -- main = print =<< getSandboxDb
nfjinjing/halive
exec/SandboxPath.hs
bsd-2-clause
1,093
0
11
192
266
142
124
23
2