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
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.ES.MX.Rules (rules) where import qualified Data.HashMap.Strict as HashMap import Data.Maybe import Data.String import qualified Data.Text as Text import Prelude import Duckling.Dimensions.Types import Duckling.Numeral.Helpers import Duckling.Regex.Types import Duckling.Types ruleDecimalWithThousandsSeparator :: Rule ruleDecimalWithThousandsSeparator = Rule { name = "decimal with thousands separator" , pattern = [regex "(\\d+(\\,\\d\\d\\d)+\\.\\d+)"] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match : _)) : _) -> parseDouble (Text.replace "," Text.empty match) >>= double _ -> Nothing } ruleDecimalNumeral :: Rule ruleDecimalNumeral = Rule { name = "decimal number ." , pattern = [regex "(\\d*\\.\\d+)"] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match : _)) : _) -> parseDecimal False match _ -> Nothing } ruleIntegerWithThousandsSeparator :: Rule ruleIntegerWithThousandsSeparator = Rule { name = "integer with thousands separator ," , pattern = [regex "(\\d{1,3}(\\,\\d\\d\\d){1,5})"] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match : _)) : _) -> parseDouble (Text.replace "," Text.empty match) >>= double _ -> Nothing } rules :: [Rule] rules = [ ruleDecimalNumeral , ruleDecimalWithThousandsSeparator , ruleIntegerWithThousandsSeparator ]
facebookincubator/duckling
Duckling/Numeral/ES/MX/Rules.hs
bsd-3-clause
1,704
0
17
317
389
227
162
41
2
{-# LANGUAGE OverloadedStrings #-} -- | Documentation page controller. module HL.C.Documentation where import HL.C import HL.V.Documentation -- | Documentation controller. getDocumentationR :: C Html getDocumentationR = senza documentationV
yogsototh/hl
src/HL/C/Documentation.hs
bsd-3-clause
247
0
5
34
37
23
14
7
1
module Main where import System.Environment import Text.Read import Math main :: IO () main = do args <- getArgs putStrLn $ unlines $ exec args exec :: [String] -> [String] exec args = case args of [] -> exampleI (0 :: Int) (x:_) -> --let r = readMaybe x in case readMaybe x :: Maybe Int of Just i -> exampleI i Nothing -> case readMaybe x :: Maybe Double of Just d -> exampleF d Nothing -> []
ott8bre/first-haskell
executable/Main.hs
bsd-3-clause
491
0
14
176
175
89
86
21
4
module Language.Haskell.Preprocess ( ModuleName(..), SrcTreePath, Pkg, unSTP,stFile,stDir,stpStr, pkgRoot,pkgCabalFile,pkgModules,pkgMacros,pkgIncludeDirs,pkgDefaultExtensions, directoriesThatRequireAutotoolsConfiguration, configureWithAutotools,configureWithAutotoolsRecursive, analyseCopy,analyseConfiguredCopy, scan, scanPkg, processFile, parseCode) where import Language.Haskell.Preprocess.Internal
sourcegraph/preprocess-haskell
src/Language/Haskell/Preprocess.hs
bsd-3-clause
414
0
5
29
86
58
28
12
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} module Main where import Control.Concurrent.STM (TVar, newTVarIO) import qualified Data.Map.Strict as Map import Data.UUID (toString) import Lucid (Html, body_, content_, doctypehtml_, head_, href_, link_, meta_, name_, rel_, script_, src_, title_) import Network.Wai (Application) import Network.Wai.Handler.Warp (run) import Servant ((:<|>) ((:<|>)), (:>), Get, Proxy (Proxy), Raw, Server, serve, serveDirectory) import Servant.HTML.Lucid (HTML) import System.Random (randomIO) import qualified Api.Server import qualified Api.Types type SiteApi = "api" :> Api.Types.Api :<|> Get '[HTML] (Html ()) :<|> "assets" :> Raw siteApi :: Proxy SiteApi siteApi = Proxy server :: TVar Api.Types.BookDB -> Server SiteApi server bookDb = apiServer :<|> home :<|> assets where home = return homePage apiServer = Api.Server.server bookDb assets = serveDirectory "frontend/dist" homePage :: Html () homePage = doctypehtml_ $ do head_ $ do title_ "Example Servant-Elm App" meta_ [ name_ "viewport" , content_ "width=device-width, initial-scale=1" ] link_ [ rel_ "stylesheet" , href_ "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" ] script_ [src_ "assets/app.js"] "" body_ (script_ "var elmApp = Elm.Main.fullscreen()") app :: TVar Api.Types.BookDB -> Application app bookDb = serve siteApi (server bookDb) main :: IO () main = do let port = 8000 uuid1 <- toString <$> randomIO uuid2 <- toString <$> randomIO let books = [ Api.Types.Book (Just uuid1) "Real World Haskell" (Api.Types.Author "Bryan O'Sullivan, Don Stewart, and John Goerzen" 1970) , Api.Types.Book (Just uuid2) "Learn You a Haskell for Great Good" (Api.Types.Author "Miran Lipovača" 1970) ] bookDb <- newTVarIO (Map.fromList (zip [uuid1, uuid2] books)) putStrLn $ "Serving on port " ++ show port ++ "..." run port (app bookDb)
mattjbray/servant-elm-example-app
backend/Main.hs
bsd-3-clause
2,465
0
14
792
609
333
276
53
1
-- | -- Module : Crypto.Number.Prime -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : Good {-# LANGUAGE BangPatterns #-} module Crypto.Number.Prime ( generatePrime , generateSafePrime , isProbablyPrime , findPrimeFrom , findPrimeFromWith , primalityTestMillerRabin , primalityTestNaive , primalityTestFermat , isCoprime ) where import Crypto.Internal.Imports import Crypto.Number.Compat import Crypto.Number.Generate import Crypto.Number.Basic (sqrti, gcde) import Crypto.Number.ModArithmetic (expSafe) import Crypto.Random.Types import Crypto.Random.Probabilistic import Crypto.Error import Data.Bits -- | Returns if the number is probably prime. -- First a list of small primes are implicitely tested for divisibility, -- then a fermat primality test is used with arbitrary numbers and -- then the Miller Rabin algorithm is used with an accuracy of 30 recursions. isProbablyPrime :: Integer -> Bool isProbablyPrime !n | any (\p -> p `divides` n) (filter (< n) firstPrimes) = False | n >= 2 && n <= 2903 = True | primalityTestFermat 50 (n `div` 2) n = primalityTestMillerRabin 30 n | otherwise = False -- | Generate a prime number of the required bitsize (i.e. in the range -- [2^(b-1)+2^(b-2), 2^b)). -- -- May throw a 'CryptoError_PrimeSizeInvalid' if the requested size is less -- than 5 bits, as the smallest prime meeting these conditions is 29. -- This function requires that the two highest bits are set, so that when -- multiplied with another prime to create a key, it is guaranteed to be of -- the proper size. generatePrime :: MonadRandom m => Int -> m Integer generatePrime bits = do if bits < 5 then throwCryptoError $ CryptoFailed $ CryptoError_PrimeSizeInvalid else do sp <- generateParams bits (Just SetTwoHighest) True let prime = findPrimeFrom sp if prime < 1 `shiftL` bits then return $ prime else generatePrime bits -- | Generate a prime number of the form 2p+1 where p is also prime. -- it is also knowed as a Sophie Germaine prime or safe prime. -- -- The number of safe prime is significantly smaller to the number of prime, -- as such it shouldn't be used if this number is supposed to be kept safe. -- -- May throw a 'CryptoError_PrimeSizeInvalid' if the requested size is less than -- 6 bits, as the smallest safe prime with the two highest bits set is 59. generateSafePrime :: MonadRandom m => Int -> m Integer generateSafePrime bits = do if bits < 6 then throwCryptoError $ CryptoFailed $ CryptoError_PrimeSizeInvalid else do sp <- generateParams bits (Just SetTwoHighest) True let p = findPrimeFromWith (\i -> isProbablyPrime (2*i+1)) (sp `div` 2) let val = 2 * p + 1 if val < 1 `shiftL` bits then return $ val else generateSafePrime bits -- | Find a prime from a starting point where the property hold. findPrimeFromWith :: (Integer -> Bool) -> Integer -> Integer findPrimeFromWith prop !n | even n = findPrimeFromWith prop (n+1) | otherwise = if not (isProbablyPrime n) then findPrimeFromWith prop (n+2) else if prop n then n else findPrimeFromWith prop (n+2) -- | Find a prime from a starting point with no specific property. findPrimeFrom :: Integer -> Integer findPrimeFrom n = case gmpNextPrime n of GmpSupported p -> p GmpUnsupported -> findPrimeFromWith (\_ -> True) n -- | Miller Rabin algorithm return if the number is probably prime or composite. -- the tries parameter is the number of recursion, that determines the accuracy of the test. primalityTestMillerRabin :: Int -> Integer -> Bool primalityTestMillerRabin tries !n = case gmpTestPrimeMillerRabin tries n of GmpSupported b -> b GmpUnsupported -> probabilistic run where run | n <= 3 = error "Miller-Rabin requires tested value to be > 3" | even n = return False | tries <= 0 = error "Miller-Rabin tries need to be > 0" | otherwise = loop <$> generateTries tries !nm1 = n-1 !nm2 = n-2 (!s,!d) = (factorise 0 nm1) generateTries 0 = return [] generateTries t = do v <- generateBetween 2 nm2 vs <- generateTries (t-1) return (v:vs) -- factorise n-1 into the form 2^s*d factorise :: Integer -> Integer -> (Integer, Integer) factorise !si !vi | vi `testBit` 0 = (si, vi) | otherwise = factorise (si+1) (vi `shiftR` 1) -- probably faster to not shift v continously, but just once. expmod = expSafe -- when iteration reach zero, we have a probable prime loop [] = True loop (w:ws) = let x = expmod w d n in if x == (1 :: Integer) || x == nm1 then loop ws else loop' ws ((x*x) `mod` n) 1 -- loop from 1 to s-1. if we reach the end then it's composite loop' ws !x2 !r | r == s = False | x2 == 1 = False | x2 /= nm1 = loop' ws ((x2*x2) `mod` n) (r+1) | otherwise = loop ws {- n < z -> witness to test 1373653 [2,3] 9080191 [31,73] 4759123141 [2,7,61] 2152302898747 [2,3,5,7,11] 3474749660383 [2,3,5,7,11,13] 341550071728321 [2,3,5,7,11,13,17] -} -- | Probabilitic Test using Fermat primility test. -- Beware of Carmichael numbers that are Fermat liars, i.e. this test -- is useless for them. always combines with some other test. primalityTestFermat :: Int -- ^ number of iterations of the algorithm -> Integer -- ^ starting a -> Integer -- ^ number to test for primality -> Bool primalityTestFermat n a p = and $ map expTest [a..(a+fromIntegral n)] where !pm1 = p-1 expTest i = expSafe i pm1 p == 1 -- | Test naively is integer is prime. -- while naive, we skip even number and stop iteration at i > sqrt(n) primalityTestNaive :: Integer -> Bool primalityTestNaive n | n <= 1 = False | n == 2 = True | even n = False | otherwise = search 3 where !ubound = snd $ sqrti n search !i | i > ubound = True | i `divides` n = False | otherwise = search (i+2) -- | Test is two integer are coprime to each other isCoprime :: Integer -> Integer -> Bool isCoprime m n = case gcde m n of (_,_,d) -> d == 1 -- | List of the first primes till 2903. firstPrimes :: [Integer] firstPrimes = [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 , 101 , 103 , 107 , 109 , 113 , 127 , 131 , 137 , 139 , 149 , 151 , 157 , 163 , 167 , 173 , 179 , 181 , 191 , 193 , 197 , 199 , 211 , 223 , 227 , 229 , 233 , 239 , 241 , 251 , 257 , 263 , 269 , 271 , 277 , 281 , 283 , 293 , 307 , 311 , 313 , 317 , 331 , 337 , 347 , 349 , 353 , 359 , 367 , 373 , 379 , 383 , 389 , 397 , 401 , 409 , 419 , 421 , 431 , 433 , 439 , 443 , 449 , 457 , 461 , 463 , 467 , 479 , 487 , 491 , 499 , 503 , 509 , 521 , 523 , 541 , 547 , 557 , 563 , 569 , 571 , 577 , 587 , 593 , 599 , 601 , 607 , 613 , 617 , 619 , 631 , 641 , 643 , 647 , 653 , 659 , 661 , 673 , 677 , 683 , 691 , 701 , 709 , 719 , 727 , 733 , 739 , 743 , 751 , 757 , 761 , 769 , 773 , 787 , 797 , 809 , 811 , 821 , 823 , 827 , 829 , 839 , 853 , 857 , 859 , 863 , 877 , 881 , 883 , 887 , 907 , 911 , 919 , 929 , 937 , 941 , 947 , 953 , 967 , 971 , 977 , 983 , 991 , 997 , 1009 , 1013 , 1019 , 1021 , 1031 , 1033 , 1039 , 1049 , 1051 , 1061 , 1063 , 1069 , 1087 , 1091 , 1093 , 1097 , 1103 , 1109 , 1117 , 1123 , 1129 , 1151 , 1153 , 1163 , 1171 , 1181 , 1187 , 1193 , 1201 , 1213 , 1217 , 1223 , 1229 , 1231 , 1237 , 1249 , 1259 , 1277 , 1279 , 1283 , 1289 , 1291 , 1297 , 1301 , 1303 , 1307 , 1319 , 1321 , 1327 , 1361 , 1367 , 1373 , 1381 , 1399 , 1409 , 1423 , 1427 , 1429 , 1433 , 1439 , 1447 , 1451 , 1453 , 1459 , 1471 , 1481 , 1483 , 1487 , 1489 , 1493 , 1499 , 1511 , 1523 , 1531 , 1543 , 1549 , 1553 , 1559 , 1567 , 1571 , 1579 , 1583 , 1597 , 1601 , 1607 , 1609 , 1613 , 1619 , 1621 , 1627 , 1637 , 1657 , 1663 , 1667 , 1669 , 1693 , 1697 , 1699 , 1709 , 1721 , 1723 , 1733 , 1741 , 1747 , 1753 , 1759 , 1777 , 1783 , 1787 , 1789 , 1801 , 1811 , 1823 , 1831 , 1847 , 1861 , 1867 , 1871 , 1873 , 1877 , 1879 , 1889 , 1901 , 1907 , 1913 , 1931 , 1933 , 1949 , 1951 , 1973 , 1979 , 1987 , 1993 , 1997 , 1999 , 2003 , 2011 , 2017 , 2027 , 2029 , 2039 , 2053 , 2063 , 2069 , 2081 , 2083 , 2087 , 2089 , 2099 , 2111 , 2113 , 2129 , 2131 , 2137 , 2141 , 2143 , 2153 , 2161 , 2179 , 2203 , 2207 , 2213 , 2221 , 2237 , 2239 , 2243 , 2251 , 2267 , 2269 , 2273 , 2281 , 2287 , 2293 , 2297 , 2309 , 2311 , 2333 , 2339 , 2341 , 2347 , 2351 , 2357 , 2371 , 2377 , 2381 , 2383 , 2389 , 2393 , 2399 , 2411 , 2417 , 2423 , 2437 , 2441 , 2447 , 2459 , 2467 , 2473 , 2477 , 2503 , 2521 , 2531 , 2539 , 2543 , 2549 , 2551 , 2557 , 2579 , 2591 , 2593 , 2609 , 2617 , 2621 , 2633 , 2647 , 2657 , 2659 , 2663 , 2671 , 2677 , 2683 , 2687 , 2689 , 2693 , 2699 , 2707 , 2711 , 2713 , 2719 , 2729 , 2731 , 2741 , 2749 , 2753 , 2767 , 2777 , 2789 , 2791 , 2797 , 2801 , 2803 , 2819 , 2833 , 2837 , 2843 , 2851 , 2857 , 2861 , 2879 , 2887 , 2897 , 2903 ] {-# INLINE divides #-} divides :: Integer -> Integer -> Bool divides i n = n `mod` i == 0
tekul/cryptonite
Crypto/Number/Prime.hs
bsd-3-clause
10,013
0
19
3,226
2,769
1,626
1,143
162
5
module Main where import Ivory.Tower.Config import Ivory.OS.FreeRTOS.Tower.STM32 import LDrive.Platforms import LDrive.Tests.CAN2UART (app) main :: IO () main = compileTowerSTM32FreeRTOS testplatform_stm32 p $ app (stm32config_clock . testplatform_stm32) testplatform_can testplatform_uart testplatform_leds where p topts = getConfig topts testPlatformParser
sorki/odrive
test/CAN2UART.hs
bsd-3-clause
411
0
8
88
89
50
39
12
1
{-# language CPP #-} -- No documentation found for Chapter "PipelineLayout" module Vulkan.Core10.PipelineLayout ( createPipelineLayout , withPipelineLayout , destroyPipelineLayout , PushConstantRange(..) , PipelineLayoutCreateInfo(..) , PipelineLayout(..) ) where import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import qualified Data.Vector (imapM_) import qualified Data.Vector (length) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.NamedType ((:::)) import Vulkan.Core10.AllocationCallbacks (AllocationCallbacks) import Vulkan.Core10.Handles (DescriptorSetLayout) import Vulkan.Core10.Handles (Device) import Vulkan.Core10.Handles (Device(..)) import Vulkan.Core10.Handles (Device(Device)) import Vulkan.Dynamic (DeviceCmds(pVkCreatePipelineLayout)) import Vulkan.Dynamic (DeviceCmds(pVkDestroyPipelineLayout)) import Vulkan.Core10.Handles (Device_T) import Vulkan.Core10.Handles (PipelineLayout) import Vulkan.Core10.Handles (PipelineLayout(..)) import Vulkan.Core10.Enums.PipelineLayoutCreateFlags (PipelineLayoutCreateFlags) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import Vulkan.Core10.Enums.ShaderStageFlagBits (ShaderStageFlags) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Exception (VulkanException(..)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Core10.Handles (PipelineLayout(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCreatePipelineLayout :: FunPtr (Ptr Device_T -> Ptr PipelineLayoutCreateInfo -> Ptr AllocationCallbacks -> Ptr PipelineLayout -> IO Result) -> Ptr Device_T -> Ptr PipelineLayoutCreateInfo -> Ptr AllocationCallbacks -> Ptr PipelineLayout -> IO Result -- | vkCreatePipelineLayout - Creates a new pipeline layout object -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCreatePipelineLayout-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkCreatePipelineLayout-pCreateInfo-parameter# @pCreateInfo@ -- /must/ be a valid pointer to a valid 'PipelineLayoutCreateInfo' -- structure -- -- - #VUID-vkCreatePipelineLayout-pAllocator-parameter# If @pAllocator@ -- is not @NULL@, @pAllocator@ /must/ be a valid pointer to a valid -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure -- -- - #VUID-vkCreatePipelineLayout-pPipelineLayout-parameter# -- @pPipelineLayout@ /must/ be a valid pointer to a -- 'Vulkan.Core10.Handles.PipelineLayout' handle -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>, -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.PipelineLayout', -- 'PipelineLayoutCreateInfo' createPipelineLayout :: forall io . (MonadIO io) => -- | @device@ is the logical device that creates the pipeline layout. Device -> -- | @pCreateInfo@ is a pointer to a 'PipelineLayoutCreateInfo' structure -- specifying the state of the pipeline layout object. PipelineLayoutCreateInfo -> -- | @pAllocator@ controls host memory allocation as described in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation> -- chapter. ("allocator" ::: Maybe AllocationCallbacks) -> io (PipelineLayout) createPipelineLayout device createInfo allocator = liftIO . evalContT $ do let vkCreatePipelineLayoutPtr = pVkCreatePipelineLayout (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkCreatePipelineLayoutPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCreatePipelineLayout is null" Nothing Nothing let vkCreatePipelineLayout' = mkVkCreatePipelineLayout vkCreatePipelineLayoutPtr pCreateInfo <- ContT $ withCStruct (createInfo) pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) pPPipelineLayout <- ContT $ bracket (callocBytes @PipelineLayout 8) free r <- lift $ traceAroundEvent "vkCreatePipelineLayout" (vkCreatePipelineLayout' (deviceHandle (device)) pCreateInfo pAllocator (pPPipelineLayout)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pPipelineLayout <- lift $ peek @PipelineLayout pPPipelineLayout pure $ (pPipelineLayout) -- | A convenience wrapper to make a compatible pair of calls to -- 'createPipelineLayout' and 'destroyPipelineLayout' -- -- To ensure that 'destroyPipelineLayout' is always called: pass -- 'Control.Exception.bracket' (or the allocate function from your -- favourite resource management library) as the last argument. -- To just extract the pair pass '(,)' as the last argument. -- withPipelineLayout :: forall io r . MonadIO io => Device -> PipelineLayoutCreateInfo -> Maybe AllocationCallbacks -> (io PipelineLayout -> (PipelineLayout -> io ()) -> r) -> r withPipelineLayout device pCreateInfo pAllocator b = b (createPipelineLayout device pCreateInfo pAllocator) (\(o0) -> destroyPipelineLayout device o0 pAllocator) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkDestroyPipelineLayout :: FunPtr (Ptr Device_T -> PipelineLayout -> Ptr AllocationCallbacks -> IO ()) -> Ptr Device_T -> PipelineLayout -> Ptr AllocationCallbacks -> IO () -- | vkDestroyPipelineLayout - Destroy a pipeline layout object -- -- == Valid Usage -- -- - #VUID-vkDestroyPipelineLayout-pipelineLayout-00299# If -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' were -- provided when @pipelineLayout@ was created, a compatible set of -- callbacks /must/ be provided here -- -- - #VUID-vkDestroyPipelineLayout-pipelineLayout-00300# If no -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' were -- provided when @pipelineLayout@ was created, @pAllocator@ /must/ be -- @NULL@ -- -- - #VUID-vkDestroyPipelineLayout-pipelineLayout-02004# @pipelineLayout@ -- /must/ not have been passed to any @vkCmd*@ command for any command -- buffers that are still in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#commandbuffers-lifecycle recording state> -- when 'destroyPipelineLayout' is called -- -- == Valid Usage (Implicit) -- -- - #VUID-vkDestroyPipelineLayout-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkDestroyPipelineLayout-pipelineLayout-parameter# If -- @pipelineLayout@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- @pipelineLayout@ /must/ be a valid -- 'Vulkan.Core10.Handles.PipelineLayout' handle -- -- - #VUID-vkDestroyPipelineLayout-pAllocator-parameter# If @pAllocator@ -- is not @NULL@, @pAllocator@ /must/ be a valid pointer to a valid -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure -- -- - #VUID-vkDestroyPipelineLayout-pipelineLayout-parent# If -- @pipelineLayout@ is a valid handle, it /must/ have been created, -- allocated, or retrieved from @device@ -- -- == Host Synchronization -- -- - Host access to @pipelineLayout@ /must/ be externally synchronized -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>, -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.PipelineLayout' destroyPipelineLayout :: forall io . (MonadIO io) => -- | @device@ is the logical device that destroys the pipeline layout. Device -> -- | @pipelineLayout@ is the pipeline layout to destroy. PipelineLayout -> -- | @pAllocator@ controls host memory allocation as described in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation> -- chapter. ("allocator" ::: Maybe AllocationCallbacks) -> io () destroyPipelineLayout device pipelineLayout allocator = liftIO . evalContT $ do let vkDestroyPipelineLayoutPtr = pVkDestroyPipelineLayout (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkDestroyPipelineLayoutPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkDestroyPipelineLayout is null" Nothing Nothing let vkDestroyPipelineLayout' = mkVkDestroyPipelineLayout vkDestroyPipelineLayoutPtr pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) lift $ traceAroundEvent "vkDestroyPipelineLayout" (vkDestroyPipelineLayout' (deviceHandle (device)) (pipelineLayout) pAllocator) pure $ () -- | VkPushConstantRange - Structure specifying a push constant range -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>, -- 'PipelineLayoutCreateInfo', -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.ShaderStageFlags' data PushConstantRange = PushConstantRange { -- | @stageFlags@ is a set of stage flags describing the shader stages that -- will access a range of push constants. If a particular stage is not -- included in the range, then accessing members of that range of push -- constants from the corresponding shader stage will return undefined -- values. -- -- #VUID-VkPushConstantRange-stageFlags-parameter# @stageFlags@ /must/ be a -- valid combination of -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.ShaderStageFlagBits' values -- -- #VUID-VkPushConstantRange-stageFlags-requiredbitmask# @stageFlags@ -- /must/ not be @0@ stageFlags :: ShaderStageFlags , -- | @offset@ and @size@ are the start offset and size, respectively, -- consumed by the range. Both @offset@ and @size@ are in units of bytes -- and /must/ be a multiple of 4. The layout of the push constant variables -- is specified in the shader. -- -- #VUID-VkPushConstantRange-offset-00294# @offset@ /must/ be less than -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxPushConstantsSize@ -- -- #VUID-VkPushConstantRange-offset-00295# @offset@ /must/ be a multiple of -- @4@ offset :: Word32 , -- | #VUID-VkPushConstantRange-size-00296# @size@ /must/ be greater than @0@ -- -- #VUID-VkPushConstantRange-size-00297# @size@ /must/ be a multiple of @4@ -- -- #VUID-VkPushConstantRange-size-00298# @size@ /must/ be less than or -- equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxPushConstantsSize@ -- minus @offset@ size :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (PushConstantRange) #endif deriving instance Show PushConstantRange instance ToCStruct PushConstantRange where withCStruct x f = allocaBytes 12 $ \p -> pokeCStruct p x (f p) pokeCStruct p PushConstantRange{..} f = do poke ((p `plusPtr` 0 :: Ptr ShaderStageFlags)) (stageFlags) poke ((p `plusPtr` 4 :: Ptr Word32)) (offset) poke ((p `plusPtr` 8 :: Ptr Word32)) (size) f cStructSize = 12 cStructAlignment = 4 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr ShaderStageFlags)) (zero) poke ((p `plusPtr` 4 :: Ptr Word32)) (zero) poke ((p `plusPtr` 8 :: Ptr Word32)) (zero) f instance FromCStruct PushConstantRange where peekCStruct p = do stageFlags <- peek @ShaderStageFlags ((p `plusPtr` 0 :: Ptr ShaderStageFlags)) offset <- peek @Word32 ((p `plusPtr` 4 :: Ptr Word32)) size <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32)) pure $ PushConstantRange stageFlags offset size instance Storable PushConstantRange where sizeOf ~_ = 12 alignment ~_ = 4 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PushConstantRange where zero = PushConstantRange zero zero zero -- | VkPipelineLayoutCreateInfo - Structure specifying the parameters of a -- newly created pipeline layout object -- -- == Valid Usage -- -- - #VUID-VkPipelineLayoutCreateInfo-setLayoutCount-00286# -- @setLayoutCount@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxBoundDescriptorSets@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03016# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_SAMPLER' and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxPerStageDescriptorSamplers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03017# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_BUFFER' -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxPerStageDescriptorUniformBuffers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03018# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_BUFFER' -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxPerStageDescriptorStorageBuffers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03019# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER', -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_SAMPLED_IMAGE', -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxPerStageDescriptorSampledImages@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03020# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_IMAGE', -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxPerStageDescriptorStorageImages@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03021# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_INPUT_ATTACHMENT' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxPerStageDescriptorInputAttachments@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-02214# The total -- number of bindings in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core13.Promoted_From_VK_EXT_inline_uniform_block.PhysicalDeviceInlineUniformBlockProperties'::@maxPerStageDescriptorInlineUniformBlocks@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03022# The total -- number of descriptors with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_SAMPLER' and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxPerStageDescriptorUpdateAfterBindSamplers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03023# The total -- number of descriptors with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_BUFFER' -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxPerStageDescriptorUpdateAfterBindUniformBuffers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03024# The total -- number of descriptors with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_BUFFER' -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxPerStageDescriptorUpdateAfterBindStorageBuffers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03025# The total -- number of descriptors with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER', -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_SAMPLED_IMAGE', -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxPerStageDescriptorUpdateAfterBindSampledImages@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03026# The total -- number of descriptors with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_IMAGE', -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxPerStageDescriptorUpdateAfterBindStorageImages@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03027# The total -- number of descriptors with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_INPUT_ATTACHMENT' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxPerStageDescriptorUpdateAfterBindInputAttachments@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-02215# The total -- number of bindings with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core13.Promoted_From_VK_EXT_inline_uniform_block.PhysicalDeviceInlineUniformBlockProperties'::@maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03028# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_SAMPLER' and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxDescriptorSetSamplers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03029# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_BUFFER' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxDescriptorSetUniformBuffers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03030# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxDescriptorSetUniformBuffersDynamic@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03031# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_BUFFER' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxDescriptorSetStorageBuffers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03032# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxDescriptorSetStorageBuffersDynamic@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03033# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER', -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_SAMPLED_IMAGE', -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxDescriptorSetSampledImages@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03034# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_IMAGE', -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxDescriptorSetStorageImages@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03035# The total -- number of descriptors in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_INPUT_ATTACHMENT' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxDescriptorSetInputAttachments@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-02216# The total -- number of bindings in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core13.Promoted_From_VK_EXT_inline_uniform_block.PhysicalDeviceInlineUniformBlockProperties'::@maxDescriptorSetInlineUniformBlocks@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03036# The total number -- of descriptors of the type -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_SAMPLER' and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxDescriptorSetUpdateAfterBindSamplers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03037# The total number -- of descriptors of the type -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_BUFFER' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxDescriptorSetUpdateAfterBindUniformBuffers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03038# The total number -- of descriptors of the type -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxDescriptorSetUpdateAfterBindUniformBuffersDynamic@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03039# The total number -- of descriptors of the type -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_BUFFER' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxDescriptorSetUpdateAfterBindStorageBuffers@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03040# The total number -- of descriptors of the type -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxDescriptorSetUpdateAfterBindStorageBuffersDynamic@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03041# The total number -- of descriptors of the type -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER', -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_SAMPLED_IMAGE', -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxDescriptorSetUpdateAfterBindSampledImages@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03042# The total number -- of descriptors of the type -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_IMAGE', -- and -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxDescriptorSetUpdateAfterBindStorageImages@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03043# The total number -- of descriptors of the type -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_INPUT_ATTACHMENT' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing.PhysicalDeviceDescriptorIndexingProperties'::@maxDescriptorSetUpdateAfterBindInputAttachments@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-02217# The total -- number of bindings with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Core13.Promoted_From_VK_EXT_inline_uniform_block.PhysicalDeviceInlineUniformBlockProperties'::@maxDescriptorSetUpdateAfterBindInlineUniformBlocks@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pPushConstantRanges-00292# Any two -- elements of @pPushConstantRanges@ /must/ not include the same stage -- in @stageFlags@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00293# @pSetLayouts@ -- /must/ not contain more than one descriptor set layout that was -- created with -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR' -- set -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03571# The total -- number of bindings in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Extensions.VK_KHR_acceleration_structure.PhysicalDeviceAccelerationStructurePropertiesKHR'::@maxPerStageDescriptorAccelerationStructures@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03572# The total -- number of bindings with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR' -- accessible to any given shader stage across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Extensions.VK_KHR_acceleration_structure.PhysicalDeviceAccelerationStructurePropertiesKHR'::@maxPerStageDescriptorUpdateAfterBindAccelerationStructures@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03573# The total -- number of bindings in descriptor set layouts created without the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT' -- bit set with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Extensions.VK_KHR_acceleration_structure.PhysicalDeviceAccelerationStructurePropertiesKHR'::@maxDescriptorSetAccelerationStructures@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-03574# The total -- number of bindings with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Extensions.VK_KHR_acceleration_structure.PhysicalDeviceAccelerationStructurePropertiesKHR'::@maxDescriptorSetUpdateAfterBindAccelerationStructures@ -- -- - #VUID-VkPipelineLayoutCreateInfo-descriptorType-02381# The total -- number of bindings with a @descriptorType@ of -- 'Vulkan.Core10.Enums.DescriptorType.DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV' -- accessible across all shader stages and across all elements of -- @pSetLayouts@ /must/ be less than or equal to -- 'Vulkan.Extensions.VK_NV_ray_tracing.PhysicalDeviceRayTracingPropertiesNV'::@maxDescriptorSetAccelerationStructures@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pImmutableSamplers-03566# The total -- number of @pImmutableSamplers@ created with @flags@ containing -- 'Vulkan.Core10.Enums.SamplerCreateFlagBits.SAMPLER_CREATE_SUBSAMPLED_BIT_EXT' -- or -- 'Vulkan.Core10.Enums.SamplerCreateFlagBits.SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT' -- across all shader stages and across all elements of @pSetLayouts@ -- /must/ be less than or equal to -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-maxDescriptorSetSubsampledSamplers ::maxDescriptorSetSubsampledSamplers> -- -- - #VUID-VkPipelineLayoutCreateInfo-pSetLayouts-04606# Any element of -- @pSetLayouts@ /must/ not have been created with the -- 'Vulkan.Core10.Enums.DescriptorSetLayoutCreateFlagBits.DESCRIPTOR_SET_LAYOUT_CREATE_HOST_ONLY_POOL_BIT_VALVE' -- bit set -- -- == Valid Usage (Implicit) -- -- - #VUID-VkPipelineLayoutCreateInfo-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO' -- -- - #VUID-VkPipelineLayoutCreateInfo-pNext-pNext# @pNext@ /must/ be -- @NULL@ -- -- - #VUID-VkPipelineLayoutCreateInfo-flags-zerobitmask# @flags@ /must/ -- be @0@ -- -- - #VUID-VkPipelineLayoutCreateInfo-pSetLayouts-parameter# If -- @setLayoutCount@ is not @0@, @pSetLayouts@ /must/ be a valid pointer -- to an array of @setLayoutCount@ valid -- 'Vulkan.Core10.Handles.DescriptorSetLayout' handles -- -- - #VUID-VkPipelineLayoutCreateInfo-pPushConstantRanges-parameter# If -- @pushConstantRangeCount@ is not @0@, @pPushConstantRanges@ /must/ be -- a valid pointer to an array of @pushConstantRangeCount@ valid -- 'PushConstantRange' structures -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>, -- 'Vulkan.Core10.Handles.DescriptorSetLayout', -- 'Vulkan.Core10.Enums.PipelineLayoutCreateFlags.PipelineLayoutCreateFlags', -- 'PushConstantRange', 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'createPipelineLayout' data PipelineLayoutCreateInfo = PipelineLayoutCreateInfo { -- | @flags@ is reserved for future use. flags :: PipelineLayoutCreateFlags , -- | @pSetLayouts@ is a pointer to an array of -- 'Vulkan.Core10.Handles.DescriptorSetLayout' objects. setLayouts :: Vector DescriptorSetLayout , -- | @pPushConstantRanges@ is a pointer to an array of 'PushConstantRange' -- structures defining a set of push constant ranges for use in a single -- pipeline layout. In addition to descriptor set layouts, a pipeline -- layout also describes how many push constants /can/ be accessed by each -- stage of the pipeline. -- -- Note -- -- Push constants represent a high speed path to modify constant data in -- pipelines that is expected to outperform memory-backed resource updates. pushConstantRanges :: Vector PushConstantRange } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (PipelineLayoutCreateInfo) #endif deriving instance Show PipelineLayoutCreateInfo instance ToCStruct PipelineLayoutCreateInfo where withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p) pokeCStruct p PipelineLayoutCreateInfo{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr PipelineLayoutCreateFlags)) (flags) lift $ poke ((p `plusPtr` 20 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (setLayouts)) :: Word32)) pPSetLayouts' <- ContT $ allocaBytes @DescriptorSetLayout ((Data.Vector.length (setLayouts)) * 8) lift $ Data.Vector.imapM_ (\i e -> poke (pPSetLayouts' `plusPtr` (8 * (i)) :: Ptr DescriptorSetLayout) (e)) (setLayouts) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr DescriptorSetLayout))) (pPSetLayouts') lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (pushConstantRanges)) :: Word32)) pPPushConstantRanges' <- ContT $ allocaBytes @PushConstantRange ((Data.Vector.length (pushConstantRanges)) * 12) lift $ Data.Vector.imapM_ (\i e -> poke (pPPushConstantRanges' `plusPtr` (12 * (i)) :: Ptr PushConstantRange) (e)) (pushConstantRanges) lift $ poke ((p `plusPtr` 40 :: Ptr (Ptr PushConstantRange))) (pPPushConstantRanges') lift $ f cStructSize = 48 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) f instance FromCStruct PipelineLayoutCreateInfo where peekCStruct p = do flags <- peek @PipelineLayoutCreateFlags ((p `plusPtr` 16 :: Ptr PipelineLayoutCreateFlags)) setLayoutCount <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32)) pSetLayouts <- peek @(Ptr DescriptorSetLayout) ((p `plusPtr` 24 :: Ptr (Ptr DescriptorSetLayout))) pSetLayouts' <- generateM (fromIntegral setLayoutCount) (\i -> peek @DescriptorSetLayout ((pSetLayouts `advancePtrBytes` (8 * (i)) :: Ptr DescriptorSetLayout))) pushConstantRangeCount <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32)) pPushConstantRanges <- peek @(Ptr PushConstantRange) ((p `plusPtr` 40 :: Ptr (Ptr PushConstantRange))) pPushConstantRanges' <- generateM (fromIntegral pushConstantRangeCount) (\i -> peekCStruct @PushConstantRange ((pPushConstantRanges `advancePtrBytes` (12 * (i)) :: Ptr PushConstantRange))) pure $ PipelineLayoutCreateInfo flags pSetLayouts' pPushConstantRanges' instance Zero PipelineLayoutCreateInfo where zero = PipelineLayoutCreateInfo zero mempty mempty
expipiplus1/vulkan
src/Vulkan/Core10/PipelineLayout.hs
bsd-3-clause
43,090
0
18
6,400
3,711
2,278
1,433
-1
-1
module Y21.D10 where import qualified Data.Map.Strict as M import Imports opener2closer :: Map Char Char opener2closer = M.fromList $ zip "([{<" ")]}>" reduce :: String -> String -> (String, String) -- stack -> input -> (stack, input) reduce stack [] = (stack, []) -- stop (exhausted input) reduce stack (i:input) = if i `M.member` opener2closer then reduce (i:stack) input -- continue (push opener) else case stack of [] -> (stack, i:input) -- stop (unexpected closer) (x:xs) -> if opener2closer M.! x == i then reduce xs input -- continue (pop opener) else (stack, i:input) -- stop (closer doesn't match opener) solve1 :: String -> Int solve1 = sum . fmap (score . reduce "") . lines where score (_, []) = 0 score (_, i:_) = closer2score M.! i closer2score = M.fromList $ zip ")]}>" [3, 57, 1197, 25137] solve2 :: String -> Int solve2 = middle . sort . filter (/= 0) . fmap (score . reduce "") . lines where score (xs, []) = foldl' (\s x -> 5 * s + opener2score M.! x) 0 xs score _ = 0 opener2score = M.fromList $ zip "([{<" [1, 2, 3, 4] middle xs = length xs & \l -> if even l then error "even length" else xs !! (l `quot` 2)
oshyshko/adventofcode
src/Y21/D10.hs
bsd-3-clause
1,430
0
12
515
489
270
219
37
4
import Graphics.Gloss import AI.HNN.FF.Network import Control.Arrow ((&&&)) import Numeric.LinearAlgebra trainingSet :: Samples Float trainingSet = [ (fromList [0, 0], fromList [0]) , (fromList [0, 1], fromList [1]) , (fromList [1, 0], fromList [1]) , (fromList [1, 1], fromList [0]) ] samples :: [Numeric.LinearAlgebra.Vector Float] samples = map fst trainingSet ++ [ fromList [x, y] | x <- [0.0, 0.025..1], y <- [0.0, 0.025..1] ] toRepr :: (Numeric.LinearAlgebra.Vector Float, Numeric.LinearAlgebra.Vector Float) -> (Float, Float, Color) toRepr (inp, out) = ( (inp @> 0)*600 - 300, (inp @> 1)*600 - 300, if (out @> 0) >= 0.5 then red else blue) toPicture :: (Float, Float, Color) -> Picture toPicture (x, y, color) = Color color $ Translate x (y-100) $ circleSolid 5 main :: IO () main = do n <- createNetwork 2 [2] 1 let n' = trainNTimes 1000 0.8 tanh tanh' n trainingSet let outputs = map (id &&& output n' tanh) samples let prePics = map toRepr outputs let pictures = Pictures $ map toPicture prePics ++ header display (InWindow "hnn HEAD meets gloss on XOR" (700,700) (0,0)) white pictures header :: [Picture] header = [ Translate (-300) 310 $ Scale 0.2 0.2 $ Text "hnn feed-forward net, trained to simulate XOR" , Translate (-250) 280 $ Color red $ circleSolid 5 , Translate (-200) 280 $ Scale 0.1 0.1 $ Text "x `xor` y near 1" , Translate 50 280 $ Color blue $ circleSolid 5 , Translate 100 280 $ Scale 0.1 0.1 $ Text "x `xor` y near 0" ]
alpmestan/hnn-gloss
Main.hs
bsd-3-clause
1,619
3
13
426
697
362
335
32
2
module PartialGame ( PartialGame(..) , partialGame , unPartialGame , partialGameFor ) where import Board (cluesFor) import Clues (Clues) import Game (Game(..)) import PartialBoard (PartialBoard) data PartialGame = PartialGame { getPartialGameBoard :: PartialBoard, getPartialGameClues :: Clues } deriving (Eq, Ord, Show) -- Constructor for a PartialGame partialGame :: PartialBoard -> Clues -> PartialGame partialGame pb cs = PartialGame pb cs -- Deconstructor for a PartialGame unPartialGame :: PartialGame -> (PartialBoard, Clues) unPartialGame (PartialGame pb cs) = (pb, cs) -- Returns the PartialGame formed by taking the PartialBoard of the given Game -- and the Clues calculated from the Board of the given Game. partialGameFor :: Game -> PartialGame partialGameFor g = partialGame (getGamePartialBoard g) (cluesFor $ getGameBoard g)
jameshales/voltorb-flip
src/PartialGame.hs
bsd-3-clause
859
0
8
136
201
117
84
19
1
module ParserTest where import Data.Char import LambdaCalc.Parser import LambdaCalc.Syntax import Text.Parsec prop_ParseInt i = runParser number () "" (show i) == Right (Lit (LInt i)) where types = i :: Integer prop_ParseBool b = runParser bool () "" (map toLower . show $ b) == Right (Lit (LBool b)) where types = b :: Bool
AlphaMarc/WYAH
test/ParserTest.hs
bsd-3-clause
408
0
10
138
140
73
67
9
1
{-# LANGUAGE TemplateHaskell #-} -------------------------------------------------------------------------------- -- | -- Module : Life.Model -- Copyright : (C) 2013 Sam Fredrickson -- License : BSD-style (see "LICENSE" file) -- Maintainer : Sam Fredrickson <kinghajj@gmail.com> -- Stability : experimental -- Portability : GHC -- -- The model to be simulated by the program. -------------------------------------------------------------------------------- module Life.Model where import Control.Lens import Data.Monoid import Prelude hiding (id) import qualified Data.Set as Set -- There are only two sexes. data Sex = Male | Female | None deriving (Show) -- For some reason, (^.) wants Sex to be an instance of Monoid... OK, why not? instance Monoid Sex where mempty = None Male `mappend` Male = Male Male `mappend` Female = None Female `mappend` Male = None Female `mappend` Female = Female a `mappend` None = a None `mappend` a = a instance Monoid Float where mempty = 0.0 mappend = (+) -- There are two kinds of objects, food and organisms. Both have ids, positions, -- sizes, and energies. Organisms also have velocities and genders. data Object = Food { _id :: Int , _position :: (Float, Float) , _size :: Float , _energy :: Float } | Organism { _id :: Int , _position :: (Float, Float) , _velocity :: (Float, Float) , _size :: Float , _energy :: Float , _metabolism :: Float , _gender :: Sex } deriving (Show) makeLenses ''Object isFood :: Object -> Bool isFood (Food _ _ _ _) = True isFood _ = False isOrganism :: Object -> Bool isOrganism (Organism _ _ _ _ _ _ _) = True isOrganism _ = False isMale :: Object -> Bool isMale (Organism _ _ _ _ _ _ Male) = True isMale _ = False isFemale :: Object -> Bool isFemale (Organism _ _ _ _ _ _ Female) = True isFemale _ = False collide :: Object -> Object -> Bool collide o1 o2 = let (x1, y1) = o1 ^. position (x2, y2) = o2 ^. position d = sqrt ((x2-x1)**2 + (y2-y1)**2) rs = o1 ^. size + o2 ^. size in d < rs -- Use objects' ids for determining equality and ordering. instance Eq Object where o1 == o2 = (o1 ^. id) == (o2 ^. id) instance Ord Object where compare o1 o2 = compare (o1 ^. id) (o2 ^. id) -- The model is simply a set of objects. type Model = Set.Set Object
kinghajj/Life
src/Life/Model.hs
bsd-3-clause
2,623
0
15
803
665
376
289
56
1
import Data.Map as M (Map, (!)) import qualified Data.Map as M import Data.List (elemIndex) import Control.Monad.State stableMatching :: (Ord a, Ord b) => [(a, [b])] -> [(b, [a])] -> [(a, b)] stableMatching men women = evalState (propose (M.fromList women) men) M.empty propose :: (Ord a, Ord b) => Map b [a] -> [(a, [b])] -> State (Map b (a, [b])) [(a, b)] propose _ [] = get >>= return . map (\(w, (m,_)) -> (m, w)) . M.assocs propose women ((man, pref):bachelors) = do let theOne = head pref couples <- get case M.lookup theOne couples of Nothing -> do modify $ M.insert theOne (man, (tail pref)) propose women bachelors Just (boyfriend, planB) -> do let rank x = elemIndex x (women!theOne) if rank boyfriend < rank man then propose women $ (man, tail pref): bachelors else do modify $ M.insert theOne (man, (tail pref)) . M.delete theOne propose women $ (boyfriend, planB): bachelors main = do let aPref = [('A',"YXZ"), ('B',"ZYX"),('C', "XZY")] bPref = [('X',"BAC"), ('Y',"CBA"),('Z', "ACB")] print $ stableMatching aPref bPref
Gathros/algorithm-archive
contents/stable_marriage_problem/code/haskell/stableMarriage.hs
mit
1,207
0
20
347
586
320
266
28
3
f x | x > 10 = 10 | x < 0 = 0 | otherwise = x
itchyny/vim-haskell-indent
test/guard/reindent.out.hs
mit
54
0
8
26
41
18
23
3
1
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} -- | -- Module : Network.OAuth.Type.Credentials -- Copyright : (c) Joseph Abrahamson 2013 -- License : MIT -- -- Maintainer : me@jspha.com -- Stability : experimental -- Portability : non-portable -- -- Credentials, 'Cred's, are built from 'Token's, public/private key pairs, and -- come in 3 varieties. -- -- - 'Client': Represents a particular client or consumer, used as part of -- every transaction that client signs. -- -- - 'Temporary': Resource token representing a short-lived grant to access a -- restricted set of server resources on behalf of the user. Typically used as -- part of a authorization negotiation protocol. -- -- - 'Permanent': Resource token representing a long-lived grant to access an -- authorized set of server resources on behalf of the user. Outside of access -- negotiation this is the most common kind of resource 'Token'. -- 'Token's are constructed freely from public/private pairs and have -- 'FromJSON' instances for easy retreival. 'Cred's are more strictly -- controlled and must be constructed out of a 'Client' 'Token' and -- (optionally) some kind of resource 'Token'. module Network.OAuth.Types.Credentials ( -- * Tokens and their parameterization Token (..), Key, Secret, Client, Temporary, Permanent, ResourceToken, -- ** Deserialization fromUrlEncoded, -- * Credentials and credential construction Cred, clientCred, temporaryCred, permanentCred, upgradeCred, -- * Accessors key, secret, clientToken, resourceToken, getResourceTokenDef, signingKey ) where import Control.Applicative import Control.Monad import Data.Aeson import qualified Data.ByteString as S import Data.Data import Data.Monoid import Network.HTTP.Types (parseQuery, urlEncode) import Network.OAuth.Util import Data.Text.Encoding (decodeLatin1, encodeUtf8) -- Constructors aren't exported. They're only used for derivation -- purposes. -- | 'Client' 'Cred'entials and 'Token's are assigned to a particular client by -- the server and are used for all requests sent by that client. They form the -- core component of resource specific credentials. data Client = Client deriving ( Data, Typeable ) -- | 'Temporary' 'Token's and 'Cred'entials are created during authorization -- protocols and are rarely meant to be kept for more than a few minutes. -- Typically they are authorized to access only a very select set of server -- resources. During \"three-legged authorization\" in OAuth 1.0 they are used -- to generate the authorization request URI the client sends and, after that, -- in the 'Permanent' 'Token' request. data Temporary = Temporary deriving ( Data, Typeable ) -- | 'Permanent' 'Token's and 'Cred'entials are the primary means of accessing -- server resources. They must be maintained by the client for each user who -- authorizes that client to access resources on their behalf. data Permanent = Permanent deriving ( Data, Typeable ) -- | 'Token' 'Key's are public keys which allow a server to uniquely identify a -- particular 'Token'. type Key = S.ByteString -- | 'Token' 'Secret's are private keys which the 'Token' uses for -- cryptographic purposes. type Secret = S.ByteString -- | 'Token's are public, private key pairs and come in many varieties, -- 'Client', 'Temporary', and 'Permanent'. data Token ty = Token {-# UNPACK #-} !Key {-# UNPACK #-} !Secret deriving ( Show, Eq, Ord, Data, Typeable ) class ResourceToken tk where upgradeCred' :: Token tk -> Cred tk' -> Cred tk upgradeCred' tok (Cred k s ) = CredAndToken k s tok upgradeCred' tok (CredAndToken k s _) = CredAndToken k s tok instance ResourceToken Temporary instance ResourceToken Permanent upgradeCred :: ResourceToken tk => Token tk -> Cred tk' -> Cred tk upgradeCred = upgradeCred' -- | Parses a JSON object with keys @oauth_token@ and @oauth_token_secret@, the -- standard format for OAuth 1.0. instance FromJSON (Token ty) where parseJSON = withObject "OAuth Token" $ \o -> Token <$> fmap encodeUtf8 (o .: "oauth_token") <*> fmap encodeUtf8 (o .: "oauth_token_secret") -- | Produces a JSON object using keys named @oauth_token@ and -- @oauth_token_secret@. instance ToJSON (Token ty) where toJSON (Token k s) = object [ "oauth_token" .= (decodeLatin1 k) , "oauth_token_secret" .= (decodeLatin1 s) ] -- | Parses a @www-form-urlencoded@ stream to produce a 'Token' if possible. -- The first result value is whether or not the token data is OAuth 1.0a -- compatible. -- -- >>> fromUrlEncoded "oauth_token=key&oauth_token_secret=secret" -- Just (False, Token "key" "secret") -- -- >>> fromUrlEncoded "oauth_token=key&oauth_token_secret=secret&oauth_callback_confirmed=true" -- Just (True, Token "key" "secret") -- fromUrlEncoded :: S.ByteString -> Maybe (Bool, Token ty) fromUrlEncoded = tryParse . parseQuery where tryParse q = do tok <- Token <$> lookupV "oauth_token" q <*> lookupV "oauth_token_secret" q confirmed <- lookupV "oauth_callback_confirmed" q <|> pure "" return (confirmed == "true", tok) lookupV k = join . lookup k -- | Lens on the key component of a 'Token'. key :: Functor f => (Key -> f Key) -> Token ty -> f (Token ty) key inj (Token k s) = (`Token` s) <$> inj k {-# INLINE key #-} -- | Lens on the key secret component of a 'Token'. secret :: Functor f => (Secret -> f Secret) -> Token ty -> f (Token ty) secret inj (Token k s) = Token k <$> inj s {-# INLINE secret #-} -- | 'Cred'entials pair a 'Client' 'Token' and either a 'Temporary' or -- 'Permanent' token corresponding to a particular set of user -- resources on the server. data Cred ty = Cred {-# UNPACK #-} !Key {-# UNPACK #-} !Secret | CredAndToken {-# UNPACK #-} !Key {-# UNPACK #-} !Secret {-# UNPACK #-} !(Token ty) deriving ( Show, Eq, Ord, Data, Typeable ) -- | A lens on the client 'Token' in any 'Cred'. clientToken :: Functor f => (Token Client -> f (Token Client)) -> Cred ty -> f (Cred ty) clientToken inj (Cred k s) = fixUp <$> inj (Token k s) where fixUp (Token k' s') = Cred k' s' clientToken inj (CredAndToken k s tok) = fixUp <$> inj (Token k s) where fixUp (Token k' s') = CredAndToken k' s' tok {-# INLINE clientToken #-} -- | A lens focused on the resource 'Token' when available. The only -- instances of 'ResourceToken' are 'Temporary' and 'Permanent'. This can -- be used to upgrade 'Temporary' 'Cred's to 'Permanent' 'Cred's. resourceToken :: (ResourceToken ty, ResourceToken ty', Functor f) => (Token ty -> f (Token ty')) -> Cred ty -> f (Cred ty') resourceToken inj (CredAndToken k s tok) = CredAndToken k s <$> inj tok {-# INLINE resourceToken #-} -- | OAuth assumes that, by default, any credential has a resource 'Token' that -- is by default completely blank. In this way we can talk about the resource -- 'Token' of even 'Client' 'Cred's. -- -- >>> getResourceTokenDef (clientCred $ Token "key" "secret") -- Token "" "" getResourceTokenDef :: Cred ty -> Token ty getResourceTokenDef Cred{} = Token "" "" getResourceTokenDef (CredAndToken _ _ tok) = tok clientCred :: Token Client -> Cred Client clientCred (Token k s) = Cred k s temporaryCred :: Token Temporary -> Cred Client -> Cred Temporary temporaryCred tok (Cred k s ) = CredAndToken k s tok permanentCred :: Token Permanent -> Cred Client -> Cred Permanent permanentCred tok (Cred k s ) = CredAndToken k s tok -- | Produce a 'signingKey' from a set of credentials. This is a URL -- encoded string built from the client secret and the token -- secret. -- -- If no token secret exists then the blank string is used. -- -- prop> \secret -> signingKey (clientCred $ Token "key" secret) == (pctEncode secret <> "&" <> "") signingKey :: Cred ty -> S.ByteString signingKey (Cred _ clSec) = urlEncode True clSec <> "&" <> "" signingKey (CredAndToken _ clSec (Token _ tkSec)) = pctEncode clSec <> "&" <> pctEncode tkSec
ibotty/oauthenticated
src/Network/OAuth/Types/Credentials.hs
mit
8,194
0
12
1,660
1,440
778
662
81
1
module Commands.Plugins.Spiros.IntelliJ.Run where -- import Commands.Plugins.Spiros.Extra -- import Commands.Backends.OSX
sboosali/commands-spiros
config/Commands/Plugins/Spiros/IntelliJ/Run.hs
gpl-2.0
134
0
3
21
11
9
2
1
0
module Response ( -- | @/about@ module Response.About, -- | @/calendar@ module Response.Calendar, -- | @/draw@ module Response.Draw, -- | @/graph@ module Response.Graph, -- | @/grid@ module Response.Grid, -- | @/image@ module Response.Image, -- | @/loading@ module Response.Loading, -- | 404 errors module Response.NotFound, -- | @/post@ module Response.Post, -- | @/privacy@ module Response.Privacy, -- | @/timesearch@ module Response.Search, -- | @/export@ module Response.Export ) where import Response.About import Response.Calendar import Response.Draw import Response.Graph import Response.Grid import Response.Image import Response.Loading import Response.NotFound import Response.Post import Response.Privacy import Response.Search import Response.Export
bell-kelly/courseography
app/Response.hs
gpl-3.0
968
0
5
295
150
100
50
26
0
-- {-# LANGUAGE ScopedTypeVariables #-} {- | Finite categories are categories with a finite number of arrows. In our case, this corresponds to functions with finite domains (and hence, ranges). These functions have a number of possible representations. Which is best will depend on the given function. One common property is that these functions support decidable equality. -} module SubHask.Category.Finite ( -- * Function representations -- ** Sparse permutations SparseFunction , proveSparseFunction , list2sparseFunction -- ** Sparse monoids , SparseFunctionMonoid -- ** Dense functions , DenseFunction , proveDenseFunction -- * Finite types , FiniteType (..) , ZIndex ) where import GHC.TypeLits import Data.Proxy import qualified Data.Map as Map import qualified Data.Vector.Unboxed as VU import qualified Prelude as P import SubHask.Algebra import SubHask.Algebra.Group import SubHask.Category import SubHask.Internal.Prelude import SubHask.TemplateHaskell.Deriving ------------------------------------------------------------------------------- -- | A type is finite if there is a bijection between it and the natural numbers. -- The 'index'/'deZIndex' functions implement this bijection. class KnownNat (Order a) => FiniteType a where type Order a :: Nat index :: a -> ZIndex a deZIndex :: ZIndex a -> a enumerate :: [a] getOrder :: a -> Integer instance KnownNat n => FiniteType (Z n) where type Order (Z n) = n index i = ZIndex i deZIndex (ZIndex i) = i enumerate = [ mkQuotient i | i <- [0..n - 1] ] where n = natVal (Proxy :: Proxy n) getOrder _ = natVal (Proxy :: Proxy n) -- | The 'ZIndex' class is a newtype wrapper around the natural numbers 'Z'. -- -- FIXME: remove this layer; I don't think it helps -- newtype ZIndex a = ZIndex (Z (Order a)) deriveHierarchy ''ZIndex [ ''Eq_, ''P.Ord ] -- | Swap the phantom type between two indices. swapZIndex :: Order a ~ Order b => ZIndex a -> ZIndex b swapZIndex (ZIndex i) = ZIndex i ------------------------------------------------------------------------------- -- | Represents finite functions as a map associating input/output pairs. data SparseFunction a b where SparseFunction :: ( FiniteType a , FiniteType b , Order a ~ Order b ) => Map.Map (ZIndex a) (ZIndex b) -> SparseFunction a b instance Category SparseFunction where type ValidCategory SparseFunction a = ( FiniteType a ) id = SparseFunction $ Map.empty (SparseFunction f1).(SparseFunction f2) = SparseFunction (Map.map (\a -> find a f1) f2) where find k map' = case Map.lookup k map' of Just v -> v Nothing -> swapZIndex k -- | Generates a sparse representation of a 'Hask' function. -- This proof will always succeed, although it may be computationally expensive if the 'Order' of a and b is large. proveSparseFunction :: ( ValidCategory SparseFunction a , ValidCategory SparseFunction b , Order a ~ Order b ) => (a -> b) -> SparseFunction a b proveSparseFunction f = SparseFunction $ Map.fromList $ P.map (\a -> (index a,index $ f a)) enumerate -- | Generate sparse functions on some subset of the domain. list2sparseFunction :: ( ValidCategory SparseFunction a , ValidCategory SparseFunction b , Order a ~ Order b ) => [Z (Order a)] -> SparseFunction a b list2sparseFunction xs = SparseFunction $ Map.fromList $ go xs where go [] = undefined go (y:[]) = [(ZIndex y, ZIndex $ P.head xs)] go (y1:y2:ys) = (ZIndex y1,ZIndex y2):go (y2:ys) data SparseFunctionMonoid a b where SparseFunctionMonoid :: ( FiniteType a , FiniteType b , Monoid a , Monoid b , Order a ~ Order b ) => Map.Map (ZIndex a) (ZIndex b) -> SparseFunctionMonoid a b instance Category SparseFunctionMonoid where type ValidCategory SparseFunctionMonoid a = ( FiniteType a , Monoid a ) id :: forall a. ValidCategory SparseFunctionMonoid a => SparseFunctionMonoid a a id = SparseFunctionMonoid $ Map.fromList $ P.zip xs xs where xs = P.map index (enumerate :: [a]) (SparseFunctionMonoid f1).(SparseFunctionMonoid f2) = SparseFunctionMonoid (Map.map (\a -> find a f1) f2) where find k map' = case Map.lookup k map' of Just v -> v Nothing -> index zero -- | Represents finite functions as a hash table associating input/output value pairs. data DenseFunction (a :: *) (b :: *) where DenseFunction :: ( FiniteType a , FiniteType b ) => VU.Vector Int -> DenseFunction a b instance Category DenseFunction where type ValidCategory DenseFunction (a :: *) = ( FiniteType a ) id :: forall a. ValidCategory DenseFunction a => DenseFunction a a id = DenseFunction $ VU.generate n id where n = fromIntegral $ natVal (Proxy :: Proxy (Order a)) (DenseFunction f).(DenseFunction g) = DenseFunction $ VU.map (f VU.!) g -- | Generates a dense representation of a 'Hask' function. -- This proof will always succeed; however, if the 'Order' of the finite types -- are very large, it may take a long time. -- In that case, a `SparseFunction` is probably the better representation. proveDenseFunction :: forall a b. ( ValidCategory DenseFunction a , ValidCategory DenseFunction b ) => (a -> b) -> DenseFunction a b proveDenseFunction f = DenseFunction $ VU.generate n (index2int . index . f . deZIndex . int2index) where n = fromIntegral $ natVal (Proxy :: Proxy (Order a)) --------------------------------------- -- internal functions only int2index :: Int -> ZIndex a int2index i = ZIndex $ Mod $ fromIntegral i index2int :: ZIndex a -> Int index2int (ZIndex (Mod i)) = fromIntegral i
Drezil/subhask
src/SubHask/Category/Finite.hs
bsd-3-clause
5,980
74
10
1,488
1,472
791
681
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Site ( app ) where import Data.ByteString (ByteString) import Data.ByteString.UTF8 (toString) import Snap.Core import Snap.Util.FileServe import Snap.Snaplet import Snap.Snaplet.Heist import Snap.Snaplet.MongoDB import Heist.Interpreted import Application import Example.Foo indexView :: Handler App App () indexView = ifTop $ heistLocal (bindSplices indexSplices) $ render "index" where indexSplices = [ ("documents", documentsSplice "test-collection") ] indexHandler :: Handler App App () indexHandler = insertTeamHandler >> redirect "/" insertTeamHandler :: Handler App App () insertTeamHandler = do name <- getParamOr "form1-name" (redirect "/") city <- getParamOr "form1-city" (redirect "/") eitherWithDB $ insert "test-collection" $ makeTeamDocument name city return () where getParamOr param action = getParam param >>= maybe action (return . toString) routes :: [(ByteString, Handler App App ())] routes = [ ("/", method POST indexHandler) , ("/", indexView) , ("", with heist heistServe) , ("", serveDirectory "static") ] app :: SnapletInit App App app = makeSnaplet "app" "An snaplet example application." Nothing $ do h <- nestSnaplet "heist" heist $ heistInit "templates" d <- nestSnaplet "database" database $ mongoDBInit 10 (host "127.0.0.1") "Snaplet-MongoDB" addRoutes routes return $ App h d
Palmik/snaplet-mongodb-minimalistic
examples/example1/src/Site.hs
bsd-3-clause
1,475
0
12
305
438
227
211
37
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} module Ros.Geometry_msgs.PointStamped where import qualified Prelude as P import Prelude ((.), (+), (*)) import qualified Data.Typeable as T import Control.Applicative import Ros.Internal.RosBinary import Ros.Internal.Msg.MsgInfo import qualified GHC.Generics as G import qualified Data.Default.Generics as D import Ros.Internal.Msg.HeaderSupport import qualified Ros.Geometry_msgs.Point as Point import qualified Ros.Std_msgs.Header as Header import Lens.Family.TH (makeLenses) import Lens.Family (view, set) data PointStamped = PointStamped { _header :: Header.Header , _point :: Point.Point } deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic) $(makeLenses ''PointStamped) instance RosBinary PointStamped where put obj' = put (_header obj') *> put (_point obj') get = PointStamped <$> get <*> get putMsg = putStampedMsg instance HasHeader PointStamped where getSequence = view (header . Header.seq) getFrame = view (header . Header.frame_id) getStamp = view (header . Header.stamp) setSequence = set (header . Header.seq) instance MsgInfo PointStamped where sourceMD5 _ = "c63aecb41bfdfd6b7e1fac37c7cbe7bf" msgTypeName _ = "geometry_msgs/PointStamped" instance D.Default PointStamped
acowley/roshask
msgs/Geometry_msgs/Ros/Geometry_msgs/PointStamped.hs
bsd-3-clause
1,423
1
9
255
364
215
149
35
0
module Tests.Language.Parser.Symbols ( parserSymbolTests ) where import Test.Framework ( Test , testGroup ) import Test.Framework.Providers.HUnit ( testCase ) import Test.HUnit ( Assertion ) import TestHelpers.Util ( parserTest ) import Language.Ast parserSymbolTests :: Test parserSymbolTests = testGroup "Symbol Tests" [ testCase "parses simple symbol usage as function name" test_parses_simple_symbol_usage , testCase "parses symbol variable assignment" test_parses_symbol_variable_assignment ] test_parses_simple_symbol_usage :: Assertion test_parses_simple_symbol_usage = let program = "texture(:crystal)" texture = Application (LocalVariable "texture") [ApplicationSingleArg $ EVal $ Symbol "crystal"] Nothing expected = Program [StExpression $ EApp texture] in parserTest program expected test_parses_symbol_variable_assignment :: Assertion test_parses_symbol_variable_assignment = let program = "a = :symbol" assignment = AbsoluteAssignment "a" (EVal $ Symbol "symbol") expected = Program [StAssign assignment] in parserTest program expected
rumblesan/improviz
test/Tests/Language/Parser/Symbols.hs
bsd-3-clause
1,384
0
12
450
230
124
106
29
1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sq-AL"> <title>Context Alert Filters | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
0xkasun/security-tools
src/org/zaproxy/zap/extension/alertFilters/resources/help_sq_AL/helpset_sq_AL.hs
apache-2.0
983
80
66
161
417
211
206
-1
-1
module DatatypesTermInstances where import Datatypes import TermRep {- Generated by DrIFT (Automatic class derivations for Haskell) -} {-# LINE 1 "Datatypes.hs" #-} {-* Generated by DrIFT : Look, but Don't Touch. *-} instance Term Assignment where explode (x::Assignment) = TermRep (toDyn x, f x, g x) where f (Assignment aa ab) = [explode aa,explode ab] g (Assignment _ _) xs = case TermRep.fArgs xs of [aa,ab] -> toDyn ((Assignment (TermRep.fDyn aa) (TermRep.fDyn ab))::Assignment) ; _ -> error "Term explosion error." _tc_AssignmentTc = mkTyCon "Assignment" instance Typeable Assignment where typeOf x = mkTyConApp _tc_AssignmentTc [ ] instance Term InstanceCreation where explode (x::InstanceCreation) = TermRep (toDyn x, f x, g x) where f (InstanceCreation aa ab) = [explode aa,explode ab] g (InstanceCreation _ _) xs = case TermRep.fArgs xs of [aa,ab] -> toDyn ((InstanceCreation (TermRep.fDyn aa) (TermRep.fDyn ab))::InstanceCreation) ; _ -> error "Term explosion error." _tc_InstanceCreationTc = mkTyCon "InstanceCreation" instance Typeable InstanceCreation where typeOf x = mkTyConApp _tc_InstanceCreationTc [ ] instance Term MethodInvocation where explode (x::MethodInvocation) = TermRep (toDyn x, f x, g x) where f (ExpressionInvocation aa ab ac) = [explode aa,explode ab,explode ac] f (SuperInvocation ad ae) = [explode ad,explode ae] g (ExpressionInvocation _ _ _) xs = case TermRep.fArgs xs of [aa,ab,ac] -> toDyn ((ExpressionInvocation (TermRep.fDyn aa) (TermRep.fDyn ab) (TermRep.fDyn ac))::MethodInvocation) ; _ -> error "Term explosion error." g (SuperInvocation _ _) xs = case TermRep.fArgs xs of [ad,ae] -> toDyn ((SuperInvocation (TermRep.fDyn ad) (TermRep.fDyn ae))::MethodInvocation) ; _ -> error "Term explosion error." _tc_MethodInvocationTc = mkTyCon "MethodInvocation" instance Typeable MethodInvocation where typeOf x = mkTyConApp _tc_MethodInvocationTc [ ] instance Term Arguments where explode (x::Arguments) = TermRep (toDyn x, f x, g x) where f (Arguments aa) = [explode aa] g (Arguments _) xs = case TermRep.fArgs xs of [aa] -> toDyn ((Arguments (TermRep.fDyn aa))::Arguments) ; _ -> error "Term explosion error." _tc_ArgumentsTc = mkTyCon "Arguments" instance Typeable Arguments where typeOf x = mkTyConApp _tc_ArgumentsTc [ ] instance Term Expression where explode (x::Expression) = TermRep (toDyn x, f x, g x) where f (Literal aa) = [explode aa] f (Identifier ab) = [explode ab] f This = [] f (PrefixExpr ac ad) = [explode ac,explode ad] f (InfixExpr ae af ag) = [explode ae,explode af,explode ag] f (AndOrExpr ah ai aj) = [explode ah,explode ai,explode aj] f (InstanceOf ak al) = [explode ak,explode al] f (TypeCast am an) = [explode am,explode an] f (BracketExpr ao) = [explode ao] f (AssignmentExpr ap) = [explode ap] f (InstanceCreationExpr aq) = [explode aq] f (MethodInvocationExpr ar) = [explode ar] g (Literal _) xs = case TermRep.fArgs xs of [aa] -> toDyn ((Literal (TermRep.fDyn aa))::Expression) ; _ -> error "Term explosion error." g (Identifier _) xs = case TermRep.fArgs xs of [ab] -> toDyn ((Identifier (TermRep.fDyn ab))::Expression) ; _ -> error "Term explosion error." g This xs = case TermRep.fArgs xs of [] -> toDyn ((This)::Expression) ; _ -> error "Term explosion error." g (PrefixExpr _ _) xs = case TermRep.fArgs xs of [ac,ad] -> toDyn ((PrefixExpr (TermRep.fDyn ac) (TermRep.fDyn ad))::Expression) ; _ -> error "Term explosion error." g (InfixExpr _ _ _) xs = case TermRep.fArgs xs of [ae,af,ag] -> toDyn ((InfixExpr (TermRep.fDyn ae) (TermRep.fDyn af) (TermRep.fDyn ag))::Expression) ; _ -> error "Term explosion error." g (AndOrExpr _ _ _) xs = case TermRep.fArgs xs of [ah,ai,aj] -> toDyn ((AndOrExpr (TermRep.fDyn ah) (TermRep.fDyn ai) (TermRep.fDyn aj))::Expression) ; _ -> error "Term explosion error." g (InstanceOf _ _) xs = case TermRep.fArgs xs of [ak,al] -> toDyn ((InstanceOf (TermRep.fDyn ak) (TermRep.fDyn al))::Expression) ; _ -> error "Term explosion error." g (TypeCast _ _) xs = case TermRep.fArgs xs of [am,an] -> toDyn ((TypeCast (TermRep.fDyn am) (TermRep.fDyn an))::Expression) ; _ -> error "Term explosion error." g (BracketExpr _) xs = case TermRep.fArgs xs of [ao] -> toDyn ((BracketExpr (TermRep.fDyn ao))::Expression) ; _ -> error "Term explosion error." g (AssignmentExpr _) xs = case TermRep.fArgs xs of [ap] -> toDyn ((AssignmentExpr (TermRep.fDyn ap))::Expression) ; _ -> error "Term explosion error." g (InstanceCreationExpr _) xs = case TermRep.fArgs xs of [aq] -> toDyn ((InstanceCreationExpr (TermRep.fDyn aq))::Expression) ; _ -> error "Term explosion error." g (MethodInvocationExpr _) xs = case TermRep.fArgs xs of [ar] -> toDyn ((MethodInvocationExpr (TermRep.fDyn ar))::Expression) ; _ -> error "Term explosion error." _tc_ExpressionTc = mkTyCon "Expression" instance Typeable Expression where typeOf x = mkTyConApp _tc_ExpressionTc [ ] instance Term AndOr where explode (x::AndOr) = TermRep (toDyn x, f x, g x) where f AND = [] f OR = [] g AND xs = case TermRep.fArgs xs of [] -> toDyn ((AND)::AndOr) ; _ -> error "Term explosion error." g OR xs = case TermRep.fArgs xs of [] -> toDyn ((OR)::AndOr) ; _ -> error "Term explosion error." _tc_AndOrTc = mkTyCon "AndOr" instance Typeable AndOr where typeOf x = mkTyConApp _tc_AndOrTc [ ] instance Term PrefixOperator where explode (x::PrefixOperator) = TermRep (toDyn x, f x, g x) where f Neg = [] f Fac = [] g Neg xs = case TermRep.fArgs xs of [] -> toDyn ((Neg)::PrefixOperator) ; _ -> error "Term explosion error." g Fac xs = case TermRep.fArgs xs of [] -> toDyn ((Fac)::PrefixOperator) ; _ -> error "Term explosion error." _tc_PrefixOperatorTc = mkTyCon "PrefixOperator" instance Typeable PrefixOperator where typeOf x = mkTyConApp _tc_PrefixOperatorTc [ ] instance Term InfixOperator where explode (x::InfixOperator) = TermRep (toDyn x, f x, g x) where f Eq = [] f NEQ = [] f Lt = [] f Gt = [] f LEQ = [] f GEQ = [] f PLUS = [] f MINUS = [] f MUL = [] f DIV = [] f MOD = [] g Eq xs = case TermRep.fArgs xs of [] -> toDyn ((Eq)::InfixOperator) ; _ -> error "Term explosion error." g NEQ xs = case TermRep.fArgs xs of [] -> toDyn ((NEQ)::InfixOperator) ; _ -> error "Term explosion error." g Lt xs = case TermRep.fArgs xs of [] -> toDyn ((Lt)::InfixOperator) ; _ -> error "Term explosion error." g Gt xs = case TermRep.fArgs xs of [] -> toDyn ((Gt)::InfixOperator) ; _ -> error "Term explosion error." g LEQ xs = case TermRep.fArgs xs of [] -> toDyn ((LEQ)::InfixOperator) ; _ -> error "Term explosion error." g GEQ xs = case TermRep.fArgs xs of [] -> toDyn ((GEQ)::InfixOperator) ; _ -> error "Term explosion error." g PLUS xs = case TermRep.fArgs xs of [] -> toDyn ((PLUS)::InfixOperator) ; _ -> error "Term explosion error." g MINUS xs = case TermRep.fArgs xs of [] -> toDyn ((MINUS)::InfixOperator) ; _ -> error "Term explosion error." g MUL xs = case TermRep.fArgs xs of [] -> toDyn ((MUL)::InfixOperator) ; _ -> error "Term explosion error." g DIV xs = case TermRep.fArgs xs of [] -> toDyn ((DIV)::InfixOperator) ; _ -> error "Term explosion error." g MOD xs = case TermRep.fArgs xs of [] -> toDyn ((MOD)::InfixOperator) ; _ -> error "Term explosion error." _tc_InfixOperatorTc = mkTyCon "InfixOperator" instance Typeable InfixOperator where typeOf x = mkTyConApp _tc_InfixOperatorTc [ ] instance Term Literal where explode (x::Literal) = TermRep (toDyn x, f x, g x) where f (BooleanLit aa) = [explode aa] f (IntegerLit ab) = [explode ab] f Null = [] f (StringLit ac) = [explode ac] g (BooleanLit _) xs = case TermRep.fArgs xs of [aa] -> toDyn ((BooleanLit (TermRep.fDyn aa))::Literal) ; _ -> error "Term explosion error." g (IntegerLit _) xs = case TermRep.fArgs xs of [ab] -> toDyn ((IntegerLit (TermRep.fDyn ab))::Literal) ; _ -> error "Term explosion error." g Null xs = case TermRep.fArgs xs of [] -> toDyn ((Null)::Literal) ; _ -> error "Term explosion error." g (StringLit _) xs = case TermRep.fArgs xs of [ac] -> toDyn ((StringLit (TermRep.fDyn ac))::Literal) ; _ -> error "Term explosion error." _tc_LiteralTc = mkTyCon "Literal" instance Typeable Literal where typeOf x = mkTyConApp _tc_LiteralTc [ ] instance Term BooleanLiteral where explode (x::BooleanLiteral) = TermRep (toDyn x, f x, g x) where f TRUE = [] f FALSE = [] g TRUE xs = case TermRep.fArgs xs of [] -> toDyn ((TRUE)::BooleanLiteral) ; _ -> error "Term explosion error." g FALSE xs = case TermRep.fArgs xs of [] -> toDyn ((FALSE)::BooleanLiteral) ; _ -> error "Term explosion error." _tc_BooleanLiteralTc = mkTyCon "BooleanLiteral" instance Typeable BooleanLiteral where typeOf x = mkTyConApp _tc_BooleanLiteralTc [ ] instance Term BlockStatements where explode (x::BlockStatements) = TermRep (toDyn x, f x, g x) where f (BlockStatements aa ab) = [explode aa,explode ab] g (BlockStatements _ _) xs = case TermRep.fArgs xs of [aa,ab] -> toDyn ((BlockStatements (TermRep.fDyn aa) (TermRep.fDyn ab))::BlockStatements) ; _ -> error "Term explosion error." _tc_BlockStatementsTc = mkTyCon "BlockStatements" instance Typeable BlockStatements where typeOf x = mkTyConApp _tc_BlockStatementsTc [ ] instance Term Statement where explode (x::Statement) = TermRep (toDyn x, f x, g x) where f Skip = [] f (Block aa) = [explode aa] f (AssignmentStat ab) = [explode ab] f (InstanceCreationStat ac) = [explode ac] f (MethodInvocationStat ad) = [explode ad] f (ReturnStat ae) = [explode ae] f (IfStat af ag ah) = [explode af,explode ag,explode ah] f (WhileStat ai aj) = [explode ai,explode aj] f (StatFocus ak) = [explode ak] g Skip xs = case TermRep.fArgs xs of [] -> toDyn ((Skip)::Statement) ; _ -> error "Term explosion error." g (Block _) xs = case TermRep.fArgs xs of [aa] -> toDyn ((Block (TermRep.fDyn aa))::Statement) ; _ -> error "Term explosion error." g (AssignmentStat _) xs = case TermRep.fArgs xs of [ab] -> toDyn ((AssignmentStat (TermRep.fDyn ab))::Statement) ; _ -> error "Term explosion error." g (InstanceCreationStat _) xs = case TermRep.fArgs xs of [ac] -> toDyn ((InstanceCreationStat (TermRep.fDyn ac))::Statement) ; _ -> error "Term explosion error." g (MethodInvocationStat _) xs = case TermRep.fArgs xs of [ad] -> toDyn ((MethodInvocationStat (TermRep.fDyn ad))::Statement) ; _ -> error "Term explosion error." g (ReturnStat _) xs = case TermRep.fArgs xs of [ae] -> toDyn ((ReturnStat (TermRep.fDyn ae))::Statement) ; _ -> error "Term explosion error." g (IfStat _ _ _) xs = case TermRep.fArgs xs of [af,ag,ah] -> toDyn ((IfStat (TermRep.fDyn af) (TermRep.fDyn ag) (TermRep.fDyn ah))::Statement) ; _ -> error "Term explosion error." g (WhileStat _ _) xs = case TermRep.fArgs xs of [ai,aj] -> toDyn ((WhileStat (TermRep.fDyn ai) (TermRep.fDyn aj))::Statement) ; _ -> error "Term explosion error." g (StatFocus _) xs = case TermRep.fArgs xs of [ak] -> toDyn ((StatFocus (TermRep.fDyn ak))::Statement) ; _ -> error "Term explosion error." _tc_StatementTc = mkTyCon "Statement" instance Typeable Statement where typeOf x = mkTyConApp _tc_StatementTc [ ] instance Term ClassDeclaration where explode (x::ClassDeclaration) = TermRep (toDyn x, f x, g x) where f (ClassDecl aa ab ac ad ae af) = [explode aa,explode ab,explode ac,explode ad,explode ae,explode af] g (ClassDecl _ _ _ _ _ _) xs = case TermRep.fArgs xs of [aa,ab,ac,ad,ae,af] -> toDyn ((ClassDecl (TermRep.fDyn aa) (TermRep.fDyn ab) (TermRep.fDyn ac) (TermRep.fDyn ad) (TermRep.fDyn ae) (TermRep.fDyn af))::ClassDeclaration) ; _ -> error "Term explosion error." _tc_ClassDeclarationTc = mkTyCon "ClassDeclaration" instance Typeable ClassDeclaration where typeOf x = mkTyConApp _tc_ClassDeclarationTc [ ] instance Term FieldDeclaration where explode (x::FieldDeclaration) = TermRep (toDyn x, f x, g x) where f (FieldDecl aa ab) = [explode aa,explode ab] g (FieldDecl _ _) xs = case TermRep.fArgs xs of [aa,ab] -> toDyn ((FieldDecl (TermRep.fDyn aa) (TermRep.fDyn ab))::FieldDeclaration) ; _ -> error "Term explosion error." _tc_FieldDeclarationTc = mkTyCon "FieldDeclaration" instance Typeable FieldDeclaration where typeOf x = mkTyConApp _tc_FieldDeclarationTc [ ] instance Term ConstructorDeclaration where explode (x::ConstructorDeclaration) = TermRep (toDyn x, f x, g x) where f (ConstructorDecl aa ab ac ad) = [explode aa,explode ab,explode ac,explode ad] g (ConstructorDecl _ _ _ _) xs = case TermRep.fArgs xs of [aa,ab,ac,ad] -> toDyn ((ConstructorDecl (TermRep.fDyn aa) (TermRep.fDyn ab) (TermRep.fDyn ac) (TermRep.fDyn ad))::ConstructorDeclaration) ; _ -> error "Term explosion error." _tc_ConstructorDeclarationTc = mkTyCon "ConstructorDeclaration" instance Typeable ConstructorDeclaration where typeOf x = mkTyConApp _tc_ConstructorDeclarationTc [ ] instance Term MethodDeclaration where explode (x::MethodDeclaration) = TermRep (toDyn x, f x, g x) where f (MethodDecl aa ab ac ad) = [explode aa,explode ab,explode ac,explode ad] g (MethodDecl _ _ _ _) xs = case TermRep.fArgs xs of [aa,ab,ac,ad] -> toDyn ((MethodDecl (TermRep.fDyn aa) (TermRep.fDyn ab) (TermRep.fDyn ac) (TermRep.fDyn ad))::MethodDeclaration) ; _ -> error "Term explosion error." _tc_MethodDeclarationTc = mkTyCon "MethodDeclaration" instance Typeable MethodDeclaration where typeOf x = mkTyConApp _tc_MethodDeclarationTc [ ] instance Term FormalParameters where explode (x::FormalParameters) = TermRep (toDyn x, f x, g x) where f (FormalParams aa) = [explode aa] g (FormalParams _) xs = case TermRep.fArgs xs of [aa] -> toDyn ((FormalParams (TermRep.fDyn aa))::FormalParameters) ; _ -> error "Term explosion error." _tc_FormalParametersTc = mkTyCon "FormalParameters" instance Typeable FormalParameters where typeOf x = mkTyConApp _tc_FormalParametersTc [ ] instance Term FormalParameter where explode (x::FormalParameter) = TermRep (toDyn x, f x, g x) where f (FormalParam aa ab) = [explode aa,explode ab] g (FormalParam _ _) xs = case TermRep.fArgs xs of [aa,ab] -> toDyn ((FormalParam (TermRep.fDyn aa) (TermRep.fDyn ab))::FormalParameter) ; _ -> error "Term explosion error." _tc_FormalParameterTc = mkTyCon "FormalParameter" instance Typeable FormalParameter where typeOf x = mkTyConApp _tc_FormalParameterTc [ ] instance Term VariableDeclaration where explode (x::VariableDeclaration) = TermRep (toDyn x, f x, g x) where f (VariableDecl aa ab) = [explode aa,explode ab] g (VariableDecl _ _) xs = case TermRep.fArgs xs of [aa,ab] -> toDyn ((VariableDecl (TermRep.fDyn aa) (TermRep.fDyn ab))::VariableDeclaration) ; _ -> error "Term explosion error." _tc_VariableDeclarationTc = mkTyCon "VariableDeclaration" instance Typeable VariableDeclaration where typeOf x = mkTyConApp _tc_VariableDeclarationTc [ ] instance Term Type where explode (x::Type) = TermRep (toDyn x, f x, g x) where f INT = [] f BOOLEAN = [] f (Type aa) = [explode aa] g INT xs = case TermRep.fArgs xs of [] -> toDyn ((INT)::Type) ; _ -> error "Term explosion error." g BOOLEAN xs = case TermRep.fArgs xs of [] -> toDyn ((BOOLEAN)::Type) ; _ -> error "Term explosion error." g (Type _) xs = case TermRep.fArgs xs of [aa] -> toDyn ((Type (TermRep.fDyn aa))::Type) ; _ -> error "Term explosion error." _tc_TypeTc = mkTyCon "Type" instance Typeable Type where typeOf x = mkTyConApp _tc_TypeTc [ ] -- Imported from other files :-
forste/haReFork
StrategyLib-4.0-beta/examples/joos-padl02/DatatypesTermInstances.hs
bsd-3-clause
15,393
0
17
2,619
6,674
3,375
3,299
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} -- --------------------------------------------------------------------------- -- | -- Module : Data.Vector.Algorithms.Common -- Copyright : (c) 2008-2011 Dan Doel -- Maintainer : Dan Doel -- Stability : Experimental -- Portability : Portable -- -- Common operations and utility functions for all sorts module Data.Vector.Algorithms.Common where import Language.Haskell.Liquid.Prelude (liquidAssert) import Prelude hiding (read, length) import Control.Monad.Primitive import Data.Vector.Generic.Mutable import qualified Data.Vector.Primitive.Mutable as PV import qualified Data.Vector.Primitive.Mutable ---------------------------------------------------------------------------- -- LIQUID Specifications --------------------------------------------------- ---------------------------------------------------------------------------- -- | Vector Size Measure {-@ measure vsize :: (v m e) -> Int @-} -- | Vector Type Aliases {-@ type NeVec v m e = {v: (v (PrimState m) e) | 0 < (vsize v)} @-} {-@ type OkIdx X = {v:Nat | (OkRng v X 0)} @-} {-@ type AOkIdx X = {v:Nat | v <= (vsize X)} @-} {-@ type Pos = {v:Int | v > 0 } @-} {-@ type LtIdxOff Off Vec = {v:Nat | v+Off < (vsize Vec)} @-} {-@ type LeIdxOff Off Vec = {v:Nat | v+Off <= (vsize Vec)} @-} -- | Only mention of ordering {-@ predicate InRngL V L U = (L < V && V <= U) @-} {-@ predicate InRng V L U = (L <= V && V <= U) @-} {-@ predicate EqSiz X Y = (vsize X) = (vsize Y) @-} -- | Abstractly defined using @InRng@ {-@ predicate OkOff X B O = (InRng (B + O) 0 (vsize X)) @-} {-@ predicate OkRng V X N = (InRng V 0 ((vsize X) - (N + 1))) @-} -- | Assumed Types for Vector {-@ Data.Vector.Generic.Mutable.length :: (Data.Vector.Generic.Mutable.MVector v a) => x:(v s a) -> {v:Nat | v = (vsize x)} @-} {-@ Data.Vector.Generic.Mutable.unsafeRead :: (PrimMonad m, Data.Vector.Generic.Mutable.MVector v a) => x:(v (PrimState m) a) -> (OkIdx x) -> m a @-} {-@ Data.Vector.Generic.Mutable.unsafeWrite :: (PrimMonad m, Data.Vector.Generic.Mutable.MVector v a) => x:(v (PrimState m) a) -> (OkIdx x) -> a -> m () @-} {-@ Data.Vector.Generic.Mutable.unsafeSwap :: (PrimMonad m, Data.Vector.Generic.Mutable.MVector v a) => x:(v (PrimState m) a) -> (OkIdx x) -> (OkIdx x) -> m () @-} {-@ Data.Vector.Generic.Mutable.unsafeSlice :: Data.Vector.Generic.Mutable.MVector v a => i:Nat -> n:Nat -> {v:(v s a) | (OkOff v i n)} -> {v:(v s a) | (vsize v) = n} @-} {-@ Data.Vector.Generic.Mutable.unsafeCopy :: (PrimMonad m, Data.Vector.Generic.Mutable.MVector v a) => src:(v (PrimState m) a) -> {dst:(v (PrimState m) a) | (EqSiz src dst)} -> m () @-} {-@ Data.Vector.Generic.Mutable.new :: (PrimMonad m, Data.Vector.Generic.Mutable.MVector v a) => nINTENDO:Nat -> m {v: (v (PrimState m) a) | (vsize v) = nINTENDO} @-} {-@ Data.Vector.Primitive.Mutable.new :: (PrimMonad m, Data.Vector.Primitive.Mutable.Prim a) => nONKEY:Nat -> m {v: (Data.Vector.Primitive.Mutable.MVector (PrimState m) a) | (vsize v) = nONKEY} @-} {-@ qualif Termination(v:Int, l:Int, twit:Int): v = l + twit @-} {-@ qualif NonEmpty(v:a): 0 < (vsize v) @-} {-@ qualif Cmp(v:a, x:b): v < x @-} {-@ qualif OkIdx(v:a, x:b): v <= (vsize x) @-} {-@ qualif OkIdx(v:a, x:b): v < (vsize x) @-} {-@ qualif EqSiz(x:a, y:b): (vsize x) = y @-} {-@ qualif EqSiz(x:a, y:b): x = (vsize y) @-} {-@ qualif EqSiz(x:a, y:b): (vsize x) = (vsize y) @-} {-@ qualif Plus(v:Int, x:Int, y:Int): v + x = y @-} -- TODO: push this type into the signature for `shiftR`. Issue: math on non-num types. -- TODO: support unchecked `assume`. Currently writing `undefined` to suppress warning -- {- assume shiftRI :: x:Nat -> {v:Int | v = 1} -> {v:Nat | (x <= 2*v + 1 && 2*v <= x)} @-} {-@ assume shiftRI :: x:Nat -> s:Nat -> {v:Nat | ( (s=1 => (2*v <= x && x <= 2*v + 1)) && (s=2 => (4*v <= x && x <= 4*v + 3))) } @-} shiftRI :: Int -> Int -> Int shiftRI = undefined -- shiftR {-@ assume shiftLI :: x:Nat -> s:Nat -> {v:Nat | ( (s = 1 => v = 2 * x) && (s = 2 => v = 4 * x)) } @-} shiftLI :: Int -> Int -> Int shiftLI = undefined -- shiftL ---------------------------------------------------------------------------- -- | A type of comparisons between two values of a given type. type Comparison e = e -> e -> Ordering {-@ copyOffset :: (PrimMonad m, MVector v e) => from : (v (PrimState m) e) -> to : (v (PrimState m) e) -> iFrom : Nat -> iTo : Nat -> {len : Nat | ((OkOff from iFrom len) && (OkOff to iTo len))} -> m () @-} copyOffset :: (PrimMonad m, MVector v e) => v (PrimState m) e -> v (PrimState m) e -> Int -> Int -> Int -> m () copyOffset from to iFrom iTo len = unsafeCopy (unsafeSlice iTo len to) (unsafeSlice iFrom len from) {-# INLINE copyOffset #-} {-@ inc :: (PrimMonad m, MVector v Int) => x:(v (PrimState m) Int) -> (OkIdx x) -> m Int @-} inc :: (PrimMonad m, MVector v Int) => v (PrimState m) Int -> Int -> m Int inc arr i = unsafeRead arr i >>= \e -> unsafeWrite arr i (e+1) >> return e {-# INLINE inc #-} -- LIQUID: flipping order to allow dependency. -- shared bucket sorting stuff {-@ countLoop :: (PrimMonad m, MVector v e) => (v (PrimState m) e) -> count:(PV.MVector (PrimState m) Int) -> (e -> (OkIdx count)) -> m () @-} countLoop :: (PrimMonad m, MVector v e) => (v (PrimState m) e) -> (PV.MVector (PrimState m) Int) -> (e -> Int) -> m () countLoop src count rdx = set count 0 >> go len 0 where len = length src go (m :: Int) i | i < len = let lenSrc = length src in ({- liquidAssert (i < lenSrc) $ -} unsafeRead src i) >>= inc count . rdx >> go (m-1) (i+1) | otherwise = return () {-# INLINE countLoop #-}
mightymoose/liquidhaskell
benchmarks/vector-algorithms-0.5.4.2/Data/Vector/Algorithms/Common.hs
bsd-3-clause
6,409
0
14
1,813
588
340
248
32
1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="hi-IN"> <title>Quick Start | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
msrader/zap-extensions
src/org/zaproxy/zap/extension/quickstart/resources/help_hi_IN/helpset_hi_IN.hs
apache-2.0
973
80
66
160
415
210
205
-1
-1
module ShouldFail where -- See Trac #1176 -- This is really a pretty-printer test, not a typechecker test -- -- Before ghc-7.2 the error messages looked like this (notice the wrong -- indentation): {- tcfail177.hs:9:12: Couldn't match expected type `Bool' with actual type `Int' In the return type of a call of `foo' In the expression: foo ["One........" ~?= "1", "Two" ~?= "2", "Thre........." ~?= "3", "Four" ~?= "4", ....] In an equation for `allTest1': allTest1 = foo ["One........" ~?= "1", "Two" ~?= "2", "Thre........." ~?= "3", ....] tcfail177.hs:18:12: Couldn't match expected type `Bool' with actual type `Int' In the return type of a call of `foo' In the expression: foo ["One........" ~?= "1", "Two.................." ~?= "2", "Thre........." ~?= "3", "Four" ~?= "4", ....] In an equation for `allTest2': allTest2 = foo ["One........" ~?= "1", "Two.................." ~?= "2", "Thre........." ~?= "3", ....] -} allTest1 :: Bool allTest1 = foo ["One........" ~?= "1" ,"Two" ~?= "2" ,"Thre........." ~?= "3" ,"Four" ~?= "4" ,"Five" ~?= "5" ] allTest2 :: Bool allTest2 = foo ["One........" ~?= "1" ,"Two.................." ~?= "2" ,"Thre........." ~?= "3" ,"Four" ~?= "4" ,"Five" ~?= "5" ] (~?=) :: a -> a -> Bool (~?=) = error "urk" foo :: a -> Int foo x = 0
ezyang/ghc
testsuite/tests/typecheck/should_fail/tcfail177.hs
bsd-3-clause
1,566
0
7
504
148
87
61
19
1
{-# LANGUAGE CPP #-} -- | Main implementation of the OpenPGP message format <http://tools.ietf.org/html/rfc4880> -- -- The recommended way to import this module is: -- -- > import qualified Data.OpenPGP as OpenPGP module Data.OpenPGP ( Packet( AsymmetricSessionKeyPacket, OnePassSignaturePacket, SymmetricSessionKeyPacket, PublicKeyPacket, SecretKeyPacket, CompressedDataPacket, MarkerPacket, LiteralDataPacket, TrustPacket, UserIDPacket, EncryptedDataPacket, ModificationDetectionCodePacket, UnsupportedPacket, compression_algorithm, content, encrypted_data, filename, format, hash_algorithm, hashed_subpackets, hash_head, key, is_subkey, v3_days_of_validity, key_algorithm, key_id, message, nested, s2k_useage, s2k, signature, signature_type, symmetric_algorithm, timestamp, trailer, unhashed_subpackets, version ), isSignaturePacket, signaturePacket, Message(..), SignatureSubpacket(..), S2K(..), string2key, HashAlgorithm(..), KeyAlgorithm(..), SymmetricAlgorithm(..), CompressionAlgorithm(..), RevocationCode(..), MPI(..), find_key, fingerprint_material, SignatureOver(..), signatures, signature_issuer, public_key_fields, secret_key_fields ) where import Numeric import Control.Monad import Control.Arrow import Control.Applicative import Data.Monoid import Data.Bits import Data.Word import Data.Char import Data.List import Data.OpenPGP.Internal import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LZ #ifdef CEREAL import Data.Serialize hiding (decode) import qualified Data.ByteString as B import qualified Data.ByteString.UTF8 as B (toString, fromString) #define BINARY_CLASS Serialize #else import Data.Binary hiding (decode) import Data.Binary.Get import Data.Binary.Put import qualified Data.ByteString.Lazy as B import qualified Data.ByteString.Lazy.UTF8 as B (toString, fromString) #define BINARY_CLASS Binary #endif import qualified Codec.Compression.Zlib.Raw as Zip import qualified Codec.Compression.Zlib as Zlib import qualified Codec.Compression.BZip as BZip2 #ifdef CEREAL getRemainingByteString :: Get B.ByteString getRemainingByteString = remaining >>= getByteString getSomeByteString :: Word64 -> Get B.ByteString getSomeByteString = getByteString . fromIntegral putSomeByteString :: B.ByteString -> Put putSomeByteString = putByteString localGet :: Get a -> B.ByteString -> Get a localGet g bs = case runGet g bs of Left s -> fail s Right v -> return v compress :: CompressionAlgorithm -> B.ByteString -> B.ByteString compress algo = toStrictBS . lazyCompress algo . toLazyBS decompress :: CompressionAlgorithm -> B.ByteString -> B.ByteString decompress algo = toStrictBS . lazyDecompress algo . toLazyBS toStrictBS :: LZ.ByteString -> B.ByteString toStrictBS = B.concat . LZ.toChunks toLazyBS :: B.ByteString -> LZ.ByteString toLazyBS = LZ.fromChunks . (:[]) lazyEncode :: (Serialize a) => a -> LZ.ByteString lazyEncode = toLazyBS . encode #else getRemainingByteString :: Get B.ByteString getRemainingByteString = getRemainingLazyByteString getSomeByteString :: Word64 -> Get B.ByteString getSomeByteString = getLazyByteString . fromIntegral putSomeByteString :: B.ByteString -> Put putSomeByteString = putLazyByteString localGet :: Get a -> B.ByteString -> Get a localGet g bs = case runGetOrFail g bs of Left (_,_,s) -> fail s Right (leftover,_,v) | B.null leftover -> return v | otherwise -> fail $ "Leftover in localGet: " ++ show leftover compress :: CompressionAlgorithm -> B.ByteString -> B.ByteString compress = lazyCompress decompress :: CompressionAlgorithm -> B.ByteString -> B.ByteString decompress = lazyDecompress lazyEncode :: (Binary a) => a -> LZ.ByteString lazyEncode = encode #endif lazyCompress :: CompressionAlgorithm -> LZ.ByteString -> LZ.ByteString lazyCompress Uncompressed = id lazyCompress ZIP = Zip.compress lazyCompress ZLIB = Zlib.compress lazyCompress BZip2 = BZip2.compress lazyCompress x = error ("No implementation for " ++ show x) lazyDecompress :: CompressionAlgorithm -> LZ.ByteString -> LZ.ByteString lazyDecompress Uncompressed = id lazyDecompress ZIP = Zip.decompress lazyDecompress ZLIB = Zlib.decompress lazyDecompress BZip2 = BZip2.decompress lazyDecompress x = error ("No implementation for " ++ show x) assertProp :: (Monad m, Show a) => (a -> Bool) -> a -> m a assertProp f x | f x = return $! x | otherwise = fail $ "Assertion failed for: " ++ show x pad :: Int -> String -> String pad l s = replicate (l - length s) '0' ++ s padBS :: Int -> B.ByteString -> B.ByteString padBS l s = B.replicate (fromIntegral l - B.length s) 0 `B.append` s checksum :: B.ByteString -> Word16 checksum = fromIntegral . B.foldl (\c i -> (c + fromIntegral i) `mod` 65536) (0::Integer) data Packet = AsymmetricSessionKeyPacket { version::Word8, key_id::String, key_algorithm::KeyAlgorithm, encrypted_data::B.ByteString } | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.1> SignaturePacket { version::Word8, signature_type::Word8, key_algorithm::KeyAlgorithm, hash_algorithm::HashAlgorithm, hashed_subpackets::[SignatureSubpacket], unhashed_subpackets::[SignatureSubpacket], hash_head::Word16, signature::[MPI], trailer::B.ByteString } | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.2> SymmetricSessionKeyPacket { version::Word8, symmetric_algorithm::SymmetricAlgorithm, s2k::S2K, encrypted_data::B.ByteString } | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.3> OnePassSignaturePacket { version::Word8, signature_type::Word8, hash_algorithm::HashAlgorithm, key_algorithm::KeyAlgorithm, key_id::String, nested::Word8 } | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.4> PublicKeyPacket { version::Word8, timestamp::Word32, key_algorithm::KeyAlgorithm, key::[(Char,MPI)], is_subkey::Bool, v3_days_of_validity::Maybe Word16 } | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.5.1.1> (also subkey) SecretKeyPacket { version::Word8, timestamp::Word32, key_algorithm::KeyAlgorithm, key::[(Char,MPI)], s2k_useage::Word8, s2k::S2K, -- ^ This is meaningless if symmetric_algorithm == Unencrypted symmetric_algorithm::SymmetricAlgorithm, encrypted_data::B.ByteString, is_subkey::Bool } | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.5.1.3> (also subkey) CompressedDataPacket { compression_algorithm::CompressionAlgorithm, message::Message } | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.6> MarkerPacket | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.8> LiteralDataPacket { format::Char, filename::String, timestamp::Word32, content::B.ByteString } | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.9> TrustPacket B.ByteString | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.10> UserIDPacket String | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.11> EncryptedDataPacket { version::Word8, encrypted_data::B.ByteString } | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.13> -- or <http://tools.ietf.org/html/rfc4880#section-5.7> when version is 0 ModificationDetectionCodePacket B.ByteString | -- ^ <http://tools.ietf.org/html/rfc4880#section-5.14> UnsupportedPacket Word8 B.ByteString deriving (Show, Read, Eq) instance BINARY_CLASS Packet where put p = do -- First two bits are 1 for new packet format put ((tag .|. 0xC0) :: Word8) case tag of 19 -> put =<< assertProp (<192) (blen :: Word8) _ -> do -- Use 5-octet lengths put (255 :: Word8) put (blen :: Word32) putSomeByteString body where blen :: (Num a) => a blen = fromIntegral $ B.length body (body, tag) = put_packet p get = do tag <- get let (t, l) = if (tag .&. 64) /= 0 then (tag .&. 63, parse_new_length) else ((tag `shiftR` 2) .&. 15, (,) <$> parse_old_length tag <*> pure False) packet <- uncurry get_packet_bytes =<< l localGet (parse_packet t) (B.concat packet) get_packet_bytes :: Maybe Word32 -> Bool -> Get [B.ByteString] get_packet_bytes len partial = do -- This forces the whole packet to be consumed packet <- maybe getRemainingByteString (getSomeByteString . fromIntegral) len if not partial then return [packet] else (packet:) <$> (uncurry get_packet_bytes =<< parse_new_length) -- http://tools.ietf.org/html/rfc4880#section-4.2.2 parse_new_length :: Get (Maybe Word32, Bool) parse_new_length = fmap (first Just) $ do len <- fmap fromIntegral (get :: Get Word8) case len of -- One octet length _ | len < 192 -> return (len, False) -- Two octet length _ | len > 191 && len < 224 -> do second <- fmap fromIntegral (get :: Get Word8) return (((len - 192) `shiftL` 8) + second + 192, False) -- Five octet length 255 -> (,) <$> (get :: Get Word32) <*> pure False -- Partial length (streaming) _ | len >= 224 && len < 255 -> return (1 `shiftL` (fromIntegral len .&. 0x1F), True) _ -> fail "Unsupported new packet length." -- http://tools.ietf.org/html/rfc4880#section-4.2.1 parse_old_length :: Word8 -> Get (Maybe Word32) parse_old_length tag = case tag .&. 3 of -- One octet length 0 -> fmap (Just . fromIntegral) (get :: Get Word8) -- Two octet length 1 -> fmap (Just . fromIntegral) (get :: Get Word16) -- Four octet length 2 -> fmap Just get -- Indeterminate length 3 -> return Nothing -- Error _ -> fail "Unsupported old packet length." -- http://tools.ietf.org/html/rfc4880#section-5.5.2 public_key_fields :: KeyAlgorithm -> [Char] public_key_fields RSA = ['n', 'e'] public_key_fields RSA_E = public_key_fields RSA public_key_fields RSA_S = public_key_fields RSA public_key_fields ELGAMAL = ['p', 'g', 'y'] public_key_fields DSA = ['p', 'q', 'g', 'y'] public_key_fields _ = undefined -- Nothing in the spec. Maybe empty -- http://tools.ietf.org/html/rfc4880#section-5.5.3 secret_key_fields :: KeyAlgorithm -> [Char] secret_key_fields RSA = ['d', 'p', 'q', 'u'] secret_key_fields RSA_E = secret_key_fields RSA secret_key_fields RSA_S = secret_key_fields RSA secret_key_fields ELGAMAL = ['x'] secret_key_fields DSA = ['x'] secret_key_fields _ = undefined -- Nothing in the spec. Maybe empty (!) :: (Eq k) => [(k,v)] -> k -> v (!) xs k = let Just x = lookup k xs in x -- Need this seperate for trailer calculation signature_packet_start :: Packet -> B.ByteString signature_packet_start (SignaturePacket { version = 4, signature_type = signature_type, key_algorithm = key_algorithm, hash_algorithm = hash_algorithm, hashed_subpackets = hashed_subpackets }) = B.concat [ encode (0x04 :: Word8), encode signature_type, encode key_algorithm, encode hash_algorithm, encode ((fromIntegral $ B.length hashed_subs) :: Word16), hashed_subs ] where hashed_subs = B.concat $ map encode hashed_subpackets signature_packet_start x = error ("Trying to get start of signature packet for: " ++ show x) -- The trailer is just the top of the body plus some crap calculate_signature_trailer :: Packet -> B.ByteString calculate_signature_trailer (SignaturePacket { version = v, signature_type = signature_type, unhashed_subpackets = unhashed_subpackets }) | v `elem` [2,3] = B.concat [ encode signature_type, encode creation_time ] where Just (SignatureCreationTimePacket creation_time) = find isCreation unhashed_subpackets isCreation (SignatureCreationTimePacket {}) = True isCreation _ = False calculate_signature_trailer p@(SignaturePacket {version = 4}) = B.concat [ signature_packet_start p, encode (0x04 :: Word8), encode (0xff :: Word8), encode (fromIntegral (B.length $ signature_packet_start p) :: Word32) ] calculate_signature_trailer x = error ("Trying to calculate signature trailer for: " ++ show x) put_packet :: Packet -> (B.ByteString, Word8) put_packet (AsymmetricSessionKeyPacket version key_id key_algorithm dta) = (B.concat [ encode version, encode (fst $ head $ readHex $ takeFromEnd 16 key_id :: Word64), encode key_algorithm, dta ], 1) put_packet (SignaturePacket { version = v, unhashed_subpackets = unhashed_subpackets, key_algorithm = key_algorithm, hash_algorithm = hash_algorithm, hash_head = hash_head, signature = signature, trailer = trailer }) | v `elem` [2,3] = -- TODO: Assert that there are no subpackets we cannot encode? (B.concat $ [ B.singleton v, B.singleton 0x05, trailer, -- signature_type and creation_time encode keyid, encode key_algorithm, encode hash_algorithm, encode hash_head ] ++ map encode signature, 2) where keyid = fst $ head $ readHex $ takeFromEnd 16 keyidS :: Word64 Just (IssuerPacket keyidS) = find isIssuer unhashed_subpackets isIssuer (IssuerPacket {}) = True isIssuer _ = False put_packet (SymmetricSessionKeyPacket version salgo s2k encd) = (B.concat [encode version, encode salgo, encode s2k, encd], 3) put_packet (SignaturePacket { version = 4, unhashed_subpackets = unhashed_subpackets, hash_head = hash_head, signature = signature, trailer = trailer }) = (B.concat $ [ trailer_top, encode (fromIntegral $ B.length unhashed :: Word16), unhashed, encode hash_head ] ++ map encode signature, 2) where trailer_top = B.reverse $ B.drop 6 $ B.reverse trailer unhashed = B.concat $ map encode unhashed_subpackets put_packet (OnePassSignaturePacket { version = version, signature_type = signature_type, hash_algorithm = hash_algorithm, key_algorithm = key_algorithm, key_id = key_id, nested = nested }) = (B.concat [ encode version, encode signature_type, encode hash_algorithm, encode key_algorithm, encode (fst $ head $ readHex $ takeFromEnd 16 key_id :: Word64), encode nested ], 4) put_packet (SecretKeyPacket { version = version, timestamp = timestamp, key_algorithm = algorithm, key = key, s2k_useage = s2k_useage, s2k = s2k, symmetric_algorithm = symmetric_algorithm, encrypted_data = encrypted_data, is_subkey = is_subkey }) = (B.concat $ p : (if s2k_useage `elem` [254,255] then [encode s2k_useage, encode symmetric_algorithm, encode s2k] else [encode symmetric_algorithm] ) ++ (if symmetric_algorithm /= Unencrypted then -- For V3 keys, the "encrypted data" has an unencrypted checksum -- of the unencrypted MPIs on the end [encrypted_data] else s ++ [encode $ checksum $ B.concat s]), if is_subkey then 7 else 5) where p = fst (put_packet $ PublicKeyPacket version timestamp algorithm key False Nothing) s = map (encode . (key !)) (secret_key_fields algorithm) put_packet p@(PublicKeyPacket { version = v, timestamp = timestamp, key_algorithm = algorithm, key = key, is_subkey = is_subkey }) | v == 3 = final (B.concat $ [ B.singleton 3, encode timestamp, encode v3_days, encode algorithm ] ++ material) | v == 4 = final (B.concat $ [ B.singleton 4, encode timestamp, encode algorithm ] ++ material) where Just v3_days = v3_days_of_validity p final x = (x, if is_subkey then 14 else 6) material = map (encode . (key !)) (public_key_fields algorithm) put_packet (CompressedDataPacket { compression_algorithm = algorithm, message = message }) = (B.append (encode algorithm) $ compress algorithm $ encode message, 8) put_packet MarkerPacket = (B.fromString "PGP", 10) put_packet (LiteralDataPacket { format = format, filename = filename, timestamp = timestamp, content = content }) = (B.concat [ encode format, encode filename_l, lz_filename, encode timestamp, content ], 11) where filename_l = (fromIntegral $ B.length lz_filename) :: Word8 lz_filename = B.fromString filename put_packet (TrustPacket bytes) = (bytes, 12) put_packet (UserIDPacket txt) = (B.fromString txt, 13) put_packet (EncryptedDataPacket 0 encrypted_data) = (encrypted_data, 9) put_packet (EncryptedDataPacket version encrypted_data) = (B.concat [encode version, encrypted_data], 18) put_packet (ModificationDetectionCodePacket bstr) = (bstr, 19) put_packet (UnsupportedPacket tag bytes) = (bytes, fromIntegral tag) put_packet x = error ("Unsupported Packet version or type in put_packet: " ++ show x) parse_packet :: Word8 -> Get Packet -- AsymmetricSessionKeyPacket, http://tools.ietf.org/html/rfc4880#section-5.1 parse_packet 1 = AsymmetricSessionKeyPacket <$> (assertProp (==3) =<< get) <*> fmap (pad 16 . map toUpper . flip showHex "") (get :: Get Word64) <*> get <*> getRemainingByteString -- SignaturePacket, http://tools.ietf.org/html/rfc4880#section-5.2 parse_packet 2 = do version <- get case version of _ | version `elem` [2,3] -> do _ <- assertProp (==5) =<< (get :: Get Word8) signature_type <- get creation_time <- get :: Get Word32 keyid <- get :: Get Word64 key_algorithm <- get hash_algorithm <- get hash_head <- get signature <- listUntilEnd return SignaturePacket { version = version, signature_type = signature_type, key_algorithm = key_algorithm, hash_algorithm = hash_algorithm, hashed_subpackets = [], unhashed_subpackets = [ SignatureCreationTimePacket creation_time, IssuerPacket $ pad 16 $ map toUpper $ showHex keyid "" ], hash_head = hash_head, signature = signature, trailer = B.concat [encode signature_type, encode creation_time] } 4 -> do signature_type <- get key_algorithm <- get hash_algorithm <- get hashed_size <- fmap fromIntegral (get :: Get Word16) hashed_data <- getSomeByteString hashed_size hashed <- localGet listUntilEnd hashed_data unhashed_size <- fmap fromIntegral (get :: Get Word16) unhashed_data <- getSomeByteString unhashed_size unhashed <- localGet listUntilEnd unhashed_data hash_head <- get signature <- listUntilEnd return SignaturePacket { version = version, signature_type = signature_type, key_algorithm = key_algorithm, hash_algorithm = hash_algorithm, hashed_subpackets = hashed, unhashed_subpackets = unhashed, hash_head = hash_head, signature = signature, trailer = B.concat [encode version, encode signature_type, encode key_algorithm, encode hash_algorithm, encode (fromIntegral hashed_size :: Word16), hashed_data, B.pack [4, 0xff], encode ((6 + fromIntegral hashed_size) :: Word32)] } x -> fail $ "Unknown SignaturePacket version " ++ show x ++ "." -- SymmetricSessionKeyPacket, http://tools.ietf.org/html/rfc4880#section-5.3 parse_packet 3 = SymmetricSessionKeyPacket <$> (assertProp (==4) =<< get) <*> get <*> get <*> getRemainingByteString -- OnePassSignaturePacket, http://tools.ietf.org/html/rfc4880#section-5.4 parse_packet 4 = do version <- get signature_type <- get hash_algo <- get key_algo <- get key_id <- get :: Get Word64 nested <- get return OnePassSignaturePacket { version = version, signature_type = signature_type, hash_algorithm = hash_algo, key_algorithm = key_algo, key_id = pad 16 $ map toUpper $ showHex key_id "", nested = nested } -- SecretKeyPacket, http://tools.ietf.org/html/rfc4880#section-5.5.3 parse_packet 5 = do -- Parse PublicKey part (PublicKeyPacket { version = version, timestamp = timestamp, key_algorithm = algorithm, key = key }) <- parse_packet 6 s2k_useage <- get :: Get Word8 let k = SecretKeyPacket version timestamp algorithm key s2k_useage (symmetric_algorithm, s2k) <- case () of _ | s2k_useage `elem` [255, 254] -> (,) <$> get <*> get _ | s2k_useage > 0 -> -- s2k_useage is symmetric_type in this case (,) <$> localGet get (encode s2k_useage) <*> pure (SimpleS2K MD5) _ -> return (Unencrypted, S2K 100 B.empty) if symmetric_algorithm /= Unencrypted then do { encrypted <- getRemainingByteString; return (k s2k symmetric_algorithm encrypted False) } else do skey <- foldM (\m f -> do mpi <- get :: Get MPI return $ (f,mpi):m) [] (secret_key_fields algorithm) chk <- get when (checksum (B.concat $ map (encode . snd) skey) /= chk) $ fail "Checksum verification failed for unencrypted secret key" return ((k s2k symmetric_algorithm B.empty False) {key = key ++ skey}) -- PublicKeyPacket, http://tools.ietf.org/html/rfc4880#section-5.5.2 parse_packet 6 = do version <- get :: Get Word8 let getVersionPacket version | version `elem` [2, 3, 4] = do timestamp <- get days <- if version == 4 then return Nothing else fmap Just get algorithm <- get key <- mapM (\f -> fmap ((,)f) get) (public_key_fields algorithm) return PublicKeyPacket { version = version, timestamp = timestamp, key_algorithm = algorithm, key = key, is_subkey = False, v3_days_of_validity = days } | otherwise = fail $ "Unsupported PublicKeyPacket version " ++ show version ++ "." getVersionPacket version -- Secret-SubKey Packet, http://tools.ietf.org/html/rfc4880#section-5.5.1.4 parse_packet 7 = do p <- parse_packet 5 return p {is_subkey = True} -- CompressedDataPacket, http://tools.ietf.org/html/rfc4880#section-5.6 parse_packet 8 = do algorithm <- get message <- localGet get =<< (decompress algorithm <$> getRemainingByteString) return CompressedDataPacket { compression_algorithm = algorithm, message = message } -- EncryptedDataPacket, http://tools.ietf.org/html/rfc4880#section-5.7 parse_packet 9 = EncryptedDataPacket 0 <$> getRemainingByteString -- MarkerPacket, http://tools.ietf.org/html/rfc4880#section-5.8 parse_packet 10 = do _ <- assertProp (== B.fromString "PGP") =<< getSomeByteString 3 return MarkerPacket -- LiteralDataPacket, http://tools.ietf.org/html/rfc4880#section-5.9 parse_packet 11 = do format <- get filenameLength <- get :: Get Word8 filename <- getSomeByteString (fromIntegral filenameLength) timestamp <- get content <- getRemainingByteString return LiteralDataPacket { format = format, filename = B.toString filename, timestamp = timestamp, content = content } -- TrustPacket, http://tools.ietf.org/html/rfc4880#section-5.10 parse_packet 12 = fmap TrustPacket getRemainingByteString -- UserIDPacket, http://tools.ietf.org/html/rfc4880#section-5.11 parse_packet 13 = fmap (UserIDPacket . B.toString) getRemainingByteString -- Public-Subkey Packet, http://tools.ietf.org/html/rfc4880#section-5.5.1.2 parse_packet 14 = do p <- parse_packet 6 return p {is_subkey = True} -- EncryptedDataPacket, http://tools.ietf.org/html/rfc4880#section-5.13 parse_packet 18 = EncryptedDataPacket <$> get <*> getRemainingByteString -- ModificationDetectionCodePacket, http://tools.ietf.org/html/rfc4880#section-5.14 parse_packet 19 = fmap ModificationDetectionCodePacket getRemainingByteString -- Represent unsupported packets as their tag and literal bytes parse_packet tag = fmap (UnsupportedPacket tag) getRemainingByteString -- | Helper method for fingerprints and such fingerprint_material :: Packet -> [B.ByteString] fingerprint_material p | version p == 4 = [ B.singleton 0x99, encode (6 + fromIntegral (B.length material) :: Word16), B.singleton 4, encode (timestamp p), encode (key_algorithm p), material ] where material = B.concat $ map (encode . (key p !)) (public_key_fields $ key_algorithm p) fingerprint_material p | version p `elem` [2, 3] = [n, e] where n = B.drop 2 (encode (key p ! 'n')) e = B.drop 2 (encode (key p ! 'e')) fingerprint_material _ = error "Unsupported Packet version or type in fingerprint_material." enum_to_word8 :: (Enum a) => a -> Word8 enum_to_word8 = fromIntegral . fromEnum enum_from_word8 :: (Enum a) => Word8 -> a enum_from_word8 = toEnum . fromIntegral data S2K = SimpleS2K HashAlgorithm | SaltedS2K HashAlgorithm Word64 | IteratedSaltedS2K HashAlgorithm Word64 Word32 | S2K Word8 B.ByteString deriving (Show, Read, Eq) instance BINARY_CLASS S2K where put (SimpleS2K halgo) = put (0::Word8) >> put halgo put (SaltedS2K halgo salt) = put (1::Word8) >> put halgo >> put salt put (IteratedSaltedS2K halgo salt count) = put (3::Word8) >> put halgo >> put salt >> put (encode_s2k_count count) put (S2K t body) = put t >> putSomeByteString body get = do t <- get :: Get Word8 case t of 0 -> SimpleS2K <$> get 1 -> SaltedS2K <$> get <*> get 3 -> IteratedSaltedS2K <$> get <*> get <*> (decode_s2k_count <$> get) _ -> S2K t <$> getRemainingByteString -- | Take a hash function and an 'S2K' value and generate the bytes -- needed for creating a symmetric key. -- -- Return value is always infinite length. -- Take the first n bytes you need for your keysize. string2key :: (HashAlgorithm -> LZ.ByteString -> BS.ByteString) -> S2K -> LZ.ByteString -> LZ.ByteString string2key hsh (SimpleS2K halgo) s = infiniHashes (hsh halgo) s string2key hsh (SaltedS2K halgo salt) s = infiniHashes (hsh halgo) (lazyEncode salt `LZ.append` s) string2key hsh (IteratedSaltedS2K halgo salt count) s = infiniHashes (hsh halgo) $ LZ.take (max (fromIntegral count) (LZ.length s)) (LZ.cycle $ lazyEncode salt `LZ.append` s) string2key _ s2k _ = error $ "Unsupported S2K specifier: " ++ show s2k infiniHashes :: (LZ.ByteString -> BS.ByteString) -> LZ.ByteString -> LZ.ByteString infiniHashes hsh s = LZ.fromChunks (hs 0) where hs c = hsh (LZ.replicate c 0 `LZ.append` s) : hs (c+1) data HashAlgorithm = MD5 | SHA1 | RIPEMD160 | SHA256 | SHA384 | SHA512 | SHA224 | HashAlgorithm Word8 deriving (Show, Read, Eq) instance Enum HashAlgorithm where toEnum 01 = MD5 toEnum 02 = SHA1 toEnum 03 = RIPEMD160 toEnum 08 = SHA256 toEnum 09 = SHA384 toEnum 10 = SHA512 toEnum 11 = SHA224 toEnum x = HashAlgorithm $ fromIntegral x fromEnum MD5 = 01 fromEnum SHA1 = 02 fromEnum RIPEMD160 = 03 fromEnum SHA256 = 08 fromEnum SHA384 = 09 fromEnum SHA512 = 10 fromEnum SHA224 = 11 fromEnum (HashAlgorithm x) = fromIntegral x instance BINARY_CLASS HashAlgorithm where put = put . enum_to_word8 get = fmap enum_from_word8 get data KeyAlgorithm = RSA | RSA_E | RSA_S | ELGAMAL | DSA | ECC | ECDSA | DH | KeyAlgorithm Word8 deriving (Show, Read, Eq) instance Enum KeyAlgorithm where toEnum 01 = RSA toEnum 02 = RSA_E toEnum 03 = RSA_S toEnum 16 = ELGAMAL toEnum 17 = DSA toEnum 18 = ECC toEnum 19 = ECDSA toEnum 21 = DH toEnum x = KeyAlgorithm $ fromIntegral x fromEnum RSA = 01 fromEnum RSA_E = 02 fromEnum RSA_S = 03 fromEnum ELGAMAL = 16 fromEnum DSA = 17 fromEnum ECC = 18 fromEnum ECDSA = 19 fromEnum DH = 21 fromEnum (KeyAlgorithm x) = fromIntegral x instance BINARY_CLASS KeyAlgorithm where put = put . enum_to_word8 get = fmap enum_from_word8 get data SymmetricAlgorithm = Unencrypted | IDEA | TripleDES | CAST5 | Blowfish | AES128 | AES192 | AES256 | Twofish | SymmetricAlgorithm Word8 deriving (Show, Read, Eq) instance Enum SymmetricAlgorithm where toEnum 00 = Unencrypted toEnum 01 = IDEA toEnum 02 = TripleDES toEnum 03 = CAST5 toEnum 04 = Blowfish toEnum 07 = AES128 toEnum 08 = AES192 toEnum 09 = AES256 toEnum 10 = Twofish toEnum x = SymmetricAlgorithm $ fromIntegral x fromEnum Unencrypted = 00 fromEnum IDEA = 01 fromEnum TripleDES = 02 fromEnum CAST5 = 03 fromEnum Blowfish = 04 fromEnum AES128 = 07 fromEnum AES192 = 08 fromEnum AES256 = 09 fromEnum Twofish = 10 fromEnum (SymmetricAlgorithm x) = fromIntegral x instance BINARY_CLASS SymmetricAlgorithm where put = put . enum_to_word8 get = fmap enum_from_word8 get data CompressionAlgorithm = Uncompressed | ZIP | ZLIB | BZip2 | CompressionAlgorithm Word8 deriving (Show, Read, Eq) instance Enum CompressionAlgorithm where toEnum 0 = Uncompressed toEnum 1 = ZIP toEnum 2 = ZLIB toEnum 3 = BZip2 toEnum x = CompressionAlgorithm $ fromIntegral x fromEnum Uncompressed = 0 fromEnum ZIP = 1 fromEnum ZLIB = 2 fromEnum BZip2 = 3 fromEnum (CompressionAlgorithm x) = fromIntegral x instance BINARY_CLASS CompressionAlgorithm where put = put . enum_to_word8 get = fmap enum_from_word8 get data RevocationCode = NoReason | KeySuperseded | KeyCompromised | KeyRetired | UserIDInvalid | RevocationCode Word8 deriving (Show, Read, Eq) instance Enum RevocationCode where toEnum 00 = NoReason toEnum 01 = KeySuperseded toEnum 02 = KeyCompromised toEnum 03 = KeyRetired toEnum 32 = UserIDInvalid toEnum x = RevocationCode $ fromIntegral x fromEnum NoReason = 00 fromEnum KeySuperseded = 01 fromEnum KeyCompromised = 02 fromEnum KeyRetired = 03 fromEnum UserIDInvalid = 32 fromEnum (RevocationCode x) = fromIntegral x instance BINARY_CLASS RevocationCode where put = put . enum_to_word8 get = fmap enum_from_word8 get -- | A message is encoded as a list that takes the entire file newtype Message = Message [Packet] deriving (Show, Read, Eq) instance BINARY_CLASS Message where put (Message xs) = mapM_ put xs get = fmap Message listUntilEnd instance Monoid Message where mempty = Message [] mappend (Message a) (Message b) = Message (a ++ b) -- | Data needed to verify a signature data SignatureOver = DataSignature {literal::Packet, signatures_over::[Packet]} | KeySignature {topkey::Packet, signatures_over::[Packet]} | SubkeySignature {topkey::Packet, subkey::Packet, signatures_over::[Packet]} | CertificationSignature {topkey::Packet, user_id::Packet, signatures_over::[Packet]} deriving (Show, Read, Eq) -- To get the signed-over bytes instance BINARY_CLASS SignatureOver where put (DataSignature (LiteralDataPacket {content = c}) _) = putSomeByteString c put (KeySignature k _) = mapM_ putSomeByteString (fingerprint_material k) put (SubkeySignature k s _) = mapM_ (mapM_ putSomeByteString) [fingerprint_material k, fingerprint_material s] put (CertificationSignature k (UserIDPacket s) _) = mapM_ (mapM_ putSomeByteString) [fingerprint_material k, [ B.singleton 0xB4, encode ((fromIntegral $ B.length bs) :: Word32), bs ]] where bs = B.fromString s put x = fail $ "Malformed signature: " ++ show x get = fail "Cannot meaningfully parse bytes to be signed over." -- | Extract signed objects from a well-formatted message -- -- Recurses into CompressedDataPacket -- -- <http://tools.ietf.org/html/rfc4880#section-11> signatures :: Message -> [SignatureOver] signatures (Message [CompressedDataPacket _ m]) = signatures m signatures (Message ps) = maybe (paired_sigs Nothing ps) (\p -> [DataSignature p sigs]) (find isDta ps) where sigs = filter isSignaturePacket ps isDta (LiteralDataPacket {}) = True isDta _ = False -- TODO: UserAttribute paired_sigs :: Maybe Packet -> [Packet] -> [SignatureOver] paired_sigs _ [] = [] paired_sigs _ (p@(PublicKeyPacket {is_subkey = False}):ps) = KeySignature p (takeWhile isSignaturePacket ps) : paired_sigs (Just p) (dropWhile isSignaturePacket ps) paired_sigs _ (p@(SecretKeyPacket {is_subkey = False}):ps) = KeySignature p (takeWhile isSignaturePacket ps) : paired_sigs (Just p) (dropWhile isSignaturePacket ps) paired_sigs (Just k) (p@(PublicKeyPacket {is_subkey = True}):ps) = SubkeySignature k p (takeWhile isSignaturePacket ps) : paired_sigs (Just k) (dropWhile isSignaturePacket ps) paired_sigs (Just k) (p@(SecretKeyPacket {is_subkey = True}):ps) = SubkeySignature k p (takeWhile isSignaturePacket ps) : paired_sigs (Just k) (dropWhile isSignaturePacket ps) paired_sigs (Just k) (p@(UserIDPacket {}):ps) = CertificationSignature k p (takeWhile isSignaturePacket ps) : paired_sigs (Just k) (dropWhile isSignaturePacket ps) paired_sigs k (_:ps) = paired_sigs k ps -- | <http://tools.ietf.org/html/rfc4880#section-3.2> newtype MPI = MPI Integer deriving (Show, Read, Eq, Ord) instance BINARY_CLASS MPI where put (MPI i) | i >= 0 = do put (bitl :: Word16) putSomeByteString bytes | otherwise = fail $ "MPI is less than 0: " ++ show i where (bytes, bitl) | B.null bytes' = (B.singleton 0, 1) | otherwise = (bytes', (fromIntegral (B.length bytes') - 1) * 8 + sigBit) sigBit = fst $ until ((==0) . snd) (first (+1) . second (`shiftR` 1)) (0,B.index bytes 0) bytes' = B.reverse $ B.unfoldr (\x -> if x == 0 then Nothing else Just (fromIntegral x, x `shiftR` 8) ) i get = do length <- fmap fromIntegral (get :: Get Word16) bytes <- getSomeByteString =<< assertProp (>0) ((length + 7) `div` 8) return (MPI (B.foldl (\a b -> a `shiftL` 8 .|. fromIntegral b) 0 bytes)) listUntilEnd :: (BINARY_CLASS a) => Get [a] listUntilEnd = do done <- isEmpty if done then return [] else do next <- get rest <- listUntilEnd return (next:rest) -- | <http://tools.ietf.org/html/rfc4880#section-5.2.3.1> data SignatureSubpacket = SignatureCreationTimePacket Word32 | SignatureExpirationTimePacket Word32 | -- ^ seconds after CreationTime ExportableCertificationPacket Bool | TrustSignaturePacket {depth::Word8, trust::Word8} | RegularExpressionPacket String | RevocablePacket Bool | KeyExpirationTimePacket Word32 | -- ^ seconds after key CreationTime PreferredSymmetricAlgorithmsPacket [SymmetricAlgorithm] | RevocationKeyPacket { sensitive::Bool, revocation_key_algorithm::KeyAlgorithm, revocation_key_fingerprint::String } | IssuerPacket String | NotationDataPacket { human_readable::Bool, notation_name::String, notation_value::String } | PreferredHashAlgorithmsPacket [HashAlgorithm] | PreferredCompressionAlgorithmsPacket [CompressionAlgorithm] | KeyServerPreferencesPacket {keyserver_no_modify::Bool} | PreferredKeyServerPacket String | PrimaryUserIDPacket Bool | PolicyURIPacket String | KeyFlagsPacket { certify_keys::Bool, sign_data::Bool, encrypt_communication::Bool, encrypt_storage::Bool, split_key::Bool, authentication::Bool, group_key::Bool } | SignerUserIDPacket String | ReasonForRevocationPacket RevocationCode String | FeaturesPacket {supports_mdc::Bool} | SignatureTargetPacket { target_key_algorithm::KeyAlgorithm, target_hash_algorithm::HashAlgorithm, hash::B.ByteString } | EmbeddedSignaturePacket Packet | UnsupportedSignatureSubpacket Word8 B.ByteString deriving (Show, Read, Eq) instance BINARY_CLASS SignatureSubpacket where put p = do -- Use 5-octet-length + 1 for tag as the first packet body octet put (255 :: Word8) put (fromIntegral (B.length body) + 1 :: Word32) put tag putSomeByteString body where (body, tag) = put_signature_subpacket p get = do len <- fmap fromIntegral (get :: Get Word8) len <- case len of _ | len >= 192 && len < 255 -> do -- Two octet length second <- fmap fromIntegral (get :: Get Word8) return $ ((len - 192) `shiftL` 8) + second + 192 255 -> -- Five octet length fmap fromIntegral (get :: Get Word32) _ -> -- One octet length, no furthur processing return len tag <- fmap stripCrit get :: Get Word8 -- This forces the whole packet to be consumed packet <- getSomeByteString (len-1) localGet (parse_signature_subpacket tag) packet where -- TODO: Decide how to actually encode the "is critical" data -- instead of just ignoring it stripCrit tag = if tag .&. 0x80 == 0x80 then tag .&. 0x7f else tag put_signature_subpacket :: SignatureSubpacket -> (B.ByteString, Word8) put_signature_subpacket (SignatureCreationTimePacket time) = (encode time, 2) put_signature_subpacket (SignatureExpirationTimePacket time) = (encode time, 3) put_signature_subpacket (ExportableCertificationPacket exportable) = (encode $ enum_to_word8 exportable, 4) put_signature_subpacket (TrustSignaturePacket depth trust) = (B.concat [encode depth, encode trust], 5) put_signature_subpacket (RegularExpressionPacket regex) = (B.concat [B.fromString regex, B.singleton 0], 6) put_signature_subpacket (RevocablePacket exportable) = (encode $ enum_to_word8 exportable, 7) put_signature_subpacket (KeyExpirationTimePacket time) = (encode time, 9) put_signature_subpacket (PreferredSymmetricAlgorithmsPacket algos) = (B.concat $ map encode algos, 11) put_signature_subpacket (RevocationKeyPacket sensitive kalgo fpr) = (B.concat [encode bitfield, encode kalgo, fprb], 12) where bitfield = 0x80 .|. (if sensitive then 0x40 else 0x0) :: Word8 fprb = padBS 20 $ B.drop 2 $ encode (MPI fpri) fpri = fst $ head $ readHex fpr put_signature_subpacket (IssuerPacket keyid) = (encode (fst $ head $ readHex $ takeFromEnd 16 keyid :: Word64), 16) put_signature_subpacket (NotationDataPacket human_readable name value) = (B.concat [ B.pack [flag1,0,0,0], encode (fromIntegral (B.length namebs) :: Word16), encode (fromIntegral (B.length valuebs) :: Word16), namebs, valuebs ], 20) where valuebs = B.fromString value namebs = B.fromString name flag1 = if human_readable then 0x80 else 0x0 put_signature_subpacket (PreferredHashAlgorithmsPacket algos) = (B.concat $ map encode algos, 21) put_signature_subpacket (PreferredCompressionAlgorithmsPacket algos) = (B.concat $ map encode algos, 22) put_signature_subpacket (KeyServerPreferencesPacket no_modify) = (B.singleton (if no_modify then 0x80 else 0x0), 23) put_signature_subpacket (PreferredKeyServerPacket uri) = (B.fromString uri, 24) put_signature_subpacket (PrimaryUserIDPacket isprimary) = (encode $ enum_to_word8 isprimary, 25) put_signature_subpacket (PolicyURIPacket uri) = (B.fromString uri, 26) put_signature_subpacket (KeyFlagsPacket certify sign encryptC encryptS split auth group) = (B.singleton $ flag 0x01 certify .|. flag 0x02 sign .|. flag 0x04 encryptC .|. flag 0x08 encryptS .|. flag 0x10 split .|. flag 0x20 auth .|. flag 0x80 group , 27) where flag x True = x flag _ False = 0x0 put_signature_subpacket (SignerUserIDPacket userid) = (B.fromString userid, 28) put_signature_subpacket (ReasonForRevocationPacket code string) = (B.concat [encode code, B.fromString string], 29) put_signature_subpacket (FeaturesPacket supports_mdc) = (B.singleton $ if supports_mdc then 0x01 else 0x00, 30) put_signature_subpacket (SignatureTargetPacket kalgo halgo hash) = (B.concat [encode kalgo, encode halgo, hash], 31) put_signature_subpacket (EmbeddedSignaturePacket packet) | isSignaturePacket packet = (fst $ put_packet packet, 32) | otherwise = error $ "Tried to put non-SignaturePacket in EmbeddedSignaturePacket: " ++ show packet put_signature_subpacket (UnsupportedSignatureSubpacket tag bytes) = (bytes, tag) parse_signature_subpacket :: Word8 -> Get SignatureSubpacket -- SignatureCreationTimePacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.4 parse_signature_subpacket 2 = fmap SignatureCreationTimePacket get -- SignatureExpirationTimePacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.10 parse_signature_subpacket 3 = fmap SignatureExpirationTimePacket get -- ExportableCertificationPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.11 parse_signature_subpacket 4 = fmap (ExportableCertificationPacket . enum_from_word8) get -- TrustSignaturePacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.13 parse_signature_subpacket 5 = liftM2 TrustSignaturePacket get get -- TrustSignaturePacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.14 parse_signature_subpacket 6 = fmap (RegularExpressionPacket . B.toString . B.init) getRemainingByteString -- RevocablePacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.12 parse_signature_subpacket 7 = fmap (RevocablePacket . enum_from_word8) get -- KeyExpirationTimePacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.6 parse_signature_subpacket 9 = fmap KeyExpirationTimePacket get -- PreferredSymmetricAlgorithms, http://tools.ietf.org/html/rfc4880#section-5.2.3.7 parse_signature_subpacket 11 = fmap PreferredSymmetricAlgorithmsPacket listUntilEnd -- RevocationKeyPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.15 parse_signature_subpacket 12 = do bitfield <- get :: Get Word8 kalgo <- get fpr <- getSomeByteString 20 -- bitfield must have bit 0x80 set, says the spec return RevocationKeyPacket { sensitive = bitfield .&. 0x40 == 0x40, revocation_key_algorithm = kalgo, revocation_key_fingerprint = pad 40 $ map toUpper $ foldr (padB `oo` showHex) "" (B.unpack fpr) } where oo = (.) . (.) padB s | odd $ length s = '0':s | otherwise = s -- IssuerPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.5 parse_signature_subpacket 16 = do keyid <- get :: Get Word64 return $ IssuerPacket (pad 16 $ map toUpper $ showHex keyid "") -- NotationDataPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.16 parse_signature_subpacket 20 = do (flag1,_,_,_) <- get4word8 (m,n) <- liftM2 (,) get get :: Get (Word16,Word16) name <- fmap B.toString $ getSomeByteString $ fromIntegral m value <- fmap B.toString $ getSomeByteString $ fromIntegral n return NotationDataPacket { human_readable = flag1 .&. 0x80 == 0x80, notation_name = name, notation_value = value } where get4word8 :: Get (Word8,Word8,Word8,Word8) get4word8 = liftM4 (,,,) get get get get -- PreferredHashAlgorithmsPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.8 parse_signature_subpacket 21 = fmap PreferredHashAlgorithmsPacket listUntilEnd -- PreferredCompressionAlgorithmsPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.9 parse_signature_subpacket 22 = fmap PreferredCompressionAlgorithmsPacket listUntilEnd -- KeyServerPreferencesPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.17 parse_signature_subpacket 23 = do empty <- isEmpty flag1 <- if empty then return 0 else get :: Get Word8 return KeyServerPreferencesPacket { keyserver_no_modify = flag1 .&. 0x80 == 0x80 } -- PreferredKeyServerPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.18 parse_signature_subpacket 24 = fmap (PreferredKeyServerPacket . B.toString) getRemainingByteString -- PrimaryUserIDPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.19 parse_signature_subpacket 25 = fmap (PrimaryUserIDPacket . enum_from_word8) get -- PolicyURIPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.20 parse_signature_subpacket 26 = fmap (PolicyURIPacket . B.toString) getRemainingByteString -- KeyFlagsPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.21 parse_signature_subpacket 27 = do empty <- isEmpty flag1 <- if empty then return 0 else get :: Get Word8 return KeyFlagsPacket { certify_keys = flag1 .&. 0x01 == 0x01, sign_data = flag1 .&. 0x02 == 0x02, encrypt_communication = flag1 .&. 0x04 == 0x04, encrypt_storage = flag1 .&. 0x08 == 0x08, split_key = flag1 .&. 0x10 == 0x10, authentication = flag1 .&. 0x20 == 0x20, group_key = flag1 .&. 0x80 == 0x80 } -- SignerUserIDPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.22 parse_signature_subpacket 28 = fmap (SignerUserIDPacket . B.toString) getRemainingByteString -- ReasonForRevocationPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.23 parse_signature_subpacket 29 = liftM2 ReasonForRevocationPacket get (fmap B.toString getRemainingByteString) -- FeaturesPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.24 parse_signature_subpacket 30 = do empty <- isEmpty flag1 <- if empty then return 0 else get :: Get Word8 return FeaturesPacket { supports_mdc = flag1 .&. 0x01 == 0x01 } -- SignatureTargetPacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.25 parse_signature_subpacket 31 = liftM3 SignatureTargetPacket get get getRemainingByteString -- EmbeddedSignaturePacket, http://tools.ietf.org/html/rfc4880#section-5.2.3.26 parse_signature_subpacket 32 = fmap EmbeddedSignaturePacket (parse_packet 2) -- Represent unsupported packets as their tag and literal bytes parse_signature_subpacket tag = fmap (UnsupportedSignatureSubpacket tag) getRemainingByteString -- | Find the keyid that issued a SignaturePacket signature_issuer :: Packet -> Maybe String signature_issuer (SignaturePacket {hashed_subpackets = hashed, unhashed_subpackets = unhashed}) = case issuers of IssuerPacket issuer : _ -> Just issuer _ -> Nothing where issuers = filter isIssuer hashed ++ filter isIssuer unhashed isIssuer (IssuerPacket {}) = True isIssuer _ = False signature_issuer _ = Nothing -- | Find a key with the given Fingerprint/KeyID find_key :: (Packet -> String) -- ^ Extract Fingerprint/KeyID from packet -> Message -- ^ List of packets (some of which are keys) -> String -- ^ Fingerprint/KeyID to search for -> Maybe Packet find_key fpr (Message (x@(PublicKeyPacket {}):xs)) keyid = find_key' fpr x xs keyid find_key fpr (Message (x@(SecretKeyPacket {}):xs)) keyid = find_key' fpr x xs keyid find_key fpr (Message (_:xs)) keyid = find_key fpr (Message xs) keyid find_key _ _ _ = Nothing find_key' :: (Packet -> String) -> Packet -> [Packet] -> String -> Maybe Packet find_key' fpr x xs keyid | thisid == keyid = Just x | otherwise = find_key fpr (Message xs) keyid where thisid = takeFromEnd (length keyid) (fpr x) takeFromEnd :: Int -> String -> String takeFromEnd l = reverse . take l . reverse -- | SignaturePacket smart constructor -- -- <http://tools.ietf.org/html/rfc4880#section-5.2> signaturePacket :: Word8 -- ^ Signature version (probably 4) -> Word8 -- ^ Signature type <http://tools.ietf.org/html/rfc4880#section-5.2.1> -> KeyAlgorithm -> HashAlgorithm -> [SignatureSubpacket] -- ^ Hashed subpackets (these get signed) -> [SignatureSubpacket] -- ^ Unhashed subpackets (these do not get signed) -> Word16 -- ^ Left 16 bits of the signed hash value -> [MPI] -- ^ The raw MPIs of the signature -> Packet signaturePacket version signature_type key_algorithm hash_algorithm hashed_subpackets unhashed_subpackets hash_head signature = let p = SignaturePacket { version = version, signature_type = signature_type, key_algorithm = key_algorithm, hash_algorithm = hash_algorithm, hashed_subpackets = hashed_subpackets, unhashed_subpackets = unhashed_subpackets, hash_head = hash_head, signature = signature, trailer = undefined } in p { trailer = calculate_signature_trailer p } isSignaturePacket :: Packet -> Bool isSignaturePacket (SignaturePacket {}) = True isSignaturePacket _ = False
acatton/OpenPGP-Haskell
Data/OpenPGP.hs
isc
46,850
950
23
8,547
13,691
7,285
6,406
1,050
7
{-# LANGUAGE OverloadedStrings #-} -- | This module exports functionality for generating a call graph of -- an Futhark program. module Futhark.Analysis.CallGraph ( CallGraph, buildCallGraph, isFunInCallGraph, calls, calledByConsts, allCalledBy, numOccurences, findNoninlined, ) where import Control.Monad.Writer.Strict import Data.List (foldl') import qualified Data.Map.Strict as M import Data.Maybe (isJust) import qualified Data.Set as S import Futhark.IR.SOACS import Futhark.Util.Pretty type FunctionTable = M.Map Name (FunDef SOACS) buildFunctionTable :: Prog SOACS -> FunctionTable buildFunctionTable = foldl expand M.empty . progFuns where expand ftab f = M.insert (funDefName f) f ftab -- | A unique (at least within a function) name identifying a function -- call. In practice the first element of the corresponding pattern. type CallId = VName data FunCalls = FunCalls { fcMap :: M.Map CallId (Attrs, Name), fcAllCalled :: S.Set Name } deriving (Eq, Ord, Show) instance Monoid FunCalls where mempty = FunCalls mempty mempty instance Semigroup FunCalls where FunCalls x1 y1 <> FunCalls x2 y2 = FunCalls (x1 <> x2) (y1 <> y2) fcCalled :: Name -> FunCalls -> Bool fcCalled f fcs = f `S.member` fcAllCalled fcs type FunGraph = M.Map Name FunCalls -- | The call graph is a mapping from a function name, i.e., the -- caller, to a record of the names of functions called *directly* (not -- transitively!) by the function. -- -- We keep track separately of the functions called by constants. data CallGraph = CallGraph { cgCalledByFuns :: FunGraph, cgCalledByConsts :: FunCalls } deriving (Eq, Ord, Show) -- | Is the given function known to the call graph? isFunInCallGraph :: Name -> CallGraph -> Bool isFunInCallGraph f = M.member f . cgCalledByFuns -- | Does the first function call the second? calls :: Name -> Name -> CallGraph -> Bool calls caller callee = maybe False (fcCalled callee) . M.lookup caller . cgCalledByFuns -- | Is the function called in any of the constants? calledByConsts :: Name -> CallGraph -> Bool calledByConsts callee = fcCalled callee . cgCalledByConsts -- | All functions called by this function. allCalledBy :: Name -> CallGraph -> S.Set Name allCalledBy f = maybe mempty fcAllCalled . M.lookup f . cgCalledByFuns -- | @buildCallGraph prog@ build the program's call graph. buildCallGraph :: Prog SOACS -> CallGraph buildCallGraph prog = CallGraph fg cg where fg = foldl' (buildFGfun ftable) M.empty entry_points cg = buildFGStms $ progConsts prog entry_points = S.fromList (map funDefName (filter (isJust . funDefEntryPoint) $ progFuns prog)) <> fcAllCalled cg ftable = buildFunctionTable prog count :: Ord k => [k] -> M.Map k Int count ks = M.fromListWith (+) $ zip ks $ repeat 1 -- | Produce a mapping of the number of occurences in the call graph -- of each function. Only counts functions that are called at least -- once. numOccurences :: CallGraph -> M.Map Name Int numOccurences (CallGraph funs consts) = count $ map snd $ M.elems (fcMap consts <> foldMap fcMap (M.elems funs)) -- | @buildCallGraph ftable fg fname@ updates @fg@ with the -- contributions of function @fname@. buildFGfun :: FunctionTable -> FunGraph -> Name -> FunGraph buildFGfun ftable fg fname = -- Check if function is a non-builtin that we have not already -- processed. case M.lookup fname ftable of Just f | Nothing <- M.lookup fname fg -> do let callees = buildFGBody $ funDefBody f fg' = M.insert fname callees fg -- recursively build the callees foldl' (buildFGfun ftable) fg' $ fcAllCalled callees _ -> fg buildFGStms :: Stms SOACS -> FunCalls buildFGStms = mconcat . map buildFGstm . stmsToList buildFGBody :: Body SOACS -> FunCalls buildFGBody = buildFGStms . bodyStms buildFGstm :: Stm SOACS -> FunCalls buildFGstm (Let (Pat (p : _)) aux (Apply fname _ _ _)) = FunCalls (M.singleton (patElemName p) (stmAuxAttrs aux, fname)) (S.singleton fname) buildFGstm (Let _ _ (Op op)) = execWriter $ mapSOACM folder op where folder = identitySOACMapper { mapOnSOACLambda = \lam -> do tell $ buildFGBody $ lambdaBody lam return lam } buildFGstm (Let _ _ e) = execWriter $ mapExpM folder e where folder = identityMapper { mapOnBody = \_ body -> do tell $ buildFGBody body return body } -- | The set of all functions that are called noinline somewhere, or -- have a noinline attribute on their definition. findNoninlined :: Prog SOACS -> S.Set Name findNoninlined prog = foldMap noinlineDef (progFuns prog) <> foldMap onStm (foldMap (bodyStms . funDefBody) (progFuns prog) <> progConsts prog) where onStm :: Stm SOACS -> S.Set Name onStm (Let _ aux (Apply fname _ _ _)) | "noinline" `inAttrs` stmAuxAttrs aux = S.singleton fname onStm (Let _ _ e) = execWriter $ mapExpM folder e where folder = identityMapper { mapOnBody = \_ body -> do tell $ foldMap onStm $ bodyStms body return body, mapOnOp = mapSOACM identitySOACMapper { mapOnSOACLambda = \lam -> do tell $ foldMap onStm $ bodyStms $ lambdaBody lam return lam } } noinlineDef fd | "noinline" `inAttrs` funDefAttrs fd = S.singleton $ funDefName fd | otherwise = mempty instance Pretty FunCalls where ppr = stack . map f . M.toList . fcMap where f (x, (attrs, y)) = "=>" <+> ppr y <+> parens ("at" <+> ppr x <+> ppr attrs) instance Pretty CallGraph where ppr (CallGraph fg cg) = stack $ punctuate line $ ppFunCalls ("called at top level", cg) : map ppFunCalls (M.toList fg) where ppFunCalls (f, fcalls) = ppr f </> text (map (const '=') (nameToString f)) </> indent 2 (ppr fcalls)
diku-dk/futhark
src/Futhark/Analysis/CallGraph.hs
isc
6,062
0
20
1,515
1,701
871
830
123
2
{-| Module : Control.Monad.Bayes.Trace Description : Probabilistic computation accumulating a trace Copyright : (c) Yufei Cai, 2016 (c) Adam Scibior, 2016 License : MIT Maintainer : ams240@cam.ac.uk Stability : experimental Portability : GHC -} {-# LANGUAGE GADTs, DeriveFunctor, ScopedTypeVariables #-} module Control.Monad.Bayes.Trace ( Trace, fromLists, toLists, Traced, hoist, mhStep, dropTrace ) where import Control.Monad.Bayes.LogDomain (LogDomain, toLogDomain, fromLogDomain) import Control.Monad.Bayes.Primitive import Control.Monad.Bayes.Class import Control.Monad.Bayes.Weighted hiding (hoist) import Control.Monad.Bayes.Coprimitive import Control.Arrow import Control.Monad import Control.Monad.Coroutine hiding (hoist) import Control.Monad.Coroutine.SuspensionFunctors import Control.Monad.Trans import Data.Maybe import Data.List import Safe (tailSafe) -- | Trace of a probabilistic program is a collection of values for all the -- latent random variables. newtype Trace r = Trace ([r],[Int]) deriving(Monoid) -- | Package values as a trace. fromLists :: ([r],[Int]) -> Trace r fromLists = Trace -- | Extract values from a trace. toLists :: Trace r -> ([r],[Int]) toLists (Trace t) = t -- | An old primitive sample is reusable if both distributions have the -- same support. reusePrimitive :: Primitive r a -> Primitive r b -> a -> Maybe b reusePrimitive d d' x = case (d,d') of (Discrete xs, Discrete xs') | support d == support d' -> Just x (Continuous xs, Continuous xs') | support d == support d' -> Just x _ -> Nothing -- | A GADT for caching primitive distributions and values drawn from them. -- The parameter is a numeric type used for representing real numbers. data Cache r where Cache :: Primitive r a -> a -> Cache r instance Eq (Cache r) where Cache d@(Discrete _) x == Cache d'@(Discrete _) x' = d == d' && x == x' Cache d@(Continuous _) x == Cache d'@(Continuous _) x' = d == d' && x == x' Cache _ _ == Cache _ _ = False instance Show r => Show (Cache r) where showsPrec p cache r = -- Haskell passes precedence 11 for Cache as a constructor argument. -- The precedence of function application seems to be 10. if p > 10 then '(' : printCache cache (')' : r) else printCache cache r where printCache :: Cache r -> String -> String printCache (Cache d@(Discrete _) x) r = "Cache " ++ showsPrec 11 d (' ' : showsPrec 11 (show x) r) printCache (Cache d@(Continuous _) x) r = "Cache " ++ showsPrec 11 d (' ' : showsPrec 11 (show x) r) -- | Suspension functor: yield primitive distribution and previous sample, await new sample. -- The first parameter is a numeric type used for representing real numbers. data Snapshot r y where Snapshot :: Primitive r a -> a -> (a -> y) -> Snapshot r y deriving instance Functor (Snapshot r) -- | Discard the continuation. snapshotToCache :: Snapshot r y -> Cache r snapshotToCache (Snapshot d x _) = Cache d x -- | An intermediate state used in the Metropolis-Hastings algorithm. data MHState m a = MHState { mhSnapshots :: [Snapshot (CustomReal m) (Weighted (Coprimitive m) a)] -- ^ A list of snapshots of all random variables in the program. -- Continuations in snapshots produce full likelihood of the whole trace. , mhPosteriorWeight :: LogDomain (CustomReal m) -- ^ Likelihood of the trace. , mhAnswer :: a -- ^ The final value in the trace. } deriving Functor -- | Reuse previous samples as much as possible, collect reuse ratio. mhReuse :: (MonadDist m) => [Cache (CustomReal m)] -> Weighted (Coprimitive m) a -> m (LogDomain (CustomReal m), MHState m a) mhReuse caches m = do result <- resume (runCoprimitive (runWeighted m)) case result of -- program finished Right (answer, weight) -> return (1, MHState [] weight answer) -- random choice encountered Left (AwaitSampler d' continuation) -> let -- package continuation wCtn = withWeight . Coprimitive . continuation -- new value and MH correction factor from reuse (newSample, reuseFactor) = case caches of -- reuse (Cache d x : cs) | Just x' <- reusePrimitive d d' x -> (return x', pdf d' x' / pdf d x) -- can't reuse - sample from prior _ -> (primitive d', 1) -- cached value is discarded even on mismatch otherCaches = tailSafe caches in do x' <- newSample let s = Snapshot d' x' wCtn (reuseRatio, MHState snaps w a) <- mhReuse otherCaches (wCtn x') return (reuseRatio * reuseFactor, MHState (s : snaps) w a) -- | Run model once, cache primitive samples together with continuations -- awaiting the samples. mhState :: (MonadDist m) => Weighted (Coprimitive m) a -> m (MHState m a) mhState m = fmap snd (mhReuse [] m) -- | Forget cached samples, return a continuation to execute from scratch. mhReset :: (MonadDist m) => m (MHState m a) -> Weighted (Coprimitive m) a mhReset m = withWeight $ Coprimitive $ Coroutine $ do MHState snapshots weight answer <- m case snapshots of [] -> return $ Right (answer, weight) Snapshot d x continuation : _ -> return $ Left $ AwaitSampler d (runCoprimitive . runWeighted . continuation) -- Adam: is it the case that mhReset . mhState = id = mhState . mhReset? -- | Propose new state, compute acceptance ratio mhPropose :: (MonadDist m) => MHState m a -> m (MHState m a, LogDomain (CustomReal m)) mhPropose oldState = do let m = length (mhSnapshots oldState) if m == 0 then return (oldState, 1) else do i <- uniformD [0 .. m - 1] let (prev, snapshot : next) = splitAt i (mhSnapshots oldState) let caches = map snapshotToCache next case snapshot of Snapshot d x continuation -> do x' <- primitive d (reuseRatio, partialState) <- mhReuse caches (continuation x') let newSnapshots = prev ++ Snapshot d x' continuation : mhSnapshots partialState let newState = partialState { mhSnapshots = newSnapshots } let n = length newSnapshots let numerator = fromIntegral m * mhPosteriorWeight newState * reuseRatio let denominator = fromIntegral n * mhPosteriorWeight oldState let acceptRatio = if denominator == 0 then 1 else min 1 (numerator / denominator) return (newState, acceptRatio) -- | The Lightweight Metropolis-Hastings kernel. Each MH-state carries all -- necessary information to compute the acceptance ratio. mhKernel :: (MonadDist m) => MHState m a -> m (MHState m a) mhKernel oldState = do (newState, acceptRatio) <- mhPropose oldState accept <- bernoulli $ fromLogDomain acceptRatio return (if accept then newState else oldState) -- | A probability monad that keeps the execution trace. -- Unlike `Trace`, it does not pass conditioning to the transformed monad. newtype Traced' m a = Traced' { unTraced' :: LogDomain (CustomReal m) -> m (MHState m a) } deriving (Functor) runTraced' :: MonadDist m => Traced' m a -> m (MHState m a) runTraced' = (`unTraced'` 1) type instance CustomReal (Traced' m) = CustomReal m instance MonadDist m => Applicative (Traced' m) where pure = return (<*>) = liftM2 ($) instance MonadDist m => Monad (Traced' m) where return x = Traced' $ \w -> return (MHState [] w x) m >>= f = Traced' $ \w -> do MHState ls lw la <- unTraced' m w MHState rs rw ra <- unTraced' (f la) lw return $ MHState (map (fmap convert) ls ++ rs) rw ra where --convert :: Weighted (Coprimitive m) a -> Weighted (Coprimitive m) b convert m = do (x,w) <- lift $ runWeighted m mhReset $ unTraced' (f x) w instance MonadTrans Traced' where lift m = Traced' $ \w -> fmap (MHState [] w) m instance (MonadDist m, MonadIO m) => MonadIO (Traced' m) where liftIO = lift . liftIO instance MonadDist m => MonadDist (Traced' m) where primitive d = Traced' $ \w -> do x <- primitive d return $ MHState [Snapshot d x (\x -> factor w >> return x)] w x instance MonadDist m => MonadBayes (Traced' m) where factor k = Traced' $ \w -> return (MHState [] (w * k) ()) -- | Modify the transformed monad. -- This is only applied to the current trace, not to future ones resulting from -- MH transitions. hoist' :: Monad m => (forall x. m x -> m x) -> Traced' m x -> Traced' m x hoist' t (Traced' m) = Traced' (t . m) -- | Perform a single step of the Lightweight Metropolis-Hastings algorithm. mhStep' :: (MonadDist m) => Traced' m a -> Traced' m a mhStep' (Traced' m) = Traced' (m >=> mhKernel) -- | Discard the trace. dropTrace' :: MonadDist m => Traced' m a -> m a dropTrace' = fmap mhAnswer . runTraced' -- | A probability monad that keeps the execution trace. -- It passes `factor`s to the transformed monad during the first execution, -- but not at subsequent ones, such as during MH transitions. -- Current implementation only works correctly if in the transformed monad -- factors can be arbitrarily reordered with other probabilistic effects -- without affecting observable behaviour. -- This property in particular holds true for `Weighted`. newtype Traced m a = Traced { runTraced :: Traced' (WeightRecorder m) a } deriving (Functor) type instance CustomReal (Traced m) = CustomReal m deriving instance MonadDist m => Applicative (Traced m) deriving instance MonadDist m => Monad (Traced m) deriving instance (MonadDist m, MonadIO m) => MonadIO (Traced m) deriving instance MonadDist m => MonadDist (Traced m) type instance CustomReal (Traced m) = CustomReal m instance MonadTrans Traced where lift = Traced . lift . lift instance MonadBayes m => MonadBayes (Traced m) where factor k = Traced $ do factor k lift (factor k) -- | Modify the transformed monad. -- This is only applied to the current trace, not to future ones resulting from -- MH transitions. hoist :: MonadDist m => (forall x. m x -> m x) -> Traced m x -> Traced m x hoist t = Traced . hoist' (hoistWeightRecorder t) . runTraced -- | Perform a single step of the Lightweight Metropolis-Hastings algorithm. -- In the new trace factors are not passed to the transformed monad, -- so in there the likelihood remains fixed. mhStep :: (MonadBayes m) => Traced m a -> Traced m a mhStep (Traced m) = Traced $ Traced' $ \w -> lift $ do (x,s) <- runWeighted $ duplicateWeight $ unTraced' (mhStep' $ hoist' resetWeightRecorder m) w -- Reverse the effect of factors in mhStep on the transformed monad. factor (1 / s) return x -- | Discard the trace. dropTrace :: MonadDist m => Traced m a -> m a dropTrace = fmap fst . runWeighted . duplicateWeight . dropTrace' . runTraced
ocramz/monad-bayes
src/Control/Monad/Bayes/Trace.hs
mit
10,854
0
21
2,523
3,167
1,624
1,543
-1
-1
module Internal where import Control.Applicative import Control.Dangerous import Control.DateTime.Absolute import Text.Pin import Text.Point import Text.Pinpoint import {-# SOURCE #-} Data.File class (Applicative i, Errorable i) => Internal i where pinpoint :: Pinpoint -> i Absolute location :: Pinpoint -> i String find :: Pin -> i (Maybe File) build :: (FilePath -> File -> i a) -> i [a] class Momented m where when :: (Internal i) => Side -> m -> i Absolute data Direction = Before | After deriving (Eq, Ord, Read, Show)
Soares/tagwiki
src/Internal.hs
mit
560
0
11
120
199
107
92
19
0
--import System.Random import System.Random.Mersenne --import System.Random.Mersenne.Pure64 import System.Environment import Text.Printf import Hoton.Distributions import Hoton.Vector import Hoton.Types import Hoton.Scene import Hoton.Scenes.Forward1D import Hoton.IO main :: IO () main = do args <- getArgs exe <- getProgName if length args < 1 then do putStrLn $ exe ++ " ACTION [params]" return () else let (action:params) = args in dispatch action params dispatch :: String -> [String] -> IO () dispatch "t1" = t1 dispatch "t2" = t2 dispatch "t3" = t3 t1 :: [String] -> IO () t1 params = if length params /= 1 then do exe <- getProgName putStrLn $ exe ++ " t1 nSamples" return () else do let numSamples = read $ head params :: Int -- gen <- getStdGen gen <- newMTGen Nothing randomNumbers <- randoms gen let rs = take numSamples $ fst (drawRandoms (HenyeyGreenstein 0.85) randomNumbers numSamples) mapM_ print rs t2 :: [String] -> IO () t2 params = if length params /= 4 then do exe <- getProgName putStrLn $ exe ++ " t2 g tau sza nPhotons" return () else do -- gen <- getStdGen -- gen <- newPureMT gen <- newMTGen Nothing randomNumbers <- randoms gen let [g, tau, sza] = map read $ take 3 params :: [Number] nphotons = read $ params !! 3 -- let top = BoundaryBox1D SourceTop -- let bottom = BoundaryBox1D SourceBottom -- let c = ContainerBox1D (Box (ContainerBox1D (Box top) (Box physics))) (Box bottom) let physics = physicsBox1D 1.0 tau $ RandomDistribution (HenyeyGreenstein g) print physics let pos0 = Cartesian 0.0 0.0 1.0 dir0 = toCartesian $ Spherical 1.0 ((sza*pi/180)+pi) 0.0 (ph0, g') = initializePhoton pos0 dir0 randomNumbers printf "SZA=%.0f, DIR=%s\n" sza $ show dir0 let (t,b) = summarize1D . take nphotons $ processManyEqualPhotons physics ph0 g' let r' = t / fromIntegral nphotons let t' = b / fromIntegral nphotons printf "TOP=%.0f BOTTOM=%.0f T=%f R=%f\n" t b t' r' t3 :: [String] -> IO () t3 params = if length params /= 3 then do exe <- getProgName putStrLn $ exe ++ " fn nphotons outFn" return () else do let fn = head params nphotons = read $ params !! 1 :: Int outFn = params !! 2 :: String atmos <- readAtmos fn let Just atmosphere = rayleighAtmos2Box atmos let Height h = getDim atmosphere -- gen <- newPureMT gen <- newMTGen Nothing let getTR gen sza = do randomNumbers <- randoms gen let pos0 = Cartesian 0.0 0.0 h dir0 = toCartesian $ Spherical 1.0 ((sza*pi/180)+pi) 0.0 (ph0, g') = initializePhoton pos0 dir0 randomNumbers (t,b) = summarize1D . take nphotons $ processManyEqualPhotons atmosphere ph0 g' let r' = t / fromIntegral nphotons let t' = b / fromIntegral nphotons printf "TOP=%.0f BOTTOM=%.0f R=%f T=%f ABS=%.6f\n" t b r' t' (1-r'-t') return (r', t') let angles = [0,5..85] res <- mapM (getTR gen) angles writeFile outFn . unlines $ zipWith (\sza (r, t) -> printf "%.1f %.6f %.6f" sza r t) angles res print "DONE"
woufrous/hoton
src/main.hs
mit
3,511
0
22
1,147
1,135
541
594
-1
-1
-- ------------------------------------------------------------------------------------- -- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved. -- For email, run on linux (perl v5.8.5): -- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"' -- ------------------------------------------------------------------------------------- toWord :: Int -> String toWord 1 = "One" toWord 2 = "Two" toWord 3 = "Three" toWord 4 = "Four" toWord 5 = "Five" toWord 6 = "Six" toWord 7 = "Seven" toWord 8 = "Eight" toWord 9 = "Nine" toWord 10 = "Ten" toWord 11 = "Eleven" toWord 12 = "Twelve" toWord 13 = "Thirteen" toWord 14 = "Fourteen" toWord 15 = "Fifteen" toWord 16 = "Sixteen" toWord 17 = "Seventeen" toWord 18 = "Eighteen" toWord 19 = "Nineteen" toWord 20 = "Twenty" toWord 30 = "Thirty" toWord 40 = "Forty" toWord 50 = "Fifty" toWord 60 = "Sixty" toWord 70 = "Seventy" toWord 80 = "Eighty" toWord 90 = "Ninety" toWord 100 = "Hundred" stringify' :: Int -> Int -> String stringify' 0 num = let lowTwenty = if lowerTwo > 0 && lowerTwo <= 20 then toWord lowerTwo else "" -- special case for low Twenty lowStr = if low /= 0 then toWord low else "" tenStr = if ten /= 0 then toWord ten else "" hundStr = if hund /= 0 then (toWord (hund `div` 100)) ++ " " ++ toWord 100 else "" low = num `mod` 10 ten = num `mod` 100 - num `mod` 10 hund = num `mod` 1000 - num `mod` 100 thou = num `mod` 10000 - num `mod` 1000 lowerTwo = num `mod` 100 lowSpace = if tenStr /= "" && lowStr /= "" then " " else "" lowTwoDigStr = if lowTwenty /= "" then lowTwenty else tenStr ++ lowSpace ++ lowStr needSpace = if hundStr /= "" && lowTwoDigStr /= "" then " " else "" in hundStr ++ needSpace ++ lowTwoDigStr stringify' n num = let testVal = 1000 ^ n upperNum = num `div` testVal restNum = num `mod` testVal choiceStr | n == 1 = "Thousand" | n == 2 = "Million" | n == 3 = "Billion" in stringify upperNum ++ " " ++ choiceStr ++ " " ++ stringify restNum stringify :: Int -> String stringify num | num `div` 1000000000 /= 0 = stringify' 3 num | num `div` 1000000 /= 0 = stringify' 2 num | num `div` 1000 /= 0 = stringify' 1 num | otherwise = stringify' 0 num main :: IO () main = do ip <- getContents let ns = map read . tail . lines $ ip anss = map stringify ns mapM_ (putStrLn) anss
cbrghostrider/Hacking
HackerRank/Contests/ProjectEuler/017_numberToWords.hs
mit
2,530
28
15
668
929
439
490
65
8
module Database (Schema(..), createSchema) where import qualified Data.Binary as Binary import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import qualified Data.UUID as UUID import qualified Timestamp as Timestamp import Data.Maybe import Language.SQL.SQLite data Schema = Schema { schemaID :: UUID.UUID, schemaVersion :: Timestamp.Timestamp, schemaTables :: [CreateTable] } createSchema :: Schema -> StatementList createSchema schema = do StatementList $ concat [[Statement $ createTable "schema" [columnDefinition "schema_id" blobType, columnDefinition "version" integerType], Statement $ Insert InsertNoAlternative (SinglyQualifiedIdentifier Nothing "schema") (InsertValues [UnqualifiedIdentifier "schema_id", UnqualifiedIdentifier "version"] (fromJust $ mkOneOrMore [ExpressionLiteralBlob $ (BS.concat . LBS.toChunks . Binary.encode) (schemaID schema), ExpressionLiteralInteger $ fromIntegral (schemaVersion schema)]))], map Statement (schemaTables schema)] createTable :: String -> [ColumnDefinition] -> CreateTable createTable name columns = CreateTable NoTemporary NoIfNotExists (SinglyQualifiedIdentifier Nothing name) (ColumnsAndConstraints (fromJust $ mkOneOrMore columns) []) primaryKeyColumnDefinition :: String -> Type -> ColumnDefinition primaryKeyColumnDefinition name type' = ColumnDefinition (UnqualifiedIdentifier name) (JustType type') [ColumnPrimaryKey NoConstraintName NoAscDesc (Just OnConflictAbort) NoAutoincrement] columnDefinition :: String -> Type -> ColumnDefinition columnDefinition name type' = ColumnDefinition (UnqualifiedIdentifier name) (JustType type') [] blobType :: Type blobType = Type TypeAffinityNone (TypeName (fromJust $ mkOneOrMore [UnqualifiedIdentifier "blob"])) NoTypeSize integerType :: Type integerType = Type TypeAffinityNone (TypeName (fromJust $ mkOneOrMore [UnqualifiedIdentifier "integer"])) NoTypeSize
IreneKnapp/ozweb
Haskell/Database.hs
mit
2,342
0
24
647
518
280
238
55
1
main :: IO () main = do firstRow <- getLine print . length . filter (=='.') . concat . take 400000 $ iterate nextRow firstRow nextRow :: String -> String nextRow row = map rule (zip3 left center right) where left = '.' : init row center = row right = tail row ++ "." rule ('^', '^', '.') = '^' rule ('.', '^', '^') = '^' rule ('^', '.', '.') = '^' rule ('.', '.', '^') = '^' rule (_, _, _) = '.'
lzlarryli/advent_of_code_2016
day18/part2.hs
mit
468
0
12
157
209
111
98
17
5
import Data.List import Data.Maybe import Data.Hash.MD5 import Debug.Trace key = "reyedfim" traceSelf x = traceShow x x result = map (fromJust . flip lookup stuff . show) [0..7] where stuff = map (\s -> traceSelf ([s !! 5], s !! 6)) $ filter (isPrefixOf "00000") $ map (\i -> md5s $ Str $ key ++ show i) [1..] main = putStrLn $ show result
msullivan/advent-of-code
2016/A5b.hs
mit
346
0
15
70
169
89
80
9
1
module ProjectRosalind.Lcsm.DirectToSet where import Data.Vector as V import Data.Set as S import Data.List as L import Data.Hashable (hash) import ProjectRosalind.Fasta (parseFasta') import ProjectRosalind.Fasta_Types import System.IO (openFile, hGetContents, IOMode(ReadMode)) import Control.Monad import Data.Time lengthToStartRunList :: Int -> [(Int, Int)] lengthToStartRunList len = Prelude.concat [[ (l, (r - l) + 1) | l <- [0..(len - 1)], l <= r ] | r <- [(len - 1), (len - 2)..0] ] startRunListForLength1000 = lengthToStartRunList 1000 substringsForLength :: Int -> Int substringsForLength n = (n * (n + 1)) `div` 2 substringsForLength1000 = substringsForLength 1000 -- why not iterate across substringsForLength1000 straight into Set? --slicesStraightToSet slicesToSet :: String -> [(Int, Int)] -> Set (Vector Char) slicesToSet str sliceInstructions = Prelude.foldr f S.empty sliceInstructions where f :: (Int, Int) -> Set (Vector Char) -> Set (Vector Char) f (start, run) acc = S.insert (V.slice start run vstr) acc vstr :: Vector Char vstr = V.fromList str fileName = "/Users/brodyberg/Documents/GitHub/Notes/ProjectRosalind.hsproj/LearnHaskell/FindingASharedMotif/rosalind_lcsm_2.txt" readLocalFile :: String -> IO String readLocalFile path = do handle <- openFile path ReadMode contents <- hGetContents handle return contents filePathToFastas :: String -> IO [FastaSequence] filePathToFastas path = do contents <- readLocalFile path return $ parseFasta' contents mainToSet :: IO () mainToSet = do now <- getZonedTime putStrLn "START: just one " putStrLn $ show now fastas <- filePathToFastas fileName putStrLn "fasta count: " putStrLn $ show $ Prelude.length fastas now <- getZonedTime putStrLn "START: all substrings on 2" putStrLn $ show now let twoFastas = L.take 2 fastas let twoDnas = fmap fastaSeq twoFastas let allSubs1 = slicesToSet (twoDnas !! 0) startRunListForLength1000 let allSubs2 = slicesToSet (twoDnas !! 1) startRunListForLength1000 putStrLn "size 1: " putStrLn $ show $ S.size allSubs1 putStrLn "size 2: " putStrLn $ show $ S.size allSubs2 now <- getZonedTime putStrLn "START intersection of 2" putStrLn $ show now let isection = S.intersection allSubs1 allSubs2 now <- getZonedTime putStrLn "END intersection of 2" putStrLn $ show now putStrLn "Intersection size: " let size = S.size isection putStrLn $ show size now <- getZonedTime putStrLn "END: all substrings on 2" putStrLn $ show now putStrLn "Done"
brodyberg/Notes
ProjectRosalind.hsproj/LearnHaskell/lib/ProjectRosalind/Lcsm/DirectToSet.hs
mit
2,720
0
12
628
820
404
416
70
1
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, TypeFamilies #-} module Imgur where import Control.Lens import Control.Monad.Reader import Data.Text (Text) import qualified Data.Text as Text import Data.Monoid ((<>)) import Network.Wreq import Network.Wreq.Session (Session) import qualified Network.Wreq.Session as Sess import Imgur.Internal.Imgur type ID = Text data Image = Image { imgID :: ID }
Solonarv/imgur-haskell
src/Imgur.hs
mit
485
0
8
93
98
65
33
19
0
{-# language TemplateHaskell #-} {-# language DeriveGeneric #-} module Flow.Action where import Autolib.TES.Identifier import Autolib.Symbol import Autolib.ToDoc import Autolib.Reader import Autolib.Size import Autolib.Hash import GHC.Generics -- | used in the alphabet for the automaton data Action = Execute Identifier | Halt deriving ( Eq, Ord, Generic ) $(derives [makeToDoc,makeReader] [''Action]) instance Show Action where show = render . toDoc instance Symbol Action -- ? instance Size Action where size = const 1 instance Hashable Action
marcellussiegburg/autotool
collection/src/Flow/Action.hs
gpl-2.0
567
0
9
95
143
80
63
19
0
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Web.SLSSpec(main, spec) where import Control.Concurrent (forkIO, killThread) import Control.Exception import Control.Exception import Control.Monad import Control.Monad.IO.Class import Data.ByteString (ByteString) import Data.ByteString.Char8 (unpack) import Data.CaseInsensitive (CI) import qualified Data.CaseInsensitive as CI import Data.List (isPrefixOf) import Data.Maybe import Data.Monoid import qualified Data.Text.Encoding as TE import qualified Data.Text.Lazy as T import Network.HTTP import Network.HTTP.Types.Header import Network.Wai.Test import System.Directory import System.Exit (exitFailure) import Test.Hspec import Test.Hspec.Wai as W import Test.Hspec.Wai.Internal import Web.Scotty as S import Web.Scotty.Cookie as C import Web.Scotty.Login.Session testPort = 4040 baseURL = "localhost" ++ ":" ++ show testPort main = do catch (void $ removeFile dbName) (\(e :: SomeException) -> return ()) hspec spec catch (void $ removeFile dbName) (\(e :: SomeException) -> return ()) spec :: Spec spec = do describe "baseline" $ do withApp routes $ do it "GET to root returns 200 code" $ do W.get "/" `shouldRespondWith` 200 describe "denial" $ do withApp routes $ do it "denies if not authed" $ do W.get "/authcheck" `shouldRespondWith` "denied" {matchStatus = 403} describe "login" $ do withApp routes $ do it "logs in successfully" $ W.postHtmlForm "/login" [("username", "guest"), ("password", "password")] `shouldRespondWith` "authed" describe "auth usage" $ do withApp routes $ do it "gives sessionID cookie when i log in" $ do resp <- W.postHtmlForm "/login" [("username", "guest"), ("password", "password")] let hs = simpleHeaders resp c = lookup "Set-Cookie" hs -- honestly i am shocked that this works liftIO $ c `shouldSatisfy` \case Nothing -> False Just s -> "SessionId=" `isPrefixOf` unpack s it "allows access to page" $ do resp <- W.postHtmlForm "/login" [("username", "guest"), ("password", "password")] let hs = simpleHeaders resp c = fromMaybe "" $ lookup "Set-Cookie" hs headers = [ ("Cookie", c) ] W.request "GET" "/authcheck" headers "" `shouldRespondWith` "authorized" it "forbids access to page" $ do resp <- W.postHtmlForm "/login" [("username", "guest"), ("password", "password")] W.get "/authcheck" `shouldRespondWith` "denied" {matchStatus = 403} describe "logout" $ do withApp routes $ do it "logs out correctly" $ do resp <- W.postHtmlForm "/login" [("username", "guest"), ("password", "password")] let hs = simpleHeaders resp c = fromMaybe "" $ lookup "Set-Cookie" hs headers = [ ("Cookie", c) ] W.request "GET" "/authcheck" headers "" `shouldRespondWith` "authorized" W.request "GET" "/logout" headers "" W.request "GET" "/authcheck" headers "" `shouldRespondWith` "denied" {matchStatus = 403} -- withApp :: ScottyM () -> SpecWith Application -> Spec -- like before_each withApp r = with (initializeCookieDb conf >> scottyApp r) ----- basic library usage dbName = "__test__.sqlite3" conf :: SessionConfig conf = defaultSessionConfig { dbPath = dbName } routes :: ScottyM () routes = do S.get "/" $ S.text "howdy" S.get "/login" $ do S.html $ T.pack $ unlines $ [ "<form method=\"POST\" action=\"/login\">" , "<input type=\"text\" name=\"username\">" , "<input type=\"password\" name=\"password\">" , "<input type=\"submit\" name=\"login\" value=\"login\">" , "</form>" ] S.post "/login" $ do (usn :: String) <- param "username" (pass :: String) <- param "password" if usn == "guest" && pass == "password" then do addSession conf S.html "authed" else do S.html "denied" S.get "/authcheck" $ authCheck (S.html "denied") $ S.html "authorized" S.get "/logout" $ removeSession conf
asg0451/scotty-login-session
test/Web/SLSSpec.hs
gpl-2.0
4,577
0
22
1,364
1,207
630
577
99
2
module Probability.Distribution.List where import Probability.Random independent_densities (d:ds) (x:xs) = densities d x ++ independent_densities ds xs independent_densities [] [] = [] independent_densities _ _ = [doubleToLogDouble 0.0] -- This cannot handle infinite lists because it uses the total number of distributions to determine the rate. independent dists = Distribution "independent" (make_densities' $ independent_densities dists) (no_quantile "independent") (sequence dists) (ListRange (map distRange dists)) -- If we try and put a sampling rate on this that depends on the length, then we can't handle infinitely long lists. -- If we tried to use the sqrt of the number of variables in the list that are instantiated, then that might actually work. independent_densities_on dist_pairs obs_pairs | length dist_pairs == length obs_pairs = go dist_pairs obs_pairs | otherwise = [doubleToLogDouble 0.0] where go [] _ = [] go ((key,dist):rest) obs_pairs = case lookup key obs_pairs of Just obs -> densities dist obs ++ go rest obs_pairs Nothing -> doubleToLogDouble 0.0 sample_independent_on [] = return [] sample_independent_on ((key,dist):rest) = do x <- dist pairs <- sample_independent_on rest return ((key,x):pairs) independent_on dists_pairs = Distribution "independent_on" (make_densities' $ independent_densities_on dists_pairs) (no_quantile "independent_on") (sample_independent_on dists_pairs) Nothing -- If we could make 'independent' work, we could then define `iid n dist = do xs <- independent (repeat dist) ; return $ take n xs` -- or something like that. iid n dist = Distribution iid_name (make_densities' $ independent_densities (replicate n dist)) (no_quantile "iid") iid_sample (ListRange $ take n $ repeat $ distRange dist) where iid_name = "iid "++(dist_name dist) iid_sample = do xs <- SamplingRate (1.0/sqrt (intToDouble n)) $ sequence (repeat dist) return $ take n xs iid_on keys dist = independent_on (zip keys (repeat dist)) plate n dist_f = independent $ map dist_f [0..n-1]
bredelings/BAli-Phy
haskell/Probability/Distribution/List.hs
gpl-2.0
2,305
0
16
580
575
284
291
24
3
module DarkPlaces.Text.Colors ( RGB(..), getRGB, getColor, simplifyColor, hReset ) where import Data.Bits import System.Console.ANSI import System.IO (Handle) newtype RGB = RGB (Int, Int, Int) deriving(Show, Eq) newtype HSV = HSV (Double, Double, Double) deriving(Show, Eq) getRGB :: Int -> RGB getRGB c = RGB (shiftR c 8 .&. 0xff, shiftR c 4 .&. 0xf , c .&. 0xf) scaleRGB :: RGB -> Int -> RGB scaleRGB (RGB (r, g, b)) s = RGB (r * s, g * s, b * s) minMaxRGB :: (Num a, Ord a) => a -> a -> a -> (a, a) minMaxRGB r g b = if r > g then if r > b then (if g < b then g else b, r) else (g, b) else if g > b then (if b < r then b else r, g) else (r, b) rgbToHSV :: RGB -> HSV rgbToHSV (RGB (r, g, b)) = HSV (hue, saturation, value) where (min, max) = minMaxRGB r g b delta = fromIntegral $ max - min :: Double hue | min == max = 0 | r == max = fromIntegral (60 * (g - b)) / delta | g == max = fromIntegral (60 * (b - r)) / delta + 120 | otherwise = fromIntegral (60 * (r - g)) / delta + 240 saturation = if max == 0 then 0 else 1 - fromIntegral min / fromIntegral max value = fromIntegral max / 255 -- from https://github.com/xonotic/darkplaces/blob/9973d76822ff8375e07694ea34c812fbbf8ebdbb/console.c#L1068 simplifyColor :: Int -> Int simplifyColor hex_c | s < 0.2 && v < 0.5 = 0 | s < 0.2 = 7 | h < 36 = 1 | h < 80 = 3 | h < 150 = 2 | h < 200 = 5 | h < 270 = 4 | h < 330 = 6 | otherwise = 1 where rgb = scaleRGB (getRGB hex_c) 17 HSV (h, s, v) = rgbToHSV rgb getColor :: Int -> [SGR] getColor 1 = [SetConsoleIntensity BoldIntensity, SetColor Foreground Dull Red] getColor 2 = [SetConsoleIntensity BoldIntensity, SetColor Foreground Dull Green] getColor 3 = [SetConsoleIntensity BoldIntensity, SetColor Foreground Dull Yellow] getColor 4 = [SetConsoleIntensity BoldIntensity, SetColor Foreground Dull Blue] getColor 5 = [SetConsoleIntensity BoldIntensity, SetColor Foreground Dull Cyan] getColor 6 = [SetConsoleIntensity BoldIntensity, SetColor Foreground Dull Magenta] getColor n | n == 0 || n == 7 = [Reset] | n == 8 || n == 9 = [SetConsoleIntensity BoldIntensity, SetColor Foreground Dull Black] | otherwise = [] hReset :: Handle -> IO () hReset h = hSetSGR h [Reset]
bacher09/darkplaces-text
src/DarkPlaces/Text/Colors.hs
gpl-2.0
2,407
0
14
668
1,035
546
489
60
6
module TestNormalize ( testNormalize ) where import Language.Python.Common.Pretty import Language.Python.Common.PrettyAST import Test.HUnit.Base import Quenelle.Normalize import QuickCheck testNormalize :: Test testNormalize = TestLabel "Normalize" $ qc roundTrip 10000 "QuickCheckNormalize" where roundTrip e = prettyText e == prettyText (normalizeExpr e)
philipturnbull/quenelle
test/TestNormalize.hs
gpl-2.0
369
0
10
50
87
49
38
10
1
{- | Module : $Header$ Copyright : Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : f.mance@jacobs-university.de Stability : provisional Portability : portable Static analysis for RDF -} module RDF.StaticAnalysis where import OWL2.AS import OWL2.Parse import RDF.AS import RDF.Sign import RDF.Parse (predefinedPrefixes) import Data.Maybe import qualified Data.Map as Map import qualified Data.Set as Set import Text.ParserCombinators.Parsec hiding (State) import Common.AS_Annotation hiding (Annotation) import Common.Id import qualified Common.IRI as IRI import Common.Result import Common.GlobalAnnotations import Common.ExtSign import Common.Lib.State -- * URI Resolution resolveFullIRI :: IRI -> IRI -> IRI resolveFullIRI absol rel = if isAbsoluteIRI rel then rel else let r = fromJust $ IRI.parseIRIReference $ expandedIRI rel a = fromJust $ IRI.parseIRI $ expandedIRI absol Just ra = IRI.relativeTo r a resolved = IRI.iriToStringUnsecure ra Right new = parse uriQ "" $ "<" ++ resolved ++ ">" in rel {expandedIRI = expandedIRI new} resolveAbbreviatedIRI :: RDFPrefixMap -> IRI -> IRI resolveAbbreviatedIRI pm new = case Map.lookup (namePrefix new) pm of Nothing -> error $ namePrefix new ++ ": prefix not declared" Just iri -> let new2 = if null (namePrefix new) {- FIXME: If null (localPart new) then head will fail! -} && null (localPart new) && head (localPart new) == ':' then new {localPart = tail $ localPart new} else new in new2 {expandedIRI = expandedIRI iri ++ localPart new2} resolveIRI :: Base -> RDFPrefixMap -> IRI -> IRI resolveIRI (Base current) pm new = case iriType new of Full -> resolveFullIRI current new Abbreviated -> resolveAbbreviatedIRI pm new NodeID -> new resolveBase :: Base -> RDFPrefixMap -> Base -> Base resolveBase b pm (Base new) = Base $ resolveIRI b pm new resolvePrefix :: Base -> RDFPrefixMap -> Prefix -> (Prefix, RDFPrefixMap) resolvePrefix b pm (Prefix s new) = let res = resolveIRI b pm new in (Prefix s res, Map.insert s res pm) resolvePredicate :: Base -> RDFPrefixMap -> Predicate -> Predicate resolvePredicate b pm (Predicate p) = Predicate $ if null (namePrefix p) && localPart p == "a" then p { expandedIRI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" , iriType = Full } else resolveIRI b pm p resolveSubject :: Base -> RDFPrefixMap -> Subject -> Subject resolveSubject b pm s = case s of Subject iri -> Subject $ resolveIRI b pm iri SubjectList ls -> SubjectList $ map (resolvePOList b pm) ls SubjectCollection ls -> SubjectCollection $ map (resolveObject b pm) ls resolvePOList :: Base -> RDFPrefixMap -> PredicateObjectList -> PredicateObjectList resolvePOList b pm (PredicateObjectList p ol) = PredicateObjectList (resolvePredicate b pm p) $ map (resolveObject b pm) ol resolveObject :: Base -> RDFPrefixMap -> Object -> Object resolveObject b pm o = case o of Object s -> Object $ resolveSubject b pm s ObjectLiteral lit -> case lit of RDFLiteral bool lf (Typed dt) -> ObjectLiteral $ RDFLiteral bool lf $ Typed $ resolveIRI b pm dt _ -> o resolveTriples :: Base -> RDFPrefixMap -> Triples -> Triples resolveTriples b pm (Triples s ls) = Triples (resolveSubject b pm s) $ map (resolvePOList b pm) ls resolveStatements :: Base -> RDFPrefixMap -> [Statement] -> [Statement] resolveStatements b pm ls = case ls of [] -> [] BaseStatement base : t -> let newBase = resolveBase b pm base in BaseStatement newBase : resolveStatements newBase pm t PrefixStatement pref : t -> let (newPref, newPrefMap) = resolvePrefix b pm pref in PrefixStatement newPref : resolveStatements b newPrefMap t Statement triples : t -> Statement (resolveTriples b pm triples) : resolveStatements b pm t extractPrefixMap :: RDFPrefixMap -> [Statement] -> RDFPrefixMap extractPrefixMap pm ls = case ls of [] -> pm h : t -> case h of PrefixStatement (Prefix p iri) -> extractPrefixMap (Map.insert p iri pm) t _ -> extractPrefixMap pm t resolveDocument :: TurtleDocument -> TurtleDocument resolveDocument doc = let newStatements = resolveStatements (Base $ documentName doc) predefinedPrefixes $ statements doc in doc { statements = newStatements , prefixMap = Map.union predefinedPrefixes $ extractPrefixMap Map.empty newStatements } -- * Axiom extraction generateBNode :: Int -> IRI generateBNode i = QN "_" ("bnode" ++ show i) NodeID ("_:bnode" ++ show i) nullRange collectionToPOList :: [Object] -> [PredicateObjectList] collectionToPOList objs = case objs of [] -> [] h : t -> [ PredicateObjectList (Predicate rdfFirst) [h] , PredicateObjectList (Predicate rdfRest) [Object $ if null t then Subject rdfNil else SubjectList $ collectionToPOList t]] expandPOList1 :: Triples -> [Triples] expandPOList1 (Triples s pols) = map (\ pol -> Triples s [pol]) pols -- | this assumes exactly one subject and one predicate expandPOList2 :: Triples -> [Triples] expandPOList2 (Triples s pols) = case pols of [PredicateObjectList p objs] -> map (\ obj -> Triples s [PredicateObjectList p [obj]]) objs _ -> error "unexpected ; abbreviated triple" -- | converts a triple to a list of triples with one predicate and one object expandPOList :: Triples -> [Triples] expandPOList = concatMap expandPOList2 . expandPOList1 -- | this assumes exactly one subject, one predicate and one object expandObject1 :: Int -> Triples -> (Int, [Triples]) expandObject1 i t@(Triples s ls) = case ls of [PredicateObjectList p [obj]] -> case obj of ObjectLiteral _ -> (i, [t]) Object (Subject _) -> (i, [t]) Object (SubjectList pol) -> let bnode = Subject $ generateBNode i newTriple = Triples s [PredicateObjectList p [Object bnode]] connectedTriples = expandPOList $ Triples bnode pol (j, expandedTriples) = expandObject2 (i + 1) connectedTriples in (j, newTriple : expandedTriples) Object (SubjectCollection col) -> let pol = collectionToPOList col in if null pol then (i, [Triples s [PredicateObjectList p [Object $ Subject rdfNil]]]) else expandObject1 i $ Triples s [PredicateObjectList p [Object $ SubjectList pol]] _ -> error "unexpected , or ; abbreviated triple" -- | this assumes each triple has one subject, one predicate and one object expandObject2 :: Int -> [Triples] -> (Int, [Triples]) expandObject2 i tl = case tl of [] -> (i, []) h : t -> let (j, triples1) = expandObject1 i h (k, triples2) = expandObject2 j t in (k, triples1 ++ triples2) expandObject :: Int -> Triples -> (Int, [Triples]) expandObject i t = expandObject2 i $ expandPOList t expandSubject :: Int -> Triples -> (Int, [Triples]) expandSubject i t@(Triples s ls) = case s of Subject _ -> (i, [t]) SubjectList pol -> let bnode = Subject $ generateBNode i in (i + 1, map (Triples bnode) [ls, pol]) SubjectCollection col -> let pol = collectionToPOList col in if null col then (i, [Triples (Subject rdfNil) ls]) else expandSubject i $ Triples (SubjectList pol) ls expandTriple :: Int -> Triples -> (Int, [Triples]) expandTriple i t = let (j, sst) = expandSubject i t in case sst of [triple] -> expandObject j triple [triple, connectedTriple] -> let (k, tl1) = expandObject j triple (l, tl2) = expandObject k connectedTriple in (l, tl1 ++ tl2) _ -> error "expanding triple before expanding subject" expandTripleList :: Int -> [Triples] -> (Int, [Triples]) expandTripleList i tl = case tl of [] -> (i, []) h : t -> let (j, tl1) = expandTriple i h (k, tl2) = expandTripleList j t in (k, tl1 ++ tl2) simpleTripleToAxiom :: Triples -> Axiom simpleTripleToAxiom (Triples s pol) = case (s, pol) of (Subject sub, [PredicateObjectList (Predicate pr) [o]]) -> Axiom (SubjectTerm sub) (PredicateTerm pr) $ ObjectTerm $ case o of ObjectLiteral lit -> Right lit Object (Subject obj) -> Left obj _ -> error "object should be an URI" _ -> error "subject should be an URI or triple should not be abbreviated" createAxioms :: TurtleDocument -> [Axiom] createAxioms doc = map simpleTripleToAxiom $ snd $ expandTripleList 1 $ triplesOfDocument $ resolveDocument doc -- | takes an entity and modifies the sign according to the given function modEntity :: (Term -> Set.Set Term -> Set.Set Term) -> RDFEntity -> State Sign () modEntity f (RDFEntity ty u) = do s <- get let chg = f u put $ case ty of SubjectEntity -> s { subjects = chg $ subjects s } PredicateEntity -> s { predicates = chg $ predicates s } ObjectEntity -> s { objects = chg $ objects s } -- | adding entities to the signature addEntity :: RDFEntity -> State Sign () addEntity = modEntity Set.insert collectEntities :: Axiom -> State Sign () collectEntities (Axiom sub pre obj) = do addEntity (RDFEntity SubjectEntity sub) addEntity (RDFEntity PredicateEntity pre) addEntity (RDFEntity ObjectEntity obj) -- | collects all entites from the axioms createSign :: TurtleDocument -> State Sign () createSign = mapM_ collectEntities . createAxioms anaAxiom :: Axiom -> Named Axiom anaAxiom = makeNamed "" -- | static analysis of document with incoming sign. basicRDFAnalysis :: (TurtleDocument, Sign, GlobalAnnos) -> Result (TurtleDocument, ExtSign Sign RDFEntity, [Named Axiom]) basicRDFAnalysis (doc, inSign, _) = do let syms = Set.difference (symOf accSign) $ symOf inSign accSign = execState (createSign doc) inSign axioms = map anaAxiom $ createAxioms doc return (doc, ExtSign accSign syms, axioms)
nevrenato/HetsAlloy
RDF/StaticAnalysis.hs
gpl-2.0
10,269
0
21
2,591
3,292
1,678
1,614
190
6
{- | Module : $Id: testwrap.hs 18342 2013-11-29 02:57:59Z sternk $ Copyright : (c) Andy Gimblett and Markus Roggenbach and Uni Bremen 2004 License : GPLv2 or higher, see LICENSE.txt Maintainer : a.m.gimblett@swan.ac.uk Stability : provisional Portability : portable Test case wrapper for CspCASL specs and fragments. This is a standalone `main' wrapper for CspCASL-related tests performed locally to the CspCASL codebase. It's probably only of interest to the CspCASL maintainers. Usage: testwrap [options] targets Options: -t Don't parse any .cspcasl files; useful for just running tests. -c Don't run any tests; useful for just parsing .cspcasl files. Obviously, specifying both of these options stops this program from doing anything useful. Parameters: targets - a list of targets, where each target can be: - a .cspcasl file; parse the file as a Core-CspCASL specification, unparse the parse tree, and print out the result of the unparse. In case of parse error, report the error. - a .testcase file; execute the test and report the outcome. A testcase file specifies one test case, whose source is contained in another file, and whose output we will check against expected contents. See below for the file format. - a .testcases file; execute the tests and report their outcomes. A testcases file specifies multiple test cases, with source integrated with each test case, and outputs we will check against expected contents. See below for the file format. - a directory; find all .cspcasl, .testcase and .testcases files in the directory (recursively) and operate on them as described above. Postive and negative tests: A positive test is one where we expect the parse to succeed; here the expected output is the result of unparsing the resultant parse tree. The test can fail with a parse error, or with unexpected output. A negative test is one where we expect the parse to fail; here the expected output is the error message produced. The test can fail with a successful parse, or with unexpected output. Format of .testcase files: A .testcase file contains a single test case. The first line is the path to the file containing the source to be parsed/tested, relative to the .testcase file; it also acts as the name of the test case. The second line identifies the test sense ("++" is positive, "--" is negative). The third line is the name of the parser to be used. The remaining lines contain the expected output of the test. Format of .testcases files: A .testcases file contains multiple test cases including their source. Individual test cases are separated by lines containing twenty '-' characters and nothing else. The format of an individual test case is similar but not identical to the format of a standalone test case (above). The first line is the name of the test (used for reporting). The second line identifies the test sense ("++" is positive, "--" is negative). The third line is the name of the parser to be used. This is followed by the expected outcome of the test and the source (input) of the test, in that order, both of which may span multiple lines; they are separated by a line containing ten '-' characters and nothing else. -} module Main where import Data.List import Control.Monad import System.Directory import System.Environment (getArgs) import System.FilePath (combine, dropFileName) import System.IO import Text.ParserCombinators.Parsec import Common.AnnoState (emptyAnnos) import Common.DocUtils import CspCASL.Parse_CspCASL (cspBasicExt) import CspCASL.Parse_CspCASL_Process (csp_casl_process) import CspCASL.Print_CspCASL () main :: IO () main = do args <- getArgs dirs <- filterM doesDirectoryExist args dir_contents <- liftM concat (mapM listFilesR dirs) files <- filterM doesFileExist (sort $ nub (args ++ dir_contents)) doIf ("-t" `notElem` args) (parseCspCASLs (filter isCspCASL files)) doIf ("-c" `notElem` args) (performTests (filter isTest files)) where isCspCASL = (".cspcasl" `isSuffixOf`) isTest f = isSuffixOf ".testcase" f || isSuffixOf ".testcases" f doIf c f = if c then f else putStr "" {- | Given a list of paths to .cspcasl files, parse each in turn, printing results as you go. -} parseCspCASLs :: [FilePath] -> IO () parseCspCASLs [] = putStr "" parseCspCASLs (f : fs) = do putStrLn dash20 prettyCspCASLFromFile f parseCspCASLs fs -- | Parse one .cspcasl file; print error or pretty print parse tree. prettyCspCASLFromFile :: FilePath -> IO () prettyCspCASLFromFile fname = do putStrLn ("Parsing " ++ fname) input <- readFile fname case runParser cspBasicExt (emptyAnnos ()) fname input of Left err -> do putStr "parse error at " print err Right x -> do putStrLn $ showDoc x "" print x {- | Test sense: do we expect parse success or failure? What is the nature of the expected output? -} data TestSense = Positive | Negative deriving (Eq, Ord) instance Show TestSense where show Positive = "++" show Negative = "--" -- | Test case details: where is source, what is it, which parser, etc. data TestCase = TestCase { -- | @name@ - test name name :: String, -- | @parser@ - name of parser to apply parser :: String, -- | @sense@ - sense of test (positive or negative) sense :: TestSense, -- | @src@ - source to be parsed src :: String, -- | @expected@ - expected output of test expected :: String } deriving (Eq, Ord) instance Show TestCase where show a = name a ++ " (" ++ show (sense a) ++ parser a ++ ")" -- | Given a list of paths of test case files, read & perform them. performTests :: [FilePath] -> IO () performTests tcs = do putStrLn "Performing tests" tests <- liftM concat (mapM readTestFile tcs) doTests tests -- | Turn a .testcase or .testcases file into list of test cases therein. readTestFile :: FilePath -> IO [TestCase] readTestFile f | ".testcase" `isSuffixOf` f = readTestCaseFile f | ".testcases" `isSuffixOf` f = readTestCasesFile f | otherwise = return [] -- | Turn a .testcase file into the test case therein. readTestCaseFile :: FilePath -> IO [TestCase] readTestCaseFile f = do hdl <- openFile f ReadMode contents <- hGetContents hdl let (a, b, c, d) = testCaseParts contents hdl_s <- openFile (combine (dropFileName f) a) ReadMode e <- hGetContents hdl_s return [TestCase { name = a, parser = b, sense = c, expected = d, src = e }] -- | Turn a .testcases file into the test cases therein. readTestCasesFile :: FilePath -> IO [TestCase] readTestCasesFile f = do hdl <- openFile f ReadMode s <- hGetContents hdl let tests = map (interpretTestCasesOne . strip) (split dash20 s) return tests -- | Turn test case string from a .testcases file into its test case. interpretTestCasesOne :: String -> TestCase interpretTestCasesOne s | length parts == 2 = TestCase { name = a, parser = b, sense = c, expected = d, src = e } | otherwise = error s where parts = map strip (split dash10 s) (a, b, c, d) = testCaseParts (head parts) e = parts !! 1 -- | Turn test case string into its constituent parts (except source). testCaseParts :: String -> (String, String, TestSense, String) testCaseParts s = (head ls, head (tail ls), interpretSense (head (tail (tail ls))), unlines (tail (tail (tail ls)))) where ls = lines s -- | Interpret a test case sense (++ or --, positive or negative) interpretSense :: String -> TestSense interpretSense s = case s of "++" -> Positive "--" -> Negative _ -> error ("Bad test sense " ++ s) {- | Given a list of test cases, perform the tests in turn, printing results as you go. -} doTests :: [TestCase] -> IO () doTests [] = putStr "" doTests (tc : ts) = do -- putStrLn dash20 let output = parseTestCase tc putStr (show tc ++ " ") printOutcome tc output doTests ts {- | Perform a test and report its outcome. There are six possibilities: 1) positive test succeeds; 2) postive test fail/non-parse (parse fails); 3) positive test error (unparse not as expected); 4) negative test succeeds; 5) negative test fail/parse (parse succeeds); 6) negative test error (error not as expected). -} printOutcome :: TestCase -> Either ParseError (String, String) -> IO () printOutcome tc out = case (sense tc, out) of (Positive, Right (o, tree)) -> if strip o == strip (expected tc) then testPass -- case 1 else do testFail "unparse" (expected tc) o -- case 3 putStrLn ("-> tree:\n" ++ tree) (Positive, Left err) -> testFail "parse failure" "" (show err) -- case 2 (Negative, Right (o, _)) -> testFail "parse success" (expected tc) o -- case 5 (Negative, Left err) -> if strip (show err) == strip (expected tc) then testPass -- case 4 else testFail "error" (expected tc) (show err) -- case 6 -- Report on a test pass testPass :: IO () testPass = putStrLn "passed" -- Report on a test failure testFail :: String -> String -> String -> IO () testFail nature expect got = do putStrLn ("failed - unexpected " ++ nature) if expect /= "" then putStrLn ("-> expected:\n" ++ strip expect) else putStr "" putStrLn "-> got:" putStrLn $ strip got -- | Run a test case through its parser. parseTestCase :: TestCase -> Either ParseError (String, String) parseTestCase t = case parser t of "CoreCspCASL" -> case runWithEof cspBasicExt of Left err -> Left err Right x -> Right (showDoc x "", show x) "Process" -> case runWithEof csp_casl_process of Left err -> Left err Right x -> Right (showDoc x "", show x) _ -> error "Parser name" where runWithEof p = runParser p' (emptyAnnos ()) (name t) (src t) where p' = do n <- p eof return n {- The above implemenation is horrible. There must be a nice way to abstract the parser out from the code to run it and collect/unparse the result. Alas, I don't know it, or don't know that I know it. -} dash20, dash10 :: String dash10 = "----------" dash20 = dash10 ++ dash10 -- Utility functions which really should be in the standard library! {- | Recursive file lister adapted from http://therning.org/magnus/archives/228 -} listFilesR :: FilePath -> IO [FilePath] listFilesR path = do allfiles <- getDirectoryContents path nodots <- filterM (return . isDODD) (map (combine path) allfiles) dirs <- filterM doesDirectoryExist nodots subdirfiles <- liftM concat $ mapM listFilesR dirs files <- filterM doesFileExist nodots return $ files ++ subdirfiles where isDODD f = not $ ("/." `isSuffixOf` f) || ("/.." `isSuffixOf` f) {- | A function inspired by python's string.split(). A list is split on a separator which is itself a list (not a single element). -} split :: Eq a => [a] -> [a] -> [[a]] split tok = unfoldr (sp1 tok) where sp1 _ [] = Nothing sp1 t s = case find (t `isSuffixOf`) (inits s) of Nothing -> Just (s, []) Just p -> Just (take (length p - length t) p, drop (length p) s) -- | String strip in style of python string.strip() strip :: String -> String strip s = dropWhile ws $ reverse $ dropWhile ws $ reverse s where ws = (`elem` " \n\t\r")
nevrenato/HetsAlloy
CspCASL/testwrap.hs
gpl-2.0
12,210
0
15
3,370
2,336
1,188
1,148
162
6
{- | Module : $Header$ Copyright : Heng Jiang, Uni Bremen 2004-2007 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : non-portable (imports Logic.Logic) analyse OWL files by calling the external Java parser. -} module OWL2.ParseOWLAsLibDefn (parseOWL) where import OWL2.AS import OWL2.MS import OWL2.Rename import Data.Char import Common.Id import Common.IRI (simpleIdToIRI) import Common.LibName import Common.ProverTools import Common.AS_Annotation hiding (isAxiom, isDef) import Logic.Grothendieck import OWL2.Logic_OWL2 import OWL2.XML import Driver.Options import Syntax.AS_Library import Syntax.AS_Structured import System.Directory import System.Exit import System.FilePath import System.Process import Text.XML.Light (parseXML, onlyElems, filterElementsName) -- | call for owl parser (env. variable $HETS_OWL_TOOLS muss be defined) parseOWL :: FilePath -- ^ local filepath or uri -> IO LIB_DEFN -- ^ map: uri -> OntologyFile parseOWL filename = do let jar = "OWL2Parser.jar" absfile <- if checkUri filename then return filename else fmap ("file://" ++) $ canonicalizePath filename (hasJar, toolPath) <- check4HetsOWLjar jar if hasJar then do (exitCode, result, errStr) <- readProcessWithExitCode "java" ["-jar", toolPath </> jar, absfile, "xml"] "" case (exitCode, errStr) of (ExitSuccess, "") -> return $ parseProc filename result _ -> error $ "process stop! " ++ shows exitCode "\n" ++ errStr else error $ jar ++ " not found, check your environment variable: " ++ hetsOWLenv parseProc :: FilePath -> String -> LIB_DEFN parseProc filename str = convertToLibDefN filename $ unifyDocs $ map xmlBasicSpec $ concatMap (filterElementsName $ isSmth "Ontology") $ onlyElems $ parseXML str cnvimport :: QName -> Annoted SPEC cnvimport i = emptyAnno $ Spec_inst (cnvtoSimpleId i) [] nullRange cnvtoSimpleId :: QName -> SPEC_NAME cnvtoSimpleId = simpleIdToIRI . mkSimpleId . filter isAlphaNum . showQN createSpec :: OntologyDocument -> Annoted SPEC createSpec o = let bs = emptyAnno $ Basic_spec (G_basic_spec OWL2 o) nullRange in case imports $ ontology o of [] -> bs is -> emptyAnno $ Extension [case is of [i] -> cnvimport i _ -> emptyAnno $ Union (map cnvimport is) nullRange , bs] nullRange convertone :: OntologyDocument -> Annoted LIB_ITEM convertone o = emptyAnno $ Spec_defn (cnvtoSimpleId $ name $ ontology o) emptyGenericity (createSpec o) nullRange convertToLibDefN :: FilePath -> [OntologyDocument] -> LIB_DEFN convertToLibDefN filename l = Lib_defn (emptyLibName $ convertFileToLibStr filename) (map convertone l) nullRange []
nevrenato/Hets_Fork
OWL2/ParseOWLAsLibDefn.hs
gpl-2.0
2,855
0
19
608
708
371
337
68
4
module HLinear.Utility.Permute where import Prelude hiding ( (+), (-), (*), recip ) import Control.DeepSeq ( NFData(..) ) import Control.Monad ( replicateM ) import Data.Permute import Math.Structure import Test.QuickCheck as QC import Test.SmallCheck.Series as SC instance NFData Permute where rnf p = seq p () instance Arbitrary Permute where arbitrary = do QC.Positive n <- arbitrary QC.Positive s <- arbitrary swaps <- replicateM s $ do i <- arbitrary j <- arbitrary return (i `mod` n, j `mod` n) return $ swapsPermute n swaps shrink p = [ swapsPermute n (s:ss) | s <- ss ] where ss = swaps p n = size p instance Monad m => Serial m Permute where series = do SC.Positive n <- series SC.Positive s <- series swaps <- replicateM s $ do i <- series j <- series return (i `mod` n, j `mod` n) return $ swapsPermute n swaps instance MultiplicativeMagma Permute where -- note: we let permutations act from the left p * p' = let n = size p n' = size p' n'' = max n n' safeAt p n i = if i < n then p `at` i else i in listPermute n'' [ safeAt p' n' $ safeAt p n ix | ix <- [0..n''-1]] instance MultiplicativeSemigroup Permute instance MultiplicativeMonoid Permute where one = permute 0 instance MultiplicativeGroup Permute where recip = inverse
martinra/hlinear
src/HLinear/Utility/Permute.hs
gpl-3.0
1,415
2
14
403
522
271
251
-1
-1
-------------------------------------------------------------------------------- -- This file is part of diplomarbeit ("Diplomarbeit Johannes Weiß"). -- -- -- -- diplomarbeit 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. -- -- -- -- diplomarbeit 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 diplomarbeit. If not, see <http://www.gnu.org/licenses/>. -- -- -- -- Copyright 2012, Johannes Weiß -- -------------------------------------------------------------------------------- -- | Simply to debug the implementation. -- -- Don't use this module in production code. module Math.FiniteFields.DebugField (DebugField) where import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Char8 as BS8 import Control.Monad.CryptoRandom (CRandom(..)) import Data.FieldTypes (Field(..)) import Data.RAE.Conduit (ByteSerializable(..)) newtype DebugField = DebugField { unDF :: String } instance ByteSerializable DebugField where serializeBytes = BSL.fromStrict . BS8.pack . unDF parseBytes = DebugField . BS8.unpack . BSL.toStrict instance Field DebugField where invert (DebugField s) = DebugField $ "("++s++")^-1" one = DebugField "1" zero = DebugField "0" instance Num DebugField where (+) (DebugField l) (DebugField r) = DebugField $ "(" ++ l ++ "+" ++ r ++ ")" (-) (DebugField l) (DebugField r) = DebugField $ "(" ++ l ++ "-" ++ r ++ ")" (*) (DebugField l) (DebugField r) = DebugField $ "(" ++ l ++ "*" ++ r ++ ")" negate (DebugField e) = DebugField $ "(-"++e++")" signum (DebugField e) = DebugField $ "signum("++e++")" abs (DebugField e) = DebugField $ "|"++e++"|" fromInteger i = DebugField $ show i instance CRandom DebugField where crandom g = case crandom g of Right (i, g') -> Right (DebugField $ "R"++ (show ((i::Int) `mod` 9999)), g') Left e -> Left e instance Eq DebugField where (==) (DebugField l) (DebugField r) = l == r instance Read DebugField where readsPrec n s = (map (\(a,b) -> (DebugField a, b)) . (readsPrec n)) s instance Show DebugField where show (DebugField e) = show e
weissi/diplomarbeit
lib/Math/FiniteFields/DebugField.hs
gpl-3.0
3,102
0
16
991
642
356
286
34
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} -- | -- Copyright : (c) 2010-2012 Benedikt Schmidt & Simon Meier -- License : GPL v3 (see LICENSE) -- -- Maintainer : Simon Meier <iridcode@gmail.com> -- Portability : GHC only -- -- Types representing constraints. module Theory.Constraint.System.Constraints ( -- * Guarded formulas module Theory.Constraint.System.Guarded -- * Graph constraints , NodePrem , NodeConc , Edge(..) , Less -- * Goal constraints , Goal(..) , isActionGoal , isStandardActionGoal , isPremiseGoal , isChainGoal , isSplitGoal , isDisjGoal -- ** Pretty-printing , prettyNode , prettyNodePrem , prettyNodeConc , prettyEdge , prettyLess , prettyGoal ) where import Data.Binary import Data.DeriveTH import Data.Generics import Extension.Data.Monoid (Monoid(..)) import Control.Basics import Control.DeepSeq import Text.PrettyPrint.Class import Text.Unicode import Logic.Connectives import Theory.Constraint.System.Guarded import Theory.Model import Theory.Text.Pretty import Theory.Tools.EquationStore ------------------------------------------------------------------------------ -- Graph part of a sequent -- ------------------------------------------------------------------------------ -- | A premise of a node. type NodePrem = (NodeId, PremIdx) -- | A conclusion of a node. type NodeConc = (NodeId, ConcIdx) -- | A labeled edge in a derivation graph. data Edge = Edge { eSrc :: NodeConc , eTgt :: NodePrem } deriving (Show, Ord, Eq, Data, Typeable) -- | A *⋖* constraint between 'NodeId's. type Less = (NodeId, NodeId) -- Instances ------------ instance Apply Edge where apply subst (Edge from to) = Edge (apply subst from) (apply subst to) instance HasFrees Edge where foldFrees f (Edge x y) = foldFrees f x `mappend` foldFrees f y foldFreesOcc f c (Edge x y) = foldFreesOcc f ("edge":c) (x, y) mapFrees f (Edge x y) = Edge <$> mapFrees f x <*> mapFrees f y ------------------------------------------------------------------------------ -- Goals ------------------------------------------------------------------------------ -- | A 'Goal' denotes that a constraint reduction rule is applicable, which -- might result in case splits. We either use a heuristic to decide what goal -- to solve next or leave the choice to user (in case of the interactive UI). data Goal = ActionG LVar LNFact -- ^ An action that must exist in the trace. | ChainG NodeConc NodePrem -- A destruction chain. | PremiseG NodePrem LNFact -- ^ A premise that must have an incoming direct edge. | SplitG SplitId -- ^ A case split over equalities. | DisjG (Disj LNGuarded) -- ^ A case split over a disjunction. deriving( Eq, Ord, Show ) -- Indicators ------------- isActionGoal :: Goal -> Bool isActionGoal (ActionG _ _) = True isActionGoal _ = False isStandardActionGoal :: Goal -> Bool isStandardActionGoal (ActionG _ fa) = not (isKUFact fa) isStandardActionGoal _ = False isPremiseGoal :: Goal -> Bool isPremiseGoal (PremiseG _ _) = True isPremiseGoal _ = False isChainGoal :: Goal -> Bool isChainGoal (ChainG _ _) = True isChainGoal _ = False isSplitGoal :: Goal -> Bool isSplitGoal (SplitG _) = True isSplitGoal _ = False isDisjGoal :: Goal -> Bool isDisjGoal (DisjG _) = True isDisjGoal _ = False -- Instances ------------ instance HasFrees Goal where foldFrees f goal = case goal of ActionG i fa -> foldFrees f i <> foldFrees f fa PremiseG p fa -> foldFrees f p <> foldFrees f fa ChainG c p -> foldFrees f c <> foldFrees f p SplitG i -> foldFrees f i DisjG x -> foldFrees f x foldFreesOcc f c goal = case goal of ActionG i fa -> foldFreesOcc f ("ActionG":c) (i, fa) ChainG co p -> foldFreesOcc f ("ChainG":c) (co, p) _ -> mempty mapFrees f goal = case goal of ActionG i fa -> ActionG <$> mapFrees f i <*> mapFrees f fa PremiseG p fa -> PremiseG <$> mapFrees f p <*> mapFrees f fa ChainG c p -> ChainG <$> mapFrees f c <*> mapFrees f p SplitG i -> SplitG <$> mapFrees f i DisjG x -> DisjG <$> mapFrees f x instance Apply Goal where apply subst goal = case goal of ActionG i fa -> ActionG (apply subst i) (apply subst fa) PremiseG p fa -> PremiseG (apply subst p) (apply subst fa) ChainG c p -> ChainG (apply subst c) (apply subst p) SplitG i -> SplitG (apply subst i) DisjG x -> DisjG (apply subst x) ------------------------------------------------------------------------------ -- Pretty printing -- ------------------------------------------------------------------------------ -- | Pretty print a node. prettyNode :: HighlightDocument d => (NodeId, RuleACInst) -> d prettyNode (v,ru) = prettyNodeId v <> colon <-> prettyRuleACInst ru -- | Pretty print a node conclusion. prettyNodeConc :: HighlightDocument d => NodeConc -> d prettyNodeConc (v, ConcIdx i) = parens (prettyNodeId v <> comma <-> int i) -- | Pretty print a node premise. prettyNodePrem :: HighlightDocument d => NodePrem -> d prettyNodePrem (v, PremIdx i) = parens (prettyNodeId v <> comma <-> int i) -- | Pretty print a edge as @src >-i--j-> tgt@. prettyEdge :: HighlightDocument d => Edge -> d prettyEdge (Edge c p) = prettyNodeConc c <-> operator_ ">-->" <-> prettyNodePrem p -- | Pretty print a less-atom as @src < tgt@. prettyLess :: HighlightDocument d => Less -> d prettyLess (i, j) = prettyNAtom $ Less (varTerm i) (varTerm j) -- | Pretty print a goal. prettyGoal :: HighlightDocument d => Goal -> d prettyGoal (ActionG i fa) = prettyNAtom (Action (varTerm i) fa) prettyGoal (ChainG c p) = prettyNodeConc c <-> operator_ "~~>" <-> prettyNodePrem p prettyGoal (PremiseG (i, (PremIdx v)) fa) = -- Note that we can use "▷" for conclusions once we need them. prettyLNFact fa <-> text ("▶" ++ subscript (show v)) <-> prettyNodeId i -- prettyNodePrem p <> brackets (prettyLNFact fa) prettyGoal (DisjG (Disj [])) = text "Disj" <-> operator_ "(⊥)" prettyGoal (DisjG (Disj gfs)) = fsep $ punctuate (operator_ " ∥") (map (nest 1 . parens . prettyGuarded) gfs) -- punctuate (operator_ " |") (map (nest 1 . parens . prettyGuarded) gfs) prettyGoal (SplitG x) = text "splitEqs" <> parens (text $ show (unSplitId x)) -- Derived instances -------------------- $( derive makeBinary ''Edge) $( derive makeBinary ''Goal) $( derive makeNFData ''Edge) $( derive makeNFData ''Goal)
ekr/tamarin-prover
lib/theory/src/Theory/Constraint/System/Constraints.hs
gpl-3.0
6,955
0
12
1,763
1,801
939
862
122
1
module Hob.Control ( maybeDo, flushEvents ) where import Control.Monad (when) import Graphics.UI.Gtk (eventsPending, mainIteration) maybeDo :: Monad b => (a -> b ()) -> Maybe a -> b () maybeDo = maybe (return()) flushEvents :: IO() flushEvents = do pending <- eventsPending when (pending > 0) $ mainIteration >> flushEvents
svalaskevicius/hob
src/lib/Hob/Control.hs
gpl-3.0
345
0
11
71
137
72
65
11
1
{-# 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.Config.DescribeDeliveryChannelStatus -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- 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 <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Returns the current status of the specified delivery channel. If a delivery -- channel is not specified, this action returns the current status of all -- delivery channels associated with the account. -- -- <http://docs.aws.amazon.com/config/latest/APIReference/API_DescribeDeliveryChannelStatus.html> module Network.AWS.Config.DescribeDeliveryChannelStatus ( -- * Request DescribeDeliveryChannelStatus -- ** Request constructor , describeDeliveryChannelStatus -- ** Request lenses , ddcsDeliveryChannelNames -- * Response , DescribeDeliveryChannelStatusResponse -- ** Response constructor , describeDeliveryChannelStatusResponse -- ** Response lenses , ddcsrDeliveryChannelsStatus ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.Config.Types import qualified GHC.Exts newtype DescribeDeliveryChannelStatus = DescribeDeliveryChannelStatus { _ddcsDeliveryChannelNames :: List "DeliveryChannelNames" Text } deriving (Eq, Ord, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList DescribeDeliveryChannelStatus where type Item DescribeDeliveryChannelStatus = Text fromList = DescribeDeliveryChannelStatus . GHC.Exts.fromList toList = GHC.Exts.toList . _ddcsDeliveryChannelNames -- | 'DescribeDeliveryChannelStatus' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ddcsDeliveryChannelNames' @::@ ['Text'] -- describeDeliveryChannelStatus :: DescribeDeliveryChannelStatus describeDeliveryChannelStatus = DescribeDeliveryChannelStatus { _ddcsDeliveryChannelNames = mempty } -- | A list of delivery channel names. ddcsDeliveryChannelNames :: Lens' DescribeDeliveryChannelStatus [Text] ddcsDeliveryChannelNames = lens _ddcsDeliveryChannelNames (\s a -> s { _ddcsDeliveryChannelNames = a }) . _List newtype DescribeDeliveryChannelStatusResponse = DescribeDeliveryChannelStatusResponse { _ddcsrDeliveryChannelsStatus :: List "DeliveryChannelsStatus" DeliveryChannelStatus } deriving (Eq, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList DescribeDeliveryChannelStatusResponse where type Item DescribeDeliveryChannelStatusResponse = DeliveryChannelStatus fromList = DescribeDeliveryChannelStatusResponse . GHC.Exts.fromList toList = GHC.Exts.toList . _ddcsrDeliveryChannelsStatus -- | 'DescribeDeliveryChannelStatusResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ddcsrDeliveryChannelsStatus' @::@ ['DeliveryChannelStatus'] -- describeDeliveryChannelStatusResponse :: DescribeDeliveryChannelStatusResponse describeDeliveryChannelStatusResponse = DescribeDeliveryChannelStatusResponse { _ddcsrDeliveryChannelsStatus = mempty } -- | A list that contains the status of a specified delivery channel. ddcsrDeliveryChannelsStatus :: Lens' DescribeDeliveryChannelStatusResponse [DeliveryChannelStatus] ddcsrDeliveryChannelsStatus = lens _ddcsrDeliveryChannelsStatus (\s a -> s { _ddcsrDeliveryChannelsStatus = a }) . _List instance ToPath DescribeDeliveryChannelStatus where toPath = const "/" instance ToQuery DescribeDeliveryChannelStatus where toQuery = const mempty instance ToHeaders DescribeDeliveryChannelStatus instance ToJSON DescribeDeliveryChannelStatus where toJSON DescribeDeliveryChannelStatus{..} = object [ "DeliveryChannelNames" .= _ddcsDeliveryChannelNames ] instance AWSRequest DescribeDeliveryChannelStatus where type Sv DescribeDeliveryChannelStatus = Config type Rs DescribeDeliveryChannelStatus = DescribeDeliveryChannelStatusResponse request = post "DescribeDeliveryChannelStatus" response = jsonResponse instance FromJSON DescribeDeliveryChannelStatusResponse where parseJSON = withObject "DescribeDeliveryChannelStatusResponse" $ \o -> DescribeDeliveryChannelStatusResponse <$> o .:? "DeliveryChannelsStatus" .!= mempty
dysinger/amazonka
amazonka-config/gen/Network/AWS/Config/DescribeDeliveryChannelStatus.hs
mpl-2.0
5,050
0
10
879
547
328
219
68
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.Projects.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns the specified Project resource. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.projects.get@. module Network.Google.Resource.Compute.Projects.Get ( -- * REST Resource ProjectsGetResource -- * Creating a Request , projectsGet , ProjectsGet -- * Request Lenses , pgProject ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.projects.get@ method which the -- 'ProjectsGet' request conforms to. type ProjectsGetResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Project -- | Returns the specified Project resource. -- -- /See:/ 'projectsGet' smart constructor. newtype ProjectsGet = ProjectsGet' { _pgProject :: Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProjectsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pgProject' projectsGet :: Text -- ^ 'pgProject' -> ProjectsGet projectsGet pPgProject_ = ProjectsGet' { _pgProject = pPgProject_ } -- | Project ID for this request. pgProject :: Lens' ProjectsGet Text pgProject = lens _pgProject (\ s a -> s{_pgProject = a}) instance GoogleRequest ProjectsGet where type Rs ProjectsGet = Project type Scopes ProjectsGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient ProjectsGet'{..} = go _pgProject (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy ProjectsGetResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Projects/Get.hs
mpl-2.0
2,709
0
12
620
305
188
117
49
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DFAReporting.CreativeFields.Insert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Inserts a new creative field. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.creativeFields.insert@. module Network.Google.Resource.DFAReporting.CreativeFields.Insert ( -- * REST Resource CreativeFieldsInsertResource -- * Creating a Request , creativeFieldsInsert , CreativeFieldsInsert -- * Request Lenses , cfiProFileId , cfiPayload ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.creativeFields.insert@ method which the -- 'CreativeFieldsInsert' request conforms to. type CreativeFieldsInsertResource = "dfareporting" :> "v2.7" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "creativeFields" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] CreativeField :> Post '[JSON] CreativeField -- | Inserts a new creative field. -- -- /See:/ 'creativeFieldsInsert' smart constructor. data CreativeFieldsInsert = CreativeFieldsInsert' { _cfiProFileId :: !(Textual Int64) , _cfiPayload :: !CreativeField } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CreativeFieldsInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cfiProFileId' -- -- * 'cfiPayload' creativeFieldsInsert :: Int64 -- ^ 'cfiProFileId' -> CreativeField -- ^ 'cfiPayload' -> CreativeFieldsInsert creativeFieldsInsert pCfiProFileId_ pCfiPayload_ = CreativeFieldsInsert' { _cfiProFileId = _Coerce # pCfiProFileId_ , _cfiPayload = pCfiPayload_ } -- | User profile ID associated with this request. cfiProFileId :: Lens' CreativeFieldsInsert Int64 cfiProFileId = lens _cfiProFileId (\ s a -> s{_cfiProFileId = a}) . _Coerce -- | Multipart request metadata. cfiPayload :: Lens' CreativeFieldsInsert CreativeField cfiPayload = lens _cfiPayload (\ s a -> s{_cfiPayload = a}) instance GoogleRequest CreativeFieldsInsert where type Rs CreativeFieldsInsert = CreativeField type Scopes CreativeFieldsInsert = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient CreativeFieldsInsert'{..} = go _cfiProFileId (Just AltJSON) _cfiPayload dFAReportingService where go = buildClient (Proxy :: Proxy CreativeFieldsInsertResource) mempty
rueshyna/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/CreativeFields/Insert.hs
mpl-2.0
3,405
0
14
760
406
242
164
64
1
import Data.List import Data.Char cs = ['A','N','a','n'] cnv c | ord('A') <= ord(c) && ord(c) <= ord('M') = 'A' | ord('N') <= ord(c) && ord(c) <= ord('Z') = 'N' | ord('a') <= ord(c) && ord(c) <= ord('m') = 'a' | ord('n') <= ord(c) && ord(c) <= ord('z') = 'n' pack [] _ = [] pack (c:cr) s = let l = length $ takeWhile (== c) s r = dropWhile (== c) s in l:(pack cr r) enc [a,b,c,d] = let ns = if a >= b then take (a-b) $ repeat 'A' else take (b-a) $ repeat 'N' ew = if c >= d then take (c-d) $ repeat 'a' else take (d-c) $ repeat 'n' in ns ++ ew ans i = let s = sort i c = map cnv s p = pack cs c a = enc p in a main = do _ <- getLine i <- getLine let o = ans i print $ length o putStrLn o
a143753/AOJ
3101.hs
apache-2.0
914
8
13
391
551
265
286
33
3
module Treepr where import Treedef -- pretty print block list ptreebl (BlockList BEmpty b) = ptreeb b ptreebl (BlockList a b) = do ptreebl a ptreeb b -- pretty print load balance block ptreelbl i (LBlockList LBEmpty b) = ptreelb i b ptreelbl i (LBlockList a b) = do ptreelbl i a ptreelb i b -- pretty print firewall block ptreefbl i (FBlockList FBEmpty b) = ptreefb i b ptreefbl i (FBlockList a b) = do ptreefbl i a ptreefb i b -- pretty print interface list ptreefl i (IFaceList IFaceEmpty b) = ptreef i b ptreefl i (IFaceList a b) = do ptreefl i a ptreef i b -- pretty print nic list ptreenbl i (INicList INicEmpty b) = ptreenb i b ptreenbl i (INicList a b) = do ptreenbl i a ptreenb i b -- pretty print vcenter block ptreeb (VBlock a b) = let z = "vcenter " ++ a in do putStrLn "" putStrLn z ptreel 1 b -- pretty print esxhost block ptreeb (EBlock a b) = let z = "esxhost " ++ a in do putStrLn "" putStrLn z ptreel 1 b -- pretty print segment block ptreeb (SBlock a b) = let z = "segment " ++ a in do putStrLn "" putStrLn z ptreel 1 b -- pretty print switch block ptreeb (SWBlock a b c d) = let z = "switch " ++ a in do putStrLn "" putStrLn z ptreel 1 b ptreefl 1 c ptreer 1 d -- FBlock String CnstrList IFaceList FBlockList IRoute ptreeb (FBlock a b c d e) = let z = "firewall " ++ a in do putStrLn "" putStrLn z ptreel 1 b ptreefl 1 c ptreefbl 1 d ptreer 1 e -- FBlock1 String CnstrList IFaceList IRoute ptreeb (FBlock1 a b c e) = let z = "firewall " ++ a in do putStrLn "" putStrLn z ptreel 1 b ptreefl 1 c ptreer 1 e -- NBlock String CnstrList INicList ptreeb (NBlock a b c) = let z = "node " ++ a in do putStrLn "" putStrLn z ptreel 1 b ptreenbl 1 c -- NBlock1 String CnstrList INicList IInsec ptreeb (NBlock1 a b c d) = let z = "node " ++ a in do putStrLn "" putStrLn z ptreel 1 b ptreenbl 1 c ptreein 1 d -- NBlock2 String CnstrList INicList IPlatform ptreeb (NBlock2 a b c d) = let z = "node " ++ a in do putStrLn "" putStrLn z ptreel 1 b ptreenbl 1 c ptreepform 1 d -- KBlock String CnstrList LBlockList IRoute ptreeb (KBlock a b c d) = let z = "kempLB " ++ a in do putStrLn "" putStrLn z ptreel 1 b ptreelbl 1 c ptreer 1 d -- pretty print nic ptreenb i (INic1 a b) = let z = (spaces i) ++ "nic " ++ (show a) in do putStrLn z ptreel (i+1) b -- pretty print interface ptreef i (IFace1 a b) = let z = (spaces i) ++ "interface " ++ (show a) in do putStrLn z ptreel (i+1) b -- pretty print route ptreer i (IRoute1 a) = let z = (spaces i) ++ "route " in do putStrLn z ptreel (i+1) a -- pretty print init ptreein i (IInsec1 a) = let z = (spaces i) ++ "init " in do putStrLn z ptreel (i+1) a -- pretty print platform ptreepform i (IPlatform1 a) = let z = (spaces i) ++ "platform " in do putStrLn z ptreel (i+1) a -- IZone1 String CnstrList ptreefb i (IZone1 a b) = let z = (spaces i) ++ "zone " ++ a in do putStrLn z ptreel (i+1) b -- IAcl1 String CnstrList ptreefb i (IAcl1 a b) = let z = (spaces i) ++ "acl " ++ a in do putStrLn z ptreel (i+1) b -- IPolicy1 String CnstrList ptreefb i (IPolicy1 a b) = let z = (spaces i) ++ "policy " ++ a in do putStrLn z ptreel (i+1) b -- IDnat1 String CnstrList ptreefb i (IDnat1 a b) = let z = (spaces i) ++ "dnat " ++ a in do putStrLn z ptreel (i+1) b -- IServ1 String CnstrList ptreefb i (IServ1 a b) = let z = (spaces i) ++ "service " ++ a in do putStrLn z ptreel (i+1) b -- ISnat1 String CnstrList ptreefb i (ISnat1 a b) = let z = (spaces i) ++ "snat " ++ a in do putStrLn z ptreel (i+1) b -- IAdxobj1 String CnstrList ptreefb i (IAdxobj1 a b) = let z = (spaces i) ++ "adxobj " ++ a in do putStrLn z ptreel (i+1) b -- IFace2 Int CnstrList ptreelb i (IFace2 a b) = let z = (spaces i) ++ "interface " ++ (show a) in do putStrLn z ptreel (i+1) b -- IServ2 String CnstrList ptreelb i (IServ2 a b) = let z = (spaces i) ++ "service " ++ a in do putStrLn z ptreel (i+1) b -- pretty print constraint list ptreel i (CnstrList Empty b) = ptree i b ptreel i (CnstrList a b) = do ptreel i a ptree i b -- pretty print constraints ptree i (Cnstr1 b c) = putStrLn ((spaces i) ++ b ++ " : " ++ c) ptree i (Cnstr2 b c) = putStrLn ((spaces i) ++ b ++ " : " ++ (show c )) ptree i (Cnstr3 b c) = putStrLn ((spaces i) ++b ++ " : \"" ++ c ++ "\"") -- spaces for formatting spaces i = let space = " " ++ space in take i space
shlomobauer/BuildIT
src/Treepr.hs
apache-2.0
4,473
0
12
1,155
2,081
965
1,116
150
1
module Graham.A292144Spec (main, spec) where import Test.Hspec import Graham.A292144 (a292144) main :: IO () main = hspec spec spec :: Spec spec = describe "A292144" $ it "correctly computes the first 20 elements" $ take 20 (map a292144 [1..]) `shouldBe` expectedValue where expectedValue = [0,0,0,1,0,0,0,2,4,0,0,3,0,0,0,9,0,8,0,5]
peterokagey/haskellOEIS
test/Graham/A292144Spec.hs
apache-2.0
347
0
10
59
160
95
65
10
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QCompleter.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QCompleter ( QqCompleter(..) ,Qcomplete(..), qcomplete ,completionColumn ,completionCount ,completionMode ,completionModel ,completionPrefix ,completionRole ,currentCompletion ,modelSorting ,QpathFromIndex(..) ,setCompletionColumn ,setCompletionMode ,setCompletionPrefix ,setCompletionRole ,setModelSorting ,setPopup ,setWrapAround ,wrapAround ,qCompleter_delete ,qCompleter_deleteLater ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Enums.Gui.QCompleter import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QCompleter ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QCompleter_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QCompleter_userMethod" qtc_QCompleter_userMethod :: Ptr (TQCompleter a) -> CInt -> IO () instance QuserMethod (QCompleterSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QCompleter_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QCompleter ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QCompleter_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QCompleter_userMethodVariant" qtc_QCompleter_userMethodVariant :: Ptr (TQCompleter a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QCompleterSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QCompleter_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqCompleter x1 where qCompleter :: x1 -> IO (QCompleter ()) instance QqCompleter (()) where qCompleter () = withQCompleterResult $ qtc_QCompleter foreign import ccall "qtc_QCompleter" qtc_QCompleter :: IO (Ptr (TQCompleter ())) instance QqCompleter (([String])) where qCompleter (x1) = withQCompleterResult $ withQListString x1 $ \cqlistlen_x1 cqliststr_x1 -> qtc_QCompleter1 cqlistlen_x1 cqliststr_x1 foreign import ccall "qtc_QCompleter1" qtc_QCompleter1 :: CInt -> Ptr (Ptr CWchar) -> IO (Ptr (TQCompleter ())) instance QqCompleter ((QObject t1)) where qCompleter (x1) = withQCompleterResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter2 cobj_x1 foreign import ccall "qtc_QCompleter2" qtc_QCompleter2 :: Ptr (TQObject t1) -> IO (Ptr (TQCompleter ())) instance QqCompleter ((QAbstractItemModel t1)) where qCompleter (x1) = withQCompleterResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter3 cobj_x1 foreign import ccall "qtc_QCompleter3" qtc_QCompleter3 :: Ptr (TQAbstractItemModel t1) -> IO (Ptr (TQCompleter ())) instance QqCompleter ((QAbstractItemModel t1, QObject t2)) where qCompleter (x1, x2) = withQCompleterResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QCompleter4 cobj_x1 cobj_x2 foreign import ccall "qtc_QCompleter4" qtc_QCompleter4 :: Ptr (TQAbstractItemModel t1) -> Ptr (TQObject t2) -> IO (Ptr (TQCompleter ())) instance QqCompleter (([String], QObject t2)) where qCompleter (x1, x2) = withQCompleterResult $ withQListString x1 $ \cqlistlen_x1 cqliststr_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QCompleter5 cqlistlen_x1 cqliststr_x1 cobj_x2 foreign import ccall "qtc_QCompleter5" qtc_QCompleter5 :: CInt -> Ptr (Ptr CWchar) -> Ptr (TQObject t2) -> IO (Ptr (TQCompleter ())) instance QcaseSensitivity (QCompleter a) (()) where caseSensitivity x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_caseSensitivity cobj_x0 foreign import ccall "qtc_QCompleter_caseSensitivity" qtc_QCompleter_caseSensitivity :: Ptr (TQCompleter a) -> IO CLong class Qcomplete x1 where complete :: QCompleter a -> x1 -> IO () instance Qcomplete (()) where complete x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_complete cobj_x0 foreign import ccall "qtc_QCompleter_complete" qtc_QCompleter_complete :: Ptr (TQCompleter a) -> IO () qcomplete :: QCompleter a -> ((QRect t1)) -> IO () qcomplete x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_complete1 cobj_x0 cobj_x1 foreign import ccall "qtc_QCompleter_complete1" qtc_QCompleter_complete1 :: Ptr (TQCompleter a) -> Ptr (TQRect t1) -> IO () instance Qcomplete ((Rect)) where complete x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QCompleter_complete1_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QCompleter_complete1_qth" qtc_QCompleter_complete1_qth :: Ptr (TQCompleter a) -> CInt -> CInt -> CInt -> CInt -> IO () completionColumn :: QCompleter a -> (()) -> IO (Int) completionColumn x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_completionColumn cobj_x0 foreign import ccall "qtc_QCompleter_completionColumn" qtc_QCompleter_completionColumn :: Ptr (TQCompleter a) -> IO CInt completionCount :: QCompleter a -> (()) -> IO (Int) completionCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_completionCount cobj_x0 foreign import ccall "qtc_QCompleter_completionCount" qtc_QCompleter_completionCount :: Ptr (TQCompleter a) -> IO CInt completionMode :: QCompleter a -> (()) -> IO (CompletionMode) completionMode x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_completionMode cobj_x0 foreign import ccall "qtc_QCompleter_completionMode" qtc_QCompleter_completionMode :: Ptr (TQCompleter a) -> IO CLong completionModel :: QCompleter a -> (()) -> IO (QAbstractItemModel ()) completionModel x0 () = withQAbstractItemModelResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_completionModel cobj_x0 foreign import ccall "qtc_QCompleter_completionModel" qtc_QCompleter_completionModel :: Ptr (TQCompleter a) -> IO (Ptr (TQAbstractItemModel ())) completionPrefix :: QCompleter a -> (()) -> IO (String) completionPrefix x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_completionPrefix cobj_x0 foreign import ccall "qtc_QCompleter_completionPrefix" qtc_QCompleter_completionPrefix :: Ptr (TQCompleter a) -> IO (Ptr (TQString ())) completionRole :: QCompleter a -> (()) -> IO (Int) completionRole x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_completionRole cobj_x0 foreign import ccall "qtc_QCompleter_completionRole" qtc_QCompleter_completionRole :: Ptr (TQCompleter a) -> IO CInt currentCompletion :: QCompleter a -> (()) -> IO (String) currentCompletion x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_currentCompletion cobj_x0 foreign import ccall "qtc_QCompleter_currentCompletion" qtc_QCompleter_currentCompletion :: Ptr (TQCompleter a) -> IO (Ptr (TQString ())) instance QcurrentIndex (QCompleter a) (()) (IO (QModelIndex ())) where currentIndex x0 () = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_currentIndex cobj_x0 foreign import ccall "qtc_QCompleter_currentIndex" qtc_QCompleter_currentIndex :: Ptr (TQCompleter a) -> IO (Ptr (TQModelIndex ())) instance QcurrentRow (QCompleter a) (()) where currentRow x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_currentRow cobj_x0 foreign import ccall "qtc_QCompleter_currentRow" qtc_QCompleter_currentRow :: Ptr (TQCompleter a) -> IO CInt instance Qevent (QCompleter ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_event cobj_x0 cobj_x1 foreign import ccall "qtc_QCompleter_event" qtc_QCompleter_event :: Ptr (TQCompleter a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QCompleterSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_event cobj_x0 cobj_x1 instance QeventFilter (QCompleter ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QCompleter_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QCompleter_eventFilter" qtc_QCompleter_eventFilter :: Ptr (TQCompleter a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QCompleterSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QCompleter_eventFilter cobj_x0 cobj_x1 cobj_x2 instance Qmodel (QCompleter a) (()) (IO (QAbstractItemModel ())) where model x0 () = withQAbstractItemModelResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_model cobj_x0 foreign import ccall "qtc_QCompleter_model" qtc_QCompleter_model :: Ptr (TQCompleter a) -> IO (Ptr (TQAbstractItemModel ())) modelSorting :: QCompleter a -> (()) -> IO (ModelSorting) modelSorting x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_modelSorting cobj_x0 foreign import ccall "qtc_QCompleter_modelSorting" qtc_QCompleter_modelSorting :: Ptr (TQCompleter a) -> IO CLong class QpathFromIndex x0 x1 where pathFromIndex :: x0 -> x1 -> IO (String) instance QpathFromIndex (QCompleter ()) ((QModelIndex t1)) where pathFromIndex x0 (x1) = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_pathFromIndex_h cobj_x0 cobj_x1 foreign import ccall "qtc_QCompleter_pathFromIndex_h" qtc_QCompleter_pathFromIndex_h :: Ptr (TQCompleter a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQString ())) instance QpathFromIndex (QCompleterSc a) ((QModelIndex t1)) where pathFromIndex x0 (x1) = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_pathFromIndex_h cobj_x0 cobj_x1 instance Qpopup (QCompleter a) (()) (IO (QAbstractItemView ())) where popup x0 () = withQAbstractItemViewResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_popup cobj_x0 foreign import ccall "qtc_QCompleter_popup" qtc_QCompleter_popup :: Ptr (TQCompleter a) -> IO (Ptr (TQAbstractItemView ())) instance QsetCaseSensitivity (QCompleter a) ((CaseSensitivity)) where setCaseSensitivity x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_setCaseSensitivity cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QCompleter_setCaseSensitivity" qtc_QCompleter_setCaseSensitivity :: Ptr (TQCompleter a) -> CLong -> IO () setCompletionColumn :: QCompleter a -> ((Int)) -> IO () setCompletionColumn x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_setCompletionColumn cobj_x0 (toCInt x1) foreign import ccall "qtc_QCompleter_setCompletionColumn" qtc_QCompleter_setCompletionColumn :: Ptr (TQCompleter a) -> CInt -> IO () setCompletionMode :: QCompleter a -> ((CompletionMode)) -> IO () setCompletionMode x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_setCompletionMode cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QCompleter_setCompletionMode" qtc_QCompleter_setCompletionMode :: Ptr (TQCompleter a) -> CLong -> IO () setCompletionPrefix :: QCompleter a -> ((String)) -> IO () setCompletionPrefix x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QCompleter_setCompletionPrefix cobj_x0 cstr_x1 foreign import ccall "qtc_QCompleter_setCompletionPrefix" qtc_QCompleter_setCompletionPrefix :: Ptr (TQCompleter a) -> CWString -> IO () setCompletionRole :: QCompleter a -> ((Int)) -> IO () setCompletionRole x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_setCompletionRole cobj_x0 (toCInt x1) foreign import ccall "qtc_QCompleter_setCompletionRole" qtc_QCompleter_setCompletionRole :: Ptr (TQCompleter a) -> CInt -> IO () instance QsetCurrentRow (QCompleter a) ((Int)) (IO (Bool)) where setCurrentRow x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_setCurrentRow cobj_x0 (toCInt x1) foreign import ccall "qtc_QCompleter_setCurrentRow" qtc_QCompleter_setCurrentRow :: Ptr (TQCompleter a) -> CInt -> IO CBool instance QsetModel (QCompleter a) ((QAbstractItemModel t1)) where setModel x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_setModel cobj_x0 cobj_x1 foreign import ccall "qtc_QCompleter_setModel" qtc_QCompleter_setModel :: Ptr (TQCompleter a) -> Ptr (TQAbstractItemModel t1) -> IO () setModelSorting :: QCompleter a -> ((ModelSorting)) -> IO () setModelSorting x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_setModelSorting cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QCompleter_setModelSorting" qtc_QCompleter_setModelSorting :: Ptr (TQCompleter a) -> CLong -> IO () setPopup :: QCompleter a -> ((QAbstractItemView t1)) -> IO () setPopup x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_setPopup cobj_x0 cobj_x1 foreign import ccall "qtc_QCompleter_setPopup" qtc_QCompleter_setPopup :: Ptr (TQCompleter a) -> Ptr (TQAbstractItemView t1) -> IO () instance QsetWidget (QCompleter a) ((QWidget t1)) where setWidget x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_setWidget cobj_x0 cobj_x1 foreign import ccall "qtc_QCompleter_setWidget" qtc_QCompleter_setWidget :: Ptr (TQCompleter a) -> Ptr (TQWidget t1) -> IO () setWrapAround :: QCompleter a -> ((Bool)) -> IO () setWrapAround x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_setWrapAround cobj_x0 (toCBool x1) foreign import ccall "qtc_QCompleter_setWrapAround" qtc_QCompleter_setWrapAround :: Ptr (TQCompleter a) -> CBool -> IO () instance Qwidget (QCompleter a) (()) where widget x0 () = withQWidgetResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_widget cobj_x0 foreign import ccall "qtc_QCompleter_widget" qtc_QCompleter_widget :: Ptr (TQCompleter a) -> IO (Ptr (TQWidget ())) wrapAround :: QCompleter a -> (()) -> IO (Bool) wrapAround x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_wrapAround cobj_x0 foreign import ccall "qtc_QCompleter_wrapAround" qtc_QCompleter_wrapAround :: Ptr (TQCompleter a) -> IO CBool qCompleter_delete :: QCompleter a -> IO () qCompleter_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_delete cobj_x0 foreign import ccall "qtc_QCompleter_delete" qtc_QCompleter_delete :: Ptr (TQCompleter a) -> IO () qCompleter_deleteLater :: QCompleter a -> IO () qCompleter_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_deleteLater cobj_x0 foreign import ccall "qtc_QCompleter_deleteLater" qtc_QCompleter_deleteLater :: Ptr (TQCompleter a) -> IO () instance QchildEvent (QCompleter ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QCompleter_childEvent" qtc_QCompleter_childEvent :: Ptr (TQCompleter a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QCompleterSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QCompleter ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QCompleter_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QCompleter_connectNotify" qtc_QCompleter_connectNotify :: Ptr (TQCompleter a) -> CWString -> IO () instance QconnectNotify (QCompleterSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QCompleter_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QCompleter ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QCompleter_customEvent" qtc_QCompleter_customEvent :: Ptr (TQCompleter a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QCompleterSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QCompleter ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QCompleter_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QCompleter_disconnectNotify" qtc_QCompleter_disconnectNotify :: Ptr (TQCompleter a) -> CWString -> IO () instance QdisconnectNotify (QCompleterSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QCompleter_disconnectNotify cobj_x0 cstr_x1 instance Qreceivers (QCompleter ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QCompleter_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QCompleter_receivers" qtc_QCompleter_receivers :: Ptr (TQCompleter a) -> CWString -> IO CInt instance Qreceivers (QCompleterSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QCompleter_receivers cobj_x0 cstr_x1 instance Qsender (QCompleter ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_sender cobj_x0 foreign import ccall "qtc_QCompleter_sender" qtc_QCompleter_sender :: Ptr (TQCompleter a) -> IO (Ptr (TQObject ())) instance Qsender (QCompleterSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCompleter_sender cobj_x0 instance QtimerEvent (QCompleter ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QCompleter_timerEvent" qtc_QCompleter_timerEvent :: Ptr (TQCompleter a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QCompleterSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QCompleter_timerEvent cobj_x0 cobj_x1
uduki/hsQt
Qtc/Gui/QCompleter.hs
bsd-2-clause
19,269
0
14
3,104
6,045
3,067
2,978
-1
-1
{-# LANGUAGE TypeOperators, DefaultSignatures, FlexibleContexts, TypeSynonymInstances, GeneralizedNewtypeDeriving #-} {-# LANGUAGE BinaryLiterals, FlexibleInstances, OverloadedStrings, DeriveLift, LambdaCase, RecordWildCards #-} {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, TemplateHaskell, DeriveGeneric, StandaloneDeriving #-} {-# LANGUAGE UndecidableInstances, ViewPatterns #-} module Network.Protocol.Minecraft.Types where import Control.Applicative (empty, (<|>)) import Control.Lens (makeFields, (^.)) import Control.Lens.Iso (Iso', iso) import Control.Monad.Identity import Data.Aeson import Data.Bits import Data.Binary (Binary(..)) import Data.Binary.Get import Data.Binary.Put import qualified Data.ByteString as BS import Data.ByteString (ByteString) import qualified Data.HashMap.Lazy as HML import Data.Int import Data.Maybe (fromMaybe) import Data.Monoid import Data.String (IsString) import Data.Text (Text) import qualified Data.Text.Encoding as TE import qualified Data.Vector as V import Data.Word import GHC.Generics import Language.Haskell.TH.Syntax (Lift) data Dimension = Overworld | Nether | TheEnd deriving (Show, Eq, Ord) instance Enum Dimension where fromEnum Overworld = 0 fromEnum Nether = -1 fromEnum TheEnd = 1 toEnum (-1) = Nether toEnum 0 = Overworld toEnum 1 = TheEnd toEnum x = error $ "Unknown dimension " ++ show x instance Binary Dimension where put = (put :: Int32 -> Put) . fromIntegral . fromEnum get = (toEnum . fromIntegral) <$> (get :: Get Int32) data LengthBS = LengthBS { lengthBSLen :: VarInt , lengthBS :: ByteString } deriving (Show) instance Binary LengthBS where put LengthBS{..} = put lengthBSLen >> putByteString lengthBS get = do len <- get LengthBS len <$> getByteString (fromIntegral len) newtype VarInt = VarInt {unVarInt :: Int32} deriving (Show, Bits, Eq, Ord, Num, Integral, Real, Enum) newtype VarLong = VarLong {unVarLong :: Int64} deriving (Show, Bits, Eq, Ord, Num, Integral, Real, Enum) instance Binary VarInt where put = putByteString . packVarInt get = do initial <- getWhile (`testBit` 7) last <- getByteString 1 pure . snd . unpackVarInt $ initial <> last instance Binary VarLong where put = putByteString . packVarLong get = do initial <- getWhile (`testBit` 7) last <- getByteString 1 pure . snd . unpackVarLong $ initial <> last packVarVal :: (Show a, Bits a, Integral a) => Int -> a -> [Word8] packVarVal _ 0 = [0] packVarVal maxSegs' i' = go i' maxSegs' where go :: (Show a, Bits a, Integral a) => a -> Int -> [Word8] go _ 0 = [] go 0 _ = [] go i maxSegs = if newVal == 0 then [temp] else temp `setBit` 7 : go newVal (maxSegs - 1) where temp = fromIntegral i .&. 0b01111111 :: Word8 newVal = i `shiftR` 7 packVarInt :: VarInt -> ByteString packVarInt vi = BS.pack $ packVarVal 5 (fromIntegral vi :: Word32) packVarLong :: VarLong -> ByteString packVarLong vl = BS.pack $ packVarVal 10 (fromIntegral vl :: Word64) unpackVarInt :: ByteString -> (ByteString, VarInt) unpackVarInt = fmap VarInt . unpackVarVal unpackVarLong :: ByteString -> (ByteString, VarLong) unpackVarLong = fmap VarLong . unpackVarVal unpackVarVal :: (Integral a, Bits a, Num a) => ByteString -> (ByteString, a) unpackVarVal bs = go $ BS.unpack bs where go :: (Num a, Bits a) => [Word8] -> (ByteString, a) go [] = ("", 0) go (x:xs) = if x `testBit` 7 then let (rest, bit) = go xs in (rest, bit `shiftL` 7 .|. (fromIntegral x .&. 0b01111111)) else (BS.pack xs, fromIntegral x .&. 0b01111111) class NetworkVar src dst | src -> dst, dst -> src where network :: Iso' src dst newtype NetworkText = NetworkText {unNetworkText :: Text} deriving (Show, Eq, Ord, IsString, Monoid) instance Binary NetworkText where get = do len <- fromIntegral <$> (get :: Get VarInt) NetworkText . TE.decodeUtf8 <$> getByteString len put (NetworkText text) = do let bs = TE.encodeUtf8 text put (fromIntegral $ (BS.length bs) :: VarInt) putByteString bs instance NetworkVar Text NetworkText where network = iso NetworkText unNetworkText newtype NetworkFloat = NetworkFloat {unNetworkFloat :: Float} deriving (Show, Eq, Ord, Num, Floating, Fractional, Enum, Real, RealFloat, RealFrac) instance Binary NetworkFloat where get = NetworkFloat <$> getFloatbe put = putFloatbe . unNetworkFloat instance NetworkVar Float NetworkFloat where network = iso NetworkFloat unNetworkFloat newtype NetworkDouble = NetworkDouble {unNetworkDouble :: Double} deriving (Show, Eq, Ord, Num, Floating, Fractional, Enum, Real, RealFloat, RealFrac) instance Binary NetworkDouble where get = NetworkDouble <$> getDoublebe put = putDoublebe . unNetworkDouble instance NetworkVar Double NetworkDouble where network = iso NetworkDouble unNetworkDouble getWhile :: (Word8 -> Bool) -> Get ByteString getWhile p = fmap (fromMaybe "") . lookAheadM $ do byte <- getWord8 if p byte then (Just . (BS.pack [byte] <>)) <$> getWhile p else pure Nothing data ConnectionState = Handshaking | LoggingIn | Playing | GettingStatus deriving (Show, Lift, Eq) class HasPacketID f where getPacketID :: f -> VarInt mode :: f -> ConnectionState class HasPayload f a | f -> a where getPayload :: f -> a instance Binary ConnectionState where put Handshaking = put (0 :: VarInt) put GettingStatus = put (1 :: VarInt) put LoggingIn = put (2 :: VarInt) put Playing = put (3 :: VarInt) get = getWord8 >>= pure . \case 0 -> Handshaking 1 -> GettingStatus 2 -> LoggingIn 3 -> Playing _ -> error "Unknown state" data ClickEvent = ClickEvent deriving (Generic, Show) data HoverEvent = HoverEvent deriving (Generic, Show) instance FromJSON ClickEvent instance FromJSON HoverEvent data Test f = Test (f Bool) data ChatShared f = ChatShared { chatSharedBold :: f Bool , chatSharedItalic :: f Bool , chatSharedUnderlined :: f Bool , chatSharedStrikethrough :: f Bool , chatSharedObfuscated :: f Bool , chatSharedColor :: f Text , chatSharedInsertion :: Maybe Text , chatSharedClickEvent :: ClickEvent , chatSharedHoverEvent :: HoverEvent } deriving (Generic) defaultChatShared :: ChatShared Maybe defaultChatShared = ChatShared Nothing Nothing Nothing Nothing Nothing Nothing Nothing ClickEvent HoverEvent baseChatShared :: ChatShared Identity baseChatShared = ChatShared false false false false false (Identity "white") Nothing ClickEvent HoverEvent where false = Identity False deriving instance (Show (f Bool), Show (f Text)) => Show (ChatShared f) instance FromJSON (ChatShared Maybe) where parseJSON (Object o) = ChatShared <$> o .:? "bold" <*> o .:? "italic" <*> o .:? "underlined" <*> o .:? "strikethrough" <*> o .:? "obfuscated" <*> o .:? "color" <*> o .:? "insertion" <*> pure ClickEvent <*> pure HoverEvent parseJSON _ = empty data ChatComponent f = StringComponent { chatComponentShared :: ChatShared f , chatComponentText :: Text , chatComponentExtra :: [ChatComponent f] } | TranslationComponent { chatComponentShared :: ChatShared f , chatComponentTranslate :: Text , chatComponentWith :: [ChatComponent f] , chatComponentExtra :: [ChatComponent f] } makeFields ''ChatShared makeFields ''ChatComponent deriving instance (Show (f Bool), Show (f Text)) => Show (ChatComponent f) instance FromJSON (ChatComponent Maybe) where parseJSON (Object o) | "text" `HML.member` o = StringComponent <$> parseJSON (Object o) <*> o .: "text" <*> (o .: "extra" <|> pure []) | "translate" `HML.member` o = TranslationComponent <$> parseJSON (Object o) <*> o .: "translate" <*> o .: "with" <*> (o .: "extra" <|> pure []) | otherwise = empty parseJSON (String s) = pure $ StringComponent defaultChatShared s [] parseJSON (Array a) | not (V.null a) = do first <- parseJSON (V.head a) rest <- sequence . V.toList $ parseJSON <$> V.drop 1 a pure $ StringComponent defaultChatShared first rest parseJSON _ = empty inheritStyle :: ChatShared Identity -> ChatShared Maybe -> ChatShared Identity inheritStyle base cc = ChatShared (Identity $ fromMaybe (runIdentity $ base ^. bold) (cc ^. bold)) (Identity $ fromMaybe (runIdentity $ base ^. italic) (cc ^. italic)) (Identity $ fromMaybe (runIdentity $ base ^. underlined) (cc ^. underlined)) (Identity $ fromMaybe (runIdentity $ base ^. strikethrough) (cc ^. strikethrough)) (Identity $ fromMaybe (runIdentity $ base ^. obfuscated) (cc ^. obfuscated)) (Identity $ fromMaybe (runIdentity $ base ^. color) (cc ^. color)) (cc ^. insertion) ClickEvent HoverEvent inheritChatComponent :: ChatShared Identity -> ChatComponent Maybe -> ChatComponent Identity inheritChatComponent base cc = case cc of StringComponent{} -> StringComponent canonicalStyle (cc ^. text) extras TranslationComponent{} -> let withs = inheritChatComponent canonicalStyle <$> cc ^. with in TranslationComponent canonicalStyle (cc ^. translate) withs extras where canonicalStyle = inheritStyle base (cc ^. shared) extras = inheritChatComponent canonicalStyle <$> cc ^. extra canonicalizeChatComponent :: ChatComponent Maybe -> ChatComponent Identity canonicalizeChatComponent = inheritChatComponent baseChatShared chatToText :: ChatComponent Identity -> Text chatToText (TranslationComponent _ key withs extra) = case key of "chat.type.text" -> "<" <> chatToText (withs !! 0) <> "> " <> chatToText (withs !! 1) <> extras "commands.message.display.incoming" -> chatToText (withs !! 0) <> " whispers to you: " <> chatToText (withs !! 1) <> extras _ -> key <> extras where extras = mconcat (chatToText <$> extra) chatToText (StringComponent _ t extra) = t <> mconcat (chatToText <$> extra) data Slot = Slot { slotBlockId :: Int16 , slotItemCount :: Maybe Int8 , slotItemDamage :: Maybe Int8 -- NBT } deriving (Show) makeFields ''Slot instance Binary Slot where get = do blockId <- getInt16be if blockId == -1 then pure $ Slot (-1) Nothing Nothing else Slot blockId <$> (Just <$> getInt8) <*> (Just <$> getInt8) put (Slot id count dmg) = do putInt16be id case count of Just c -> putInt8 c Nothing -> pure () case dmg of Just d -> putInt8 d Nothing -> pure () emptySlot :: Slot emptySlot = Slot (-1) Nothing Nothing isEmptySlot :: Slot -> Bool isEmptySlot (Slot (-1) _ _) = True isEmptySlot _ = False data Position = Position Int Int Int deriving (Show) instance Binary Position where get = do bytes <- getWord64be let xval = bytes `shiftR` 38 yval = (bytes `shiftR` 26) .&. 0xFFF zval = (bytes `shiftL` 38) `shiftR` 38 x = if xval > 2^25 then xval - 2^26 else xval y = if yval > 2^11 then yval - 2^12 else yval z = if zval > 2^25 then zval - 2^26 else zval pure $ Position (fromIntegral x) (fromIntegral y) (fromIntegral z) put (Position (fromIntegral -> x) (fromIntegral -> y) (fromIntegral -> z)) = do put ((((x .&. 0x3FFFFFF) `shiftL` 38) .|. ((y .&. 0xFFF) `shiftL` 26) .|. (z .&. 0x3FFFFFF)) :: Int64) -- TODO: -- Entity Metadata -- NBT Tag -- Angle (Word8) -- UUID --
Xandaros/MinecraftCLI
src/Network/Protocol/Minecraft/Types.hs
bsd-2-clause
14,183
0
21
5,172
3,899
2,065
1,834
277
4
{-# LANGUAGE Haskell2010 #-} module DeprecatedTypeSynonym where -- | some documentation type TypeSyn = String {-# DEPRECATED TypeSyn "TypeSyn" #-} type OtherTypeSyn = String {-# DEPRECATED OtherTypeSyn "OtherTypeSyn" #-}
haskell/haddock
html-test/src/DeprecatedTypeSynonym.hs
bsd-2-clause
224
0
4
32
20
15
5
6
0
{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} module Control.Monad.Views where import Control.Monad.Zipper import Control.Monad.Error import Control.Monad.State import Control.Monad.Identity import Control.Monad.Reader import Control.Monad.Writer class MonadMorphism g where idv :: (Monad m) => m `g` m hcomp :: (Monad l, Monad m, Monad n) => (m `g` n) -> (l `g` m) -> (l `g` n) hmap :: (Monad m, Monad n, MonadTrans t) => (m `g` n) -> (t m `g` t n) from :: (Monad m, Monad n) => (n `g` m) -> n a -> m a htmap :: (Monad (t1 n), Monad (t2 n), Monad m, Monad n, Monad (t1 m), MonadTrans t1, MonadMorphism g) => (forall m . Monad m => t1 m `g` t2 m) -> (m `g` n) -> t1 m `g` t2 n htmap t f = t `hcomp` hmap f newtype n :-> m = Uni (forall a. n a -> m a) instance MonadMorphism (:->) where idv = Uni id v2 `hcomp` v1 = Uni $ from v2 .from v1 hmap v = Uni $ tmap (from v) from (Uni v) = v liftv :: (MonadTrans t, Monad m) => m :-> t m liftv = Uni lift r1 :: (MonadTrans t, Monad m, MonadState s (t m)) => ReaderT s m :-> t m r1 = Uni $ \n -> do s <- get lift $ runReaderT n s ra = Uni (\n -> do s <- get lift $ runReaderT n s ) data n :><: m = Bi { bifrom :: forall a. n a -> m a , bito :: forall a. m a -> n a} instance MonadMorphism (:><:) where idv = Bi { bifrom = id , bito = id } v2 `hcomp` v1 = Bi { bifrom = bifrom v2 . bifrom v1 , bito = bito v1 . bito v2 } hmap v = Bi { bifrom = tmap (from v) , bito = tmap (to v) } from v = bifrom v to :: (Monad n, Monad m) => n :><: m -> m a -> n a to = bito inverse :: (Monad n, Monad m) => n :><: m -> m :><: n inverse (Bi from to) = Bi to from class MonadMorphism g => View g where view :: (forall a. n a -> m a) -> (forall a. m a -> n a) -> n `g` m instance View (:->) where view f fm1 = Uni f instance View (:><:) where view f fm1 = Bi f fm1 stateIso :: (Monad m, View g) => (s2 -> s1) -> (s1 -> s2) -> StateT s2 m `g` StateT s1 m stateIso f fm1 = view (iso f fm1) (iso fm1 f) where iso g h m = StateT $ \s2 -> do (a, s1) <- runStateT m (h s2) return (a, g s1) newtype MonadStateReaderT s m a = MonadStateReaderT { runMonadStateReaderT :: m a } instance MonadState s m => MonadReader s (MonadStateReaderT s m) where ask = MonadStateReaderT get local f m = MonadStateReaderT $ do s <- get put (f s) r <- runMonadStateReaderT m put s return r instance MonadWriter w m => MonadWriter w (MonadStateReaderT s m) where tell = lift . tell listen m = MonadStateReaderT $ do (ma, w) <- listen (runMonadStateReaderT m) return (ma, w) pass m = MonadStateReaderT $ pass $ do (ma, w) <- runMonadStateReaderT m return (ma, w) instance MonadTrans (MonadStateReaderT s) where lift = MonadStateReaderT mt = MT unlift f = MonadStateReaderT $ liftM runIdentity $ f (\tmx -> liftM Identity $ runMonadStateReaderT tmx) r2 :: (MonadState s m, View g) => MonadStateReaderT s m `g` m r2 = view runMonadStateReaderT MonadStateReaderT instance Monad m => Monad (MonadStateReaderT s m) where return = MonadStateReaderT . return x >>= f = MonadStateReaderT $ runMonadStateReaderT x >>= runMonadStateReaderT . f -- ========================= Structural Masks ========================= infixl 5 `vcomp` i :: (Monad m, View g) => m `g` m i = idv o :: (MonadTrans t1, MonadTrans t2, Monad m, View g) => (t1 :> t2) m `g` t1 (t2 m) o = view leftL rightL v1 `vcomp` v2 = v1 `hcomp` hmap v2
ifigueroap/mzv
src/Control/Monad/Views.hs
bsd-3-clause
4,205
16
14
1,330
1,678
877
801
96
1
{-# LANGUAGE RankNTypes #-} ------------------------------------------------------------------------------- -- -- Module: Network.Server.Concurrent -- Licence: BSD3 -- -- Maintainer: -- Stability: experimental -- Portability: NixOs -- -- Skeleton for Concurrent TCP Server based on green threads. -- This module based on Warp <url:http://hackage.haskell.org/package/warp-0.4.6.3> -- package -- ------------------------------------------------------------------------------- -- | light-weight TCP server -- module Network.Server.Concurrent ( -- * Datatypes Application, Request, Response, -- * Run server run, runSettings, runSettingsSocket ) where import Prelude hiding (catch) import Data.ByteString (ByteString) import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Network (sClose, Socket) import Network.Socket.Enumerator (enumSocket) import Network.Socket ( accept, Family (..) , SocketType (Stream), listen, bindSocket, setSocketOption, maxListenQueue , SockAddr, SocketOption (ReuseAddr) , AddrInfo(..), AddrInfoFlag(..), defaultHints, getAddrInfo ) import qualified Network.Socket import qualified Network.Socket.ByteString as Sock import Control.Exception ( bracket, finally, Exception, SomeException, catch , fromException, bracketOnError ) import Data.Enumerator (($$),(>>==),($=)) import qualified Data.Enumerator as E import qualified Data.Enumerator.List as EL import qualified Data.Enumerator.Binary as EB import Control.Concurrent (forkIO) import Control.Monad.IO.Class (liftIO) import Control.Monad (forever,when) import Control.Monad.Trans (MonadIO (..)) --import Debug.Trace -- | Request type type Request = ByteString -- | Response type -- TODO: add Command to Server -- smth like data Response = Send ByteString | Stop | ... type Response = ByteString -- | Application type type Application = MonadIO m => E.Enumeratee Request Response m b data Settings = Settings { settingsHost :: String -- ^ Host to bind to, or * for all. Default: * , settingsPort :: Int -- ^ port to listen on. Default: 3500 , settingsOnException :: SomeException -> IO () -- ^ Exception handler } defaultSettings :: Settings defaultSettings = Settings { settingsPort = 3500 , settingsHost = "*" , settingsOnException = \e -> return () {- case fromException e of Just x -> go x Nothing -> if go' $ fromException e then hPutStrLn stderr $ show e else return () -} } -- | Run application on specified port run :: Port -> Application -> IO () run p = runSettings defaultSettings {settingsPort = p} -- | Run application with specified settings runSettings :: Settings -> Application -> IO () runSettings set = bracket (bindPort (settingsPort set) (settingsHost set)) sClose . (flip (runSettingsSocket set)) -- | Run application with settings on created socket runSettingsSocket :: Settings -> Socket -> Application -> IO () runSettingsSocket set socket app = do let onE = settingsOnException set port = settingsPort set forever $ do (conn, sa) <- accept socket _ <- forkIO $ serveConnection set onE port app conn sa return () -- | Serve connection serveConnection settings onException port app conn remoteHost' = do catch (finally (E.run_ $ enumSocket bytesPerRead conn $= app $$ sendResponses conn) (sClose conn)) onException where sendResponses :: MonadIO m => Socket -> E.Iteratee ByteString m () sendResponses socket = do r <- EL.head case r of Just resp -> do liftIO $ print resp when (not $ S.null resp) $ liftIO (Sock.sendMany socket [resp] {-$ S.toChunks resp-}) sendResponses socket Nothing -> sendResponses socket type Port = Int bindPort :: Int -> String -> IO Socket bindPort p s = do let hints = defaultHints { addrFlags = [ AI_PASSIVE , AI_NUMERICSERV , AI_NUMERICHOST] , addrSocketType = Stream } host = if s=="*" then Nothing else Just s port = Just . show $ p addrs <- getAddrInfo (Just hints) host port let addrs' = filter (\x -> addrFamily x == AF_INET6) addrs addr = if null addrs' then head addrs else head addrs' bracketOnError (Network.Socket.socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)) (sClose) (\sock -> do setSocketOption sock ReuseAddr 1 bindSocket sock (addrAddress addr) listen sock maxListenQueue return sock ) bytesPerRead :: Integer bytesPerRead = 4096
qnikst/TcpServers
src/Network/Server/Concurrent.hs
bsd-3-clause
4,908
0
19
1,281
1,109
625
484
97
3
module Control.Handler ( Handler , new , reset , set , call ) where import UnliftIO.IORef import Control.Monad.IO.Class newtype Handler m a = Handler (IORef (a -> m ())) new :: MonadIO m => m (Handler m a) new = Handler <$> newIORef (\_ -> return ()) reset :: MonadIO m => Handler m a -> m () reset (Handler h) = writeIORef h $ \_ -> return () set :: MonadIO m => Handler m a -> (a -> m ()) -> m () set (Handler h) = writeIORef h call :: MonadIO m => Handler m a -> a -> m () call (Handler h) a = do f <- readIORef h f a
abbradar/yaxmpp
src/Control/Handler.hs
bsd-3-clause
543
0
11
138
289
146
143
19
1
{-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ConstraintKinds #-} module Vector ( Vec (..) , vmap , NVec ) where import Util import Data.Functor.Identity import Data.Serialize data Vec :: (k -> *) -> [k] -> * where Nil :: Vec fn '[] (:-) :: fn a -> ! (Vec fn as) -> Vec fn (a ': as) infixr 7 :- instance Creatable (Vec fn '[]) where seeded _ = Nil instance Show (Vec a '[]) where show _ = "Nil" instance Eq (Vec a '[]) where _ == _ = True instance (Eq (f a), Eq (Vec f ts)) => Eq (Vec f (a ': ts)) where (a :- as) == (b :- bs) = a == b && as == bs instance (Show (f a), Show (Vec f ts)) => Show (Vec f (a ': ts)) where show (x :- xs) = show x ++ " :- " ++ show xs instance (Creatable (fn a), Creatable (Vec fn as)) => Creatable (Vec fn (a ': as)) where seeded s = seeded s :- seeded s instance Serialize (Vec fn '[]) where put _ = return () get = return Nil instance (Serialize (fn a), Serialize (Vec fn as)) => Serialize (Vec fn (a ': as)) where put (x :- xs) = do put x put xs get = do x <- get xs <- get return$! x :- xs type NVec = Vec Identity {- fmap' :: SMap a b as bs => (a -> b) -> NVec as -> NVec bs fmap' f = vmap (fmap f) -} class VMap a b as bs where vmap :: (fn1 a -> fn2 b) -> Vec fn1 as -> Vec fn2 bs instance VMap a b '[] '[] where vmap :: (fn1 a -> fn2 b) -> Vec fn1 '[] -> Vec fn2 '[] vmap _ Nil = Nil instance VMap a b as bs => VMap a b (a ': as) (b ': bs) where vmap :: (fn1 a -> fn2 b) -> Vec fn1 (a ': as) -> Vec fn2 (b ': bs) vmap f (x :- xs) = f x :- vmap f xs
jonascarpay/visor
src/Vector.hs
bsd-3-clause
1,980
2
10
544
881
455
426
63
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE OverloadedStrings #-} module Guide.Api.Server ( runApiServer ) where import Imports import Data.Acid as Acid import Servant import Servant.Generic import Network.Wai.Handler.Warp (run) import Network.Wai (Middleware) import Network.Wai.Middleware.Cors (CorsResourcePolicy (..), cors , corsOrigins, simpleCorsResourcePolicy) -- putStrLn that works well with concurrency import Say (say) import Guide.State import Guide.Api.Types (Api, Site(..)) import Guide.Api.Methods (getCategories, getCategory) apiServer :: DB -> Site AsServer apiServer db = Site { -- NB. we do @fmap Right@ because some handlers return ApiError and others -- don't. The reason we add 'Right' here and not in those handlers is that -- it makes the signatures of those handlers better reflect their -- properties (i.e. whether they can fail or not). _getCategories = getCategories db & fmap Right, _getCategory = getCategory db } -- | Serve the API on port 4400. -- -- You can test this API by doing @withDB mempty runApiServer@. runApiServer :: AcidState GlobalState -> IO () runApiServer db = do say "API is running on port 4400" run 4400 $ corsPolicy $ serve (Proxy @Api) (toServant (apiServer db)) where corsPolicy :: Middleware corsPolicy = cors (const $ Just policy) policy :: CorsResourcePolicy policy = simpleCorsResourcePolicy -- TODO: Add Guides frontend address (and maybe others resources) -- to list of `corsOrigins` to allow CORS requests { corsOrigins = Just ([ "http://localhost:3333" -- ^ Guide's frontend running on localhost ], True) }
aelve/hslibs
src/Guide/Api/Server.hs
bsd-3-clause
1,832
0
12
440
309
182
127
32
1
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Safe #-} #endif #if __GLASGOW_HASKELL__ >= 710 {-# LANGUAGE AutoDeriveTypeable #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Trans.Writer.CPS -- Copyright : (c) Daniel Mendler 2016, -- (c) Andy Gill 2001, -- (c) Oregon Graduate Institute of Science and Technology, 2001 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : mail@daniel-mendler.de -- Stability : experimental -- Portability : portable -- -- The strict 'WriterT' monad transformer, which adds collection of -- outputs (such as a count or string output) to a given monad. -- -- This monad transformer provides only limited access to the output -- during the computation. For more general access, use -- "Control.Monad.Trans.State" instead. -- -- This version builds its output strictly and uses continuation-passing-style -- to achieve constant space usage. This transformer can be used as a -- drop-in replacement for "Control.Monad.Trans.Writer.Strict". ----------------------------------------------------------------------------- module Control.Monad.Trans.Writer.CPS ( -- * The Writer monad Writer, writer, runWriter, execWriter, mapWriter, -- * The WriterT monad transformer WriterT, writerT, runWriterT, execWriterT, mapWriterT, -- * Writer operations tell, listen, listens, pass, censor, -- * Lifting other operations liftCallCC, liftCatch, ) where import Control.Monad.Trans.Writer.CPS.Internal
minad/writer-cps-transformers
src/Control/Monad/Trans/Writer/CPS.hs
bsd-3-clause
1,612
0
4
288
106
84
22
20
0
{-# LANGUAGE MultiParamTypeClasses #-} module Math.VectorSpaces.InnerProduct where import qualified Math.Algebra.Vector as V infixl 7 <.> class (V.Vector a b) => InnerProduct a b where (<.>) :: b -> b -> a
michiexile/hplex
pershom/src/Math/VectorSpaces/InnerProduct.hs
bsd-3-clause
218
0
8
43
61
37
24
6
0
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE ExistentialQuantification #-} module Testing where import Data.Maybe import Control.Arrow data Test = forall a. Show a => Test String (a -> Bool) [a] data Failure = forall a. Show a => Fail String [a] instance Show Failure where show (Fail s as) = "Failed Test \"" ++ s ++ "\" on inputs " ++ show as runTest :: Test -> Maybe Failure runTest (Test s f as) = case filter (not . f) as of [] -> Nothing fs -> Just $ Fail s fs runTests :: [Test] -> [Failure] runTests = mapMaybe runTest -- Helpers testF1 :: (Show a, Show b, Eq b) => String -> (a -> b) -> [(a, b)] -> Test testF1 s f l = Test s (uncurry (==)) $ map (first f) l testF2 :: (Show a, Show b, Show c, Eq c) => String -> (a -> b -> c) -> [(a, b, c)] -> Test testF2 s f l = Test s (uncurry (==)) $ map (\(x, y, z) -> (f x y, z)) l testF3 :: (Show a, Show b, Show c, Show d, Eq d) => String -> (a -> b -> c -> d) -> [(a, b, c, d)] -> Test testF3 s f l = Test s (uncurry (==)) $ map (\(w, x, y, z) -> (f w x y, z)) l
kemskems/cis194-spring13
src/Testing.hs
bsd-3-clause
1,116
0
11
337
579
313
266
24
2
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, FlexibleInstances, TypeFamilies, FlexibleContexts, TypeSynonymInstances #-} {-# OPTIONS_GHC -funbox-strict-fields #-} module Sequence where import Data.Monoid import Data.FingerTree.Unboxed as F import Data.Unboxed data Size = Size { unSize :: {-# UNPACK #-} !Int } newtype Elem a = Elem { unElem :: a } newtype Seq a = Seq { unSeq :: FingerTree Size (Elem a) } instance Monoid Size where {-# INLINE mappend #-} mappend (Size a) (Size b) = Size (a + b) {-# INLINE mempty #-} mempty = Size 0 instance MaybeGroup Size where {-# INLINE trySubtract #-} trySubtract (Size a) (Size b) _ = Size (a - b) instance Measured Size (Elem a) where {-# INLINE measure #-} measure _ = Size 1 $(F.defineFingerTree [t| Size |]) instance F.Unpacked1 (Node Size) where {-# INLINE mk1 #-} mk1 = mk {-# INLINE unMk1 #-} unMk1 = unMk instance F.Unpacked1 (FingerTree Size) where {-# INLINE mk1 #-} mk1 = mk {-# INLINE unMk1 #-} unMk1 = unMk instance F.Unbox Size empty :: Seq a empty = Seq F.empty singleton :: a -> Seq a singleton = Seq . F.singleton . Elem (<|) :: a -> Seq a -> Seq a el <| (Seq a) = Seq (Elem el F.<| a) (><) :: Seq a -> Seq a -> Seq a (Seq l) >< (Seq r) = Seq (l F.>< r) (|>) :: Seq a -> a -> Seq a (Seq a) |> el = Seq (a F.|> Elem el) --null :: Seq a -> Bool --null (Seq a) = F.null a viewl :: Seq a -> ViewL Seq a viewl (Seq a) = case F.viewl a of EmptyL -> EmptyL Elem h :< t -> h :< Seq t --length :: Seq a -> Int --length (Seq a) = unSize (F.measure a) instance SplitPred Size Size where checkPred (Size n) (Size i) = i >= n split :: Int -> Seq a -> (Seq a, Seq a) split n (Seq a) = n `seq` case F.split (Size n) a of (l, _, r) -> (Seq l, Seq r)
reinerp/fingertree-unboxed
examples/Sequence.hs
bsd-3-clause
1,794
0
10
434
692
365
327
50
2
module Data.Array.Repa.Repr.LazyTreeSplitting ( L, Array (..) , fromRope, toRope, ropeFromList, ropeToList, setGlobalLeafSize ) where import Data.Array.Repa.Shape import Data.Array.Repa.Base hiding (toList) import Data.Array.Repa.Eval hiding (fromList, toList) import Data.Array.Repa.Index import Control.Monad import qualified Data.Rope as T import qualified Data.Rope.Seq as TS import Control.DeepSeq --TODO: FIX -- | Unboxed arrays are represented as unboxed vectors. -- -- The implementation uses @Data.Vector.Unboxed@ which is based on type -- families and picks an efficient, specialised representation for every -- element type. In particular, unboxed vectors of pairs are represented -- as pairs of unboxed vectors. -- This is the most efficient representation for numerical data. -- data L linearIndex' :: Int -> T.Rope a -> a linearIndex' n (T.Leaf x) = TS.index x n linearIndex' n (T.Cat s d l r) = if (T.length l) <= n then linearIndex' n l else linearIndex' (n - (T.length l)) r --TODO: FIX -- | Read elements from an unboxed vector array. instance Source L a where data Array L sh a --TODO: Restrict to DIM1? Can we do DIM2+? = ARope !sh !(T.Rope a) linearIndex (ARope _ vec) ix = linearIndex' ix vec {-# INLINE linearIndex #-} unsafeLinearIndex (ARope sh vec) ix = linearIndex' ix vec {-# INLINE unsafeLinearIndex #-} extent (ARope sh _) = sh {-# INLINE extent #-} deepSeqArray (ARope sh vec) x = sh `deepSeq` vec `seq` x {-# INLINE deepSeqArray #-} --TODO: Do we need to restrict Rope class to contain values that can be Show'n and Read? deriving instance (Show sh, Show e) => Show (Array L sh e) --deriving instance (Read sh, Read e) -- => Read (Array L sh e) setGlobalLeafSize :: Int -> IO () setGlobalLeafSize k = T.set_mAX_LEAF_SIZE k -- | O(1) fromRope :: Shape sh => sh -> T.Rope a -> Array L sh a fromRope sh rp = ARope sh rp {-# INLINE fromRope #-} -- | O(1) toRope :: Shape sh => Array L sh a -> T.Rope a toRope (ARope sh rp) = rp {-# INLINE toRope #-} ropeFromList :: Shape sh => sh -> [a] -> Array L sh a ropeFromList sh xs = ARope sh (let x = T.fromList xs in x `seq` x) --(ix1 (length xs)) (T.fromList xs) {-# INLINE ropeFromList #-} ropeToList :: Shape sh => Array L sh a -> [a] ropeToList (ARope _ rp) = let x = T.toList rp in x `seq` x {-# INLINE ropeToList #-}
kairne/repa-lts
Data/Array/Repa/Repr/LazyTreeSplitting.hs
bsd-3-clause
2,414
0
12
520
663
363
300
-1
-1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Infer where import Control.Monad.State import Control.Monad.Writer import Control.Monad.Except import qualified Data.Map.Strict as Map import qualified Data.Set as Set import Syntax type Constraint = (Type, Type) type Ctx = Map.Map String Type type Infer a = StateT [String] (WriterT [Texlevel] ThrowsErr) a --vars = cycle $ map (:[]) ['A'..'Z'] vars = concatMap (\n -> [c : show n | c <- ['A'..'Z']]) [1..] freshVar :: Infer Type freshVar = do name <- fmap (TyVar . head) get modify tail return name newtype Subst = Subst (Map.Map String Type) deriving (Eq, Ord, Show, Monoid) class Substitutable a where apply :: Subst -> a -> a instance Substitutable Type where apply (Subst s) t@(TyVar name) = Map.findWithDefault t name s apply s (e1 `TyArr` e2) = apply s e1 `TyArr` apply s e2 instance Substitutable Constraint where apply s (t1, t2) = (apply s t1, apply s t2) instance Substitutable a => Substitutable [a] where apply = map . apply instance Substitutable Ctx where apply s ctx = Map.map (apply s) ctx instance Substitutable Texlevel where apply s (TexVar x ty) = TexVar x (apply s ty) apply s (TexAbs x bod vty bty) = TexAbs x bod (apply s vty) (apply s bty) apply s (TexApp m n a) = TexApp m n (apply s a) ctxLookup :: String -> Ctx -> Infer Type ctxLookup name ctx = case Map.lookup name ctx of (Just ty) -> return ty Nothing -> throwError $ ErrUnboundVar name recon :: Expr -> Ctx -> [Constraint] -> Infer (Type, [Constraint]) recon expr ctx cs = case expr of (Var name) -> do ty <- ctxLookup name ctx tell [TexVar name ty] return (ty, cs) (App func arg) -> do (funcTy, cs') <- recon func ctx cs (argTy, cs'') <- recon arg ctx cs' newvar <- freshVar -- tell [(funcTy, argTy `TyArr` newvar)] tell [TexApp func arg newvar] return (newvar, (funcTy, argTy `TyArr` newvar) : cs'') (Lam var body) -> do newvar <- freshVar let ctx' = Map.insert var newvar ctx (bodyTy, cs') <- recon body ctx' cs tell [TexAbs var body newvar bodyTy] return (newvar `TyArr` bodyTy, cs') emptyCtx = Map.empty runInfer :: Expr -> ThrowsErr ((Type, [Constraint]), [Texlevel]) runInfer expr = do let writer = evalStateT (recon expr emptyCtx []) vars runWriterT writer type Unifier = (Subst, [Constraint]) emptySubst :: Subst emptySubst = mempty compose :: Subst -> Subst -> Subst -- More efficent order of substitutions possible? compose (Subst s1) (Subst s2) = Subst $ Map.map (apply (Subst s1)) s2 `Map.union` s1 inferExpr :: Expr -> ThrowsErr (Type, [Texlevel]) inferExpr inp = do ((ty, cs), tex) <- runInfer inp subst <- runSolve cs return (apply subst ty, apply subst tex) runSolve :: [Constraint] -> ThrowsErr Subst runSolve cs = solver (emptySubst, cs) solver :: Unifier -> ThrowsErr Subst solver (su, cs) = case cs of [] -> return su ((t1, t2): cs0) -> do su1 <- unifies t1 t2 solver (su1 `compose` su, apply su1 cs0) unifyMany :: [Type] -> [Type] -> ThrowsErr Subst unifyMany [] [] = return emptySubst unifyMany (t1 : ts1) (t2 : ts2) = do su1 <- unifies t1 t2 su2 <- unifyMany (apply su1 ts1) (apply su1 ts2) return (su2 `compose` su1) unifyMany t1 t2 = throwError $ ErrUnify t1 t2 unifies :: Type -> Type -> ThrowsErr Subst unifies t1 t2 | t1 == t2 = return emptySubst unifies (TyVar x) t = x `bind` t unifies t (TyVar x) = x `bind` t unifies (TyArr t1 t2) (TyArr t3 t4) = unifyMany [t1, t2] [t3, t4] unifies t1 t2 = throwError $ ErrUnify [t1] [t2] bind :: String -> Type -> ThrowsErr Subst bind a t | t == TyVar a = return emptySubst | occursCheck a t = throwError $ ErrOccursCheck a t | otherwise = return (Subst $ Map.singleton a t) freeTyVar :: Type -> Set.Set String freeTyVar (TyVar n) = Set.singleton n freeTyVar (TyArr t1 t2) = freeTyVar t1 `Set.union` freeTyVar t2 occursCheck :: String -> Type -> Bool occursCheck a t = a `Set.member` freeTyVar t
felixgb/calc2latex
src/Infer.hs
bsd-3-clause
4,166
0
14
979
1,761
904
857
105
3
{- ****************************************************************************** * I N V A D E R S * * * * Module: Animate * * Purpose: Animation of graphical signal functions. * * Author: Henrik Nilsson * * * * Copyright (c) Yale University, 2003 * * * ****************************************************************************** -} -- Approach: The signal function is sampled as frequently as possible. It's -- the OS's task to allocate resources, so we can just as well use up all the -- CPU cycles we get. But since drawing is very time consuming, we draw at a -- fixed, user-defineable, presumably lower rate, thus allowing the user to -- control the ratio between the cycles spent on drawing and the cycles spent -- on editing/simulation. This approach may result in rather uneven sampling -- intervals, but embedSynch can be used to provide a stable time base when -- that is important, e.g. for simulation, as long as there are enough cycles -- on average to keep up. -- -- For some reason, context switching does not work as it should unless -- the window tick mechanism is enabled. For that reason, we use a high -- frequency tick (1kHz). (Alternatively, passing the -C runtime flag (e.g. -- +RTS -C1) forces regular context switches. Moreover, getting events -- without delay seems to require yielding to ensure that the thread -- receiving them gets a chance to run. This can be done using yield prior to -- galling HGL.maybeGetWindowEvent. Alternatively, we can get the window tick, -- and since the tick frequency is high, no major waiting should ensue. This -- is the current method, although it seems as if this method means that -- window close events often will be missed. module Animate (WinInput, animate) where import Control.DeepSeq (NFData, force) import Control.Monad (forM_, when) import Data.IORef (IORef, newIORef, readIORef, writeIORef) import qualified Graphics.HGL as HGL import FRP.Yampa import FRP.Yampa.Event import Diagnostics (intErr) import PhysicalDimensions type WinInput = Event HGL.Event ------------------------------------------------------------------------------ -- Animation ------------------------------------------------------------------------------ -- Animate a signal function -- fr ......... Frame rate. -- title ...... Window title. -- width ...... Window width in pixels. -- height ..... Window height in pixels. -- render ..... Renderer; invoked at the frame rate. -- tco ........ Text Console Output; invoked at every step. -- sf ......... Signal function to animate. -- !!! Note: it would be easy to add an argument (a -> IO b) as well, allowing -- !!! arbitrary I/O. One could even replace the text output by such a -- !!! function. Could one possibly somehow get data back into the signal -- !!! function by means of continuations? Or maybe the IOTask monad is the -- !!! way to go, with a special "reactimateIOTask". animate :: (NFData a) => Frequency -> String -> Int -> Int -> (a -> HGL.Graphic) -> (a -> [String]) -> (SF WinInput a) -> IO () animate fr title width height render tco sf = HGL.runGraphics $ do win <- HGL.openWindowEx title Nothing -- Initial position. (width, height) -- Size. HGL.DoubleBuffered -- Painfully SLOW!!! (Just 1) -- For scheduling!?! (init, getTimeInput, isClosed) <- mkInitAndGetTimeInput win reactimate init getTimeInput (\_ (ea@(e,a), (e', c)) -> do updateWin render win ea forM_ (tco a) putStrLn when (isEvent e') (putStrLn ("Cycle#: " ++ show c)) isClosed) ((repeatedly (1/fr) () &&& sf) &&& (repeatedly 1 () &&& loop (arr ((+1) . snd) >>> iPre (0 :: Int) >>> arr dup))) HGL.closeWindow win ------------------------------------------------------------------------------ -- Support for reading time and input ------------------------------------------------------------------------------ mkInitAndGetTimeInput :: HGL.Window -> IO (IO WinInput, Bool -> IO (DTime,Maybe WinInput), IO Bool) mkInitAndGetTimeInput win = do let clkRes = 1000 tpRef <- newIORef errInitNotCalled wepRef <- newIORef errInitNotCalled weBufRef <- newIORef Nothing closedRef <- newIORef False -- Initialization and initial input let init = do -- Initial time t0 <- getElapsedTime writeIORef tpRef t0 -- Initial input mwe <- getWinInput win weBufRef writeIORef wepRef mwe -- Initial signal return (maybeToEvent mwe) -- Next delta time and input let getTimeInput _ = do -- Get time tp <- readIORef tpRef t <- getElapsedTime `repeatUntil` (/= tp) -- Wrap around possible! let dt = if t > tp then fromIntegral (t-tp)/clkRes else 1/clkRes writeIORef tpRef t -- Get input mwe <- getWinInput win weBufRef mwep <- readIORef wepRef writeIORef wepRef mwe -- Return time and input, possibly asking to close the program case (mwep, mwe) of (Nothing, Nothing) -> return (dt, Nothing) (_, Just HGL.Closed) -> do writeIORef closedRef True return (dt, Just (maybeToEvent mwe)) _ -> return (dt, Just (maybeToEvent mwe)) return (init, getTimeInput, readIORef closedRef) where errInitNotCalled = intErr "RSAnimate" "mkInitAndGetTimeInput" "Init procedure not called." -- Accurate enough? Resolution seems to be 0.01 s, which could lead -- to substantial busy waiting above. -- getElapsedTime :: IO ClockTick -- getElapsedTime = fmap elapsedTime getProcessTimes -- Use this for now. Have seen delta times down to 0.001 s. But as -- the complexity of the simulator signal function gets larger, the -- processing time for one iteration will presumably be > 0.01 s, -- and a clock resoltion of 0.01 s vs. 0.001 s becomes a non issue. getElapsedTime :: IO HGL.Time getElapsedTime = HGL.getTime -- Get window input, with "redundant" mouse moves removed. getWinInput :: HGL.Window -> IORef (Maybe HGL.Event) -> IO (Maybe HGL.Event) getWinInput win weBufRef = do mwe <- readIORef weBufRef case mwe of Just _ -> do writeIORef weBufRef Nothing return mwe Nothing -> do mwe' <- gwi win case mwe' of Just (HGL.MouseMove {}) -> mmFilter mwe' _ -> return mwe' where mmFilter jmme = do mwe' <- gwi win case mwe' of Nothing -> return jmme Just (HGL.MouseMove {}) -> mmFilter mwe' Just _ -> writeIORef weBufRef mwe' >> return jmme -- Seems as if we either have to yield or wait for a tick in order -- to ensure that the thread receiving events gets a chance to -- work. For some reason, yielding seems to result in window close -- events getting through, wheras waiting often means they don't. -- Maybe the process typically dies before the waiting time is up in -- the latter case? gwi win = do HGL.getWindowTick win mwe <- HGL.maybeGetWindowEvent win return mwe ------------------------------------------------------------------------------ -- Support for output ------------------------------------------------------------------------------ -- Need to force non-displayed elements to avoid space leaks. -- We also explicitly force displayed elements in case the renderer does not -- force everything. updateWin :: NFData a => (a -> HGL.Graphic) -> HGL.Window -> (Event (), a) -> IO () updateWin render win (e, a) = when (force a `seq` isEvent e) (HGL.setGraphic win (render a)) -- * Auxiliary function -- | Repeat m until result satisfies the predicate p repeatUntil :: Monad m => m a -> (a -> Bool) -> m a m `repeatUntil` p = m >>= \x -> if not (p x) then repeatUntil m p else return x
ivanperez-keera/SpaceInvaders
src/Animate.hs
bsd-3-clause
9,141
0
21
3,049
1,381
721
660
98
5
module Import.Configuration (DeploymentEnvironment(..), mainWrapper) where import Prelude as Import hiding (head, init, last, readFile, tail, writeFile, catch) import qualified Data.Map as Map import qualified Data.Text as Text import qualified Data.Yaml as YAML import Control.Monad.Logger import System.Environment import System.Exit import Import.Settings import Import.Types data DeploymentEnvironment = Development | Production deriving (Eq, Ord, Read, Show) mainWrapper :: (Settings -> Main ()) -> IO () mainWrapper innerMain = do let expectFilePath :: [String] -> Maybe (FilePath, [String]) expectFilePath (filePath : rest) = Just (filePath, rest) expectFilePath _ = Nothing expectDeploymentEnvironment :: [String] -> Maybe (DeploymentEnvironment, [String]) expectDeploymentEnvironment (environmentName : rest) = case reads environmentName of [(environment, "")] -> Just (environment, rest) _ -> Nothing expectDeploymentEnvironment _ = Nothing expectEnd :: [String] -> Maybe () expectEnd [] = Just () expectEnd _ = Nothing parseArguments :: [String] -> Maybe (FilePath, DeploymentEnvironment) parseArguments arguments = do (configFilePath, arguments) <- expectFilePath arguments (deploymentEnvironment, arguments) <- expectDeploymentEnvironment arguments expectEnd arguments return (configFilePath, deploymentEnvironment) arguments <- getArgs case parseArguments arguments of Just (configFilePath, deploymentEnvironment) -> do eitherSettingsMap <- YAML.decodeFileEither configFilePath case eitherSettingsMap of Left exception -> do putStrLn $ show exception exitFailure Right settingsMap -> do let key = Text.pack $ show deploymentEnvironment case Map.lookup key settingsMap of Just settings -> do if processSettingsDaemonize $ settingsProcess settings then do putStrLn "Not implemented." exitFailure else do runStdoutLoggingT $ do innerMain settings Nothing -> do putStrLn $ "Configuration file contains no information for " ++ (Text.unpack key) ++ "." exitFailure Nothing -> do putStrLn $ "Usage: qt config.yaml (Development|Production)" exitFailure
IreneKnapp/qt
Haskell/Import/Configuration.hs
bsd-3-clause
2,518
0
29
709
636
330
306
66
9
{-# LANGUAGE RebindableSyntax #-} -- Copyright : (C) 2009 Corey O'Connor -- License : BSD-style (see the file LICENSE) {-# LANGUAGE NoRebindableSyntax #-} {-# LANGUAGE ImplicitPrelude #-} import Verify import ArbMarshal import qualified ArbMarshal.Binary as Binary import qualified ArbMarshal.Dynamic as Dynamic import Bind.Marshal.Verify {-# NOINLINE bench_to_dynamic #-} bench_to_dynamic sv = return $! Dynamic.to_bytestring sv {-# NOINLINE bench_to_binary #-} bench_to_binary sv = return $! Binary.to_bytestring sv {-# NOINLINE bench_from_dynamic #-} bench_from_dynamic (Binary.ArbByteString s b) = return $! Dynamic.from_bytestring s b {-# NOINLINE bench_from_binary #-} bench_from_binary (Binary.ArbByteString s b) = return $! Binary.from_bytestring s b main = run_test $ do verify_faster "simple bytestring - versus binary" (perf_config {min_size = 8}) (return . Dynamic.simple_bytestring . unMax4KBInt ) (return . Binary.simple_bytestring . unMax4KBInt ) verify_faster "to_bytestring - versus binary" (perf_config { min_size = 3200 , max_case_size = 10 } ) bench_to_dynamic bench_to_binary verify_faster "from_bytestring - versus binary" (perf_config { min_size = 12000 , max_case_size = 10 } ) bench_from_dynamic bench_from_binary return ()
coreyoconnor/bind-marshal
test/verify_dynamic_bytestring_perf.hs
bsd-3-clause
1,717
1
12
626
257
139
118
27
1
{-# LANGUAGE DeriveFunctor , DeriveGeneric , DeriveTraversable , DeriveDataTypeable , MultiParamTypeClasses , FlexibleInstances #-} module Data.Tree.Knuth.Forest where import Prelude hiding (foldr, elem) import Data.Semigroup import Data.Foldable hiding (elem) import Data.Witherable (Filterable, catMaybes) import qualified Data.Set.Class as Sets import qualified Data.Tree as T import Control.Applicative import Control.Monad import Data.Data import GHC.Generics import Control.DeepSeq import Test.QuickCheck -- * Forest data KnuthForest a = Fork { kNode :: a , kChildren :: KnuthForest a , kSiblings :: KnuthForest a } | Nil deriving (Show, Eq, Functor, Traversable, Generic, Data, Typeable) instance NFData a => NFData (KnuthForest a) instance Arbitrary a => Arbitrary (KnuthForest a) where arbitrary = oneof [ return Nil , liftA3 Fork arbitrary arbitrary arbitrary ] -- | Siblings before children instance Ord a => Ord (KnuthForest a) where compare (Fork x xc xs) (Fork y yc ys) = compare x y <> compare xs ys <> compare xc yc compare Nil Nil = EQ compare Nil _ = LT compare _ Nil = GT -- | Zippy instance Applicative KnuthForest where pure x = Fork x Nil Nil Nil <*> _ = Nil _ <*> Nil = Nil (Fork f fc fs) <*> (Fork x xc xs) = Fork (f x) (fc <*> xc) (fs <*> xs) instance Alternative KnuthForest where empty = Nil (<|>) = union -- | Breadth-first instance Monad KnuthForest where return = pure Nil >>= _ = Nil (Fork x xc xs) >>= f = f x `union` (xs >>= f) `union` (xc >>= f) instance MonadPlus KnuthForest where mzero = Nil mplus = union instance Semigroup (KnuthForest a) where (<>) = union instance Monoid (KnuthForest a) where mempty = Nil mappend = union -- | Breadth-first instance Foldable KnuthForest where foldr _ acc Nil = acc foldr f acc (Fork x xc xs) = foldr f (foldr f (f x acc) xs) xc instance Filterable KnuthForest where catMaybes Nil = Nil catMaybes (Fork mx xc xs) = case mx of Nothing -> Nil Just x -> Fork x (catMaybes xc) (catMaybes xs) instance Sets.HasUnion (KnuthForest a) where union = union instance Eq a => Sets.HasIntersection (KnuthForest a) where intersection = intersection instance Eq a => Sets.HasDifference (KnuthForest a) where difference = difference instance Sets.HasSize (KnuthForest a) where size = size instance Sets.HasEmpty (KnuthForest a) where empty = Nil instance Sets.HasSingleton a (KnuthForest a) where singleton = singleton instance Eq a => Sets.HasDelete a (KnuthForest a) where delete = delete -- ** Query size :: KnuthForest a -> Int size Nil = 0 size (Fork _ xc xs) = 1 + size xc + size xs -- Breadth-first elem :: Eq a => a -> KnuthForest a -> Bool elem _ Nil = False elem x (Fork y yc ys) = x == y || elem x ys || elem x yc elemPath :: Eq a => [a] -> KnuthForest a -> Bool elemPath [] _ = True elemPath (x:xs) (Fork y yc ys) = (x == y && elemPath xs ys) || elemPath (x:xs) yc elemPath _ Nil = False -- Top-down, breadth-first isSubforestOf :: Eq a => KnuthForest a -> KnuthForest a -> Bool isSubforestOf Nil _ = True isSubforestOf xss yss@(Fork _ yc ys) = xss == yss || isSubforestOf xss ys || isSubforestOf xss yc isSubforestOf _ Nil = False -- Bottom-up, depth-first isSubforestOf' :: Eq a => KnuthForest a -> KnuthForest a -> Bool isSubforestOf' Nil _ = True isSubforestOf' xss yss@(Fork _ yc ys) = isSubforestOf xss yc || isSubforestOf xss ys || xss == yss isSubforestOf' _ Nil = False -- | No siblings isProperSubforestOf :: Eq a => KnuthForest a -> KnuthForest a -> Bool isProperSubforestOf Nil _ = True isProperSubforestOf xss (Fork _ yc _) = isSubforestOf xss yc isProperSubforestOf _ Nil = False -- | Depth-first isProperSubforestOf' :: Eq a => KnuthForest a -> KnuthForest a -> Bool isProperSubforestOf' Nil _ = True isProperSubforestOf' xss (Fork _ yc _) = isSubforestOf' xss yc isProperSubforestOf' _ Nil = False isSiblingOf :: Eq a => a -> KnuthForest a -> Bool isSiblingOf _ Nil = False isSiblingOf x (Fork y _ ys) = x == y || isSiblingOf x ys -- | depth of one isChildOf :: Eq a => a -> KnuthForest a -> Bool isChildOf _ Nil = False isChildOf x (Fork _ yc ys) = isSiblingOf x yc || isChildOf x ys isDescendantOf :: Eq a => a -> KnuthForest a -> Bool isDescendantOf _ Nil = False isDescendantOf x (Fork y yc _) = x == y || isDescendantOf x yc isProperDescendantOf :: Eq a => a -> KnuthForest a -> Bool isProperDescendantOf _ Nil = False isProperDescendantOf x (Fork _ yc _) = isDescendantOf x yc -- ** Construction singleton :: a -> KnuthForest a singleton x = Fork x Nil Nil delete :: Eq a => a -> KnuthForest a -> KnuthForest a delete _ Nil = Nil delete x (Fork y yc ys) | x == y = Nil | otherwise = Fork y (delete x yc) (delete x ys) -- ** Combination union :: KnuthForest a -> KnuthForest a -> KnuthForest a union Nil y = y union (Fork x xc Nil) y = Fork x xc y union (Fork x xc xs) y = Fork x xc $ union xs y intersection :: Eq a => KnuthForest a -> KnuthForest a -> KnuthForest a intersection Nil _ = Nil intersection _ Nil = Nil intersection (Fork x xc xs) (Fork y yc ys) | x == y = Fork y (intersection xc yc) (intersection xs ys) | otherwise = Nil -- | Removes the possible subtree on the right, from the left. difference :: Eq a => KnuthForest a -> KnuthForest a -> KnuthForest a difference Nil _ = Nil difference x Nil = x difference (Fork x xc xs) yss@(Fork y _ _) | x == y = Nil | otherwise = Fork x (difference xc yss) (difference xs yss) toForest :: KnuthForest a -> T.Forest a toForest Nil = [] toForest (Fork x xc xs) = (T.Node x (toForest xs)) : toForest xc fromForest :: T.Forest a -> KnuthForest a fromForest [] = Nil fromForest (T.Node x xs : xss) = Fork x (fromForest xss) (fromForest xs)
athanclark/rose-trees
src/Data/Tree/Knuth/Forest.hs
bsd-3-clause
5,863
0
11
1,318
2,336
1,171
1,165
149
1
{-# Language BlockArguments, TemplateHaskell, OverloadedStrings, BangPatterns #-} {-| Module : Client.State.Network Description : IRC network session state Copyright : (c) Eric Mertens, 2016 License : ISC Maintainer : emertens@gmail.com This module is responsible for tracking the state of an individual IRC connection while the client is connected to it. This state includes user information, server settings, channel membership, and more. This module is more complicated than many of the other modules in the client because it is responsible for interpreting each IRC message from the server and updating the connection state accordingly. -} module Client.State.Network ( -- * Connection state NetworkState(..) , AuthenticateState(..) , ConnectRestriction(..) , newNetworkState -- * Lenses , csNick , csChannels , csSocket , csModeTypes , csChannelTypes , csTransaction , csModes , csSnomask , csStatusMsg , csSettings , csUserInfo , csUsers , csUser , csModeCount , csNetwork , csNextPingTime , csPingStatus , csLatency , csLastReceived , csCertificate , csMessageHooks , csAuthenticationState , csSeed , csAway -- * Cross-message state , Transaction(..) -- * Connection predicates , isChannelIdentifier , iHaveOp -- * Messages interactions , sendMsg , initialMessages , squelchIrcMsg -- * NetworkState update , Apply(..) , applyMessage , hideMessage -- * Timer information , PingStatus(..) , _PingConnecting , TimedAction(..) , nextTimedAction , applyTimedAction -- * Moderation , useChanServ , sendModeration , sendTopic ) where import qualified Client.Authentication.Ecdsa as Ecdsa import qualified Client.Authentication.Ecdh as Ecdh import qualified Client.Authentication.Scram as Scram import Client.Configuration.ServerSettings import Client.Network.Async import Client.State.Channel import Client.UserHost import Client.Hook (MessageHook) import Client.Hooks (messageHooks) import Control.Lens import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import qualified Data.HashSet as HashSet import qualified Data.ByteString as B import qualified Data.Map.Strict as Map import Data.Bits import Data.Foldable import Data.List import qualified Data.List.NonEmpty as NonEmpty import Data.Maybe import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import qualified Data.Text.Read as Text import Data.Time import Data.Time.Clock.POSIX import Irc.Codes import Irc.Commands import Irc.Identifier import Irc.Message import Irc.Modes import Irc.RawIrcMsg import Irc.UserInfo import LensUtils import qualified System.Random as Random import qualified Data.ByteString.Base64 as B64 -- | State tracked for each IRC connection data NetworkState = NetworkState { _csChannels :: !(HashMap Identifier ChannelState) -- ^ joined channels , _csSocket :: !NetworkConnection -- ^ network socket , _csModeTypes :: !ModeTypes -- ^ channel mode meanings , _csUmodeTypes :: !ModeTypes -- ^ user mode meanings , _csChannelTypes :: ![Char] -- ^ channel identifier prefixes , _csTransaction :: !Transaction -- ^ state for multi-message sequences , _csModes :: ![Char] -- ^ modes for the connected user , _csSnomask :: ![Char] -- ^ server notice modes for the connected user , _csStatusMsg :: ![Char] -- ^ modes that prefix statusmsg channel names , _csSettings :: !ServerSettings -- ^ settings used for this connection , _csUserInfo :: !UserInfo -- ^ usermask used by the server for this connection , _csUsers :: !(HashMap Identifier UserAndHost) -- ^ user and hostname for other nicks , _csModeCount :: !Int -- ^ maximum mode changes per MODE command , _csNetwork :: !Text -- ^ name of network connection , _csMessageHooks :: ![MessageHook] -- ^ names of message hooks to apply to this connection , _csAuthenticationState :: !AuthenticateState , _csAway :: !Bool -- ^ Tracks when you are marked away -- Timing information , _csNextPingTime :: !(Maybe UTCTime) -- ^ time for next ping event , _csLatency :: !(Maybe NominalDiffTime) -- ^ latency calculated from previous pong , _csPingStatus :: !PingStatus -- ^ state of ping timer , _csLastReceived :: !(Maybe UTCTime) -- ^ time of last message received , _csCertificate :: ![Text] -- Randomization , _csSeed :: Random.StdGen } -- | State of the authentication transaction data AuthenticateState = AS_None -- ^ no active transaction | AS_PlainStarted -- ^ PLAIN mode initiated | AS_EcdsaStarted -- ^ ECDSA-NIST mode initiated | AS_EcdsaWaitChallenge -- ^ ECDSA-NIST user sent waiting for challenge | AS_ExternalStarted -- ^ EXTERNAL mode initiated | AS_ScramStarted | AS_Scram1 Scram.Phase1 | AS_Scram2 Scram.Phase2 | AS_EcdhStarted | AS_EcdhWaitChallenge Ecdh.Phase1 -- | Status of the ping timer data PingStatus = PingSent !UTCTime -- ^ ping sent at given time, waiting for pong | PingNone -- ^ not waiting for a pong | PingConnecting !Int !(Maybe UTCTime) !ConnectRestriction -- ^ number of attempts, last known connection time deriving Show data ConnectRestriction = NoRestriction -- ^ no message restriction | StartTLSRestriction -- ^ STARTTLS hasn't finished | WaitTLSRestriction -- ^ No messages allowed until TLS starts deriving Show -- | Timer-based events data TimedAction = TimedDisconnect -- ^ terminate the connection due to timeout | TimedSendPing -- ^ transmit a ping to the server | TimedForgetLatency -- ^ erase latency (when it is outdated) deriving (Eq, Ord, Show) data Transaction = NoTransaction | NamesTransaction [Text] | BanTransaction [(Text,MaskListEntry)] | WhoTransaction [UserInfo] | CapLsTransaction [(Text, Maybe Text)] deriving Show makeLenses ''NetworkState makePrisms ''Transaction makePrisms ''PingStatus makePrisms ''TimedAction defaultChannelTypes :: String defaultChannelTypes = "#&" csNick :: Lens' NetworkState Identifier csNick = csUserInfo . uiNick -- | Transmit a 'RawIrcMsg' on the connection associated -- with the given network. For @PRIVMSG@ and @NOTICE@ overlong -- commands are detected and transmitted as multiple messages. sendMsg :: NetworkState -> RawIrcMsg -> IO () sendMsg cs msg = case (view msgCommand msg, view msgParams msg) of ("PRIVMSG", [tgt,txt]) -> multiline "PRIVMSG" tgt txt ("NOTICE", [tgt,txt]) -> multiline "NOTICE" tgt txt _ -> transmit msg where transmit = send (view csSocket cs) . renderRawIrcMsg actionPrefix = "\^AACTION " actionSuffix = "\^A" -- Special case for splitting a single CTCP ACTION into -- multiple actions multiline cmd tgt txt | Just txt1 <- Text.stripPrefix actionPrefix txt , Just txt2 <- Text.stripSuffix actionSuffix txt1 = let txtChunks = utf8ChunksOf maxContentLen txt2 maxContentLen = computeMaxMessageLength (view csUserInfo cs) tgt - Text.length actionPrefix - Text.length actionSuffix in for_ txtChunks $ \txtChunk -> transmit $ rawIrcMsg cmd [tgt, actionPrefix <> txtChunk <> actionSuffix] -- Normal case multiline cmd tgt txt = let txtChunks = utf8ChunksOf maxContentLen txt maxContentLen = computeMaxMessageLength (view csUserInfo cs) tgt in for_ txtChunks $ \txtChunk -> transmit $ rawIrcMsg cmd [tgt, txtChunk] -- This is an approximation for splitting the text. It doesn't -- understand combining characters. A correct implementation -- probably needs to use icu, but its going to take some work -- to use that library to do this. utf8ChunksOf :: Int -> Text -> [Text] utf8ChunksOf n txt | B.length enc <= n = [txt] -- fast/common case | otherwise = search 0 0 txt info where isBeginning b = b .&. 0xc0 /= 0x80 enc = Text.encodeUtf8 txt beginnings = B.findIndices isBeginning enc info = zip3 [0..] -- charIndex beginnings (drop 1 beginnings ++ [B.length enc]) search startByte startChar currentTxt xs = case dropWhile (\(_,_,byteLen) -> byteLen-startByte <= n) xs of [] -> [currentTxt] (charIx,byteIx,_):xs' -> case Text.splitAt (charIx - startChar) currentTxt of (a,b) -> a : search byteIx charIx b xs' -- | Construct a new network state using the given settings and -- default values as specified by the IRC specification. newNetworkState :: Text {- ^ network name -} -> ServerSettings {- ^ server settings -} -> NetworkConnection {- ^ active network connection -} -> PingStatus {- ^ initial ping status -} -> Random.StdGen {- ^ initial random seed -} -> NetworkState {- ^ new network state -} newNetworkState network settings sock ping seed = NetworkState { _csUserInfo = UserInfo "*" "" "" , _csChannels = HashMap.empty , _csSocket = sock , _csChannelTypes = defaultChannelTypes , _csModeTypes = defaultModeTypes , _csUmodeTypes = defaultUmodeTypes , _csTransaction = NoTransaction , _csModes = "" , _csSnomask = "" , _csStatusMsg = "" , _csSettings = settings , _csModeCount = 3 , _csUsers = HashMap.empty , _csNetwork = network , _csMessageHooks = buildMessageHooks (view ssMessageHooks settings) , _csAuthenticationState = AS_None , _csAway = False , _csPingStatus = ping , _csLatency = Nothing , _csNextPingTime = Nothing , _csLastReceived = Nothing , _csCertificate = [] , _csSeed = seed } buildMessageHooks :: [HookConfig] -> [MessageHook] buildMessageHooks = mapMaybe \(HookConfig name args) -> do hookFun <- HashMap.lookup name messageHooks hookFun args data Apply = Apply [RawIrcMsg] NetworkState hideMessage :: IrcMsg -> Bool hideMessage m = case m of Authenticate{} -> True BatchStart{} -> True BatchEnd{} -> True Ping{} -> True Pong{} -> True Reply _ RPL_WHOSPCRPL [_,"616",_,_,_,_] -> True _ -> False -- | Used for updates to a 'NetworkState' that require no reply. noReply :: NetworkState -> Apply noReply = reply [] reply :: [RawIrcMsg] -> NetworkState -> Apply reply = Apply overChannel :: Identifier -> (ChannelState -> ChannelState) -> NetworkState -> NetworkState overChannel chan = overStrict (csChannels . ix chan) overChannels :: (ChannelState -> ChannelState) -> NetworkState -> NetworkState overChannels = overStrict (csChannels . traverse) applyMessage :: ZonedTime -> IrcMsg -> NetworkState -> Apply applyMessage msgWhen msg cs = applyMessage' msgWhen msg $ set csLastReceived (Just $! zonedTimeToUTC msgWhen) cs applyMessage' :: ZonedTime -> IrcMsg -> NetworkState -> Apply applyMessage' msgWhen msg cs = case msg of Ping args -> reply [ircPong args] cs Pong _ -> noReply (doPong msgWhen cs) Join user chan acct _ -> reply response $ recordUser (srcUser user) acct $ overChannel chan (joinChannel (userNick (srcUser user))) $ createOnJoin (srcUser user) chan cs where response = [ircMode chan [] | userNick (srcUser user) == view csNick cs] Account user acct -> noReply $ recordUser (srcUser user) acct cs Chghost user newUser newHost -> noReply $ updateUserInfo (userNick (srcUser user)) newUser newHost cs Quit user _reason -> noReply $ forgetUser (userNick (srcUser user)) $ overChannels (partChannel (userNick (srcUser user))) cs Part user chan _mbreason -> exitChannel chan (userNick (srcUser user)) Kick _kicker chan nick _reason -> exitChannel chan nick Nick oldNick newNick -> let nick = userNick (srcUser oldNick) in noReply $ renameUser nick newNick $ updateMyNick nick newNick $ overChannels (nickChange nick newNick) cs Reply _ RPL_WELCOME (me:_) -> doWelcome msgWhen (mkId me) cs Reply _ RPL_SASLSUCCESS _ -> reply [ircCapEnd] cs Reply _ ERR_SASLFAIL _ -> reply [ircCapEnd] cs Reply _ ERR_SASLABORTED _ -> reply [ircCapEnd] cs Reply _ RPL_SASLMECHS _ -> reply [ircCapEnd] cs Reply _ ERR_NICKNAMEINUSE (_:badnick:_) | PingConnecting{} <- view csPingStatus cs -> doBadNick badnick cs Reply _ ERR_BANNEDNICK (_:badnick:_) | PingConnecting{} <- view csPingStatus cs -> doBadNick badnick cs Reply _ ERR_ERRONEUSNICKNAME (_:badnick:_) | PingConnecting{} <- view csPingStatus cs -> doBadNick badnick cs Reply _ ERR_UNAVAILRESOURCE (_:badnick:_) | PingConnecting{} <- view csPingStatus cs -> doBadNick badnick cs Reply _ RPL_HOSTHIDDEN (_:host:_) -> noReply (set (csUserInfo . uiHost) host cs) -- /who <#channel> %tuhna,616 Reply _ RPL_WHOSPCRPL [_me,"616",user,host,nick,acct] -> let acct' = if acct == "0" then "*" else acct in noReply (recordUser (UserInfo (mkId nick) user host) acct' cs) Reply _ code args -> doRpl code msgWhen args cs Cap cmd -> doCap cmd cs Authenticate param -> doAuthenticate param cs Mode who target (modes:params) -> doMode msgWhen (srcUser who) target modes params cs Topic user chan topic -> noReply (doTopic msgWhen (srcUser user) chan topic cs) _ -> noReply cs where exitChannel chan nick | nick == view csNick cs = noReply $ pruneUsers $ over csChannels (sans chan) cs | otherwise = noReply $ forgetUser' nick $ overChannel chan (partChannel nick) cs -- | Restrict 'csUsers' to only users are in a channel that the client -- is connected to. pruneUsers :: NetworkState -> NetworkState pruneUsers cs = over csUsers (`HashMap.intersection` u) cs where u = foldOf (csChannels . folded . chanUsers) cs -- | 001 'RPL_WELCOME' is the first message received when transitioning -- from the initial handshake to a connected state. At this point we know -- what nickname the server is using for our connection, and we can start -- scheduling PINGs. doWelcome :: ZonedTime {- ^ message received -} -> Identifier {- ^ my nickname -} -> NetworkState -> Apply doWelcome msgWhen me = noReply . set csNick me . set csNextPingTime (Just $! addUTCTime 30 (zonedTimeToUTC msgWhen)) . set csPingStatus PingNone -- | Handle 'ERR_NICKNAMEINUSE' errors when connecting. doBadNick :: Text {- ^ bad nickname -} -> NetworkState -> Apply doBadNick badNick cs = case NonEmpty.dropWhile (badNick/=) (view (csSettings . ssNicks) cs) of _:next:_ -> reply [ircNick next] cs _ -> doRandomNick cs -- | Pick a random nickname now that we've run out of choices doRandomNick :: NetworkState -> Apply doRandomNick cs = reply [ircNick candidate] cs' where limit = 9 -- RFC 2812 puts the maximum nickname length as low as 9! range = (0, 99999::Int) -- up to 5 random digits suffix = show n primaryNick = NonEmpty.head (view (csSettings . ssNicks) cs) candidate = Text.take (limit-length suffix) primaryNick <> Text.pack suffix (n, cs') = cs & csSeed %%~ Random.randomR range doTopic :: ZonedTime -> UserInfo -> Identifier -> Text -> NetworkState -> NetworkState doTopic when user chan topic = overChannel chan (setTopic topic . set chanTopicProvenance (Just $! prov)) where prov = TopicProvenance { _topicAuthor = user , _topicTime = zonedTimeToUTC when } parseTimeParam :: Text -> Maybe UTCTime parseTimeParam txt = case Text.decimal txt of Right (i, rest) | Text.null rest -> Just $! posixSecondsToUTCTime (fromInteger i) _ -> Nothing doRpl :: ReplyCode -> ZonedTime -> [Text] -> NetworkState -> Apply doRpl cmd msgWhen args cs = case cmd of RPL_UMODEIS -> case args of _me:modes:params | Just xs <- splitModes (view csUmodeTypes cs) modes params -> noReply $ doMyModes xs $ set csModes "" cs -- reset modes _ -> noReply cs RPL_SNOMASK -> case args of _me:snomask0:_ | Just snomask <- Text.stripPrefix "+" snomask0 -> noReply (set csSnomask (Text.unpack snomask) cs) _ -> noReply cs RPL_NOTOPIC -> case args of _me:chan:_ -> noReply $ overChannel (mkId chan) (setTopic "" . set chanTopicProvenance Nothing) cs _ -> noReply cs RPL_TOPIC -> case args of _me:chan:topic:_ -> noReply (overChannel (mkId chan) (setTopic topic) cs) _ -> noReply cs RPL_TOPICWHOTIME -> case args of _me:chan:who:whenTxt:_ | Just when <- parseTimeParam whenTxt -> let !prov = TopicProvenance { _topicAuthor = parseUserInfo who , _topicTime = when } in noReply (overChannel (mkId chan) (set chanTopicProvenance (Just prov)) cs) _ -> noReply cs RPL_CREATIONTIME -> case args of _me:chan:whenTxt:_ | Just when <- parseTimeParam whenTxt -> noReply (overChannel (mkId chan) (set chanCreation (Just when)) cs) _ -> noReply cs RPL_CHANNEL_URL -> case args of _me:chan:urlTxt:_ -> noReply (overChannel (mkId chan) (set chanUrl (Just urlTxt)) cs) _ -> noReply cs RPL_MYINFO -> noReply (myinfo args cs) RPL_ISUPPORT -> noReply (isupport args cs) RPL_NAMREPLY -> case args of _me:_sym:_tgt:x:_ -> noReply $ over csTransaction (\t -> let xs = view _NamesTransaction t in xs `seq` NamesTransaction (x:xs)) cs _ -> noReply cs RPL_ENDOFNAMES -> case args of _me:tgt:_ -> noReply (loadNamesList (mkId tgt) cs) _ -> noReply cs RPL_BANLIST -> case args of _me:_tgt:mask:who:whenTxt:_ -> noReply (recordListEntry mask who whenTxt cs) _ -> noReply cs RPL_ENDOFBANLIST -> case args of _me:tgt:_ -> noReply (saveList 'b' tgt cs) _ -> noReply cs RPL_QUIETLIST -> case args of _me:_tgt:_q:mask:who:whenTxt:_ -> noReply (recordListEntry mask who whenTxt cs) _ -> noReply cs RPL_ENDOFQUIETLIST -> case args of _me:tgt:_ -> noReply (saveList 'q' tgt cs) _ -> noReply cs RPL_INVEXLIST -> case args of _me:_tgt:mask:who:whenTxt:_ -> noReply (recordListEntry mask who whenTxt cs) _ -> noReply cs RPL_ENDOFINVEXLIST -> case args of _me:tgt:_ -> noReply (saveList 'I' tgt cs) _ -> noReply cs RPL_EXCEPTLIST -> case args of _me:_tgt:mask:who:whenTxt:_ -> noReply (recordListEntry mask who whenTxt cs) _ -> noReply cs RPL_ENDOFEXCEPTLIST -> case args of _me:tgt:_ -> noReply (saveList 'e' tgt cs) _ -> noReply cs RPL_WHOREPLY -> case args of _me:_tgt:uname:host:_server:nick:_ -> noReply $ over csTransaction (\t -> let !x = UserInfo (mkId nick) uname host !xs = view _WhoTransaction t in WhoTransaction (x : xs)) cs _ -> noReply cs RPL_ENDOFWHO -> noReply (massRegistration cs) RPL_CHANNELMODEIS -> case args of _me:chan:modes:params -> doMode msgWhen who chanId modes params $ set (csChannels . ix chanId . chanModes) Map.empty cs where chanId = mkId chan !who = UserInfo "*" "" "" _ -> noReply cs -- Away flag tracking RPL_NOWAWAY -> noReply (set csAway True cs) RPL_UNAWAY -> noReply (set csAway False cs) _ -> noReply cs -- | Add an entry to a mode list transaction recordListEntry :: Text {- ^ mask -} -> Text {- ^ set by -} -> Text {- ^ set time -} -> NetworkState -> NetworkState recordListEntry mask who whenTxt = case parseTimeParam whenTxt of Nothing -> id Just when -> over csTransaction $ \t -> let !x = MaskListEntry { _maskListSetter = who , _maskListTime = when } !xs = view _BanTransaction t in BanTransaction ((mask,x):xs) -- | Save a completed ban, quiet, invex, or exempt list into the channel -- state. saveList :: Char {- ^ mode -} -> Text {- ^ channel -} -> NetworkState -> NetworkState saveList mode tgt cs = set csTransaction NoTransaction $ setStrict (csChannels . ix (mkId tgt) . chanLists . at mode) (Just $! newList) cs where newList = HashMap.fromList (view (csTransaction . _BanTransaction) cs) -- | These replies are interpreted by the client and should only be shown -- in the detailed view. squelchReply :: ReplyCode -> Bool squelchReply rpl = case rpl of RPL_NAMREPLY -> True RPL_ENDOFNAMES -> True RPL_BANLIST -> True RPL_ENDOFBANLIST -> True RPL_INVEXLIST -> True RPL_ENDOFINVEXLIST -> True RPL_EXCEPTLIST -> True RPL_ENDOFEXCEPTLIST -> True RPL_QUIETLIST -> True RPL_ENDOFQUIETLIST -> True RPL_CHANNELMODEIS -> True RPL_UMODEIS -> True RPL_SNOMASK -> True RPL_WHOREPLY -> True RPL_ENDOFWHO -> True RPL_WHOSPCRPL -> True RPL_TOPICWHOTIME -> True RPL_CREATIONTIME -> True RPL_CHANNEL_URL -> True RPL_NOTOPIC -> True _ -> False -- | Return 'True' for messages that should be hidden outside of -- full detail view. These messages are interpreted by the client -- so the user shouldn't need to see them directly to get the -- relevant information. squelchIrcMsg :: IrcMsg -> Bool squelchIrcMsg (Reply _ rpl _) = squelchReply rpl squelchIrcMsg _ = False doMode :: ZonedTime {- ^ time of message -} -> UserInfo {- ^ sender -} -> Identifier {- ^ channel -} -> Text {- ^ mode flags -} -> [Text] {- ^ mode parameters -} -> NetworkState -> Apply doMode when who target modes args cs | view csNick cs == target , Just xs <- splitModes (view csUmodeTypes cs) modes args = noReply (doMyModes xs cs) | isChannelIdentifier cs target , Just xs <- splitModes (view csModeTypes cs) modes args , let cs' = doChannelModes when who target xs cs = if iHaveOp target cs' then let (response, cs_) = cs' & csChannels . ix target . chanQueuedModeration <<.~ [] in reply response cs_ else noReply cs' doMode _ _ _ _ _ cs = noReply cs -- ignore bad mode command -- | Predicate to test if the connection has op in a given channel. iHaveOp :: Identifier -> NetworkState -> Bool iHaveOp channel cs = elemOf (csChannels . ix channel . chanUsers . ix me . folded) '@' cs where me = view csNick cs doChannelModes :: ZonedTime -> UserInfo -> Identifier -> [(Bool, Char, Text)] -> NetworkState -> NetworkState doChannelModes when who chan changes cs = overChannel chan applyChannelModes cs where modeTypes = view csModeTypes cs sigilMap = view modesPrefixModes modeTypes listModes = view modesLists modeTypes applyChannelModes c = foldl' applyChannelMode c changes applyChannelMode c (polarity, mode, arg) | Just sigil <- lookup mode sigilMap = overStrict (chanUsers . ix (mkId arg)) (setPrefixMode polarity sigil) c | mode `elem` listModes = let entry | polarity = Just $! MaskListEntry { _maskListSetter = renderUserInfo who , _maskListTime = zonedTimeToUTC when } | otherwise = Nothing in setStrict (chanLists . ix mode . at arg) entry c | polarity = set (chanModes . at mode) (Just arg) c | otherwise = over chanModes (sans mode) c setPrefixMode polarity sigil sigils | not polarity = delete sigil sigils | sigil `elem` sigils = sigils | otherwise = filter (`elem` sigils') (map snd sigilMap) where sigils' = sigil : sigils doMyModes :: [(Bool, Char, Text)] -> NetworkState -> NetworkState doMyModes changes = over csModes $ \modes -> sort (foldl' applyOne modes changes) where applyOne modes (True, mode, _) | mode `elem` modes = modes | otherwise = mode:modes applyOne modes (False, mode, _) = delete mode modes selectCaps :: NetworkState {- ^ network state -} -> [(Text, Maybe Text)] {- ^ server caps -} -> [Text] {- ^ caps to enable -} selectCaps cs offered = (supported `intersect` Map.keys capMap) `union` view (csSettings . ssCapabilities) cs where capMap = Map.fromList offered supported = sasl ++ serverTime ++ ["multi-prefix", "batch", "znc.in/playback", "znc.in/self-message" , "cap-notify", "extended-join", "account-notify", "chghost" , "userhost-in-names", "account-tag", "solanum.chat/identify-msg" , "solanum.chat/realhost" ] -- logic for using IRCv3.2 server-time if available and falling back -- to ZNC's specific extension otherwise. serverTime | "server-time" `Map.member` capMap = ["server-time"] | "znc.in/server-time-iso" `Map.member` capMap = ["znc.in/server-time-iso"] | otherwise = [] ss = view csSettings cs sasl = ["sasl" | isJust (view ssSaslMechanism ss) ] decodeAuthParam :: Text -> Maybe B.ByteString decodeAuthParam "+" = Just "" decodeAuthParam xs = case B64.decode (Text.encodeUtf8 xs) of Right bs -> Just bs Left _ -> Nothing abortAuth :: NetworkState -> Apply abortAuth = reply [ircAuthenticate "*"] . set csAuthenticationState AS_None doAuthenticate :: Text -> NetworkState -> Apply doAuthenticate paramTxt cs = case decodeAuthParam paramTxt of Nothing -> abortAuth cs Just param -> doAuthenticate' param cs doAuthenticate' :: B.ByteString -> NetworkState -> Apply doAuthenticate' param cs = case view csAuthenticationState cs of AS_PlainStarted | B.null param , Just (SaslPlain mbAuthz authc (SecretText pass)) <- view ssSaslMechanism ss , let authz = fromMaybe "" mbAuthz -> reply (ircAuthenticates (encodePlainAuthentication authz authc pass)) (set csAuthenticationState AS_None cs) AS_ExternalStarted | B.null param , Just (SaslExternal mbAuthz) <- view ssSaslMechanism ss , let authz = fromMaybe "" mbAuthz -> reply (ircAuthenticates (encodeExternalAuthentication authz)) (set csAuthenticationState AS_None cs) AS_EcdsaStarted | B.null param , Just (SaslEcdsa mbAuthz authc _) <- view ssSaslMechanism ss -> reply (ircAuthenticates (Ecdsa.encodeAuthentication mbAuthz authc)) (set csAuthenticationState AS_EcdsaWaitChallenge cs) AS_EcdsaWaitChallenge -> noReply cs -- handled in Client.EventLoop! AS_ScramStarted | B.null param , Just (SaslScram digest mbAuthz user (SecretText pass)) <- view ssSaslMechanism ss , let authz = fromMaybe "" mbAuthz , (nonce, cs') <- cs & csSeed %%~ scramNonce , (msg, scram1) <- Scram.initiateScram digest (Text.encodeUtf8 user) (Text.encodeUtf8 authz) (Text.encodeUtf8 pass) nonce -> reply (ircAuthenticates msg) (set csAuthenticationState (AS_Scram1 scram1) cs') AS_Scram1 scram1 | Just (rsp, scram2) <- Scram.addServerFirst scram1 param -> reply (ircAuthenticates rsp) (set csAuthenticationState (AS_Scram2 scram2) cs) AS_Scram2 scram2 | Scram.addServerFinal scram2 param -> reply [ircAuthenticate "+"] (set csAuthenticationState AS_None cs) AS_EcdhStarted | B.null param , Just (SaslEcdh mbAuthz authc (SecretText key)) <- view ssSaslMechanism ss , Just (rsp, ecdh1) <- Ecdh.clientFirst mbAuthz authc key -> reply (ircAuthenticates rsp) (set csAuthenticationState (AS_EcdhWaitChallenge ecdh1) cs) AS_EcdhWaitChallenge ecdh1 | Just rsp <- Ecdh.clientResponse ecdh1 param -> reply (ircAuthenticates rsp) (set csAuthenticationState AS_None cs) _ -> abortAuth cs where ss = view csSettings cs scramNonce :: Random.StdGen -> (B.ByteString, Random.StdGen) scramNonce = go [] nonceSize where alphabet = "!\"#$%&'()*+-./0123456789:;<=>?@\ \ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`\ \abcdefghijklmnopqrstuvwxyz{|}~" nonceSize = 20 :: Int -- ceiling (128 / logBase 9 (length alphabet)) go acc 0 g = (B.pack acc, g) go acc i g = case Random.randomR (0, B.length alphabet-1) g of (x,g') -> go (B.index alphabet x:acc) (i-1) g' doCap :: CapCmd -> NetworkState -> Apply doCap cmd cs = case cmd of (CapLs CapMore caps) -> noReply (set csTransaction (CapLsTransaction (caps ++ prevCaps)) cs) where prevCaps = view (csTransaction . _CapLsTransaction) cs CapLs CapDone caps | null reqCaps -> reply [ircCapEnd] cs' | otherwise -> reply [ircCapReq reqCaps] cs' where reqCaps = selectCaps cs (caps ++ view (csTransaction . _CapLsTransaction) cs) cs' = set csTransaction NoTransaction cs CapNew caps | null reqCaps -> noReply cs | otherwise -> reply [ircCapReq reqCaps] cs where reqCaps = selectCaps cs caps CapDel _ -> noReply cs CapAck caps | let ss = view csSettings cs , "sasl" `elem` caps , Just mech <- view ssSaslMechanism ss -> case mech of SaslEcdsa{} -> reply [ircAuthenticate Ecdsa.authenticationMode] (set csAuthenticationState AS_EcdsaStarted cs) SaslPlain{} -> reply [ircAuthenticate "PLAIN"] (set csAuthenticationState AS_PlainStarted cs) SaslExternal{} -> reply [ircAuthenticate "EXTERNAL"] (set csAuthenticationState AS_ExternalStarted cs) SaslScram digest _ _ _ -> reply [ircAuthenticate (Scram.mechanismName digest)] (set csAuthenticationState AS_ScramStarted cs) SaslEcdh{} -> reply [ircAuthenticate Ecdh.mechanismName] (set csAuthenticationState AS_EcdhStarted cs) _ -> reply [ircCapEnd] cs initialMessages :: NetworkState -> [RawIrcMsg] initialMessages cs = [ ircCapLs ] ++ [ ircPass pass | Just (SecretText pass) <- [view ssPassword ss]] ++ [ ircNick (views ssNicks NonEmpty.head ss) , ircUser (view ssUser ss) (view ssReal ss) ] where ss = view csSettings cs loadNamesList :: Identifier -> NetworkState -> NetworkState loadNamesList chan cs = set csTransaction NoTransaction $ flip (foldl' (flip learnUserInfo)) (fst <$> entries) $ setStrict (csChannels . ix chan . chanUsers) newChanUsers $ cs where newChanUsers = HashMap.fromList [ (view uiNick ui, modes) | (ui, modes) <- entries ] -- userhost-in-names might or might not include the user and host -- if we find it we update the user information. learnUserInfo (UserInfo n u h) | Text.null u || Text.null h = id | otherwise = updateUserInfo n u h sigils = toListOf (csModeTypes . modesPrefixModes . folded . _2) cs splitEntry modes str | Text.head str `elem` sigils = splitEntry (Text.head str : modes) (Text.tail str) | otherwise = (parseUserInfo str, reverse modes) entries :: [(UserInfo, [Char])] entries = fmap (splitEntry "") $ concatMap Text.words $ view (csTransaction . _NamesTransaction) cs createOnJoin :: UserInfo -> Identifier -> NetworkState -> NetworkState createOnJoin who chan cs | userNick who == view csNick cs = set csUserInfo who -- great time to learn our userinfo $ set (csChannels . at chan) (Just newChannel) cs | otherwise = cs updateMyNick :: Identifier -> Identifier -> NetworkState -> NetworkState updateMyNick oldNick newNick cs | oldNick == view csNick cs = set csNick newNick cs | otherwise = cs myinfo :: [Text] -> NetworkState -> NetworkState myinfo (_me : _host : _version : umodes : _) = -- special logic for s because I know it has arguments set (csUmodeTypes . modesNeverArg) (delete 's' (Text.unpack umodes)) myinfo _ = id -- ISUPPORT is defined by -- https://tools.ietf.org/html/draft-brocklesby-irc-isupport-03#section-3.14 isupport :: [Text] {- ^ ["key=value"] -} -> NetworkState -> NetworkState isupport [] conn = conn isupport params conn = foldl' (flip isupport1) conn $ map parseISupport $ init params where isupport1 ("CHANTYPES",types) = set csChannelTypes (Text.unpack types) isupport1 ("CHANMODES",modes) = updateChanModes modes isupport1 ("PREFIX" ,modes) = updateChanPrefix modes isupport1 ("STATUSMSG",prefix) = set csStatusMsg (Text.unpack prefix) isupport1 ("MODES",nstr) | Right (n,"") <- Text.decimal nstr = set csModeCount n isupport1 _ = id parseISupport :: Text -> (Text,Text) parseISupport str = case Text.break (=='=') str of (key,val) -> (key, Text.drop 1 val) updateChanModes :: Text {- lists,always,set,never -} -> NetworkState -> NetworkState updateChanModes modes = over csModeTypes $ set modesLists listModes . set modesAlwaysArg alwaysModes . set modesSetArg setModes . set modesNeverArg neverModes -- Note: doesn't set modesPrefixModes where next = over _2 (drop 1) . break (==',') (listModes ,modes1) = next (Text.unpack modes) (alwaysModes,modes2) = next modes1 (setModes ,modes3) = next modes2 (neverModes ,_) = next modes3 updateChanPrefix :: Text {- e.g. "(ov)@+" -} -> NetworkState -> NetworkState updateChanPrefix txt = case parsePrefixes txt of Just prefixes -> set (csModeTypes . modesPrefixModes) prefixes Nothing -> id parsePrefixes :: Text -> Maybe [(Char,Char)] parsePrefixes txt = case uncurry Text.zip (Text.break (==')') txt) of ('(',')'):rest -> Just rest _ -> Nothing isChannelIdentifier :: NetworkState -> Identifier -> Bool isChannelIdentifier cs ident = case Text.uncons (idText ident) of Just (p, _) -> p `elem` view csChannelTypes cs _ -> False ------------------------------------------------------------------------ -- Helpers for managing the user list ------------------------------------------------------------------------ csUser :: Functor f => Identifier -> LensLike' f NetworkState (Maybe UserAndHost) csUser i = csUsers . at i recordUser :: UserInfo -> Text -> NetworkState -> NetworkState recordUser (UserInfo nick user host) acct | Text.null user || Text.null host = id | otherwise = set (csUsers . at nick) (Just $! UserAndHost user host acct) -- | Process a CHGHOST command, updating a users information updateUserInfo :: Identifier {- ^ nickname -} -> Text {- ^ new username -} -> Text {- ^ new hostname -} -> NetworkState -> NetworkState updateUserInfo nick user host = over (csUsers . at nick) $ \old -> Just $! UserAndHost user host (maybe "" _uhAccount old) forgetUser :: Identifier -> NetworkState -> NetworkState forgetUser = over csUsers . sans renameUser :: Identifier -> Identifier -> NetworkState -> NetworkState renameUser old new cs = set (csUsers . at new) entry cs' where (entry,cs') = cs & csUsers . at old <<.~ Nothing forgetUser' :: Identifier -> NetworkState -> NetworkState forgetUser' nick cs | keep = cs | otherwise = forgetUser nick cs where keep = has (csChannels . folded . chanUsers . ix nick) cs -- | Process a list of WHO replies massRegistration :: NetworkState -> NetworkState massRegistration cs = set csTransaction NoTransaction $ over csUsers updateUsers cs where infos = view (csTransaction . _WhoTransaction) cs channelUsers = HashSet.fromList (views (csChannels . folded . chanUsers) HashMap.keys cs) updateUsers users = foldl' updateUser users infos updateUser users (UserInfo nick user host) | not (Text.null user) , not (Text.null host) , HashSet.member nick channelUsers = HashMap.alter (\mb -> case mb of Nothing -> Just $! UserAndHost user host "" Just (UserAndHost _ _ acct) -> Just $! UserAndHost user host acct ) nick users | otherwise = users -- | Compute the earliest timed action for a connection, if any nextTimedAction :: NetworkState -> Maybe (UTCTime, TimedAction) nextTimedAction ns = minimumOf (folded.folded) actions where actions = [nextPingAction ns, nextForgetAction ns] -- | Compute the timed action for forgetting the ping latency. -- The client will wait for a multiple of the current latency -- for the next pong response in order to reduce jitter in -- the rendered latency when everything is fine. nextForgetAction :: NetworkState -> Maybe (UTCTime, TimedAction) nextForgetAction ns = do sentAt <- preview (csPingStatus . _PingSent) ns latency <- view csLatency ns let delay = max 0.1 (3 * latency) -- wait at least 0.1s (ensure positive waits) eventAt = addUTCTime delay sentAt return (eventAt, TimedForgetLatency) -- | Compute the next action needed for the client ping logic. nextPingAction :: NetworkState -> Maybe (UTCTime, TimedAction) nextPingAction cs = do runAt <- view csNextPingTime cs return (runAt, action) where action = case view csPingStatus cs of PingSent sentAt | Just sentAt < view csLastReceived cs -> TimedSendPing | otherwise -> TimedDisconnect PingNone -> TimedSendPing PingConnecting{} -> TimedSendPing doPong :: ZonedTime -> NetworkState -> NetworkState doPong when cs = set csPingStatus PingNone $ set csLatency (Just delta) cs where delta = case view csPingStatus cs of PingSent sent -> diffUTCTime (zonedTimeToUTC when) sent _ -> 0 -- | Apply the given 'TimedAction' to a connection state. applyTimedAction :: TimedAction -> NetworkState -> IO NetworkState applyTimedAction action cs = case action of TimedForgetLatency -> do return $! set csLatency Nothing cs TimedDisconnect -> do abortConnection PingTimeout (view csSocket cs) return $! set csNextPingTime Nothing cs TimedSendPing -> do now <- getCurrentTime sendMsg cs (ircPing ["ping"]) return $! set csNextPingTime (Just $! addUTCTime 60 now) $ set csPingStatus (PingSent now) cs ------------------------------------------------------------------------ -- Moderation ------------------------------------------------------------------------ -- | Used to send commands that require ops to perform. -- If this channel is one that the user has chanserv access and ops are needed -- then ops are requested and the commands are queued, otherwise send them -- directly. sendModeration :: Identifier {- ^ channel -} -> [RawIrcMsg] {- ^ commands -} -> NetworkState {- ^ network state -} -> IO NetworkState sendModeration channel cmds cs | useChanServ channel cs = do let cmd = ircPrivmsg "ChanServ" (Text.unwords ["OP", idText channel]) sendMsg cs cmd return $ csChannels . ix channel . chanQueuedModeration <>~ cmds $ cs | otherwise = cs <$ traverse_ (sendMsg cs) cmds useChanServ :: Identifier {- ^ channel -} -> NetworkState {- ^ network state -} -> Bool {- ^ chanserv available -} useChanServ channel cs = channel `elem` view (csSettings . ssChanservChannels) cs && not (iHaveOp channel cs) sendTopic :: Identifier {- ^ channel -} -> Text {- ^ topic -} -> NetworkState {- ^ network state -} -> IO () sendTopic channelId topic cs = sendMsg cs cmd where chanservTopicCmd = ircPrivmsg "ChanServ" (Text.unwords ["TOPIC", idText channelId, topic]) cmd | Text.null topic = ircTopic channelId "" | useChanServ channelId cs = chanservTopicCmd | otherwise = ircTopic channelId topic
glguy/irc-core
src/Client/State/Network.hs
isc
41,480
7
22
11,377
11,023
5,627
5,396
-1
-1
main = concat $ map id [1, 2, 3]
pbrisbin/codeclimate-hlint
test/example.hs
mit
33
0
7
9
24
13
11
1
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CloudSearch.DeleteIndexField -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Removes an 'IndexField' from the search domain. For more information, -- see -- <http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-index-fields.html Configuring Index Fields> -- in the /Amazon CloudSearch Developer Guide/. -- -- /See:/ <http://docs.aws.amazon.com/cloudsearch/latest/developerguide/API_DeleteIndexField.html AWS API Reference> for DeleteIndexField. module Network.AWS.CloudSearch.DeleteIndexField ( -- * Creating a Request deleteIndexField , DeleteIndexField -- * Request Lenses , difiDomainName , difiIndexFieldName -- * Destructuring the Response , deleteIndexFieldResponse , DeleteIndexFieldResponse -- * Response Lenses , difrsResponseStatus , difrsIndexField ) where import Network.AWS.CloudSearch.Types import Network.AWS.CloudSearch.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Container for the parameters to the 'DeleteIndexField' operation. -- Specifies the name of the domain you want to update and the name of the -- index field you want to delete. -- -- /See:/ 'deleteIndexField' smart constructor. data DeleteIndexField = DeleteIndexField' { _difiDomainName :: !Text , _difiIndexFieldName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteIndexField' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'difiDomainName' -- -- * 'difiIndexFieldName' deleteIndexField :: Text -- ^ 'difiDomainName' -> Text -- ^ 'difiIndexFieldName' -> DeleteIndexField deleteIndexField pDomainName_ pIndexFieldName_ = DeleteIndexField' { _difiDomainName = pDomainName_ , _difiIndexFieldName = pIndexFieldName_ } -- | Undocumented member. difiDomainName :: Lens' DeleteIndexField Text difiDomainName = lens _difiDomainName (\ s a -> s{_difiDomainName = a}); -- | The name of the index field your want to remove from the domain\'s -- indexing options. difiIndexFieldName :: Lens' DeleteIndexField Text difiIndexFieldName = lens _difiIndexFieldName (\ s a -> s{_difiIndexFieldName = a}); instance AWSRequest DeleteIndexField where type Rs DeleteIndexField = DeleteIndexFieldResponse request = postQuery cloudSearch response = receiveXMLWrapper "DeleteIndexFieldResult" (\ s h x -> DeleteIndexFieldResponse' <$> (pure (fromEnum s)) <*> (x .@ "IndexField")) instance ToHeaders DeleteIndexField where toHeaders = const mempty instance ToPath DeleteIndexField where toPath = const "/" instance ToQuery DeleteIndexField where toQuery DeleteIndexField'{..} = mconcat ["Action" =: ("DeleteIndexField" :: ByteString), "Version" =: ("2013-01-01" :: ByteString), "DomainName" =: _difiDomainName, "IndexFieldName" =: _difiIndexFieldName] -- | The result of a 'DeleteIndexField' request. -- -- /See:/ 'deleteIndexFieldResponse' smart constructor. data DeleteIndexFieldResponse = DeleteIndexFieldResponse' { _difrsResponseStatus :: !Int , _difrsIndexField :: !IndexFieldStatus } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteIndexFieldResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'difrsResponseStatus' -- -- * 'difrsIndexField' deleteIndexFieldResponse :: Int -- ^ 'difrsResponseStatus' -> IndexFieldStatus -- ^ 'difrsIndexField' -> DeleteIndexFieldResponse deleteIndexFieldResponse pResponseStatus_ pIndexField_ = DeleteIndexFieldResponse' { _difrsResponseStatus = pResponseStatus_ , _difrsIndexField = pIndexField_ } -- | The response status code. difrsResponseStatus :: Lens' DeleteIndexFieldResponse Int difrsResponseStatus = lens _difrsResponseStatus (\ s a -> s{_difrsResponseStatus = a}); -- | The status of the index field being deleted. difrsIndexField :: Lens' DeleteIndexFieldResponse IndexFieldStatus difrsIndexField = lens _difrsIndexField (\ s a -> s{_difrsIndexField = a});
fmapfmapfmap/amazonka
amazonka-cloudsearch/gen/Network/AWS/CloudSearch/DeleteIndexField.hs
mpl-2.0
4,980
0
14
969
626
379
247
82
1
{-# LANGUAGE TypeFamilies, DataKinds, GADTs, KindSignatures #-} data Tree :: Bool -> * -> * where E :: Tree False a T :: Tree False a -> a -> Tree False a -> Tree True a type family If (cond :: Bool) thenn elsse :: * type instance If True a b = a type instance If False a b = b type family And (a :: Bool) (b :: Bool) :: Bool type instance And True True = True type instance And False b = False type instance And a False = False f :: Tree h a -> If (And h h) Bool Integer f E = 5 f (T _ _ _) = True main :: IO () main = do print $ "f E:" print $ f E print $ "f (T E 3 E)" print $ f (T E 3 E)
toonn/sciartt
if.hs
bsd-2-clause
632
0
10
186
276
148
128
19
1
module ForeignObj( ForeignObj, module ForeignObj ) where import Prelude -- data ForeignObj -- in Prelude -- recently renamed newForeignObj = makeForeignObj primitive newForeignPtr_ :: Addr{-free-} -> IO ForeignObj primitive addForeignPtrFinalizer :: ForeignObj -> Addr{-free-} -> IO () primitive writeForeignObj :: ForeignObj -> Addr -> IO () primitive eqForeignObj :: ForeignObj -> ForeignObj -> Bool makeForeignObj addr finalizer = do fo <- newForeignPtr_ addr addForeignPtrFinalizer fo finalizer return fo instance Eq ForeignObj where (==) = eqForeignObj
FranklinChen/hugs98-plus-Sep2006
lib/exts/ForeignObj.hs
bsd-3-clause
578
11
8
95
144
76
68
-1
-1
-- | -- Module : Data.ASN1.BinaryEncoding.Writer -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- -- Serialize events for streaming. -- module Data.ASN1.BinaryEncoding.Writer ( toByteString , toLazyByteString ) where import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.ASN1.Types.Lowlevel import Data.ASN1.Serialize -- | transform a list of ASN1 Events into a strict bytestring toByteString :: [ASN1Event] -> ByteString toByteString = B.concat . L.toChunks . toLazyByteString -- | transform a list of ASN1 Events into a lazy bytestring toLazyByteString :: [ASN1Event] -> L.ByteString toLazyByteString evs = L.fromChunks $ loop [] evs where loop _ [] = [] loop acc (x@(Header (ASN1Header _ _ pc len)):xs) = toBs x : loop (if pc then (len == LenIndefinite):acc else acc) xs loop acc (ConstructionEnd:xs) = case acc of [] -> error "malformed stream: end before construction" (True:r) -> toBs ConstructionEnd : loop r xs (False:r) -> loop r xs loop acc (x:xs) = toBs x : loop acc xs toBs (Header hdr) = putHeader hdr toBs (Primitive bs) = bs toBs ConstructionBegin = B.empty toBs ConstructionEnd = B.empty
mboes/hs-asn1
encoding/Data/ASN1/BinaryEncoding/Writer.hs
bsd-3-clause
1,519
0
14
448
374
206
168
23
10
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP, DeriveDataTypeable #-} -- | -- #name_types# -- GHC uses several kinds of name internally: -- -- * 'OccName.OccName': see "OccName#name_types" -- -- * 'RdrName.RdrName' is the type of names that come directly from the parser. They -- have not yet had their scoping and binding resolved by the renamer and can be -- thought of to a first approximation as an 'OccName.OccName' with an optional module -- qualifier -- -- * 'Name.Name': see "Name#name_types" -- -- * 'Id.Id': see "Id#name_types" -- -- * 'Var.Var': see "Var#name_types" module RdrName ( -- * The main type RdrName(..), -- Constructors exported only to BinIface -- ** Construction mkRdrUnqual, mkRdrQual, mkUnqual, mkVarUnqual, mkQual, mkOrig, nameRdrName, getRdrName, -- ** Destruction rdrNameOcc, rdrNameSpace, demoteRdrName, isRdrDataCon, isRdrTyVar, isRdrTc, isQual, isQual_maybe, isUnqual, isOrig, isOrig_maybe, isExact, isExact_maybe, isSrcRdrName, -- * Local mapping of 'RdrName' to 'Name.Name' LocalRdrEnv, emptyLocalRdrEnv, extendLocalRdrEnv, extendLocalRdrEnvList, lookupLocalRdrEnv, lookupLocalRdrOcc, elemLocalRdrEnv, inLocalRdrEnvScope, localRdrEnvElts, delLocalRdrEnvList, -- * Global mapping of 'RdrName' to 'GlobalRdrElt's GlobalRdrEnv, emptyGlobalRdrEnv, mkGlobalRdrEnv, plusGlobalRdrEnv, lookupGlobalRdrEnv, extendGlobalRdrEnv, greOccName, shadowNames, pprGlobalRdrEnv, globalRdrEnvElts, lookupGRE_RdrName, lookupGRE_Name, lookupGRE_Field_Name, getGRE_NameQualifier_maybes, transformGREs, pickGREs, pickGREsModExp, -- * GlobalRdrElts gresFromAvails, gresFromAvail, localGREsFromAvail, availFromGRE, greUsedRdrName, greRdrNames, greSrcSpan, greQualModName, gresToAvailInfo, -- ** Global 'RdrName' mapping elements: 'GlobalRdrElt', 'Provenance', 'ImportSpec' GlobalRdrElt(..), isLocalGRE, isRecFldGRE, greLabel, unQualOK, qualSpecOK, unQualSpecOK, pprNameProvenance, Parent(..), ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..), importSpecLoc, importSpecModule, isExplicitItem, bestImport ) where #include "HsVersions.h" import Module import Name import Avail import NameSet import Maybes import SrcLoc import FastString import FieldLabel import Outputable import Unique import UniqFM import Util import StaticFlags( opt_PprStyle_Debug ) import NameEnv import Data.Data import Data.List( sortBy, foldl', nub ) {- ************************************************************************ * * \subsection{The main data type} * * ************************************************************************ -} -- | Reader Name -- -- Do not use the data constructors of RdrName directly: prefer the family -- of functions that creates them, such as 'mkRdrUnqual' -- -- - Note: A Located RdrName will only have API Annotations if it is a -- compound one, -- e.g. -- -- > `bar` -- > ( ~ ) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType', -- 'ApiAnnotation.AnnOpen' @'('@ or @'['@ or @'[:'@, -- 'ApiAnnotation.AnnClose' @')'@ or @']'@ or @':]'@,, -- 'ApiAnnotation.AnnBackquote' @'`'@, -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnTildehsh', -- 'ApiAnnotation.AnnTilde', -- For details on above see note [Api annotations] in ApiAnnotation data RdrName = Unqual OccName -- ^ Unqualified name -- -- Used for ordinary, unqualified occurrences, e.g. @x@, @y@ or @Foo@. -- Create such a 'RdrName' with 'mkRdrUnqual' | Qual ModuleName OccName -- ^ Qualified name -- -- A qualified name written by the user in -- /source/ code. The module isn't necessarily -- the module where the thing is defined; -- just the one from which it is imported. -- Examples are @Bar.x@, @Bar.y@ or @Bar.Foo@. -- Create such a 'RdrName' with 'mkRdrQual' | Orig Module OccName -- ^ Original name -- -- An original name; the module is the /defining/ module. -- This is used when GHC generates code that will be fed -- into the renamer (e.g. from deriving clauses), but where -- we want to say \"Use Prelude.map dammit\". One of these -- can be created with 'mkOrig' | Exact Name -- ^ Exact name -- -- We know exactly the 'Name'. This is used: -- -- (1) When the parser parses built-in syntax like @[]@ -- and @(,)@, but wants a 'RdrName' from it -- -- (2) By Template Haskell, when TH has generated a unique name -- -- Such a 'RdrName' can be created by using 'getRdrName' on a 'Name' deriving Data {- ************************************************************************ * * \subsection{Simple functions} * * ************************************************************************ -} instance HasOccName RdrName where occName = rdrNameOcc rdrNameOcc :: RdrName -> OccName rdrNameOcc (Qual _ occ) = occ rdrNameOcc (Unqual occ) = occ rdrNameOcc (Orig _ occ) = occ rdrNameOcc (Exact name) = nameOccName name rdrNameSpace :: RdrName -> NameSpace rdrNameSpace = occNameSpace . rdrNameOcc -- demoteRdrName lowers the NameSpace of RdrName. -- see Note [Demotion] in OccName demoteRdrName :: RdrName -> Maybe RdrName demoteRdrName (Unqual occ) = fmap Unqual (demoteOccName occ) demoteRdrName (Qual m occ) = fmap (Qual m) (demoteOccName occ) demoteRdrName (Orig _ _) = panic "demoteRdrName" demoteRdrName (Exact _) = panic "demoteRdrName" -- These two are the basic constructors mkRdrUnqual :: OccName -> RdrName mkRdrUnqual occ = Unqual occ mkRdrQual :: ModuleName -> OccName -> RdrName mkRdrQual mod occ = Qual mod occ mkOrig :: Module -> OccName -> RdrName mkOrig mod occ = Orig mod occ --------------- -- These two are used when parsing source files -- They do encode the module and occurrence names mkUnqual :: NameSpace -> FastString -> RdrName mkUnqual sp n = Unqual (mkOccNameFS sp n) mkVarUnqual :: FastString -> RdrName mkVarUnqual n = Unqual (mkVarOccFS n) -- | Make a qualified 'RdrName' in the given namespace and where the 'ModuleName' and -- the 'OccName' are taken from the first and second elements of the tuple respectively mkQual :: NameSpace -> (FastString, FastString) -> RdrName mkQual sp (m, n) = Qual (mkModuleNameFS m) (mkOccNameFS sp n) getRdrName :: NamedThing thing => thing -> RdrName getRdrName name = nameRdrName (getName name) nameRdrName :: Name -> RdrName nameRdrName name = Exact name -- Keep the Name even for Internal names, so that the -- unique is still there for debug printing, particularly -- of Types (which are converted to IfaceTypes before printing) nukeExact :: Name -> RdrName nukeExact n | isExternalName n = Orig (nameModule n) (nameOccName n) | otherwise = Unqual (nameOccName n) isRdrDataCon :: RdrName -> Bool isRdrTyVar :: RdrName -> Bool isRdrTc :: RdrName -> Bool isRdrDataCon rn = isDataOcc (rdrNameOcc rn) isRdrTyVar rn = isTvOcc (rdrNameOcc rn) isRdrTc rn = isTcOcc (rdrNameOcc rn) isSrcRdrName :: RdrName -> Bool isSrcRdrName (Unqual _) = True isSrcRdrName (Qual _ _) = True isSrcRdrName _ = False isUnqual :: RdrName -> Bool isUnqual (Unqual _) = True isUnqual _ = False isQual :: RdrName -> Bool isQual (Qual _ _) = True isQual _ = False isQual_maybe :: RdrName -> Maybe (ModuleName, OccName) isQual_maybe (Qual m n) = Just (m,n) isQual_maybe _ = Nothing isOrig :: RdrName -> Bool isOrig (Orig _ _) = True isOrig _ = False isOrig_maybe :: RdrName -> Maybe (Module, OccName) isOrig_maybe (Orig m n) = Just (m,n) isOrig_maybe _ = Nothing isExact :: RdrName -> Bool isExact (Exact _) = True isExact _ = False isExact_maybe :: RdrName -> Maybe Name isExact_maybe (Exact n) = Just n isExact_maybe _ = Nothing {- ************************************************************************ * * \subsection{Instances} * * ************************************************************************ -} instance Outputable RdrName where ppr (Exact name) = ppr name ppr (Unqual occ) = ppr occ ppr (Qual mod occ) = ppr mod <> dot <> ppr occ ppr (Orig mod occ) = getPprStyle (\sty -> pprModulePrefix sty mod occ <> ppr occ) instance OutputableBndr RdrName where pprBndr _ n | isTvOcc (rdrNameOcc n) = char '@' <+> ppr n | otherwise = ppr n pprInfixOcc rdr = pprInfixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr) pprPrefixOcc rdr | Just name <- isExact_maybe rdr = pprPrefixName name -- pprPrefixName has some special cases, so -- we delegate to them rather than reproduce them | otherwise = pprPrefixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr) instance Eq RdrName where (Exact n1) == (Exact n2) = n1==n2 -- Convert exact to orig (Exact n1) == r2@(Orig _ _) = nukeExact n1 == r2 r1@(Orig _ _) == (Exact n2) = r1 == nukeExact n2 (Orig m1 o1) == (Orig m2 o2) = m1==m2 && o1==o2 (Qual m1 o1) == (Qual m2 o2) = m1==m2 && o1==o2 (Unqual o1) == (Unqual o2) = o1==o2 _ == _ = False instance Ord RdrName where a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False } a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False } a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True } a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True } -- Exact < Unqual < Qual < Orig -- [Note: Apr 2004] We used to use nukeExact to convert Exact to Orig -- before comparing so that Prelude.map == the exact Prelude.map, but -- that meant that we reported duplicates when renaming bindings -- generated by Template Haskell; e.g -- do { n1 <- newName "foo"; n2 <- newName "foo"; -- <decl involving n1,n2> } -- I think we can do without this conversion compare (Exact n1) (Exact n2) = n1 `compare` n2 compare (Exact _) _ = LT compare (Unqual _) (Exact _) = GT compare (Unqual o1) (Unqual o2) = o1 `compare` o2 compare (Unqual _) _ = LT compare (Qual _ _) (Exact _) = GT compare (Qual _ _) (Unqual _) = GT compare (Qual m1 o1) (Qual m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) compare (Qual _ _) (Orig _ _) = LT compare (Orig m1 o1) (Orig m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) compare (Orig _ _) _ = GT {- ************************************************************************ * * LocalRdrEnv * * ************************************************************************ -} -- | Local Reader Environment -- -- This environment is used to store local bindings -- (@let@, @where@, lambda, @case@). -- It is keyed by OccName, because we never use it for qualified names -- We keep the current mapping, *and* the set of all Names in scope -- Reason: see Note [Splicing Exact names] in RnEnv data LocalRdrEnv = LRE { lre_env :: OccEnv Name , lre_in_scope :: NameSet } instance Outputable LocalRdrEnv where ppr (LRE {lre_env = env, lre_in_scope = ns}) = hang (text "LocalRdrEnv {") 2 (vcat [ text "env =" <+> pprOccEnv ppr_elt env , text "in_scope =" <+> pprUFM ns (braces . pprWithCommas ppr) ] <+> char '}') where ppr_elt name = parens (ppr (getUnique (nameOccName name))) <+> ppr name -- So we can see if the keys line up correctly emptyLocalRdrEnv :: LocalRdrEnv emptyLocalRdrEnv = LRE { lre_env = emptyOccEnv , lre_in_scope = emptyNameSet } extendLocalRdrEnv :: LocalRdrEnv -> Name -> LocalRdrEnv -- The Name should be a non-top-level thing extendLocalRdrEnv lre@(LRE { lre_env = env, lre_in_scope = ns }) name = WARN( isExternalName name, ppr name ) lre { lre_env = extendOccEnv env (nameOccName name) name , lre_in_scope = extendNameSet ns name } extendLocalRdrEnvList :: LocalRdrEnv -> [Name] -> LocalRdrEnv extendLocalRdrEnvList lre@(LRE { lre_env = env, lre_in_scope = ns }) names = WARN( any isExternalName names, ppr names ) lre { lre_env = extendOccEnvList env [(nameOccName n, n) | n <- names] , lre_in_scope = extendNameSetList ns names } lookupLocalRdrEnv :: LocalRdrEnv -> RdrName -> Maybe Name lookupLocalRdrEnv (LRE { lre_env = env, lre_in_scope = ns }) rdr | Unqual occ <- rdr = lookupOccEnv env occ -- See Note [Local bindings with Exact Names] | Exact name <- rdr , name `elemNameSet` ns = Just name | otherwise = Nothing lookupLocalRdrOcc :: LocalRdrEnv -> OccName -> Maybe Name lookupLocalRdrOcc (LRE { lre_env = env }) occ = lookupOccEnv env occ elemLocalRdrEnv :: RdrName -> LocalRdrEnv -> Bool elemLocalRdrEnv rdr_name (LRE { lre_env = env, lre_in_scope = ns }) = case rdr_name of Unqual occ -> occ `elemOccEnv` env Exact name -> name `elemNameSet` ns -- See Note [Local bindings with Exact Names] Qual {} -> False Orig {} -> False localRdrEnvElts :: LocalRdrEnv -> [Name] localRdrEnvElts (LRE { lre_env = env }) = occEnvElts env inLocalRdrEnvScope :: Name -> LocalRdrEnv -> Bool -- This is the point of the NameSet inLocalRdrEnvScope name (LRE { lre_in_scope = ns }) = name `elemNameSet` ns delLocalRdrEnvList :: LocalRdrEnv -> [OccName] -> LocalRdrEnv delLocalRdrEnvList lre@(LRE { lre_env = env }) occs = lre { lre_env = delListFromOccEnv env occs } {- Note [Local bindings with Exact Names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With Template Haskell we can make local bindings that have Exact Names. Computing shadowing etc may use elemLocalRdrEnv (at least it certainly does so in RnTpes.bindHsQTyVars), so for an Exact Name we must consult the in-scope-name-set. ************************************************************************ * * GlobalRdrEnv * * ************************************************************************ -} -- | Global Reader Environment type GlobalRdrEnv = OccEnv [GlobalRdrElt] -- ^ Keyed by 'OccName'; when looking up a qualified name -- we look up the 'OccName' part, and then check the 'Provenance' -- to see if the appropriate qualification is valid. This -- saves routinely doubling the size of the env by adding both -- qualified and unqualified names to the domain. -- -- The list in the codomain is required because there may be name clashes -- These only get reported on lookup, not on construction -- -- INVARIANT 1: All the members of the list have distinct -- 'gre_name' fields; that is, no duplicate Names -- -- INVARIANT 2: Imported provenance => Name is an ExternalName -- However LocalDefs can have an InternalName. This -- happens only when type-checking a [d| ... |] Template -- Haskell quotation; see this note in RnNames -- Note [Top-level Names in Template Haskell decl quotes] -- -- INVARIANT 3: If the GlobalRdrEnv maps [occ -> gre], then -- greOccName gre = occ -- -- NB: greOccName gre is usually the same as -- nameOccName (gre_name gre), but not always in the -- case of record seectors; see greOccName -- | Global Reader Element -- -- An element of the 'GlobalRdrEnv' data GlobalRdrElt = GRE { gre_name :: Name , gre_par :: Parent , gre_lcl :: Bool -- ^ True <=> the thing was defined locally , gre_imp :: [ImportSpec] -- ^ In scope through these imports } deriving (Data, Eq) -- INVARIANT: either gre_lcl = True or gre_imp is non-empty -- See Note [GlobalRdrElt provenance] -- | The children of a Name are the things that are abbreviated by the ".." -- notation in export lists. See Note [Parents] data Parent = NoParent | ParentIs { par_is :: Name } | FldParent { par_is :: Name, par_lbl :: Maybe FieldLabelString } -- ^ See Note [Parents for record fields] deriving (Eq, Data, Typeable) instance Outputable Parent where ppr NoParent = empty ppr (ParentIs n) = text "parent:" <> ppr n ppr (FldParent n f) = text "fldparent:" <> ppr n <> colon <> ppr f plusParent :: Parent -> Parent -> Parent -- See Note [Combining parents] plusParent p1@(ParentIs _) p2 = hasParent p1 p2 plusParent p1@(FldParent _ _) p2 = hasParent p1 p2 plusParent p1 p2@(ParentIs _) = hasParent p2 p1 plusParent p1 p2@(FldParent _ _) = hasParent p2 p1 plusParent _ _ = NoParent hasParent :: Parent -> Parent -> Parent #ifdef DEBUG hasParent p NoParent = p hasParent p p' | p /= p' = pprPanic "hasParent" (ppr p <+> ppr p') -- Parents should agree #endif hasParent p _ = p {- Note [GlobalRdrElt provenance] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The gre_lcl and gre_imp fields of a GlobalRdrElt describe its "provenance", i.e. how the Name came to be in scope. It can be in scope two ways: - gre_lcl = True: it is bound in this module - gre_imp: a list of all the imports that brought it into scope It's an INVARIANT that you have one or the other; that is, either gre_lcl is True, or gre_imp is non-empty. It is just possible to have *both* if there is a module loop: a Name is defined locally in A, and also brought into scope by importing a module that SOURCE-imported A. Exapmle (Trac #7672): A.hs-boot module A where data T B.hs module B(Decl.T) where import {-# SOURCE #-} qualified A as Decl A.hs module A where import qualified B data T = Z | S B.T In A.hs, 'T' is locally bound, *and* imported as B.T. Note [Parents] ~~~~~~~~~~~~~~~~~ Parent Children ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ data T Data constructors Record-field ids data family T Data constructors and record-field ids of all visible data instances of T class C Class operations Associated type constructors ~~~~~~~~~~~~~~~~~~~~~~~~~ Constructor Meaning ~~~~~~~~~~~~~~~~~~~~~~~~ NoParent Can not be bundled with a type constructor. ParentIs n Can be bundled with the type constructor corresponding to n. FldParent See Note [Parents for record fields] Note [Parents for record fields] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For record fields, in addition to the Name of the type constructor (stored in par_is), we use FldParent to store the field label. This extra information is used for identifying overloaded record fields during renaming. In a definition arising from a normal module (without -XDuplicateRecordFields), par_lbl will be Nothing, meaning that the field's label is the same as the OccName of the selector's Name. The GlobalRdrEnv will contain an entry like this: "x" |-> GRE x (FldParent T Nothing) LocalDef When -XDuplicateRecordFields is enabled for the module that contains T, the selector's Name will be mangled (see comments in FieldLabel). Thus we store the actual field label in par_lbl, and the GlobalRdrEnv entry looks like this: "x" |-> GRE $sel:x:MkT (FldParent T (Just "x")) LocalDef Note that the OccName used when adding a GRE to the environment (greOccName) now depends on the parent field: for FldParent it is the field label, if present, rather than the selector name. ~~ Record pattern synonym selectors are treated differently. Their parent information is `NoParent` in the module in which they are defined. This is because a pattern synonym `P` has no parent constructor either. However, if `f` is bundled with a type constructor `T` then whenever `f` is imported the parent will use the `Parent` constructor so the parent of `f` is now `T`. Note [Combining parents] ~~~~~~~~~~~~~~~~~~~~~~~~ With an associated type we might have module M where class C a where data T a op :: T a -> a instance C Int where data T Int = TInt instance C Bool where data T Bool = TBool Then: C is the parent of T T is the parent of TInt and TBool So: in an export list C(..) is short for C( op, T ) T(..) is short for T( TInt, TBool ) Module M exports everything, so its exports will be AvailTC C [C,T,op] AvailTC T [T,TInt,TBool] On import we convert to GlobalRdrElt and then combine those. For T that will mean we have one GRE with Parent C one GRE with NoParent That's why plusParent picks the "best" case. -} -- | make a 'GlobalRdrEnv' where all the elements point to the same -- Provenance (useful for "hiding" imports, or imports with no details). gresFromAvails :: Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt] -- prov = Nothing => locally bound -- Just spec => imported as described by spec gresFromAvails prov avails = concatMap (gresFromAvail (const prov)) avails localGREsFromAvail :: AvailInfo -> [GlobalRdrElt] -- Turn an Avail into a list of LocalDef GlobalRdrElts localGREsFromAvail = gresFromAvail (const Nothing) gresFromAvail :: (Name -> Maybe ImportSpec) -> AvailInfo -> [GlobalRdrElt] gresFromAvail prov_fn avail = map mk_gre (availNonFldNames avail) ++ map mk_fld_gre (availFlds avail) where mk_gre n = case prov_fn n of -- Nothing => bound locally -- Just is => imported from 'is' Nothing -> GRE { gre_name = n, gre_par = mkParent n avail , gre_lcl = True, gre_imp = [] } Just is -> GRE { gre_name = n, gre_par = mkParent n avail , gre_lcl = False, gre_imp = [is] } mk_fld_gre (FieldLabel { flLabel = lbl, flIsOverloaded = is_overloaded , flSelector = n }) = case prov_fn n of -- Nothing => bound locally -- Just is => imported from 'is' Nothing -> GRE { gre_name = n, gre_par = FldParent (availName avail) mb_lbl , gre_lcl = True, gre_imp = [] } Just is -> GRE { gre_name = n, gre_par = FldParent (availName avail) mb_lbl , gre_lcl = False, gre_imp = [is] } where mb_lbl | is_overloaded = Just lbl | otherwise = Nothing greQualModName :: GlobalRdrElt -> ModuleName -- Get a suitable module qualifier for the GRE -- (used in mkPrintUnqualified) -- Prerecondition: the gre_name is always External greQualModName gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss }) | lcl, Just mod <- nameModule_maybe name = moduleName mod | (is:_) <- iss = is_as (is_decl is) | otherwise = pprPanic "greQualModName" (ppr gre) greUsedRdrName :: GlobalRdrElt -> RdrName -- For imported things, return a RdrName to add to the used-RdrName -- set, which is used to generate unused-import-decl warnings. -- Return a Qual RdrName if poss, so that identifies the most -- specific ImportSpec. See Trac #10890 for some good examples. greUsedRdrName gre@GRE{ gre_name = name, gre_lcl = lcl, gre_imp = iss } | lcl, Just mod <- nameModule_maybe name = Qual (moduleName mod) occ | not (null iss), is <- bestImport iss = Qual (is_as (is_decl is)) occ | otherwise = pprTrace "greUsedRdrName" (ppr gre) (Unqual occ) where occ = greOccName gre greRdrNames :: GlobalRdrElt -> [RdrName] greRdrNames gre@GRE{ gre_lcl = lcl, gre_imp = iss } = (if lcl then [unqual] else []) ++ concatMap do_spec (map is_decl iss) where occ = greOccName gre unqual = Unqual occ do_spec decl_spec | is_qual decl_spec = [qual] | otherwise = [unqual,qual] where qual = Qual (is_as decl_spec) occ -- the SrcSpan that pprNameProvenance prints out depends on whether -- the Name is defined locally or not: for a local definition the -- definition site is used, otherwise the location of the import -- declaration. We want to sort the export locations in -- exportClashErr by this SrcSpan, we need to extract it: greSrcSpan :: GlobalRdrElt -> SrcSpan greSrcSpan gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss } ) | lcl = nameSrcSpan name | (is:_) <- iss = is_dloc (is_decl is) | otherwise = pprPanic "greSrcSpan" (ppr gre) mkParent :: Name -> AvailInfo -> Parent mkParent _ (Avail _) = NoParent mkParent n (AvailTC m _ _) | n == m = NoParent | otherwise = ParentIs m greParentName :: GlobalRdrElt -> Maybe Name greParentName gre = case gre_par gre of NoParent -> Nothing ParentIs n -> Just n FldParent n _ -> Just n -- | Takes a list of distinct GREs and folds them -- into AvailInfos. This is more efficient than mapping each individual -- GRE to an AvailInfo and the folding using `plusAvail` but needs the -- uniqueness assumption. gresToAvailInfo :: [GlobalRdrElt] -> [AvailInfo] gresToAvailInfo gres = ASSERT( nub gres == gres ) nameEnvElts avail_env where avail_env :: NameEnv AvailInfo -- keyed by the parent avail_env = foldl' add emptyNameEnv gres add :: NameEnv AvailInfo -> GlobalRdrElt -> NameEnv AvailInfo add env gre = extendNameEnv_Acc comb availFromGRE env (fromMaybe (gre_name gre) (greParentName gre)) gre where -- We want to insert the child `k` into a list of children but -- need to maintain the invariant that the parent is first. -- -- We also use the invariant that `k` is not already in `ns`. insertChildIntoChildren :: Name -> [Name] -> Name -> [Name] insertChildIntoChildren _ [] k = [k] insertChildIntoChildren p (n:ns) k | p == k = k:n:ns | otherwise = n:k:ns comb :: GlobalRdrElt -> AvailInfo -> AvailInfo comb _ (Avail n) = Avail n -- Duplicated name comb gre (AvailTC m ns fls) = let n = gre_name gre in case gre_par gre of NoParent -> AvailTC m (n:ns) fls -- Not sure this ever happens ParentIs {} -> AvailTC m (insertChildIntoChildren m ns n) fls FldParent _ mb_lbl -> AvailTC m ns (mkFieldLabel n mb_lbl : fls) availFromGRE :: GlobalRdrElt -> AvailInfo availFromGRE (GRE { gre_name = me, gre_par = parent }) = case parent of ParentIs p -> AvailTC p [me] [] NoParent | isTyConName me -> AvailTC me [me] [] | otherwise -> avail me FldParent p mb_lbl -> AvailTC p [] [mkFieldLabel me mb_lbl] where mkFieldLabel :: Name -> Maybe FastString -> FieldLabel mkFieldLabel me mb_lbl = case mb_lbl of Nothing -> FieldLabel { flLabel = occNameFS (nameOccName me) , flIsOverloaded = False , flSelector = me } Just lbl -> FieldLabel { flLabel = lbl , flIsOverloaded = True , flSelector = me } emptyGlobalRdrEnv :: GlobalRdrEnv emptyGlobalRdrEnv = emptyOccEnv globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt] globalRdrEnvElts env = foldOccEnv (++) [] env instance Outputable GlobalRdrElt where ppr gre = hang (ppr (gre_name gre) <+> ppr (gre_par gre)) 2 (pprNameProvenance gre) pprGlobalRdrEnv :: Bool -> GlobalRdrEnv -> SDoc pprGlobalRdrEnv locals_only env = vcat [ text "GlobalRdrEnv" <+> ppWhen locals_only (ptext (sLit "(locals only)")) <+> lbrace , nest 2 (vcat [ pp (remove_locals gre_list) | gre_list <- occEnvElts env ] <+> rbrace) ] where remove_locals gres | locals_only = filter isLocalGRE gres | otherwise = gres pp [] = empty pp gres = hang (ppr occ <+> parens (text "unique" <+> ppr (getUnique occ)) <> colon) 2 (vcat (map ppr gres)) where occ = nameOccName (gre_name (head gres)) lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt] lookupGlobalRdrEnv env occ_name = case lookupOccEnv env occ_name of Nothing -> [] Just gres -> gres greOccName :: GlobalRdrElt -> OccName greOccName (GRE{gre_par = FldParent{par_lbl = Just lbl}}) = mkVarOccFS lbl greOccName gre = nameOccName (gre_name gre) lookupGRE_RdrName :: RdrName -> GlobalRdrEnv -> [GlobalRdrElt] lookupGRE_RdrName rdr_name env = case lookupOccEnv env (rdrNameOcc rdr_name) of Nothing -> [] Just gres -> pickGREs rdr_name gres lookupGRE_Name :: GlobalRdrEnv -> Name -> Maybe GlobalRdrElt lookupGRE_Name env name = case [ gre | gre <- lookupGlobalRdrEnv env (nameOccName name) , gre_name gre == name ] of [] -> Nothing [gre] -> Just gre gres -> pprPanic "lookupGRE_Name" (ppr name $$ ppr gres) -- See INVARIANT 1 on GlobalRdrEnv lookupGRE_Field_Name :: GlobalRdrEnv -> Name -> FastString -> [GlobalRdrElt] -- Used when looking up record fields, where the selector name and -- field label are different: the GlobalRdrEnv is keyed on the label lookupGRE_Field_Name env sel_name lbl = [ gre | gre <- lookupGlobalRdrEnv env (mkVarOccFS lbl), gre_name gre == sel_name ] getGRE_NameQualifier_maybes :: GlobalRdrEnv -> Name -> [Maybe [ModuleName]] -- Returns all the qualifiers by which 'x' is in scope -- Nothing means "the unqualified version is in scope" -- [] means the thing is not in scope at all getGRE_NameQualifier_maybes env name = case lookupGRE_Name env name of Just gre -> [qualifier_maybe gre] Nothing -> [] where qualifier_maybe (GRE { gre_lcl = lcl, gre_imp = iss }) | lcl = Nothing | otherwise = Just $ map (is_as . is_decl) iss isLocalGRE :: GlobalRdrElt -> Bool isLocalGRE (GRE {gre_lcl = lcl }) = lcl isRecFldGRE :: GlobalRdrElt -> Bool isRecFldGRE (GRE {gre_par = FldParent{}}) = True isRecFldGRE _ = False -- Returns the field label of this GRE, if it has one greLabel :: GlobalRdrElt -> Maybe FieldLabelString greLabel (GRE{gre_par = FldParent{par_lbl = Just lbl}}) = Just lbl greLabel (GRE{gre_name = n, gre_par = FldParent{}}) = Just (occNameFS (nameOccName n)) greLabel _ = Nothing unQualOK :: GlobalRdrElt -> Bool -- ^ Test if an unqualifed version of this thing would be in scope unQualOK (GRE {gre_lcl = lcl, gre_imp = iss }) | lcl = True | otherwise = any unQualSpecOK iss {- Note [GRE filtering] ~~~~~~~~~~~~~~~~~~~~~~~ (pickGREs rdr gres) takes a list of GREs which have the same OccName as 'rdr', say "x". It does two things: (a) filters the GREs to a subset that are in scope * Qualified, as 'M.x' if want_qual is Qual M _ * Unqualified, as 'x' if want_unqual is Unqual _ (b) for that subset, filter the provenance field (gre_lcl and gre_imp) to ones that brought it into scope qualifed or unqualified resp. Example: module A ( f ) where import qualified Foo( f ) import Baz( f ) f = undefined Let's suppose that Foo.f and Baz.f are the same entity really, but the local 'f' is different, so there will be two GREs matching "f": gre1: gre_lcl = True, gre_imp = [] gre2: gre_lcl = False, gre_imp = [ imported from Foo, imported from Bar ] The use of "f" in the export list is ambiguous because it's in scope from the local def and the import Baz(f); but *not* the import qualified Foo. pickGREs returns two GRE gre1: gre_lcl = True, gre_imp = [] gre2: gre_lcl = False, gre_imp = [ imported from Bar ] Now the the "ambiguous occurrence" message can correctly report how the ambiguity arises. -} pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt] -- ^ Takes a list of GREs which have the right OccName 'x' -- Pick those GREs that are are in scope -- * Qualified, as 'M.x' if want_qual is Qual M _ -- * Unqualified, as 'x' if want_unqual is Unqual _ -- -- Return each such GRE, with its ImportSpecs filtered, to reflect -- how it is in scope qualifed or unqualified respectively. -- See Note [GRE filtering] pickGREs (Unqual {}) gres = mapMaybe pickUnqualGRE gres pickGREs (Qual mod _) gres = mapMaybe (pickQualGRE mod) gres pickGREs _ _ = [] -- I don't think this actually happens pickUnqualGRE :: GlobalRdrElt -> Maybe GlobalRdrElt pickUnqualGRE gre@(GRE { gre_lcl = lcl, gre_imp = iss }) | not lcl, null iss' = Nothing | otherwise = Just (gre { gre_imp = iss' }) where iss' = filter unQualSpecOK iss pickQualGRE :: ModuleName -> GlobalRdrElt -> Maybe GlobalRdrElt pickQualGRE mod gre@(GRE { gre_name = n, gre_lcl = lcl, gre_imp = iss }) | not lcl', null iss' = Nothing | otherwise = Just (gre { gre_lcl = lcl', gre_imp = iss' }) where iss' = filter (qualSpecOK mod) iss lcl' = lcl && name_is_from mod n name_is_from :: ModuleName -> Name -> Bool name_is_from mod name = case nameModule_maybe name of Just n_mod -> moduleName n_mod == mod Nothing -> False pickGREsModExp :: ModuleName -> [GlobalRdrElt] -> [(GlobalRdrElt,GlobalRdrElt)] -- ^ Pick GREs that are in scope *both* qualified *and* unqualified -- Return each GRE that is, as a pair -- (qual_gre, unqual_gre) -- These two GREs are the original GRE with imports filtered to express how -- it is in scope qualified an unqualified respectively -- -- Used only for the 'module M' item in export list; -- see RnNames.exports_from_avail pickGREsModExp mod gres = mapMaybe (pickBothGRE mod) gres pickBothGRE :: ModuleName -> GlobalRdrElt -> Maybe (GlobalRdrElt, GlobalRdrElt) pickBothGRE mod gre@(GRE { gre_name = n }) | isBuiltInSyntax n = Nothing | Just gre1 <- pickQualGRE mod gre , Just gre2 <- pickUnqualGRE gre = Just (gre1, gre2) | otherwise = Nothing where -- isBuiltInSyntax filter out names for built-in syntax They -- just clutter up the environment (esp tuples), and the -- parser will generate Exact RdrNames for them, so the -- cluttered envt is no use. Really, it's only useful for -- GHC.Base and GHC.Tuple. -- Building GlobalRdrEnvs plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2 mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv mkGlobalRdrEnv gres = foldr add emptyGlobalRdrEnv gres where add gre env = extendOccEnv_Acc insertGRE singleton env (greOccName gre) gre insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt] insertGRE new_g [] = [new_g] insertGRE new_g (old_g : old_gs) | gre_name new_g == gre_name old_g = new_g `plusGRE` old_g : old_gs | otherwise = old_g : insertGRE new_g old_gs plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt -- Used when the gre_name fields match plusGRE g1 g2 = GRE { gre_name = gre_name g1 , gre_lcl = gre_lcl g1 || gre_lcl g2 , gre_imp = gre_imp g1 ++ gre_imp g2 , gre_par = gre_par g1 `plusParent` gre_par g2 } transformGREs :: (GlobalRdrElt -> GlobalRdrElt) -> [OccName] -> GlobalRdrEnv -> GlobalRdrEnv -- ^ Apply a transformation function to the GREs for these OccNames transformGREs trans_gre occs rdr_env = foldr trans rdr_env occs where trans occ env = case lookupOccEnv env occ of Just gres -> extendOccEnv env occ (map trans_gre gres) Nothing -> env extendGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrElt -> GlobalRdrEnv extendGlobalRdrEnv env gre = extendOccEnv_Acc insertGRE singleton env (greOccName gre) gre shadowNames :: GlobalRdrEnv -> [Name] -> GlobalRdrEnv shadowNames = foldl shadowName {- Note [GlobalRdrEnv shadowing] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before adding new names to the GlobalRdrEnv we nuke some existing entries; this is "shadowing". The actual work is done by RdrEnv.shadowNames. There are two reasons for shadowing: * The GHCi REPL - Ids bought into scope on the command line (eg let x = True) have External Names, like Ghci4.x. We want a new binding for 'x' (say) to override the existing binding for 'x'. See Note [Interactively-bound Ids in GHCi] in HscTypes - Data types also have Extenal Names, like Ghci4.T; but we still want 'T' to mean the newly-declared 'T', not an old one. * Nested Template Haskell declaration brackets See Note [Top-level Names in Template Haskell decl quotes] in RnNames Consider a TH decl quote: module M where f x = h [d| f = 3 |] We must shadow the outer declaration of 'f', else we'll get a complaint when extending the GlobalRdrEnv, saying that there are two bindings for 'f'. There are several tricky points: - This shadowing applies even if the binding for 'f' is in a where-clause, and hence is in the *local* RdrEnv not the *global* RdrEnv. This is done in lcl_env_TH in extendGlobalRdrEnvRn. - The External Name M.f from the enclosing module must certainly still be available. So we don't nuke it entirely; we just make it seem like qualified import. - We only shadow *External* names (which come from the main module), or from earlier GHCi commands. Do not shadow *Internal* names because in the bracket [d| class C a where f :: a f = 4 |] rnSrcDecls will first call extendGlobalRdrEnvRn with C[f] from the class decl, and *separately* extend the envt with the value binding. At that stage, the class op 'f' will have an Internal name. -} shadowName :: GlobalRdrEnv -> Name -> GlobalRdrEnv -- Remove certain old GREs that share the same OccName as this new Name. -- See Note [GlobalRdrEnv shadowing] for details shadowName env name = alterOccEnv (fmap alter_fn) env (nameOccName name) where alter_fn :: [GlobalRdrElt] -> [GlobalRdrElt] alter_fn gres = mapMaybe (shadow_with name) gres shadow_with :: Name -> GlobalRdrElt -> Maybe GlobalRdrElt shadow_with new_name old_gre@(GRE { gre_name = old_name, gre_lcl = lcl, gre_imp = iss }) = case nameModule_maybe old_name of Nothing -> Just old_gre -- Old name is Internal; do not shadow Just old_mod | Just new_mod <- nameModule_maybe new_name , new_mod == old_mod -- Old name same as new name; shadow completely -> Nothing | null iss' -- Nothing remains -> Nothing | otherwise -> Just (old_gre { gre_lcl = False, gre_imp = iss' }) where iss' = lcl_imp ++ mapMaybe (shadow_is new_name) iss lcl_imp | lcl = [mk_fake_imp_spec old_name old_mod] | otherwise = [] mk_fake_imp_spec old_name old_mod -- Urgh! = ImpSpec id_spec ImpAll where old_mod_name = moduleName old_mod id_spec = ImpDeclSpec { is_mod = old_mod_name , is_as = old_mod_name , is_qual = True , is_dloc = nameSrcSpan old_name } shadow_is :: Name -> ImportSpec -> Maybe ImportSpec shadow_is new_name is@(ImpSpec { is_decl = id_spec }) | Just new_mod <- nameModule_maybe new_name , is_as id_spec == moduleName new_mod = Nothing -- Shadow both qualified and unqualified | otherwise -- Shadow unqualified only = Just (is { is_decl = id_spec { is_qual = True } }) {- ************************************************************************ * * ImportSpec * * ************************************************************************ -} -- | Import Specification -- -- The 'ImportSpec' of something says how it came to be imported -- It's quite elaborate so that we can give accurate unused-name warnings. data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec, is_item :: ImpItemSpec } deriving( Eq, Ord, Data ) -- | Import Declaration Specification -- -- Describes a particular import declaration and is -- shared among all the 'Provenance's for that decl data ImpDeclSpec = ImpDeclSpec { is_mod :: ModuleName, -- ^ Module imported, e.g. @import Muggle@ -- Note the @Muggle@ may well not be -- the defining module for this thing! -- TODO: either should be Module, or there -- should be a Maybe UnitId here too. is_as :: ModuleName, -- ^ Import alias, e.g. from @as M@ (or @Muggle@ if there is no @as@ clause) is_qual :: Bool, -- ^ Was this import qualified? is_dloc :: SrcSpan -- ^ The location of the entire import declaration } deriving Data -- | Import Item Specification -- -- Describes import info a particular Name data ImpItemSpec = ImpAll -- ^ The import had no import list, -- or had a hiding list | ImpSome { is_explicit :: Bool, is_iloc :: SrcSpan -- Location of the import item } -- ^ The import had an import list. -- The 'is_explicit' field is @True@ iff the thing was named -- /explicitly/ in the import specs rather -- than being imported as part of a "..." group. Consider: -- -- > import C( T(..) ) -- -- Here the constructors of @T@ are not named explicitly; -- only @T@ is named explicitly. deriving Data instance Eq ImpDeclSpec where p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False instance Ord ImpDeclSpec where compare is1 is2 = (is_mod is1 `compare` is_mod is2) `thenCmp` (is_dloc is1 `compare` is_dloc is2) instance Eq ImpItemSpec where p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False instance Ord ImpItemSpec where compare is1 is2 = case (is1, is2) of (ImpAll, ImpAll) -> EQ (ImpAll, _) -> GT (_, ImpAll) -> LT (ImpSome _ l1, ImpSome _ l2) -> l1 `compare` l2 bestImport :: [ImportSpec] -> ImportSpec -- Given a non-empty bunch of ImportSpecs, return the one that -- imported the item most specficially (e.g. by name), using -- textually-first as a tie breaker. This is used when reporting -- redundant imports bestImport iss = case sortBy best iss of (is:_) -> is [] -> pprPanic "bestImport" (ppr iss) where best :: ImportSpec -> ImportSpec -> Ordering -- Less means better best (ImpSpec { is_item = item1, is_decl = d1 }) (ImpSpec { is_item = item2, is_decl = d2 }) = best_item item1 item2 `thenCmp` (is_dloc d1 `compare` is_dloc d2) best_item :: ImpItemSpec -> ImpItemSpec -> Ordering best_item ImpAll ImpAll = EQ best_item ImpAll (ImpSome {}) = GT best_item (ImpSome {}) ImpAll = LT best_item (ImpSome { is_explicit = e1 }) (ImpSome { is_explicit = e2 }) = e2 `compare` e1 -- False < True, so if e1 is explicit and e2 is not, we get LT unQualSpecOK :: ImportSpec -> Bool -- ^ Is in scope unqualified? unQualSpecOK is = not (is_qual (is_decl is)) qualSpecOK :: ModuleName -> ImportSpec -> Bool -- ^ Is in scope qualified with the given module? qualSpecOK mod is = mod == is_as (is_decl is) importSpecLoc :: ImportSpec -> SrcSpan importSpecLoc (ImpSpec decl ImpAll) = is_dloc decl importSpecLoc (ImpSpec _ item) = is_iloc item importSpecModule :: ImportSpec -> ModuleName importSpecModule is = is_mod (is_decl is) isExplicitItem :: ImpItemSpec -> Bool isExplicitItem ImpAll = False isExplicitItem (ImpSome {is_explicit = exp}) = exp pprNameProvenance :: GlobalRdrElt -> SDoc -- ^ Print out one place where the name was define/imported -- (With -dppr-debug, print them all) pprNameProvenance (GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss }) | opt_PprStyle_Debug = vcat pp_provs | otherwise = head pp_provs where pp_provs = pp_lcl ++ map pp_is iss pp_lcl = if lcl then [text "defined at" <+> ppr (nameSrcLoc name)] else [] pp_is is = sep [ppr is, ppr_defn_site is name] -- If we know the exact definition point (which we may do with GHCi) -- then show that too. But not if it's just "imported from X". ppr_defn_site :: ImportSpec -> Name -> SDoc ppr_defn_site imp_spec name | same_module && not (isGoodSrcSpan loc) = empty -- Nothing interesting to say | otherwise = parens $ hang (text "and originally defined" <+> pp_mod) 2 (pprLoc loc) where loc = nameSrcSpan name defining_mod = ASSERT2( isExternalName name, ppr name ) nameModule name same_module = importSpecModule imp_spec == moduleName defining_mod pp_mod | same_module = empty | otherwise = text "in" <+> quotes (ppr defining_mod) instance Outputable ImportSpec where ppr imp_spec = text "imported" <+> qual <+> text "from" <+> quotes (ppr (importSpecModule imp_spec)) <+> pprLoc (importSpecLoc imp_spec) where qual | is_qual (is_decl imp_spec) = text "qualified" | otherwise = empty pprLoc :: SrcSpan -> SDoc pprLoc (RealSrcSpan s) = text "at" <+> ppr s pprLoc (UnhelpfulSpan {}) = empty
olsner/ghc
compiler/basicTypes/RdrName.hs
bsd-3-clause
47,094
0
17
13,167
8,866
4,725
4,141
568
5
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} -- | Cache information about previous builds module Stack.Build.Cache ( tryGetBuildCache , tryGetConfigCache , tryGetCabalMod , tryGetSetupConfigMod , getInstalledExes , tryGetFlagCache , deleteCaches , markExeInstalled , markExeNotInstalled , writeFlagCache , writeBuildCache , writeConfigCache , writeCabalMod , TestStatus (..) , setTestStatus , getTestStatus , writePrecompiledCache , readPrecompiledCache -- Exported for testing , BuildCache(..) ) where import Stack.Prelude import Crypto.Hash (hashWith, SHA256(..)) import qualified Data.ByteArray as Mem (convert) import qualified Data.Map as M import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Yaml as Yaml import Foreign.C.Types (CTime) import Path import Path.IO import Stack.Constants import Stack.Constants.Config import Stack.Storage.Project import Stack.Storage.User import Stack.Types.Build import Stack.Types.Cache import Stack.Types.Config import Stack.Types.GhcPkgId import Stack.Types.NamedComponent import Stack.Types.SourceMap (smRelDir) import System.PosixCompat.Files (modificationTime, getFileStatus, setFileTimes) -- | Directory containing files to mark an executable as installed exeInstalledDir :: (HasEnvConfig env) => InstallLocation -> RIO env (Path Abs Dir) exeInstalledDir Snap = (</> relDirInstalledPackages) `liftM` installationRootDeps exeInstalledDir Local = (</> relDirInstalledPackages) `liftM` installationRootLocal -- | Get all of the installed executables getInstalledExes :: (HasEnvConfig env) => InstallLocation -> RIO env [PackageIdentifier] getInstalledExes loc = do dir <- exeInstalledDir loc (_, files) <- liftIO $ handleIO (const $ return ([], [])) $ listDir dir return $ concat $ M.elems $ -- If there are multiple install records (from a stack version -- before https://github.com/commercialhaskell/stack/issues/2373 -- was fixed), then we don't know which is correct - ignore them. M.fromListWith (\_ _ -> []) $ map (\x -> (pkgName x, [x])) $ mapMaybe (parsePackageIdentifier . toFilePath . filename) files -- | Mark the given executable as installed markExeInstalled :: (HasEnvConfig env) => InstallLocation -> PackageIdentifier -> RIO env () markExeInstalled loc ident = do dir <- exeInstalledDir loc ensureDir dir ident' <- parseRelFile $ packageIdentifierString ident let fp = dir </> ident' -- Remove old install records for this package. -- TODO: This is a bit in-efficient. Put all this metadata into one file? installed <- getInstalledExes loc forM_ (filter (\x -> pkgName ident == pkgName x) installed) (markExeNotInstalled loc) -- TODO consideration for the future: list all of the executables -- installed, and invalidate this file in getInstalledExes if they no -- longer exist writeBinaryFileAtomic fp "Installed" -- | Mark the given executable as not installed markExeNotInstalled :: (HasEnvConfig env) => InstallLocation -> PackageIdentifier -> RIO env () markExeNotInstalled loc ident = do dir <- exeInstalledDir loc ident' <- parseRelFile $ packageIdentifierString ident liftIO $ ignoringAbsence (removeFile $ dir </> ident') buildCacheFile :: (HasEnvConfig env, MonadReader env m, MonadThrow m) => Path Abs Dir -> NamedComponent -> m (Path Abs File) buildCacheFile dir component = do cachesDir <- buildCachesDir dir smh <- view $ envConfigL.to envConfigSourceMapHash smDirName <- smRelDir smh let nonLibComponent prefix name = prefix <> "-" <> T.unpack name cacheFileName <- parseRelFile $ case component of CLib -> "lib" CInternalLib name -> nonLibComponent "internal-lib" name CExe name -> nonLibComponent "exe" name CTest name -> nonLibComponent "test" name CBench name -> nonLibComponent "bench" name return $ cachesDir </> smDirName </> cacheFileName -- | Try to read the dirtiness cache for the given package directory. tryGetBuildCache :: HasEnvConfig env => Path Abs Dir -> NamedComponent -> RIO env (Maybe (Map FilePath FileCacheInfo)) tryGetBuildCache dir component = do fp <- buildCacheFile dir component ensureDir $ parent fp either (const Nothing) (Just . buildCacheTimes) <$> liftIO (tryAny (Yaml.decodeFileThrow (toFilePath fp))) -- | Try to read the dirtiness cache for the given package directory. tryGetConfigCache :: HasEnvConfig env => Path Abs Dir -> RIO env (Maybe ConfigCache) tryGetConfigCache dir = loadConfigCache $ configCacheKey dir ConfigCacheTypeConfig -- | Try to read the mod time of the cabal file from the last build tryGetCabalMod :: HasEnvConfig env => Path Abs Dir -> RIO env (Maybe CTime) tryGetCabalMod dir = do fp <- toFilePath <$> configCabalMod dir tryGetFileMod fp -- | Try to read the mod time of setup-config file from the last build tryGetSetupConfigMod :: HasEnvConfig env => Path Abs Dir -> RIO env (Maybe CTime) tryGetSetupConfigMod dir = do fp <- toFilePath <$> configSetupConfigMod dir tryGetFileMod fp tryGetFileMod :: MonadIO m => FilePath -> m (Maybe CTime) tryGetFileMod fp = liftIO $ either (const Nothing) (Just . modificationTime) <$> tryIO (getFileStatus fp) -- | Write the dirtiness cache for this package's files. writeBuildCache :: HasEnvConfig env => Path Abs Dir -> NamedComponent -> Map FilePath FileCacheInfo -> RIO env () writeBuildCache dir component times = do fp <- toFilePath <$> buildCacheFile dir component liftIO $ Yaml.encodeFile fp BuildCache { buildCacheTimes = times } -- | Write the dirtiness cache for this package's configuration. writeConfigCache :: HasEnvConfig env => Path Abs Dir -> ConfigCache -> RIO env () writeConfigCache dir = saveConfigCache (configCacheKey dir ConfigCacheTypeConfig) -- | See 'tryGetCabalMod' writeCabalMod :: HasEnvConfig env => Path Abs Dir -> CTime -> RIO env () writeCabalMod dir x = do fp <- configCabalMod dir writeBinaryFileAtomic fp "Just used for its modification time" liftIO $ setFileTimes (toFilePath fp) x x -- | Delete the caches for the project. deleteCaches :: HasEnvConfig env => Path Abs Dir -> RIO env () deleteCaches dir {- FIXME confirm that this is acceptable to remove bfp <- buildCacheFile dir removeFileIfExists bfp -} = deactiveConfigCache $ configCacheKey dir ConfigCacheTypeConfig flagCacheKey :: (HasEnvConfig env) => Installed -> RIO env ConfigCacheKey flagCacheKey installed = do installationRoot <- installationRootLocal case installed of Library _ gid _ -> return $ configCacheKey installationRoot (ConfigCacheTypeFlagLibrary gid) Executable ident -> return $ configCacheKey installationRoot (ConfigCacheTypeFlagExecutable ident) -- | Loads the flag cache for the given installed extra-deps tryGetFlagCache :: HasEnvConfig env => Installed -> RIO env (Maybe ConfigCache) tryGetFlagCache gid = do key <- flagCacheKey gid loadConfigCache key writeFlagCache :: HasEnvConfig env => Installed -> ConfigCache -> RIO env () writeFlagCache gid cache = do key <- flagCacheKey gid saveConfigCache key cache successBS, failureBS, unknownBS :: IsString s => s successBS = "success" failureBS = "failure" unknownBS = "unknown" -- | Status of a test suite data TestStatus = TSSuccess | TSFailure | TSUnknown -- | Mark test suite status setTestStatus :: HasEnvConfig env => Path Abs Dir -> TestStatus -> RIO env () setTestStatus dir status = do fp <- testSuccessFile dir writeBinaryFileAtomic fp $ case status of TSSuccess -> successBS TSFailure -> failureBS TSUnknown -> unknownBS -- | Check if the test suite already passed getTestStatus :: HasEnvConfig env => Path Abs Dir -> RIO env TestStatus getTestStatus dir = do fp <- testSuccessFile dir -- we could ensure the file is the right size first, -- but we're not expected an attack from the user's filesystem eres <- tryIO (readFileBinary $ toFilePath fp) pure $ case eres of Right bs | bs == successBS -> TSSuccess | bs == failureBS -> TSFailure _ -> TSUnknown -------------------------------------- -- Precompiled Cache -- -- Idea is simple: cache information about packages built in other snapshots, -- and then for identical matches (same flags, config options, dependencies) -- just copy over the executables and reregister the libraries. -------------------------------------- -- | The key containing information on the given package/configuration -- combination. The key contains a hash of the non-directory configure -- options for quick lookup if there's a match. -- -- We only pay attention to non-directory options. We don't want to avoid a -- cache hit just because it was installed in a different directory. getPrecompiledCacheKey :: HasEnvConfig env => PackageLocationImmutable -> ConfigureOpts -> Bool -- ^ build haddocks -> Set GhcPkgId -- ^ dependencies -> RIO env PrecompiledCacheKey getPrecompiledCacheKey loc copts buildHaddocks installedPackageIDs = do compiler <- view actualCompilerVersionL cabalVersion <- view cabalVersionL -- The goal here is to come up with a string representing the -- package location which is unique. Luckily @TreeKey@s are exactly -- that! treeKey <- getPackageLocationTreeKey loc let packageKey = utf8BuilderToText $ display treeKey platformGhcDir <- platformGhcRelDir -- In Cabal versions 1.22 and later, the configure options contain the -- installed package IDs, which is what we need for a unique hash. -- Unfortunately, earlier Cabals don't have the information, so we must -- supplement it with the installed package IDs directly. -- See issue: https://github.com/commercialhaskell/stack/issues/1103 let input = (coNoDirs copts, installedPackageIDs) optionsHash = Mem.convert $ hashWith SHA256 $ encodeUtf8 $ tshow input return $ precompiledCacheKey platformGhcDir compiler cabalVersion packageKey optionsHash buildHaddocks -- | Write out information about a newly built package writePrecompiledCache :: HasEnvConfig env => BaseConfigOpts -> PackageLocationImmutable -> ConfigureOpts -> Bool -- ^ build haddocks -> Set GhcPkgId -- ^ dependencies -> Installed -- ^ library -> [GhcPkgId] -- ^ sublibraries, in the GhcPkgId format -> Set Text -- ^ executables -> RIO env () writePrecompiledCache baseConfigOpts loc copts buildHaddocks depIDs mghcPkgId sublibs exes = do key <- getPrecompiledCacheKey loc copts buildHaddocks depIDs ec <- view envConfigL let stackRootRelative = makeRelative (view stackRootL ec) mlibpath <- case mghcPkgId of Executable _ -> return Nothing Library _ ipid _ -> Just <$> pathFromPkgId stackRootRelative ipid sublibpaths <- mapM (pathFromPkgId stackRootRelative) sublibs exes' <- forM (Set.toList exes) $ \exe -> do name <- parseRelFile $ T.unpack exe stackRootRelative $ bcoSnapInstallRoot baseConfigOpts </> bindirSuffix </> name let precompiled = PrecompiledCache { pcLibrary = mlibpath , pcSubLibs = sublibpaths , pcExes = exes' } savePrecompiledCache key precompiled -- reuse precompiled cache with haddocks also in case when haddocks are not required when buildHaddocks $ do key' <- getPrecompiledCacheKey loc copts False depIDs savePrecompiledCache key' precompiled where pathFromPkgId stackRootRelative ipid = do ipid' <- parseRelFile $ ghcPkgIdString ipid ++ ".conf" stackRootRelative $ bcoSnapDB baseConfigOpts </> ipid' -- | Check the cache for a precompiled package matching the given -- configuration. readPrecompiledCache :: forall env. HasEnvConfig env => PackageLocationImmutable -- ^ target package -> ConfigureOpts -> Bool -- ^ build haddocks -> Set GhcPkgId -- ^ dependencies -> RIO env (Maybe (PrecompiledCache Abs)) readPrecompiledCache loc copts buildHaddocks depIDs = do key <- getPrecompiledCacheKey loc copts buildHaddocks depIDs mcache <- loadPrecompiledCache key maybe (pure Nothing) (fmap Just . mkAbs) mcache where -- Since commit ed9ccc08f327bad68dd2d09a1851ce0d055c0422, -- pcLibrary paths are stored as relative to the stack -- root. Therefore, we need to prepend the stack root when -- checking that the file exists. For the older cached paths, the -- file will contain an absolute path, which will make `stackRoot -- </>` a no-op. mkAbs :: PrecompiledCache Rel -> RIO env (PrecompiledCache Abs) mkAbs pc0 = do stackRoot <- view stackRootL let mkAbs' = (stackRoot </>) return PrecompiledCache { pcLibrary = mkAbs' <$> pcLibrary pc0 , pcSubLibs = mkAbs' <$> pcSubLibs pc0 , pcExes = mkAbs' <$> pcExes pc0 }
juhp/stack
src/Stack/Build/Cache.hs
bsd-3-clause
14,230
0
15
3,693
2,825
1,424
1,401
266
5
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.TopHandler -- Copyright : (c) The University of Glasgow, 2001-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- Support for catching exceptions raised during top-level computations -- (e.g. @Main.main@, 'Control.Concurrent.forkIO', and foreign exports) -- ----------------------------------------------------------------------------- module GHC.TopHandler ( runMainIO, runIO, runNonIO, reportStackOverflow, reportError, flushStdHandles ) where import Control.Exception import Java.Exception import Data.Maybe import Foreign import Foreign.C import GHC.Base import GHC.Conc hiding (throwTo) import GHC.Real import GHC.IO import GHC.IO.Handle.FD import GHC.IO.Handle import GHC.IO.Exception import GHC.Weak -- | 'runMainIO' is wrapped around 'Main.main' (or whatever main is -- called in the program). It catches otherwise uncaught exceptions, -- and also flushes stdout\/stderr before exiting. runMainIO :: IO a -> IO a runMainIO main = catch main (\(e :: ExitCode) -> do case e of ExitSuccess -> exit 0 ExitFailure n -> exit n return (errorWithoutStackTrace "runMainIO: Exception raised.")) foreign import java unsafe "@static java.lang.System.exit" exit :: Int -> IO () -- | 'runIO' is wrapped around every @foreign export@ and @foreign -- import \"wrapper\"@ to mop up any uncaught exceptions. Thus, the -- result of running 'System.Exit.exitWith' in a foreign-exported -- function is the same as in the main thread: it terminates the -- program. -- runIO :: IO a -> IO a runIO main = main -- | The same as 'runIO', but for non-IO computations. Used for -- wrapping @foreign export@ and @foreign import \"wrapper\"@ when these -- are used to export Haskell functions with non-IO types. -- runNonIO :: a -> IO a runNonIO a = a `seq` return a -- try to flush stdout/stderr, but don't worry if we fail -- (these handles might have errors, and we don't want to go into -- an infinite loop). flushStdHandles :: IO () flushStdHandles = do hFlush stdout `catchAny` \_ -> return () hFlush stderr `catchAny` \_ -> return ()
rahulmutt/ghcvm
libraries/base/GHC/TopHandler.hs
bsd-3-clause
2,499
5
13
478
349
204
145
-1
-1
module Data.Graph.Inductive.Query.TransClos( trc ) where import Data.Graph.Inductive.Graph import Data.Graph.Inductive.Query.DFS (reachable) getNewEdges :: (DynGraph gr) => [LNode a] -> gr a b -> [LEdge ()] getNewEdges vs g = concatMap (\(u,_)->r u g) vs where r = \u g' -> map (\v->(u,v,())) (reachable u g') {-| Finds the transitive closure of a directed graph. Given a graph G=(V,E), its transitive closure is the graph: G* = (V,E*) where E*={(i,j): i,j in V and there is a path from i to j in G} -} trc :: (DynGraph gr) => gr a b -> gr a () trc g = insEdges (getNewEdges ln g) (insNodes ln empty) where ln = labNodes g
scolobb/fgl
Data/Graph/Inductive/Query/TransClos.hs
bsd-3-clause
658
0
12
145
225
124
101
10
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples, BangPatterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Real -- Copyright : (c) The University of Glasgow, 1994-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- The types 'Ratio' and 'Rational', and the classes 'Real', 'Fractional', -- 'Integral', and 'RealFrac'. -- ----------------------------------------------------------------------------- module GHC.Real ( Fractional(..), Integral(..), Ratio(..), Real(..), RealFrac(..), Rational, (%), (^), (^%^), (^^), (^^%^^), denominator, divZeroError, even, fromIntegral, gcd, infinity, integralEnumFrom, integralEnumFromThen, integralEnumFromThenTo, integralEnumFromTo, lcm, notANumber, numerator, numericEnumFrom, numericEnumFromThen, numericEnumFromThenTo, numericEnumFromTo, odd, overflowError, ratioPrec, ratioPrec1, ratioZeroDenominatorError, realToFrac, reduce, showSigned ) where import GHC.Base import GHC.Num import GHC.List import GHC.Enum import GHC.Show import {-# SOURCE #-} GHC.Exception( divZeroException, overflowException, ratioZeroDenomException ) #ifdef OPTIMISE_INTEGER_GCD_LCM # if defined(MIN_VERSION_integer_gmp) import GHC.Integer.GMP.Internals # else # error unsupported OPTIMISE_INTEGER_GCD_LCM configuration # endif #endif infixr 8 ^, ^^ infixl 7 /, `quot`, `rem`, `div`, `mod` infixl 7 % default () -- Double isn't available yet, -- and we shouldn't be using defaults anyway ------------------------------------------------------------------------ -- Divide by zero and arithmetic overflow ------------------------------------------------------------------------ -- We put them here because they are needed relatively early -- in the libraries before the Exception type has been defined yet. {-# NOINLINE divZeroError #-} divZeroError :: a divZeroError = raise# divZeroException {-# NOINLINE ratioZeroDenominatorError #-} ratioZeroDenominatorError :: a ratioZeroDenominatorError = raise# ratioZeroDenomException {-# NOINLINE overflowError #-} overflowError :: a overflowError = raise# overflowException -------------------------------------------------------------- -- The Ratio and Rational types -------------------------------------------------------------- -- | Rational numbers, with numerator and denominator of some 'Integral' type. data Ratio a = !a :% !a deriving (Eq) -- | Arbitrary-precision rational numbers, represented as a ratio of -- two 'Integer' values. A rational number may be constructed using -- the '%' operator. type Rational = Ratio Integer ratioPrec, ratioPrec1 :: Int ratioPrec = 7 -- Precedence of ':%' constructor ratioPrec1 = ratioPrec + 1 infinity, notANumber :: Rational infinity = 1 :% 0 notANumber = 0 :% 0 -- Use :%, not % for Inf/NaN; the latter would -- immediately lead to a runtime error, because it normalises. -- | Forms the ratio of two integral numbers. {-# SPECIALISE (%) :: Integer -> Integer -> Rational #-} (%) :: (Integral a) => a -> a -> Ratio a -- | Extract the numerator of the ratio in reduced form: -- the numerator and denominator have no common factor and the denominator -- is positive. numerator :: Ratio a -> a -- | Extract the denominator of the ratio in reduced form: -- the numerator and denominator have no common factor and the denominator -- is positive. denominator :: Ratio a -> a -- | 'reduce' is a subsidiary function used only in this module. -- It normalises a ratio by dividing both numerator and denominator by -- their greatest common divisor. reduce :: (Integral a) => a -> a -> Ratio a {-# SPECIALISE reduce :: Integer -> Integer -> Rational #-} reduce _ 0 = ratioZeroDenominatorError reduce x y = (x `quot` d) :% (y `quot` d) where d = gcd x y x % y = reduce (x * signum y) (abs y) numerator (x :% _) = x denominator (_ :% y) = y -------------------------------------------------------------- -- Standard numeric classes -------------------------------------------------------------- class (Num a, Ord a) => Real a where -- | the rational equivalent of its real argument with full precision toRational :: a -> Rational -- | Integral numbers, supporting integer division. class (Real a, Enum a) => Integral a where -- | integer division truncated toward zero quot :: a -> a -> a -- | integer remainder, satisfying -- -- > (x `quot` y)*y + (x `rem` y) == x rem :: a -> a -> a -- | integer division truncated toward negative infinity div :: a -> a -> a -- | integer modulus, satisfying -- -- > (x `div` y)*y + (x `mod` y) == x mod :: a -> a -> a -- | simultaneous 'quot' and 'rem' quotRem :: a -> a -> (a,a) -- | simultaneous 'div' and 'mod' divMod :: a -> a -> (a,a) -- | conversion to 'Integer' toInteger :: a -> Integer {-# INLINE quot #-} {-# INLINE rem #-} {-# INLINE div #-} {-# INLINE mod #-} n `quot` d = q where (q,_) = quotRem n d n `rem` d = r where (_,r) = quotRem n d n `div` d = q where (q,_) = divMod n d n `mod` d = r where (_,r) = divMod n d divMod n d = if signum r == negate (signum d) then (q-1, r+d) else qr where qr@(q,r) = quotRem n d -- | Fractional numbers, supporting real division. class (Num a) => Fractional a where {-# MINIMAL fromRational, (recip | (/)) #-} -- | fractional division (/) :: a -> a -> a -- | reciprocal fraction recip :: a -> a -- | Conversion from a 'Rational' (that is @'Ratio' 'Integer'@). -- A floating literal stands for an application of 'fromRational' -- to a value of type 'Rational', so such literals have type -- @('Fractional' a) => a@. fromRational :: Rational -> a {-# INLINE recip #-} {-# INLINE (/) #-} recip x = 1 / x x / y = x * recip y -- | Extracting components of fractions. class (Real a, Fractional a) => RealFrac a where -- | The function 'properFraction' takes a real fractional number @x@ -- and returns a pair @(n,f)@ such that @x = n+f@, and: -- -- * @n@ is an integral number with the same sign as @x@; and -- -- * @f@ is a fraction with the same type and sign as @x@, -- and with absolute value less than @1@. -- -- The default definitions of the 'ceiling', 'floor', 'truncate' -- and 'round' functions are in terms of 'properFraction'. properFraction :: (Integral b) => a -> (b,a) -- | @'truncate' x@ returns the integer nearest @x@ between zero and @x@ truncate :: (Integral b) => a -> b -- | @'round' x@ returns the nearest integer to @x@; -- the even integer if @x@ is equidistant between two integers round :: (Integral b) => a -> b -- | @'ceiling' x@ returns the least integer not less than @x@ ceiling :: (Integral b) => a -> b -- | @'floor' x@ returns the greatest integer not greater than @x@ floor :: (Integral b) => a -> b {-# INLINE truncate #-} truncate x = m where (m,_) = properFraction x round x = let (n,r) = properFraction x m = if r < 0 then n - 1 else n + 1 in case signum (abs r - 0.5) of -1 -> n 0 -> if even n then n else m 1 -> m _ -> error "round default defn: Bad value" ceiling x = if r > 0 then n + 1 else n where (n,r) = properFraction x floor x = if r < 0 then n - 1 else n where (n,r) = properFraction x -- These 'numeric' enumerations come straight from the Report numericEnumFrom :: (Fractional a) => a -> [a] numericEnumFrom n = n `seq` (n : numericEnumFrom (n + 1)) numericEnumFromThen :: (Fractional a) => a -> a -> [a] numericEnumFromThen n m = n `seq` m `seq` (n : numericEnumFromThen m (m+m-n)) numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromTo n m = takeWhile (<= m + 1/2) (numericEnumFrom n) numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFromThenTo e1 e2 e3 = takeWhile predicate (numericEnumFromThen e1 e2) where mid = (e2 - e1) / 2 predicate | e2 >= e1 = (<= e3 + mid) | otherwise = (>= e3 + mid) -------------------------------------------------------------- -- Instances for Int -------------------------------------------------------------- instance Real Int where toRational x = toInteger x :% 1 instance Integral Int where toInteger (I# i) = smallInteger i a `quot` b | b == 0 = divZeroError | b == (-1) && a == minBound = overflowError -- Note [Order of tests] -- in GHC.Int | otherwise = a `quotInt` b a `rem` b | b == 0 = divZeroError -- The quotRem CPU instruction fails for minBound `quotRem` -1, -- but minBound `rem` -1 is well-defined (0). We therefore -- special-case it. | b == (-1) = 0 | otherwise = a `remInt` b a `div` b | b == 0 = divZeroError | b == (-1) && a == minBound = overflowError -- Note [Order of tests] -- in GHC.Int | otherwise = a `divInt` b a `mod` b | b == 0 = divZeroError -- The divMod CPU instruction fails for minBound `divMod` -1, -- but minBound `mod` -1 is well-defined (0). We therefore -- special-case it. | b == (-1) = 0 | otherwise = a `modInt` b a `quotRem` b | b == 0 = divZeroError -- Note [Order of tests] in GHC.Int | b == (-1) && a == minBound = (overflowError, 0) | otherwise = a `quotRemInt` b a `divMod` b | b == 0 = divZeroError -- Note [Order of tests] in GHC.Int | b == (-1) && a == minBound = (overflowError, 0) | otherwise = a `divModInt` b -------------------------------------------------------------- -- Instances for @Word@ -------------------------------------------------------------- instance Real Word where toRational x = toInteger x % 1 instance Integral Word where quot (W# x#) y@(W# y#) | y /= 0 = W# (x# `quotWord#` y#) | otherwise = divZeroError rem (W# x#) y@(W# y#) | y /= 0 = W# (x# `remWord#` y#) | otherwise = divZeroError div (W# x#) y@(W# y#) | y /= 0 = W# (x# `quotWord#` y#) | otherwise = divZeroError mod (W# x#) y@(W# y#) | y /= 0 = W# (x# `remWord#` y#) | otherwise = divZeroError quotRem (W# x#) y@(W# y#) | y /= 0 = case x# `quotRemWord#` y# of (# q, r #) -> (W# q, W# r) | otherwise = divZeroError divMod (W# x#) y@(W# y#) | y /= 0 = (W# (x# `quotWord#` y#), W# (x# `remWord#` y#)) | otherwise = divZeroError toInteger (W# x#) = wordToInteger x# -------------------------------------------------------------- -- Instances for Integer -------------------------------------------------------------- instance Real Integer where toRational x = x :% 1 -- Note [Integer division constant folding] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- Constant folding of quot, rem, div, mod, divMod and quotRem for -- Integer arguments depends crucially on inlining. Constant folding -- rules defined in compiler/prelude/PrelRules.lhs trigger for -- quotInteger, remInteger and so on. So if calls to quot, rem and so on -- were not inlined the rules would not fire. The rules would also not -- fire if calls to quotInteger and so on were inlined, but this does not -- happen because they are all marked with NOINLINE pragma - see documentation -- of integer-gmp or integer-simple. instance Integral Integer where toInteger n = n {-# INLINE quot #-} _ `quot` 0 = divZeroError n `quot` d = n `quotInteger` d {-# INLINE rem #-} _ `rem` 0 = divZeroError n `rem` d = n `remInteger` d {-# INLINE div #-} _ `div` 0 = divZeroError n `div` d = n `divInteger` d {-# INLINE mod #-} _ `mod` 0 = divZeroError n `mod` d = n `modInteger` d {-# INLINE divMod #-} _ `divMod` 0 = divZeroError n `divMod` d = case n `divModInteger` d of (# x, y #) -> (x, y) {-# INLINE quotRem #-} _ `quotRem` 0 = divZeroError n `quotRem` d = case n `quotRemInteger` d of (# q, r #) -> (q, r) -------------------------------------------------------------- -- Instances for @Ratio@ -------------------------------------------------------------- instance (Integral a) => Ord (Ratio a) where {-# SPECIALIZE instance Ord Rational #-} (x:%y) <= (x':%y') = x * y' <= x' * y (x:%y) < (x':%y') = x * y' < x' * y instance (Integral a) => Num (Ratio a) where {-# SPECIALIZE instance Num Rational #-} (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y') (x:%y) - (x':%y') = reduce (x*y' - x'*y) (y*y') (x:%y) * (x':%y') = reduce (x * x') (y * y') negate (x:%y) = (-x) :% y abs (x:%y) = abs x :% y signum (x:%_) = signum x :% 1 fromInteger x = fromInteger x :% 1 {-# RULES "fromRational/id" fromRational = id :: Rational -> Rational #-} instance (Integral a) => Fractional (Ratio a) where {-# SPECIALIZE instance Fractional Rational #-} (x:%y) / (x':%y') = (x*y') % (y*x') recip (0:%_) = ratioZeroDenominatorError recip (x:%y) | x < 0 = negate y :% negate x | otherwise = y :% x fromRational (x:%y) = fromInteger x % fromInteger y instance (Integral a) => Real (Ratio a) where {-# SPECIALIZE instance Real Rational #-} toRational (x:%y) = toInteger x :% toInteger y instance (Integral a) => RealFrac (Ratio a) where {-# SPECIALIZE instance RealFrac Rational #-} properFraction (x:%y) = (fromInteger (toInteger q), r:%y) where (q,r) = quotRem x y instance (Show a) => Show (Ratio a) where {-# SPECIALIZE instance Show Rational #-} showsPrec p (x:%y) = showParen (p > ratioPrec) $ showsPrec ratioPrec1 x . showString " % " . -- H98 report has spaces round the % -- but we removed them [May 04] -- and added them again for consistency with -- Haskell 98 [Sep 08, #1920] showsPrec ratioPrec1 y instance (Integral a) => Enum (Ratio a) where {-# SPECIALIZE instance Enum Rational #-} succ x = x + 1 pred x = x - 1 toEnum n = fromIntegral n :% 1 fromEnum = fromInteger . truncate enumFrom = numericEnumFrom enumFromThen = numericEnumFromThen enumFromTo = numericEnumFromTo enumFromThenTo = numericEnumFromThenTo -------------------------------------------------------------- -- Coercions -------------------------------------------------------------- -- | general coercion from integral types {-# NOINLINE [1] fromIntegral #-} fromIntegral :: (Integral a, Num b) => a -> b fromIntegral = fromInteger . toInteger {-# RULES "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int #-} {-# RULES "fromIntegral/Int->Word" fromIntegral = \(I# x#) -> W# (int2Word# x#) "fromIntegral/Word->Int" fromIntegral = \(W# x#) -> I# (word2Int# x#) "fromIntegral/Word->Word" fromIntegral = id :: Word -> Word #-} -- | general coercion to fractional types realToFrac :: (Real a, Fractional b) => a -> b {-# NOINLINE [1] realToFrac #-} realToFrac = fromRational . toRational -------------------------------------------------------------- -- Overloaded numeric functions -------------------------------------------------------------- -- | Converts a possibly-negative 'Real' value to a string. showSigned :: (Real a) => (a -> ShowS) -- ^ a function that can show unsigned values -> Int -- ^ the precedence of the enclosing context -> a -- ^ the value to show -> ShowS showSigned showPos p x | x < 0 = showParen (p > 6) (showChar '-' . showPos (-x)) | otherwise = showPos x even, odd :: (Integral a) => a -> Bool even n = n `rem` 2 == 0 odd = not . even {-# SPECIALISE even :: Int -> Bool #-} {-# SPECIALISE odd :: Int -> Bool #-} {-# SPECIALISE even :: Integer -> Bool #-} {-# SPECIALISE odd :: Integer -> Bool #-} ------------------------------------------------------- -- | raise a number to a non-negative integral power {-# SPECIALISE [1] (^) :: Integer -> Integer -> Integer, Integer -> Int -> Integer, Int -> Int -> Int #-} {-# INLINABLE [1] (^) #-} -- See Note [Inlining (^)] (^) :: (Num a, Integral b) => a -> b -> a x0 ^ y0 | y0 < 0 = error "Negative exponent" | y0 == 0 = 1 | otherwise = f x0 y0 where -- f : x0 ^ y0 = x ^ y f x y | even y = f (x * x) (y `quot` 2) | y == 1 = x | otherwise = g (x * x) ((y - 1) `quot` 2) x -- g : x0 ^ y0 = (x ^ y) * z g x y z | even y = g (x * x) (y `quot` 2) z | y == 1 = x * z | otherwise = g (x * x) ((y - 1) `quot` 2) (x * z) -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a {-# INLINABLE [1] (^^) #-} -- See Note [Inlining (^) x ^^ n = if n >= 0 then x^n else recip (x^(negate n)) {- Note [Inlining (^) ~~~~~~~~~~~~~~~~~~~~~ The INLINABLE pragma allows (^) to be specialised at its call sites. If it is called repeatedly at the same type, that can make a huge difference, because of those constants which can be repeatedly calculated. Currently the fromInteger calls are not floated because we get \d1 d2 x y -> blah after the gentle round of simplification. -} {- Rules for powers with known small exponent see #5237 For small exponents, (^) is inefficient compared to manually expanding the multiplication tree. Here, rules for the most common exponent types are given. The range of exponents for which rules are given is quite arbitrary and kept small to not unduly increase the number of rules. 0 and 1 are excluded based on the assumption that nobody would write x^0 or x^1 in code and the cases where an exponent could be statically resolved to 0 or 1 are rare. It might be desirable to have corresponding rules also for exponents of other types, in particular Word, but we can't have those rules here (importing GHC.Word or GHC.Int would create a cyclic module dependency), and it's doubtful they would fire, since the exponents of other types tend to get floated out before the rule has a chance to fire. Also desirable would be rules for (^^), but I haven't managed to get those to fire. Note: Trying to save multiplications by sharing the square for exponents 4 and 5 does not save time, indeed, for Double, it is up to twice slower, so the rules contain flat sequences of multiplications. -} {-# RULES "^2/Int" forall x. x ^ (2 :: Int) = let u = x in u*u "^3/Int" forall x. x ^ (3 :: Int) = let u = x in u*u*u "^4/Int" forall x. x ^ (4 :: Int) = let u = x in u*u*u*u "^5/Int" forall x. x ^ (5 :: Int) = let u = x in u*u*u*u*u "^2/Integer" forall x. x ^ (2 :: Integer) = let u = x in u*u "^3/Integer" forall x. x ^ (3 :: Integer) = let u = x in u*u*u "^4/Integer" forall x. x ^ (4 :: Integer) = let u = x in u*u*u*u "^5/Integer" forall x. x ^ (5 :: Integer) = let u = x in u*u*u*u*u #-} ------------------------------------------------------- -- Special power functions for Rational -- -- see #4337 -- -- Rationale: -- For a legitimate Rational (n :% d), the numerator and denominator are -- coprime, i.e. they have no common prime factor. -- Therefore all powers (n ^ a) and (d ^ b) are also coprime, so it is -- not necessary to compute the greatest common divisor, which would be -- done in the default implementation at each multiplication step. -- Since exponentiation quickly leads to very large numbers and -- calculation of gcds is generally very slow for large numbers, -- avoiding the gcd leads to an order of magnitude speedup relatively -- soon (and an asymptotic improvement overall). -- -- Note: -- We cannot use these functions for general Ratio a because that would -- change results in a multitude of cases. -- The cause is that if a and b are coprime, their remainders by any -- positive modulus generally aren't, so in the default implementation -- reduction occurs. -- -- Example: -- (17 % 3) ^ 3 :: Ratio Word8 -- Default: -- (17 % 3) ^ 3 = ((17 % 3) ^ 2) * (17 % 3) -- = ((289 `mod` 256) % 9) * (17 % 3) -- = (33 % 9) * (17 % 3) -- = (11 % 3) * (17 % 3) -- = (187 % 9) -- But: -- ((17^3) `mod` 256) % (3^3) = (4913 `mod` 256) % 27 -- = 49 % 27 -- -- TODO: -- Find out whether special-casing for numerator, denominator or -- exponent = 1 (or -1, where that may apply) gains something. -- Special version of (^) for Rational base {-# RULES "(^)/Rational" (^) = (^%^) #-} (^%^) :: Integral a => Rational -> a -> Rational (n :% d) ^%^ e | e < 0 = error "Negative exponent" | e == 0 = 1 :% 1 | otherwise = (n ^ e) :% (d ^ e) -- Special version of (^^) for Rational base {-# RULES "(^^)/Rational" (^^) = (^^%^^) #-} (^^%^^) :: Integral a => Rational -> a -> Rational (n :% d) ^^%^^ e | e > 0 = (n ^ e) :% (d ^ e) | e == 0 = 1 :% 1 | n > 0 = (d ^ (negate e)) :% (n ^ (negate e)) | n == 0 = ratioZeroDenominatorError | otherwise = let nn = d ^ (negate e) dd = (negate n) ^ (negate e) in if even e then (nn :% dd) else (negate nn :% dd) ------------------------------------------------------- -- | @'gcd' x y@ is the non-negative factor of both @x@ and @y@ of which -- every common factor of @x@ and @y@ is also a factor; for example -- @'gcd' 4 2 = 2@, @'gcd' (-4) 6 = 2@, @'gcd' 0 4@ = @4@. @'gcd' 0 0@ = @0@. -- (That is, the common divisor that is \"greatest\" in the divisibility -- preordering.) -- -- Note: Since for signed fixed-width integer types, @'abs' 'minBound' < 0@, -- the result may be negative if one of the arguments is @'minBound'@ (and -- necessarily is if the other is @0@ or @'minBound'@) for such types. gcd :: (Integral a) => a -> a -> a {-# NOINLINE [1] gcd #-} gcd x y = gcd' (abs x) (abs y) where gcd' a 0 = a gcd' a b = gcd' b (a `rem` b) -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide. lcm :: (Integral a) => a -> a -> a {-# SPECIALISE lcm :: Int -> Int -> Int #-} {-# NOINLINE [1] lcm #-} lcm _ 0 = 0 lcm 0 _ = 0 lcm x y = abs ((x `quot` (gcd x y)) * y) #ifdef OPTIMISE_INTEGER_GCD_LCM {-# RULES "gcd/Int->Int->Int" gcd = gcdInt' "gcd/Integer->Integer->Integer" gcd = gcdInteger "lcm/Integer->Integer->Integer" lcm = lcmInteger #-} gcdInt' :: Int -> Int -> Int gcdInt' (I# x) (I# y) = I# (gcdInt x y) #if MIN_VERSION_integer_gmp(1,0,0) {-# RULES "gcd/Word->Word->Word" gcd = gcdWord' #-} gcdWord' :: Word -> Word -> Word gcdWord' (W# x) (W# y) = W# (gcdWord x y) #endif #endif integralEnumFrom :: (Integral a, Bounded a) => a -> [a] integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)] integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a] integralEnumFromThen n1 n2 | i_n2 >= i_n1 = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)] | otherwise = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)] where i_n1 = toInteger n1 i_n2 = toInteger n2 integralEnumFromTo :: Integral a => a -> a -> [a] integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m] integralEnumFromThenTo :: Integral a => a -> a -> a -> [a] integralEnumFromThenTo n1 n2 m = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]
green-haskell/ghc
libraries/base/GHC/Real.hs
bsd-3-clause
25,755
0
13
7,758
5,230
2,881
2,349
330
2
{-| Module : Idris.Elab.Rewrite Description : Code to elaborate rewrite rules. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE PatternGuards, ViewPatterns #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.Elab.Rewrite(elabRewrite, elabRewriteLemma) where import Idris.AbsSyntax import Idris.AbsSyntaxTree import Idris.Delaborate import Idris.Error import Idris.Core.TT import Idris.Core.Elaborate import Idris.Core.Evaluate import Idris.Docstrings import Control.Monad import Control.Monad.State.Strict import Data.List import Debug.Trace elabRewrite :: (PTerm -> ElabD ()) -> IState -> FC -> Maybe Name -> PTerm -> PTerm -> Maybe PTerm -> ElabD () -- Old version, no rewrite rule given {- elabRewrite elab ist fc Nothing rule sc newg = do attack tyn <- getNameFrom (sMN 0 "rty") claim tyn RType valn <- getNameFrom (sMN 0 "rval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "_rewrite_rule") letbind letn (Var tyn) (Var valn) focus valn elab rule compute g <- goal rewrite (Var letn) g' <- goal when (g == g') $ lift $ tfail (NoRewriting g) case newg of Nothing -> elab sc Just t -> doEquiv elab fc t sc solve -} elabRewrite elab ist fc substfn_in rule sc_in newg = do attack sc <- case newg of Nothing -> return sc_in Just t -> do letn <- getNameFrom (sMN 0 "rewrite_result") return $ PLet fc letn fc t sc_in (PRef fc [] letn) tyn <- getNameFrom (sMN 0 "rty") claim tyn RType valn <- getNameFrom (sMN 0 "rval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "_rewrite_rule") letbind letn (Var tyn) (Var valn) focus valn elab rule compute g <- goal (tmv, rule_in) <- get_type_val (Var letn) env <- get_env let ttrule = normalise (tt_ctxt ist) env rule_in rname <- unique_hole (sMN 0 "replaced") case unApply ttrule of (P _ (UN q) _, [lt, rt, l, r]) | q == txt "=" -> do substfn <- findSubstFn substfn_in ist lt rt let pred_tt = mkP (P Bound rname rt) l r g when (g == pred_tt) $ lift $ tfail (NoRewriting l r g) let pred = PLam fc rname fc Placeholder (delab ist pred_tt) let rewrite = stripImpls $ addImplBound ist (map fst env) (PApp fc (PRef fc [] substfn) [pexp pred, pexp rule, pexp sc]) -- trace ("LHS: " ++ show l ++ "\n" ++ -- "RHS: " ++ show r ++ "\n" ++ -- "REWRITE: " ++ show rewrite ++ "\n" ++ -- "GOAL: " ++ show (delab ist g)) $ elab rewrite solve _ -> lift $ tfail (NotEquality tmv ttrule) where mkP :: TT Name -> -- Left term, top level TT Name -> TT Name -> TT Name -> TT Name mkP lt l r ty | l == ty = lt mkP lt l r (App s f a) = let f' = if (r /= f) then mkP lt l r f else f a' = if (r /= a) then mkP lt l r a else a in App s f' a' mkP lt l r (Bind n b sc) = let b' = mkPB b sc' = if (r /= sc) then mkP lt l r sc else sc in Bind n b' sc' where mkPB (Let t v) = let t' = if (r /= t) then mkP lt l r t else t v' = if (r /= v) then mkP lt l r v else v in Let t' v' mkPB b = let ty = binderTy b ty' = if (r /= ty) then mkP lt l r ty else ty in b { binderTy = ty' } mkP lt l r x = x -- If we're rewriting a dependent type, the rewrite type the rewrite -- may break the indices. -- So, for any function argument which can be determined by looking -- at the indices (i.e. any constructor guarded elsewhere in the type) -- replace it with a _. e.g. (++) a n m xs ys becomes (++) _ _ _ xs ys -- because a,n, and m are constructor guarded later in the type of ++ -- FIXME: Currently this is an approximation which just strips -- implicits. This is perfectly fine for most cases, but not as -- general as it should be. stripImpls tm = mapPT phApps tm phApps (PApp fc f args) = PApp fc f (map removeImp args) where removeImp tm@(PImp{}) = tm { getTm = Placeholder } removeImp t = t phApps tm = tm findSubstFn :: Maybe Name -> IState -> Type -> Type -> ElabD Name findSubstFn Nothing ist lt rt | lt == rt = return (sUN "rewrite__impl") -- TODO: Find correct rewriting lemma, if it exists, and tidy up this -- error | (P _ lcon _, _) <- unApply lt, (P _ rcon _, _) <- unApply rt, lcon == rcon = case lookupTyExact (rewrite_name lcon) (tt_ctxt ist) of Just _ -> return (rewrite_name lcon) Nothing -> rewriteFail lt rt | otherwise = rewriteFail lt rt where rewriteFail lt rt = lift . tfail . Msg $ "Can't rewrite heterogeneous equality on types " ++ show (delab ist lt) ++ " and " ++ show (delab ist rt) findSubstFn (Just substfn_in) ist lt rt = case lookupTyName substfn_in (tt_ctxt ist) of [(n, t)] -> return n [] -> lift . tfail . NoSuchVariable $ substfn_in more -> lift . tfail . CantResolveAlts $ map fst more rewrite_name :: Name -> Name rewrite_name n = sMN 0 (show n ++ "_rewrite_lemma") data ParamInfo = Index | Param | ImplicitIndex | ImplicitParam deriving Show getParamInfo :: Type -> [PArg] -> Int -> [Int] -> [ParamInfo] -- Skip the top level implicits, we just need the explicit ones getParamInfo (Bind n (Pi _ _ _) sc) (PExp{} : is) i ps | i `elem` ps = Param : getParamInfo sc is (i + 1) ps | otherwise = Index : getParamInfo sc is (i + 1) ps getParamInfo (Bind n (Pi _ _ _) sc) (_ : is) i ps | i `elem` ps = ImplicitParam : getParamInfo sc is (i + 1) ps | otherwise = ImplicitIndex : getParamInfo sc is (i + 1) ps getParamInfo _ _ _ _ = [] isParam Index = False isParam Param = True isParam ImplicitIndex = False isParam ImplicitParam = True -- | Make a rewriting lemma for the given type constructor. -- -- If it fails, fail silently (it may well fail for some very complex -- types. We can fix this later, for now this gives us a lot more -- working rewrites...) elabRewriteLemma :: ElabInfo -> Name -> Type -> Idris () elabRewriteLemma info n cty_in = do ist <- getIState let cty = normalise (tt_ctxt ist) [] cty_in let rewrite_lem = rewrite_name n case lookupCtxtExact n (idris_datatypes ist) of Nothing -> fail $ "Can't happen, elabRewriteLemma for " ++ show n Just ti -> do let imps = case lookupCtxtExact n (idris_implicits ist) of Nothing -> repeat (pexp Placeholder) Just is -> is let pinfo = getParamInfo cty imps 0 (param_pos ti) if all isParam pinfo then return () -- no need for a lemma, = will be homogeneous else idrisCatch (mkLemma info rewrite_lem n pinfo cty) (\_ -> return ()) mkLemma :: ElabInfo -> Name -> Name -> [ParamInfo] -> Type -> Idris () mkLemma info lemma tcon ps ty = do ist <- getIState let leftty = mkTy tcon ps (namesFrom "p" 0) (namesFrom "left" 0) rightty = mkTy tcon ps (namesFrom "p" 0) (namesFrom "right" 0) predty = bindIdxs ist ps ty (namesFrom "pred" 0) $ PPi expl (sMN 0 "rep") fc (mkTy tcon ps (namesFrom "p" 0) (namesFrom "pred" 0)) (PType fc) let xarg = sMN 0 "x" let yarg = sMN 0 "y" let parg = sMN 0 "P" let eq = sMN 0 "eq" let prop = sMN 0 "prop" let lemTy = PPi impl xarg fc leftty $ PPi impl yarg fc rightty $ PPi expl parg fc predty $ PPi expl eq fc (PApp fc (PRef fc [] (sUN "=")) [pexp (PRef fc [] xarg), pexp (PRef fc [] yarg)]) $ PPi expl prop fc (PApp fc (PRef fc [] parg) [pexp (PRef fc [] yarg)]) $ PApp fc (PRef fc [] parg) [pexp (PRef fc [] xarg)] let lemLHS = PApp fc (PRef fc [] lemma) [pexp (PRef fc [] parg), pexp (PRef fc [] (sUN "Refl")), pexp (PRef fc [] prop)] let lemRHS = PRef fc [] prop -- Elaborate the type of the lemma rec_elabDecl info EAll info (PTy emptyDocstring [] defaultSyntax fc [] lemma fc lemTy) -- Elaborate the definition rec_elabDecl info EAll info (PClauses fc [] lemma [PClause fc lemma lemLHS [] lemRHS []]) where fc = emptyFC namesFrom x i = sMN i x : namesFrom x (i + 1) mkTy fn pinfo ps is = PApp fc (PRef fc [] fn) (mkArgs pinfo ps is) mkArgs [] ps is = [] mkArgs (Param : pinfo) (p : ps) is = pexp (PRef fc [] p) : mkArgs pinfo ps is mkArgs (Index : pinfo) ps (i : is) = pexp (PRef fc [] i) : mkArgs pinfo ps is mkArgs (ImplicitParam : pinfo) (p : ps) is = mkArgs pinfo ps is mkArgs (ImplicitIndex : pinfo) ps (i : is) = mkArgs pinfo ps is mkArgs _ _ _ = [] bindIdxs ist [] ty is tm = tm bindIdxs ist (Param : pinfo) (Bind n (Pi _ ty _) sc) is tm = bindIdxs ist pinfo (instantiate (P Bound n ty) sc) is tm bindIdxs ist (Index : pinfo) (Bind n (Pi _ ty _) sc) (i : is) tm = PPi forall_imp i fc (delab ist ty) (bindIdxs ist pinfo (instantiate (P Bound n ty) sc) is tm) bindIdxs ist (ImplicitParam : pinfo) (Bind n (Pi _ ty _) sc) is tm = bindIdxs ist pinfo (instantiate (P Bound n ty) sc) is tm bindIdxs ist (ImplicitIndex : pinfo) (Bind n (Pi _ ty _) sc) (i : is) tm = bindIdxs ist pinfo (instantiate (P Bound n ty) sc) is tm bindIdxs _ _ _ _ tm = tm
tpsinnem/Idris-dev
src/Idris/Elab/Rewrite.hs
bsd-3-clause
10,999
0
22
4,360
3,435
1,700
1,735
185
15
{-# language GeneralizedNewtypeDeriving, ScopedTypeVariables, OverloadedStrings #-} -- | Module for human readable text. module Base.Prose ( Prose(..), standardFontColor, headerFontColor, colorizeProse, capitalizeProse, getText, getString, nullProse, lengthProse, p, pVerbatim, pv, unP, pFile, zeroSpaceChar, watchChar, batteryChar, switchChar, sumSignChar, brackets, ) where import Data.Monoid import Data.Char (chr) import Data.Text as Text hiding (all) import Control.Arrow import Text.Logging import System.Directory import Graphics.Qt import Utils standardFontColor :: Color = QtColor 70 210 245 255 headerFontColor :: Color = QtColor 36 110 128 255 -- | Type for human readable text. -- (utf8 encoded) newtype Prose = Prose [(Color, Text)] deriving (Show, Monoid) colorizeProse :: Color -> Prose -> Prose colorizeProse color p = Prose $ return $ tuple color $ getText p -- | Returns the content of a Prose as a Text. getText :: Prose -> Text getText (Prose list) = Prelude.foldr (append) "" $ fmap snd list getString :: Prose -> String getString = getText >>> unpack capitalizeProse :: Prose -> Prose capitalizeProse (Prose list) = Prose $ fmap (second toUpper) list nullProse :: Prose -> Bool nullProse (Prose snippets) = all Text.null $ fmap snd snippets lengthProse :: Prose -> Int lengthProse (Prose snippets) = sum $ fmap (Text.length . snd) snippets -- | Converts haskell Strings to human readable text. -- Will be used for translations in the future. p :: String -> Prose p = pVerbatim -- | Convert any (ASCII-) string to Prose without doing any translation. pVerbatim :: String -> Prose pVerbatim x = Prose [(standardFontColor, pack x)] -- | shortcut for pVerbatim pv = pVerbatim -- | inverse of p unP :: Prose -> String unP = getString -- | Read files and return their content as Prose. -- Should be replaced with something that supports -- multiple languages of files. -- (Needs to be separated from p, because it has to return multiple lines.) pFile :: FilePath -> IO [Prose] pFile file = do exists <- doesFileExist file if exists then fmap (Prose . return . tuple standardFontColor) . Text.lines <$> readUnicodeText file else do logg Error ("file not found: " <> file) return $ pure (p "file not found: " <> pv file) -- | special characters zeroSpaceChar :: Char zeroSpaceChar = chr 8203 watchChar :: Char watchChar = chr 8986 batteryChar :: Char batteryChar = chr 128267 switchChar :: Char switchChar = chr 128306 sumSignChar :: Char sumSignChar = chr 8721 -- | put brackets around a string brackets :: Prose -> Prose brackets x = pVerbatim "[" <> x <> pVerbatim "]"
geocurnoff/nikki
src/Base/Prose.hs
lgpl-3.0
2,763
0
14
595
696
380
316
79
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------- -- Autogenerated by Thrift -- -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- module Module_Consts where import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..), Eq, Show, Ord, concat, error, fromIntegral, fromEnum, length, map, maybe, not, null, otherwise, return, show, toEnum, enumFromTo, Bounded, minBound, maxBound, (.), (&&), (||), (==), (++), ($), (-), (>>=), (>>)) import Control.Applicative (ZipList(..), (<*>)) import Control.Exception import Control.Monad ( liftM, ap, when ) import Data.ByteString.Lazy (ByteString) import Data.Functor ( (<$>) ) import Data.Hashable import Data.Int import Data.Maybe (catMaybes) import Data.Text.Lazy ( Text ) import Data.Text.Lazy.Encoding ( decodeUtf8, encodeUtf8 ) import qualified Data.Text.Lazy as T import Data.Typeable ( Typeable ) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector import Test.QuickCheck.Arbitrary ( Arbitrary(..) ) import Test.QuickCheck ( elements ) import Thrift hiding (ProtocolExnType(..)) import qualified Thrift (ProtocolExnType(..)) import Thrift.Types import Thrift.Arbitraries import qualified Includes_Types import Module_Types
raphaelamorim/fbthrift
thrift/compiler/test/fixtures/includes/gen-hs/Module_Consts.hs
apache-2.0
1,815
0
6
339
377
262
115
37
0
module A4 where --Any type/data constructor name declared in this module can be renamed. --Any type variable can be renamed. --Rename type Constructor 'BTree' to 'MyBTree' data BTree a = Empty | T a (BTree a) (BTree a) deriving Show buildtree :: Ord a => [a] -> BTree a buildtree [] = Empty buildtree (x:xs) = insert x (buildtree xs) insert :: Ord a => a -> BTree a -> BTree a insert val (T val (T val Empty Empty) (T val1 Empty Empty)) = T val Empty (result Empty) where result Empty = T val Empty Empty insert val (T tval left right) | val > tval = T tval left (insert val right) | otherwise = T tval (insert val left) right newPat_1 = Empty main :: BTree Int main = buildtree [3,1,2]
kmate/HaRe
old/testing/asPatterns/A4.hs
bsd-3-clause
736
0
9
184
292
148
144
16
1
{-# LANGUAGE Safe #-} {-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : System.Environment -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : portable -- -- Miscellaneous information about the system environment. -- ----------------------------------------------------------------------------- module System.Environment ( getArgs, getProgName, getExecutablePath, getEnv, lookupEnv, setEnv, unsetEnv, withArgs, withProgName, getEnvironment, ) where import Foreign import Foreign.C import System.IO.Error (mkIOError) import Control.Exception.Base (bracket_, throwIO) #if defined(mingw32_HOST_OS) import Control.Exception.Base (bracket) #endif -- import GHC.IO import GHC.IO.Exception import qualified GHC.Foreign as GHC import Control.Monad #if defined(mingw32_HOST_OS) import GHC.IO.Encoding (argvEncoding) import GHC.Windows #else import GHC.IO.Encoding (getFileSystemEncoding, argvEncoding) import System.Posix.Internals (withFilePath) #endif import System.Environment.ExecutablePath #if defined(mingw32_HOST_OS) # if defined(i386_HOST_ARCH) # define WINDOWS_CCONV stdcall # elif defined(x86_64_HOST_ARCH) # define WINDOWS_CCONV ccall # else # error Unknown mingw32 arch # endif #endif #include "HsBaseConfig.h" -- --------------------------------------------------------------------------- -- getArgs, getProgName, getEnv -- | Computation 'getArgs' returns a list of the program's command -- line arguments (not including the program name). getArgs :: IO [String] getArgs = alloca $ \ p_argc -> alloca $ \ p_argv -> do getProgArgv p_argc p_argv p <- fromIntegral `liftM` peek p_argc argv <- peek p_argv enc <- argvEncoding peekArray (p - 1) (advancePtr argv 1) >>= mapM (GHC.peekCString enc) foreign import ccall unsafe "getProgArgv" getProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO () {-| Computation 'getProgName' returns the name of the program as it was invoked. However, this is hard-to-impossible to implement on some non-Unix OSes, so instead, for maximum portability, we just return the leafname of the program as invoked. Even then there are some differences between platforms: on Windows, for example, a program invoked as foo is probably really @FOO.EXE@, and that is what 'getProgName' will return. -} getProgName :: IO String -- Ignore the arguments to hs_init on Windows for the sake of Unicode compat getProgName = alloca $ \ p_argc -> alloca $ \ p_argv -> do getProgArgv p_argc p_argv argv <- peek p_argv unpackProgName argv unpackProgName :: Ptr (Ptr CChar) -> IO String -- argv[0] unpackProgName argv = do enc <- argvEncoding s <- peekElemOff argv 0 >>= GHC.peekCString enc return (basename s) basename :: FilePath -> FilePath basename f = go f f where go acc [] = acc go acc (x:xs) | isPathSeparator x = go xs xs | otherwise = go acc xs isPathSeparator :: Char -> Bool isPathSeparator '/' = True #if defined(mingw32_HOST_OS) isPathSeparator '\\' = True #endif isPathSeparator _ = False -- | Computation 'getEnv' @var@ returns the value -- of the environment variable @var@. For the inverse, the -- `System.Environment.setEnv` function can be used. -- -- This computation may fail with: -- -- * 'System.IO.Error.isDoesNotExistError' if the environment variable -- does not exist. getEnv :: String -> IO String getEnv name = lookupEnv name >>= maybe handleError return where #if defined(mingw32_HOST_OS) handleError = do err <- c_GetLastError if err == eRROR_ENVVAR_NOT_FOUND then ioe_missingEnvVar name else throwGetLastError "getEnv" eRROR_ENVVAR_NOT_FOUND :: DWORD eRROR_ENVVAR_NOT_FOUND = 203 foreign import WINDOWS_CCONV unsafe "windows.h GetLastError" c_GetLastError:: IO DWORD #else handleError = ioe_missingEnvVar name #endif -- | Return the value of the environment variable @var@, or @Nothing@ if -- there is no such value. -- -- For POSIX users, this is equivalent to 'System.Posix.Env.getEnv'. -- -- @since 4.6.0.0 lookupEnv :: String -> IO (Maybe String) #if defined(mingw32_HOST_OS) lookupEnv name = withCWString name $ \s -> try_size s 256 where try_size s size = allocaArray (fromIntegral size) $ \p_value -> do res <- c_GetEnvironmentVariable s p_value size case res of 0 -> return Nothing _ | res > size -> try_size s res -- Rare: size increased between calls to GetEnvironmentVariable | otherwise -> peekCWString p_value >>= return . Just foreign import WINDOWS_CCONV unsafe "windows.h GetEnvironmentVariableW" c_GetEnvironmentVariable :: LPWSTR -> LPWSTR -> DWORD -> IO DWORD #else lookupEnv name = withCString name $ \s -> do litstring <- c_getenv s if litstring /= nullPtr then do enc <- getFileSystemEncoding result <- GHC.peekCString enc litstring return $ Just result else return Nothing foreign import ccall unsafe "getenv" c_getenv :: CString -> IO (Ptr CChar) #endif ioe_missingEnvVar :: String -> IO a ioe_missingEnvVar name = ioException (IOError Nothing NoSuchThing "getEnv" "no environment variable" Nothing (Just name)) -- | @setEnv name value@ sets the specified environment variable to @value@. -- -- Early versions of this function operated under the mistaken belief that -- setting an environment variable to the /empty string/ on Windows removes -- that environment variable from the environment. For the sake of -- compatibility, it adopted that behavior on POSIX. In particular -- -- @ -- setEnv name \"\" -- @ -- -- has the same effect as -- -- @ -- `unsetEnv` name -- @ -- -- If you'd like to be able to set environment variables to blank strings, -- use `System.Environment.Blank.setEnv`. -- -- Throws `Control.Exception.IOException` if @name@ is the empty string or -- contains an equals sign. -- -- @since 4.7.0.0 setEnv :: String -> String -> IO () setEnv key_ value_ | null key = throwIO (mkIOError InvalidArgument "setEnv" Nothing Nothing) | '=' `elem` key = throwIO (mkIOError InvalidArgument "setEnv" Nothing Nothing) | null value = unsetEnv key | otherwise = setEnv_ key value where key = takeWhile (/= '\NUL') key_ value = takeWhile (/= '\NUL') value_ setEnv_ :: String -> String -> IO () #if defined(mingw32_HOST_OS) setEnv_ key value = withCWString key $ \k -> withCWString value $ \v -> do success <- c_SetEnvironmentVariable k v unless success (throwGetLastError "setEnv") foreign import WINDOWS_CCONV unsafe "windows.h SetEnvironmentVariableW" c_SetEnvironmentVariable :: LPTSTR -> LPTSTR -> IO Bool #else -- NOTE: The 'setenv()' function is not available on all systems, hence we use -- 'putenv()'. This leaks memory, but so do common implementations of -- 'setenv()' (AFAIK). setEnv_ k v = putEnv (k ++ "=" ++ v) putEnv :: String -> IO () putEnv keyvalue = do s <- getFileSystemEncoding >>= (`GHC.newCString` keyvalue) -- IMPORTANT: Do not free `s` after calling putenv! -- -- According to SUSv2, the string passed to putenv becomes part of the -- environment. throwErrnoIf_ (/= 0) "putenv" (c_putenv s) foreign import ccall unsafe "putenv" c_putenv :: CString -> IO CInt #endif -- | @unsetEnv name@ removes the specified environment variable from the -- environment of the current process. -- -- Throws `Control.Exception.IOException` if @name@ is the empty string or -- contains an equals sign. -- -- @since 4.7.0.0 unsetEnv :: String -> IO () #if defined(mingw32_HOST_OS) unsetEnv key = withCWString key $ \k -> do success <- c_SetEnvironmentVariable k nullPtr unless success $ do -- We consider unsetting an environment variable that does not exist not as -- an error, hence we ignore eRROR_ENVVAR_NOT_FOUND. err <- c_GetLastError unless (err == eRROR_ENVVAR_NOT_FOUND) $ do throwGetLastError "unsetEnv" #else #if defined(HAVE_UNSETENV) unsetEnv key = withFilePath key (throwErrnoIf_ (/= 0) "unsetEnv" . c_unsetenv) foreign import ccall unsafe "__hsbase_unsetenv" c_unsetenv :: CString -> IO CInt #else unsetEnv key = setEnv_ key "" #endif #endif {-| 'withArgs' @args act@ - while executing action @act@, have 'getArgs' return @args@. -} withArgs :: [String] -> IO a -> IO a withArgs xs act = do p <- System.Environment.getProgName withArgv (p:xs) act {-| 'withProgName' @name act@ - while executing action @act@, have 'getProgName' return @name@. -} withProgName :: String -> IO a -> IO a withProgName nm act = do xs <- System.Environment.getArgs withArgv (nm:xs) act -- Worker routine which marshals and replaces an argv vector for -- the duration of an action. withArgv :: [String] -> IO a -> IO a withArgv = withProgArgv withProgArgv :: [String] -> IO a -> IO a withProgArgv new_args act = do pName <- System.Environment.getProgName existing_args <- System.Environment.getArgs bracket_ (setProgArgv new_args) (setProgArgv (pName:existing_args)) act setProgArgv :: [String] -> IO () setProgArgv argv = do enc <- argvEncoding GHC.withCStringsLen enc argv $ \len css -> c_setProgArgv (fromIntegral len) css -- setProgArgv copies the arguments foreign import ccall unsafe "setProgArgv" c_setProgArgv :: CInt -> Ptr CString -> IO () -- |'getEnvironment' retrieves the entire environment as a -- list of @(key,value)@ pairs. -- -- If an environment entry does not contain an @\'=\'@ character, -- the @key@ is the whole entry and the @value@ is the empty string. getEnvironment :: IO [(String, String)] #if defined(mingw32_HOST_OS) getEnvironment = bracket c_GetEnvironmentStrings c_FreeEnvironmentStrings $ \pBlock -> if pBlock == nullPtr then return [] else go pBlock where go pBlock = do -- The block is terminated by a null byte where there -- should be an environment variable of the form X=Y c <- peek pBlock if c == 0 then return [] else do -- Seek the next pair (or terminating null): pBlock' <- seekNull pBlock False -- We now know the length in bytes, but ignore it when -- getting the actual String: str <- peekCWString pBlock fmap (divvy str :) $ go pBlock' -- Returns pointer to the byte *after* the next null seekNull pBlock done = do let pBlock' = pBlock `plusPtr` sizeOf (undefined :: CWchar) if done then return pBlock' else do c <- peek pBlock' seekNull pBlock' (c == (0 :: Word8 )) foreign import WINDOWS_CCONV unsafe "windows.h GetEnvironmentStringsW" c_GetEnvironmentStrings :: IO (Ptr CWchar) foreign import WINDOWS_CCONV unsafe "windows.h FreeEnvironmentStringsW" c_FreeEnvironmentStrings :: Ptr CWchar -> IO Bool #else getEnvironment = do pBlock <- getEnvBlock if pBlock == nullPtr then return [] else do enc <- getFileSystemEncoding stuff <- peekArray0 nullPtr pBlock >>= mapM (GHC.peekCString enc) return (map divvy stuff) foreign import ccall unsafe "__hscore_environ" getEnvBlock :: IO (Ptr CString) #endif divvy :: String -> (String, String) divvy str = case break (=='=') str of (xs,[]) -> (xs,[]) -- don't barf (like Posix.getEnvironment) (name,_:value) -> (name,value)
sdiehl/ghc
libraries/base/System/Environment.hs
bsd-3-clause
11,545
127
16
2,351
1,899
1,050
849
129
3
{-# LANGUAGE PolyKinds, DataKinds, TypeFamilies, GADTs, RankNTypes #-} module T9144 where import Data.Proxy import GHC.TypeLits data family Sing (a :: k) data SomeSing :: KProxy k -> * where SomeSing :: forall (a :: k). Sing a -> SomeSing ('KProxy :: KProxy k) class kproxy ~ 'KProxy => SingKind (kproxy :: KProxy k) where fromSing :: forall (a :: k). Sing a -> DemoteRep ('KProxy :: KProxy k) toSing :: DemoteRep ('KProxy :: KProxy k) -> SomeSing ('KProxy :: KProxy k) type family DemoteRep (kproxy :: KProxy k) :: * data Foo = Bar Nat data FooTerm = BarTerm Integer data instance Sing (x :: Foo) where SBar :: Sing n -> Sing (Bar n) type instance DemoteRep ('KProxy :: KProxy Nat) = Integer type instance DemoteRep ('KProxy :: KProxy Foo) = FooTerm instance SingKind ('KProxy :: KProxy Nat) where fromSing = undefined toSing = undefined instance SingKind ('KProxy :: KProxy Foo) where fromSing (SBar n) = BarTerm (fromSing n) toSing n = case toSing n of SomeSing n' -> SomeSing (SBar n')
urbanslug/ghc
testsuite/tests/polykinds/T9144.hs
bsd-3-clause
1,017
8
12
200
406
215
191
23
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} module SaveFormat where import Building import Debug.Trace import Data.ByteString (ByteString) import Data.ByteString.Base64 import Data.Char import Data.Map (Map) import Data.Text (Text) import Data.Text.Encoding import Data.Text.Read import Data.Time import Data.Time.Clock.POSIX import Numeric import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import qualified Data.Map as Map import qualified Data.Text as Text data BuildingSave = BuildingSave { bldgCurrent, bldgTotal, bldgSpecial :: Int , bldgBaked :: Double , bldgMinigame :: [Text] } deriving (Show) -- NOTE: The order of the fields in SaveStats, SavePrefs, and SaveMain -- must match the order found in the save format data SaveStats = SaveStats { savSessionStart, savLegacyStart, savLastSave :: UTCTime , savName :: Text } deriving (Show) data SavePrefs = SavePrefs { savParticles, savNumbers, savAutosave, savAutoupdate , savMilk, savFancy, savWarn, savCursors , savFocus, savFormat, savNotifs, savWobbly , savMonospace, savFilters, savCookieSound , savCrates, savBackupWarning :: Bool } deriving (Show) data SaveMain = SaveMain { savCookies, savCookiesEarned :: Double , savCookieClicks, savGoldenClicks :: Int , savHandmadeCookies :: Double , savMissedGoldenClicks, savBackgroundType, savMilkType :: Int , savCookiesReset :: Double , savElderWrath, savPledges, savPledgesT, savNextResearch , savResearchT, savResets, savGoldenClicksLocal :: Int , savCookiesSucked :: Double , savWrinklersPopped, savSantaLevel, savReindeerClicked , savSeasonT, savSeasonUses :: Int , savSeason :: Text , savMunched :: Double , savWrinklers :: Int , savPrestige, savHeavenlyChips, savHeavenlyChipsSpent , savHeavenlyCookies :: Double , savAscensionMode :: Int , savPermUpgrade1, savPermUpgrade2 , savPermUpgrade3, savPermUpgrade4, savPermUpgrade5 , savDragonLevel, savDragonAura, savDragonAura2 , savChimeType, savVolume, savShinyWrinklers :: Int , savShinyMunched :: Double , savSugarLumps, savTotalSugarLumps :: Int , savSugarLumpTime :: Double } deriving (Show) data SaveFile = SaveFile { savVersion :: Double , savReserved :: Text , savStats :: SaveStats , savPrefs :: SavePrefs , savMain :: SaveMain , savBuildings :: Map Building BuildingSave , savUpgrades :: [(Bool,Bool)] --(unlocked,bought) , savAchievements :: [Bool] } deriving (Show) unescape :: String -> String unescape ('%':x:y:z) = case readHex [x,y] of [(c,"")] -> chr c : unescape z _ -> error "unescape: bad escape" unescape [] = [] unescape (x:xs) = x : unescape xs removeEnd :: ByteString -> Either String ByteString removeEnd bs = case B.breakSubstring (B8.pack "!END!") bs of (a,b) | B.null b -> Left "removeEnd: No end marker" | otherwise -> Right a loadMySave :: IO SaveFile loadMySave = either fail return . loadSave =<< readFile "save.txt" decodeSaveString :: String -> Either String Text decodeSaveString raw = do let unesc = B8.pack (unescape raw) noend <- removeEnd unesc let utf8utf8 = Data.ByteString.Base64.decodeLenient noend txt = decodeUtf8 (B8.pack (Text.unpack (decodeUtf8 utf8utf8))) -- sorry, not my format return txt -- encodeSaveString :: Text -> String encodeSaveString str = B8.unpack (utf8Bytes <> "%21END%21\n") where utf8Bytes = Data.ByteString.Base64.encode (encodeUtf8 (Text.pack (B8.unpack (encodeUtf8 str)))) loadSave :: String -> Either String SaveFile loadSave raw = parse =<< decodeSaveString raw parseBldg :: Text -> Either String BuildingSave parseBldg str = do let bldgCurrentStr : bldgTotalStr : bldgBakedStr : bldgSpecialStr : bldgMinigame = Text.splitOn "," str bldgCurrent <- fst <$> decimal bldgCurrentStr bldgTotal <- fst <$> decimal bldgTotalStr bldgBaked <- fst <$> rational bldgBakedStr bldgSpecial <- fst <$> decimal bldgSpecialStr return BuildingSave{..} unpackBits :: Text -> [Bool] unpackBits = map ('1'==) . Text.unpack toPairs :: [a] -> [(a,a)] toPairs (x:y:z) = (x,y) : toPairs z toPairs _ = [] integerToUTCTime :: Integer -> UTCTime integerToUTCTime ms = posixSecondsToUTCTime (realToFrac s) where s = fromInteger ms / 1000 :: Rational parsePrefs :: Text -> SavePrefs parsePrefs x = case unpackBits x of [ savParticles, savNumbers, savAutosave, savAutoupdate , savMilk, savFancy, savWarn, savCursors , savFocus, savFormat, savNotifs, savWobbly , savMonospace, savFilters, savCookieSound , savCrates, savBackupWarning, _, _ ] -> SavePrefs{..} actual -> error ("parsePrefs: Unexpected bits list: " ++ show actual) parse :: Text -> Either String SaveFile parse str = do let [savVersionStr, savReserved, region1, region2, region3, region4, region5, region6, region7] = Text.splitOn "|" str savVersion <- parser savVersionStr savStats <- populate (Text.splitOn ";" region1) SaveStats let savPrefs = parsePrefs region2 savMain <- populate (Text.splitOn ";" region3) SaveMain savBuildings <- Map.fromList . zip [Cursor ..] <$> traverse parseBldg (init (Text.splitOn ";" region4)) let savUpgrades = toPairs $ unpackBits region5 savAchievements = unpackBits region6 return SaveFile{..} data PantheonSave = PantheonSave { savPantheon1, savPantheon2, savPantheon3 :: Int } deriving (Read, Show) parsePantheon :: Text -> Either String PantheonSave parsePantheon str = case Text.splitOn " " str of [slotStrs, _swaps, _time, _other] -> do slots <- traverse parser (Text.splitOn "/" slotStrs) -- extra permissive to deal with incorrectly encoded slots after a change case slots ++ repeat (-1) of slot1 : slot2 : slot3 : _ -> pure (PantheonSave slot1 slot2 slot3) actual -> Left ("Wrong number of entries in: " ++ show actual) class HasParser a where parser :: Text -> Either String a instance HasParser Double where parser x = fst <$> signed rational x instance HasParser Int where parser x = fst <$> signed decimal x instance HasParser Text where parser = Right instance HasParser UTCTime where parser "NaN" = Right (posixSecondsToUTCTime 0) parser x = integerToUTCTime . fst <$> decimal x class Populate a r where populate :: [Text] -> a -> Either String r instance (HasParser a, Populate b r) => Populate (a -> b) r where populate [] _ = Left "Too few arguments" populate (x:xs) f = do g <- f <$> parser x populate xs g instance Populate r r where populate _ r = Right r
glguy/CookieCalculator
src/SaveFormat.hs
isc
6,886
0
16
1,478
1,947
1,086
861
163
2
{-# LANGUAGE OverloadedStrings , PatternGuards #-} module Text.BraVal.Report where import qualified Data.Text as Text import qualified Data.Text.Lazy as Lazy import Data.Text.Template import Data.Tuple (swap) import Control.Monad.Trans.Writer import Control.Arrow ((>>>)) import Text.BraVal.Types type Text = Text.Text report :: Writer [Symbol] [Symbol] -> String report = runWriter >>> ( \(left, extra) -> if length left == 0 && length extra == 0 then "Everything matches.\n" else ( (if length left /= 0 then reportLeft left else "") `Text.append` (if length extra /= 0 then reportExtra extra else ""))) >>> Text.unpack where reportOne :: Symbol -> Text reportOne symbol = Lazy.toStrict $ substitute "Character '${c}' at line $line, column $column.\n" (contextOne symbol) contextOne :: Symbol -> Text -> Text contextOne sym tag | tag == "c" = contextOneChar sym | tag == "line" = contextOneLine sym | tag == "column" = contextOneColumn sym | otherwise = undefined -- Should never happen. contextOneChar (Symbol _ sym) | (Blank string) <- sym = Text.pack string | Just char <- lookup sym (swap <$> table) = Text.pack [char] contextOneChar, contextOneLine, contextOneColumn :: Symbol -> Text contextOneLine (Symbol cursor _) = Text.pack . show $ line cursor contextOneColumn (Symbol cursor _) = Text.pack . show $ column cursor reportLeft left = "Left open:\n" `Text.append` Text.concat (reportOne <$> reverse left) reportExtra extra = "Close nothing:\n" `Text.append` Text.concat (reportOne <$> extra)
kindaro/BraVal
src/Text/BraVal/Report.hs
isc
1,762
0
15
482
519
277
242
32
4
module Database.Kafka.Core ( connectProducer, connectConsumer, push, pull ) where import Database.Kafka.Types (KafkaConfig, ProducerConfig, ConsumerConfig, TopicConfig, Consumer, Producer, Message) connectProducer :: KafkaConfig -> ProducerConfig -> TopicConfig -> IO (Either String Producer) connectProducer = error "Not Implemented" connectConsumer :: KafkaConfig -> ConsumerConfig -> TopicConfig -> IO (Either String Consumer) connectConsumer = error "Not Implemented" push :: Producer -> Message k v -> IO (Either String ()) push = error "Not Implemented" pull :: Consumer -> IO (Either String (Message k v)) pull = error "Not Implemented"
yanatan16/haskell-kafka
src/Database/Kafka/Core.hs
mit
658
0
10
98
197
106
91
14
1
-- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. {-# LANGUAGE OverloadedStrings, RecordWildCards, DeriveGeneric, StandaloneDeriving #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Copyright : (c) Microsoft License : MIT Maintainer : adamsap@microsoft.com Stability : alpha Portability : portable -} module Language.Bond.Syntax.JSON ( -- * FromJSON and ToJSON instances -- $aeson ) where import Data.Aeson import Data.Aeson.Types import Control.Applicative import Prelude import GHC.Generics (Generic) import Language.Bond.Syntax.Types -- $aeson -- -- This module defines 'FromJSON' and 'ToJSON' instances for Bond abstract -- syntax tree. They allow using the <http://hackage.haskell.org/package/aeson aeson> -- library to encode Bond AST types to <https://microsoft.github.io/bond/manual/compiler.html#schema-ast JSON format>: -- -- > > encode (Bond [] [Namespace Nothing ["example"]] []) -- > "{\"namespaces\":[{\"name\":[\"example\"]}],\"imports\":[],\"declarations\":[]}" -- -- and decode Bond data types from JSON: -- -- > > decode "{\"namespaces\":[{\"name\":[\"example\"]}],\"imports\":[],\"declarations\":[]}" :: Maybe Bond -- > Just (Bond {bondImports = [], bondNamespaces = [Namespace {nsLanguage = Nothing, nsName = ["example"]}], bondDeclarations = []}) deriving instance Generic Modifier instance FromJSON Modifier instance ToJSON Modifier instance FromJSON Type where parseJSON (String "int8") = pure BT_Int8 parseJSON (String "int16") = pure BT_Int16 parseJSON (String "int32") = pure BT_Int32 parseJSON (String "int64") = pure BT_Int64 parseJSON (String "uint8") = pure BT_UInt8 parseJSON (String "uint16") = pure BT_UInt16 parseJSON (String "uint32") = pure BT_UInt32 parseJSON (String "uint64") = pure BT_UInt64 parseJSON (String "float") = pure BT_Float parseJSON (String "double") = pure BT_Double parseJSON (String "bool") = pure BT_Bool parseJSON (String "string") = pure BT_String parseJSON (String "wstring") = pure BT_WString parseJSON (String "bond_meta::name") = pure BT_MetaName parseJSON (String "bond_meta::full_name") = pure BT_MetaFullName parseJSON (String "blob") = pure BT_Blob parseJSON (Object o) = do type_ <- o .: "type" case type_ of String "maybe" -> BT_Maybe <$> o .: "element" String "list" -> BT_List <$> o .: "element" String "vector" -> BT_Vector <$> o .: "element" String "nullable" -> BT_Nullable <$> o .: "element" String "set" -> BT_Set <$> o .: "element" String "map" -> BT_Map <$> o .: "key" <*> o .: "element" String "bonded" -> BT_Bonded <$> o .: "element" String "constant" -> BT_IntTypeArg <$> o .: "value" String "parameter" -> BT_TypeParam <$> o .: "value" String "user" -> BT_UserDefined <$> o .: "declaration" <*> o .:? "arguments" .!= [] _ -> modifyFailure (const $ "Invalid value `" ++ show type_ ++ "` for the `type` key.") empty parseJSON x = modifyFailure (const $ "Expected a representation of Type but found: " ++ show x) empty instance ToJSON Type where toJSON BT_Int8 = "int8" toJSON BT_Int16 = "int16" toJSON BT_Int32 = "int32" toJSON BT_Int64 = "int64" toJSON BT_UInt8 = "uint8" toJSON BT_UInt16 = "uint16" toJSON BT_UInt32 = "uint32" toJSON BT_UInt64 = "uint64" toJSON BT_Float = "float" toJSON BT_Double = "double" toJSON BT_Bool = "bool" toJSON BT_String = "string" toJSON BT_WString = "wstring" toJSON BT_MetaName = "bond_meta::name" toJSON BT_MetaFullName = "bond_meta::full_name" toJSON BT_Blob = "blob" toJSON (BT_Maybe t) = object [ "type" .= String "maybe" , "element" .= t ] toJSON (BT_List t) = object [ "type" .= String "list" , "element" .= t ] toJSON (BT_Vector t) = object [ "type" .= String "vector" , "element" .= t ] toJSON (BT_Nullable t) = object [ "type" .= String "nullable" , "element" .= t ] toJSON (BT_Set t) = object [ "type" .= String "set" , "element" .= t ] toJSON (BT_Map k t) = object [ "type" .= String "map" , "key" .= k , "element" .= t ] toJSON (BT_Bonded t) = object [ "type" .= String "bonded" , "element" .= t ] toJSON (BT_IntTypeArg n) = object [ "type" .= String "constant" , "value" .= n ] toJSON (BT_TypeParam p) = object [ "type" .= String "parameter" , "value" .= p ] toJSON (BT_UserDefined decl []) = object [ "type" .= String "user" , "declaration" .= decl ] toJSON (BT_UserDefined decl args) = object [ "type" .= String "user" , "declaration" .= decl , "arguments" .= args ] instance FromJSON Default where parseJSON (Object o) = do type_ <- o .: "type" case type_ of String "bool" -> DefaultBool <$> o .: "value" String "integer" -> DefaultInteger <$> o .: "value" String "float" -> DefaultFloat <$> o .: "value" String "string" -> DefaultString <$> o .: "value" String "enum" -> DefaultEnum <$> o .: "value" String "nothing" -> pure DefaultNothing _ -> modifyFailure (const $ "Invalid value `" ++ show type_ ++ "` for the `type` key.") empty parseJSON x = modifyFailure (const $ "Expected a representation of Default but found: " ++ show x) empty instance ToJSON Default where toJSON (DefaultBool x) = object [ "type" .= String "bool" , "value" .= x ] toJSON (DefaultInteger x) = object [ "type" .= String "integer" , "value" .= x ] toJSON (DefaultFloat x) = object [ "type" .= String "float" , "value" .= x ] toJSON (DefaultString x) = object [ "type" .= String "string" , "value" .= x ] toJSON (DefaultEnum x) = object [ "type" .= String "enum" , "value" .= x ] toJSON DefaultNothing = object [ "type" .= String "nothing" ] deriving instance Generic Attribute instance FromJSON Attribute instance ToJSON Attribute deriving instance Generic Field instance FromJSON Field instance ToJSON Field deriving instance Generic Constant instance FromJSON Constant instance ToJSON Constant instance FromJSON Constraint where parseJSON (String "value") = pure Value parseJSON x = modifyFailure (const $ "Expected a representation of Constraint but found: " ++ show x) empty instance ToJSON Constraint where toJSON Value = "value" deriving instance Generic TypeParam instance FromJSON TypeParam instance ToJSON TypeParam deriving instance Generic Declaration instance FromJSON Declaration instance ToJSON Declaration deriving instance Generic Import instance FromJSON Import instance ToJSON Import deriving instance Generic Language instance FromJSON Language instance ToJSON Language instance FromJSON Namespace where parseJSON (Object v) = Namespace <$> v .:? "language" <*> v .: "name" parseJSON x = modifyFailure (const $ "Expected an object but found: " ++ show x) empty instance ToJSON Namespace where toJSON (Namespace Nothing name) = object [ "name" .= name ] toJSON Namespace {..} = object [ "language" .= nsLanguage , "name" .= nsName ] instance FromJSON Bond where parseJSON (Object v) = Bond <$> v .: "imports" <*> v .: "namespaces" <*> v .: "declarations" parseJSON x = modifyFailure (const $ "Expected an object but found: " ++ show x) empty instance ToJSON Bond where toJSON Bond {..} = object [ "imports" .= bondImports , "namespaces" .= bondNamespaces , "declarations" .= bondDeclarations ]
upsoft/bond
compiler/src/Language/Bond/Syntax/JSON.hs
mit
8,612
0
15
2,666
2,044
1,011
1,033
204
0
module SpecHelper ( module Test.Hspec , module Lib , module Control.Exception ) where import Test.Hspec import Lib import Control.Exception (evaluate)
dimus/zones
test/SpecHelper.hs
mit
162
0
5
31
40
26
14
7
0
module LogFind ( getAllFilesUnder , multipleStringsToPredicate , matchesAll , matchesSome ) where import Data.Functor import Data.List (partition) import System.Directory (doesDirectoryExist, getDirectoryContents) import Text.Regex.Posix ((=~)) -- | -- Join two file paths the Unix way using "/". -- -- >>> "a" </> "b" -- "a/b" (</>) :: FilePath -> FilePath -> FilePath a </> b = a ++ "/" ++ b -- | -- Tell whether a file is a reference to another directory (., ..) -- -- >>> isCurrentOrParentFolder "." -- True -- -- >>> isCurrentOrParentFolder ".." -- True -- -- >>> isCurrentOrParentFolder "banana" -- False isCurrentOrParentFolder :: FilePath -> Bool isCurrentOrParentFolder f = f == "." || f == ".." -- | -- Returns a list of the file paths of the files under a directory, the result -- is split in a tuple of file paths of directories and file paths of files. getDirectorySeperatedContent :: FilePath -> IO ([FilePath], [FilePath]) getDirectorySeperatedContent directory = do allFilePaths <- filter (not . isCurrentOrParentFolder) <$> getDirectoryContents directory filePathIsDirectory <- mapM doesDirectoryExist allFilePaths let absoluteFilePaths = (directory </>) <$> allFilePaths let (directories, files) = partition snd (zip absoluteFilePaths filePathIsDirectory) return (fst <$> directories, fst <$> files) -- | -- Finds recursively all files under a given directory. getAllFilesUnder :: FilePath -> IO [FilePath] getAllFilesUnder directory = do (directories, files) <- getDirectorySeperatedContent directory subChildren <- sequence $ getAllFilesUnder <$> directories return $ files ++ concat subChildren -- | -- Converts a string to a predicate testing if a filename is to include in -- the result set -- -- >>> (stringToPredicate "-xyz") "xyz" -- False -- -- >>> (stringToPredicate "+xyz") "xyz" -- True -- -- >>> (stringToPredicate "xyz") "xyz" -- True -- -- >>> (stringToPredicate "^xy+z$") "xyyyyyyyyyyz" -- True stringToPredicate :: String -> String -> Bool stringToPredicate ('-':regex) = not . (=~ regex) stringToPredicate ('+':regex) = (=~ regex) stringToPredicate regex = (=~ regex) -- | -- Converts multiple string to a predicate testing if a filename is to include in -- the result set. The filename satisties the predicate if each of the predicate -- created for each element of the list was satisfied. -- -- Putting a "-" in front of a line will negate the predicate. -- Putting a "+" or nothing in front of a line will have no effect. -- -- >>> (multipleStringsToPredicate ["-xyz", "+z"]) "xyz" -- False -- -- >>> (multipleStringsToPredicate ["-xyz", "+z"]) "yz" -- True -- -- >>> (multipleStringsToPredicate []) "yz" -- True multipleStringsToPredicate :: [String] -> String -> Bool multipleStringsToPredicate xs = and . sequence (stringToPredicate <$> xs) -- | -- Converts multiple string to a predicate testing if a filename is to include in -- the result set. The filename satisties the predicate if each of the predicate -- created for each element of the list was satisfied. -- -- >>> (matchesAll ["y", "z"]) "xyz" -- True -- -- >>> (matchesAll ["^y", "z"]) "xyz" -- False -- -- >>> (matchesAll []) "xyz" -- True matchesAll :: [String] -> String -> Bool matchesAll xs = and . sequence (flip (=~) <$> xs) -- | -- Converts multiple string to a predicate testing if a filename is to include in -- the result set. The filename satisties the predicate if any of the predicate -- created for each element of the list was satisfied. -- -- >>> (matchesSome ["y", "a"]) "xyz" -- True -- -- >>> (matchesSome ["^y", "z"]) "xyz" -- True -- -- >>> (matchesSome ["^y", "b"]) "xyz" -- False -- -- >>> (matchesSome []) "xyz" -- True matchesSome :: [String] -> String -> Bool matchesSome [] = const True matchesSome xs = or . sequence (flip (=~) <$> xs)
matthieubulte/logfind
lib/LogFind.hs
mit
3,936
0
12
771
609
362
247
35
1
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Com.Mysql.Cj.Mysqlx.Protobuf.ServerMessages.Type (Type(..)) where import Prelude ((+), (/), (.)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified GHC.Generics as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data Type = OK | ERROR | CONN_CAPABILITIES | SESS_AUTHENTICATE_CONTINUE | SESS_AUTHENTICATE_OK | NOTICE | RESULTSET_COLUMN_META_DATA | RESULTSET_ROW | RESULTSET_FETCH_DONE | RESULTSET_FETCH_SUSPENDED | RESULTSET_FETCH_DONE_MORE_RESULTSETS | SQL_STMT_EXECUTE_OK | RESULTSET_FETCH_DONE_MORE_OUT_PARAMS deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic) instance P'.Mergeable Type instance Prelude'.Bounded Type where minBound = OK maxBound = RESULTSET_FETCH_DONE_MORE_OUT_PARAMS instance P'.Default Type where defaultValue = OK toMaybe'Enum :: Prelude'.Int -> P'.Maybe Type toMaybe'Enum 0 = Prelude'.Just OK toMaybe'Enum 1 = Prelude'.Just ERROR toMaybe'Enum 2 = Prelude'.Just CONN_CAPABILITIES toMaybe'Enum 3 = Prelude'.Just SESS_AUTHENTICATE_CONTINUE toMaybe'Enum 4 = Prelude'.Just SESS_AUTHENTICATE_OK toMaybe'Enum 11 = Prelude'.Just NOTICE toMaybe'Enum 12 = Prelude'.Just RESULTSET_COLUMN_META_DATA toMaybe'Enum 13 = Prelude'.Just RESULTSET_ROW toMaybe'Enum 14 = Prelude'.Just RESULTSET_FETCH_DONE toMaybe'Enum 15 = Prelude'.Just RESULTSET_FETCH_SUSPENDED toMaybe'Enum 16 = Prelude'.Just RESULTSET_FETCH_DONE_MORE_RESULTSETS toMaybe'Enum 17 = Prelude'.Just SQL_STMT_EXECUTE_OK toMaybe'Enum 18 = Prelude'.Just RESULTSET_FETCH_DONE_MORE_OUT_PARAMS toMaybe'Enum _ = Prelude'.Nothing instance Prelude'.Enum Type where fromEnum OK = 0 fromEnum ERROR = 1 fromEnum CONN_CAPABILITIES = 2 fromEnum SESS_AUTHENTICATE_CONTINUE = 3 fromEnum SESS_AUTHENTICATE_OK = 4 fromEnum NOTICE = 11 fromEnum RESULTSET_COLUMN_META_DATA = 12 fromEnum RESULTSET_ROW = 13 fromEnum RESULTSET_FETCH_DONE = 14 fromEnum RESULTSET_FETCH_SUSPENDED = 15 fromEnum RESULTSET_FETCH_DONE_MORE_RESULTSETS = 16 fromEnum SQL_STMT_EXECUTE_OK = 17 fromEnum RESULTSET_FETCH_DONE_MORE_OUT_PARAMS = 18 toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ServerMessages.Type") . toMaybe'Enum succ OK = ERROR succ ERROR = CONN_CAPABILITIES succ CONN_CAPABILITIES = SESS_AUTHENTICATE_CONTINUE succ SESS_AUTHENTICATE_CONTINUE = SESS_AUTHENTICATE_OK succ SESS_AUTHENTICATE_OK = NOTICE succ NOTICE = RESULTSET_COLUMN_META_DATA succ RESULTSET_COLUMN_META_DATA = RESULTSET_ROW succ RESULTSET_ROW = RESULTSET_FETCH_DONE succ RESULTSET_FETCH_DONE = RESULTSET_FETCH_SUSPENDED succ RESULTSET_FETCH_SUSPENDED = RESULTSET_FETCH_DONE_MORE_RESULTSETS succ RESULTSET_FETCH_DONE_MORE_RESULTSETS = SQL_STMT_EXECUTE_OK succ SQL_STMT_EXECUTE_OK = RESULTSET_FETCH_DONE_MORE_OUT_PARAMS succ _ = Prelude'.error "hprotoc generated code: succ failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ServerMessages.Type" pred ERROR = OK pred CONN_CAPABILITIES = ERROR pred SESS_AUTHENTICATE_CONTINUE = CONN_CAPABILITIES pred SESS_AUTHENTICATE_OK = SESS_AUTHENTICATE_CONTINUE pred NOTICE = SESS_AUTHENTICATE_OK pred RESULTSET_COLUMN_META_DATA = NOTICE pred RESULTSET_ROW = RESULTSET_COLUMN_META_DATA pred RESULTSET_FETCH_DONE = RESULTSET_ROW pred RESULTSET_FETCH_SUSPENDED = RESULTSET_FETCH_DONE pred RESULTSET_FETCH_DONE_MORE_RESULTSETS = RESULTSET_FETCH_SUSPENDED pred SQL_STMT_EXECUTE_OK = RESULTSET_FETCH_DONE_MORE_RESULTSETS pred RESULTSET_FETCH_DONE_MORE_OUT_PARAMS = SQL_STMT_EXECUTE_OK pred _ = Prelude'.error "hprotoc generated code: pred failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ServerMessages.Type" instance P'.Wire Type where wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum) wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum) wireGet 14 = P'.wireGetEnum toMaybe'Enum wireGet ft' = P'.wireGetErr ft' wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum wireGetPacked ft' = P'.wireGetErr ft' instance P'.GPB Type instance P'.MessageAPI msg' (msg' -> Type) Type where getVal m' f' = f' m' instance P'.ReflectEnum Type where reflectEnum = [(0, "OK", OK), (1, "ERROR", ERROR), (2, "CONN_CAPABILITIES", CONN_CAPABILITIES), (3, "SESS_AUTHENTICATE_CONTINUE", SESS_AUTHENTICATE_CONTINUE), (4, "SESS_AUTHENTICATE_OK", SESS_AUTHENTICATE_OK), (11, "NOTICE", NOTICE), (12, "RESULTSET_COLUMN_META_DATA", RESULTSET_COLUMN_META_DATA), (13, "RESULTSET_ROW", RESULTSET_ROW), (14, "RESULTSET_FETCH_DONE", RESULTSET_FETCH_DONE), (15, "RESULTSET_FETCH_SUSPENDED", RESULTSET_FETCH_SUSPENDED), (16, "RESULTSET_FETCH_DONE_MORE_RESULTSETS", RESULTSET_FETCH_DONE_MORE_RESULTSETS), (17, "SQL_STMT_EXECUTE_OK", SQL_STMT_EXECUTE_OK), (18, "RESULTSET_FETCH_DONE_MORE_OUT_PARAMS", RESULTSET_FETCH_DONE_MORE_OUT_PARAMS)] reflectEnumInfo _ = P'.EnumInfo (P'.makePNF (P'.pack ".Mysqlx.ServerMessages.Type") [] ["Com", "Mysql", "Cj", "Mysqlx", "Protobuf", "ServerMessages"] "Type") ["Com", "Mysql", "Cj", "Mysqlx", "Protobuf", "ServerMessages", "Type.hs"] [(0, "OK"), (1, "ERROR"), (2, "CONN_CAPABILITIES"), (3, "SESS_AUTHENTICATE_CONTINUE"), (4, "SESS_AUTHENTICATE_OK"), (11, "NOTICE"), (12, "RESULTSET_COLUMN_META_DATA"), (13, "RESULTSET_ROW"), (14, "RESULTSET_FETCH_DONE"), (15, "RESULTSET_FETCH_SUSPENDED"), (16, "RESULTSET_FETCH_DONE_MORE_RESULTSETS"), (17, "SQL_STMT_EXECUTE_OK"), (18, "RESULTSET_FETCH_DONE_MORE_OUT_PARAMS")] instance P'.TextType Type where tellT = P'.tellShow getT = P'.getRead
naoto-ogawa/h-xproto-mysql
src/Com/Mysql/Cj/Mysqlx/Protobuf/ServerMessages/Type.hs
mit
5,966
0
11
872
1,309
726
583
118
1
{-# htermination elemIndices :: () -> [()] -> [Int] #-} import List
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/List_elemIndices_1.hs
mit
68
0
3
12
5
3
2
1
0
import Data.List (elemIndex, maximumBy) type Denominator = Int type CycleLength = Int reciprocalCycles :: (Denominator, CycleLength) reciprocalCycles = maximumBy (\a b -> compare (snd a) (snd b)) $ map cycleLength [1..999] cycleLength :: Int -> (Denominator, CycleLength) cycleLength d = fn 1 [] where fn n xs = case (n `elemIndex` xs) of Just(i) -> (d, length xs - i) _ -> fn ((n * 10) `mod` d) (xs ++ [n]) -- cycleLength == (983,982) -- (0.00 secs, 1,034,472 bytes)
samidarko/euler
problem026.hs
mit
501
0
14
113
205
114
91
11
2