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
module Jhc.Type.Word(module Jhc.Type.Word, module Jhc.Prim.Bits) where import Jhc.Prim.Bits -- define the lifted form of the basic -- numeric types. data {-# CTYPE "unsigned" #-} Word = Word Bits32_ data {-# CTYPE "uint8_t" #-} Word8 = Word8 Bits8_ data {-# CTYPE "uint16_t" #-} Word16 = Word16 Bits16_ data {-# CTYPE "uint32_t" #-} Word32 = Word32 Bits32_ data {-# CTYPE "uint64_t" #-} Word64 = Word64 Bits64_ data {-# CTYPE "uint128_t" #-} Word128 = Word128 Bits128_ data {-# CTYPE "uintptr_t" #-} WordPtr = WordPtr BitsPtr_ data {-# CTYPE "uintmax_t" #-} WordMax = WordMax BitsMax_ data {-# CTYPE "int" #-} Int = Int Bits32_ data {-# CTYPE "int8_t" #-} Int8 = Int8 Bits8_ data {-# CTYPE "int16_t" #-} Int16 = Int16 Bits16_ data {-# CTYPE "int32_t" #-} Int32 = Int32 Bits32_ data {-# CTYPE "int64_t" #-} Int64 = Int64 Bits64_ data {-# CTYPE "int128_t" #-} Int128 = Int128 Bits128_ data {-# CTYPE "intptr_t" #-} IntPtr = IntPtr BitsPtr_ data {-# CTYPE "intmax_t" #-} IntMax = IntMax BitsMax_
m-alvarez/jhc
lib/jhc/Jhc/Type/Word.hs
mit
1,013
0
6
183
191
118
73
18
0
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- -- Our CI does not work well with auto discover. -- Need to add build-time PATH variable to hspec-discover dir from CMake -- or install hspec system-wide for the following to work. -- {-# OPTIONS_GHC -F -pgmF hspec-discover #-} import Test.Hspec import qualified BinarySpec import qualified CompactSpec import qualified JSONSpec main :: IO () main = hspec spec spec :: Spec spec = do describe "Binary" BinarySpec.spec describe "Compact" CompactSpec.spec describe "JSON" JSONSpec.spec
jcgruenhage/dendrite
vendor/src/github.com/apache/thrift/lib/hs/test/Spec.hs
apache-2.0
1,298
0
8
216
98
61
37
11
1
{-# LANGUAGE DeriveDataTypeable #-} module Main where import qualified Data.Array.Accelerate as A import qualified Data.Array.Accelerate.CUDA as CUDA import Data.Data import Data.Int import Data.Typeable import System.Console.CmdArgs import Life data Profile = Profile { width_ :: Int , height_ :: Int , generations_ :: Int } deriving (Show, Data, Typeable) argsProfile :: Profile argsProfile = Profile { width_ = 200 &= help "The number of cells across the game board." , height_ = 200 &= help "The number of cells tall." , generations_ = 100 &= help "The number of generations to calculate." } main :: IO () main = do profile <- cmdArgs argsProfile firstGen <- randomGen (width_ profile) (height_ profile) let genAsWord = CUDA.run1 convertGen firstGen finalAlive = simulate (generations_ profile) genAsWord print $ "Final Alive: " ++ show finalAlive simulate :: Int -> Generation -> A.Scalar Int64 simulate 0 g = CUDA.run1 (A.sum . A.map (\a -> A.fromIntegral a :: A.Exp Int64)) g simulate i g = let ar = CUDA.run1 nextGen g in simulate (i - 1) ar
AndrewRademacher/game-of-life-accelerate
src/Profile.hs
mit
1,297
0
12
417
346
185
161
29
1
min :: (Int,Int) -> Int min (x,y) | x <= y =x | otherwise =y max :: (Int,Int) -> Int max (x,y) | x <= y =y | otherwise =x
MaximilianMihoc/Algorithms
Haskell/MinAndMaxwithTouples.hs
mit
127
6
8
35
104
53
51
8
1
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-} module Web.Slack.Types.IM where import Data.Aeson import Data.Aeson.Types import Control.Applicative import Control.Lens.TH import Web.Slack.Types.Id import Web.Slack.Types.Time import {-# SOURCE #-} Web.Slack.Types.ChannelOpt (ChannelOpt) import Prelude data IM = IM { _imId :: IMId , _imUser :: UserId , _imCreated :: Time , _imIsOpen :: Bool , _imIsIm :: Bool , _imOpt :: Maybe ChannelOpt } deriving (Show) makeLenses ''IM instance FromJSON IM where parseJSON = withObject "IM" (\o -> IM <$> o .: "id" <*> o .: "user" <*> o .: "created" <*> o .: "is_open" <*> o .: "is_im" <*> (pure $ parseMaybe parseJSON (Object o) :: Parser (Maybe ChannelOpt)))
madjar/slack-api
src/Web/Slack/Types/IM.hs
mit
862
0
19
263
224
130
94
26
0
{-# LANGUAGE OverloadedStrings #-} import Data.Bits import qualified Data.ByteString.Char8 as BS import Data.Maybe (catMaybes) import Data.Monoid ((<>)) import Numeric (showHex) import Pwn cfg = defaultConfig { arch = "i386", bits = 32 } main :: IO () main = pwnWith cfg $ do r <- remote "0.0.0.0" 8181 let system = 0x8048620 recv = 0x80486e0 bss = 0x804b1b4 buflen = 0x28 fd = 4 echo str = do recvuntil r "Select menu > " sendline r "1" recvuntil r "Input Your Message : " send r str recvuntil r "\n=" exit = do recvuntil r "Select menu > " sendline r "3" info "leak canary" ret <- echo $ BS.replicate (buflen + 1) 'A' let Just c = u32 $ BS.take 4 $ BS.drop buflen ret canary = c .&. 0xffffff00 success $ "canary = 0x" <> showHex canary "" info "send ROP" let buf = [ Just $ BS.replicate buflen 'A' , p32 canary , Just "BBBB" -- 0x8048b83: pop ebx , Just "BBBB" -- 0x8048b84: pop edi , p32 $ bss + 0x800 -- 0x8048b85: pop ebp , p32 recv -- recv(fd, bss, 0x100, 0) , p32 system -- system(bss) , p32 fd , p32 bss , p32 0x100 , p32 0 ] echo $ BS.concat $ catMaybes buf info "trigger ROP" exit info "execute '/bin/sh'" let fd' = BS.pack $ show fd cmd = "/bin/sh -i <&" <> fd' <> " >&" <> fd' <> " 2>&" <> fd' sendline r cmd interactive r
Tosainu/pwn.hs
example/codegate2017prequal-babypwn.hs
mit
1,682
0
15
694
476
233
243
50
1
module Ori.Misc ( module Ori.Misc ) where import Ori.Types initPoly :: Poly initPoly = mkPoly 4 [V2 0 0, V2 1 0, V2 1 1, V2 0 1] initFacets :: Facets initFacets = mkFacets 1 [mkFacet 4 [0, 1, 2, 3]] initial :: OState initial = (initPoly, (initFacets, initPoly)) init' :: Rat -> Rat -> OState init' xl yl = if xl < 1%1 && yl < 1%1 then initxy xl yl else if xl < 1%1 then initx xl else if yl < 1%1 then inity yl else initial initx :: Rat -> OState initx xl = (p, (mkFacets 2 [mkFacet 4 [0, 3, 4, 1], mkFacet 4 [1, 4, 5, 2]], p')) where p = mkPoly 6 [V2 0 0, V2 xl 0, V2 1 0, V2 0 1, V2 xl 1, V2 1 1] p' = mkPoly 6 [V2 0 0, V2 xl 0, V2 (2 * xl - 1) 0, V2 0 1, V2 xl 1, V2 (2 * xl - 1) 1] inity :: Rat -> OState inity yl = (p, (mkFacets 2 [mkFacet 4 [0, 2, 3, 1], mkFacet 4 [2, 4, 5, 3]], p')) where p = mkPoly 6 [V2 0 0, V2 1 0, V2 0 yl, V2 1 yl, V2 0 1, V2 1 1] p' = mkPoly 6 [V2 0 0, V2 1 0, V2 0 yl, V2 1 yl, V2 0 (2 * yl - 1), V2 1 (2 * yl - 1)] initxy :: Rat -> Rat -> OState initxy xl yl = (p, (mkFacets 4 [mkFacet 4 [0, 3, 4, 1], mkFacet 4 [3, 6, 7, 4], mkFacet 4 [4, 7, 8, 5], mkFacet 4 [1, 4, 5, 2]], p')) where p = mkPoly 9 [V2 0 0, V2 xl 0, V2 1 0, V2 0 yl, V2 xl yl, V2 1 yl, V2 0 1, V2 xl 1, V2 1 1] p' = mkPoly 9 [V2 0 0, V2 xl 0, V2 (2 * xl - 1) 0, V2 0 yl, V2 xl yl, V2 (2 * xl - 1) yl, V2 0 (2 * yl - 1), V2 xl (2 * yl - 1), V2 (2 * xl - 1) (2 * yl - 1)] prime1 :: Integer --prime1 = 3036778097213642195103190478643368315713063094843382010429628306506249071647 --prime1 = 73990565474352683215012157463992253223 --prime1 = 25267209622774746135892534069 --prime1 = 1175982507355577618874031 prime1 = 872217209062834066423 --prime1 = 7494468750184990933 --prime1 = 42012923523829189 --prime1 = 197270390357783 --prime1 = 10681897909304407 --prime1 = 3352338683 prime2 :: Integer --prime2 = 21963974069798849695986806315470590742217552950948984435878934777554350320133 --prime2 = 303534997543846486096573445609329234633 --prime2 = 13838171772762106613089027627 --prime2 = 5102988548796626814061999 prime2 = 4598457348228492701237 --prime2 = 5018966348183996779 --prime2 = 42012923523829189 --prime2 = 244689765343477 --prime2 = 3308679658631953 --prime2 = 4134312341 smallPrime1 = 46051 smallPrime2 = 38201
pbl64k/icfpc2016
Ori/Misc.hs
mit
2,430
0
12
655
1,045
572
473
36
4
{-# LANGUAGE Arrows #-} module Types where import FRP.Yampa.Vector3 import Graphics.UI.GLUT hiding (Level,Vector3(..),normalize) import qualified Graphics.UI.GLUT as G(Vector3(..)) -- Basic Data Types type Pos = Double type Vel = Double type Pos3 = Vector3 Pos type Vel3 = Vector3 Vel -- Reference: Graphics.UI.GLUT.Callbacks.Window data Input = Keyboard { key :: Key, -- Char, SpecialKey or MouseButton keyState :: KeyState, -- Up or Down modifiers :: Modifiers } -- shift, ctrl, alt data ParsedInput = ParsedInput { aCount :: Double, dCount :: Double } data GameState = Game { playerPos :: Pos3, ballPos :: Pos3, end :: Bool } {-| type R = GLdouble data Point3D = P3D { x :: Integer, y :: Integer, z :: Integer } deriving (Show) data Level = Level { startingPoint :: Point3D, endPoint :: Point3D, obstacles :: [Point3D] } -}
SLMT/haskell-ping-pong
Types.hs
mit
943
0
8
252
162
107
55
14
0
{-# LANGUAGE RecordWildCards #-} import Data.Set (fromList) import Stackage.Build (build, defaultBuildSettings) import Stackage.BuildPlan (readBuildPlan, writeBuildPlan) import Stackage.CheckPlan (checkPlan) import Stackage.GhcPkg (getGhcVersion) import Stackage.Init (stackageInit) import Stackage.Select (defaultSelectSettings, select) import Stackage.Tarballs (makeTarballs) import Stackage.Test (runTestSuites) import Stackage.Types import Stackage.Util (allowPermissive) import System.Environment (getArgs, getProgName) import System.IO (hFlush, stdout) data SelectArgs = SelectArgs { excluded :: [String] , noPlatform :: Bool , ignoreUpgradeable :: Bool , onlyPermissive :: Bool , allowed :: [String] , buildPlanDest :: FilePath , globalDB :: Bool } parseSelectArgs :: [String] -> IO SelectArgs parseSelectArgs = loop SelectArgs { excluded = [] , noPlatform = True , ignoreUpgradeable = False , onlyPermissive = False , allowed = [] , buildPlanDest = defaultBuildPlan , globalDB = False } where loop x [] = return x loop x ("--exclude":y:rest) = loop x { excluded = y : excluded x } rest loop x ("--no-platform":rest) = loop x { noPlatform = True } rest loop x ("--platform":rest) = loop x { noPlatform = False } rest loop x ("--ignore-upgradeable":rest) = loop x { ignoreUpgradeable = True } rest loop x ("--only-permissive":rest) = loop x { onlyPermissive = True } rest loop x ("--allow":y:rest) = loop x { allowed = y : allowed x } rest loop x ("--build-plan":y:rest) = loop x { buildPlanDest = y } rest loop x ("--use-global-db":rest) = loop x { globalDB = True } rest loop _ (y:_) = error $ "Did not understand argument: " ++ y data BuildArgs = BuildArgs { sandbox :: String , buildPlanSrc :: FilePath , extraArgs' :: [String] -> [String] , noDocs :: Bool , buildCores :: Maybe Int , testThreads :: Maybe Int } parseBuildArgs :: GhcMajorVersion -> [String] -> IO BuildArgs parseBuildArgs version = loop BuildArgs { sandbox = sandboxRoot $ defaultBuildSettings Nothing version , buildPlanSrc = defaultBuildPlan , extraArgs' = id , noDocs = False , buildCores = Nothing , testThreads = Nothing } where loop x [] = return x loop x ("--sandbox":y:rest) = loop x { sandbox = y } rest loop x ("--build-plan":y:rest) = loop x { buildPlanSrc = y } rest loop x ("--arg":y:rest) = loop x { extraArgs' = extraArgs' x . (y:) } rest loop x ("--no-docs":rest) = loop x { noDocs = True } rest loop x ("-j":y:rest) = loop x { buildCores = Just $ read y } rest loop x ("--test-threads":y:rest) = loop x { testThreads = Just $ read y } rest loop _ (y:_) = error $ "Did not understand argument: " ++ y defaultBuildPlan :: FilePath defaultBuildPlan = "build-plan.txt" withBuildSettings :: [String] -> (BuildSettings -> BuildPlan -> IO a) -> IO a withBuildSettings args f = do version <- getGhcVersion BuildArgs {..} <- parseBuildArgs version args bp <- readBuildPlan buildPlanSrc let bs = defaultBuildSettings buildCores version modTestThreads settings' = case testThreads of Nothing -> settings' Just t -> settings' { testWorkerThreads = t } settings = modTestThreads bs { sandboxRoot = sandbox , extraArgs = extraArgs' . extraArgs bs , buildDocs = not noDocs } f settings bp main :: IO () main = do args <- getArgs case args of "select":rest -> do SelectArgs {..} <- parseSelectArgs rest ghcVersion <- getGhcVersion bp <- select (defaultSelectSettings ghcVersion $ not noPlatform) { excludedPackages = fromList $ map PackageName excluded , requireHaskellPlatform = not noPlatform , ignoreUpgradeableCore = ignoreUpgradeable , allowedPackage = if onlyPermissive then allowPermissive allowed else const $ Right () , useGlobalDatabase = globalDB } writeBuildPlan buildPlanDest bp ("check":rest) -> withBuildSettings rest checkPlan ("build":rest) -> withBuildSettings rest build ("test":rest) -> withBuildSettings rest runTestSuites ("tarballs":rest) -> withBuildSettings rest $ const makeTarballs ["init"] -> do putStrLn "Note: init isn't really ready for prime time use." putStrLn "Using it may make it impossible to build stackage." putStr "Are you sure you want continue (y/n)? " hFlush stdout x <- getLine case x of c:_ | c `elem` "yY" -> stackageInit _ -> putStrLn "Probably a good decision, exiting." ["update"] -> stackageInit >> error "FIXME update" _ -> do pn <- getProgName putStrLn $ "Usage: " ++ pn ++ " <command>" putStrLn "Available commands:" --putStrLn " update Download updated Stackage databases. Automatically calls init." --putStrLn " init Initialize your cabal file to use Stackage" putStrLn " uploads" putStrLn " select [--no-clean] [--no-platform] [--exclude package...] [--only-permissive] [--allow package] [--build-plan file]" putStrLn " check [--build-plan file] [--sandbox rootdir] [--arg cabal-arg]" putStrLn " build [--build-plan file] [--sandbox rootdir] [--arg cabal-arg]" putStrLn " test [--build-plan file] [--sandbox rootdir] [--arg cabal-arg] [--no-docs]"
Tarrasch/stackage
app/stackage.hs
mit
6,102
0
19
1,957
1,560
823
737
124
10
{-# LANGUAGE NoMonomorphismRestriction #-} module Plugins.Gallery.Gallery.Manual49 where import Diagrams.Prelude example = circle 1 ||| strutX 2 ||| square 2
andrey013/pluginstest
Plugins/Gallery/Gallery/Manual49.hs
mit
170
0
7
31
36
20
16
4
1
{-# htermination (toEnumTup0 :: MyInt -> Tup0) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Tup0 = Tup0 ; data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; primEqNat :: Nat -> Nat -> MyBool; primEqNat Zero Zero = MyTrue; primEqNat Zero (Succ y) = MyFalse; primEqNat (Succ x) Zero = MyFalse; primEqNat (Succ x) (Succ y) = primEqNat x y; primEqInt :: MyInt -> MyInt -> MyBool; primEqInt (Pos (Succ x)) (Pos (Succ y)) = primEqNat x y; primEqInt (Neg (Succ x)) (Neg (Succ y)) = primEqNat x y; primEqInt (Pos Zero) (Neg Zero) = MyTrue; primEqInt (Neg Zero) (Pos Zero) = MyTrue; primEqInt (Neg Zero) (Neg Zero) = MyTrue; primEqInt (Pos Zero) (Pos Zero) = MyTrue; primEqInt vv vw = MyFalse; esEsMyInt :: MyInt -> MyInt -> MyBool esEsMyInt = primEqInt; toEnum0 MyTrue vx = Tup0; toEnum1 vx = toEnum0 (esEsMyInt vx (Pos Zero)) vx; toEnumTup0 :: MyInt -> Tup0 toEnumTup0 vx = toEnum1 vx;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/toEnum_1.hs
mit
977
0
9
209
436
234
202
25
1
{-# LANGUAGE DeriveGeneric #-} module D20.Internal.Character.BasicClass where import GHC.Generics import D20.Internal.Character.Ability import D20.Internal.Character.ClassTable import D20.Internal.Character.Feat import D20.Internal.Character.Skill import D20.Internal.Character.Talent import D20.Dice -- import qualified Data.Map as M data BasicClass = BasicClass {getClassAbility :: Ability ,getHitDie :: Die ,getActionPoints :: Int ,getClassSkills :: [(Skill,SkillRank)] , -- ,getClassSkills :: M.Map Skill SkillRank getClassTable :: ClassTable ,getClassStartingSkillPoints :: SkillGain ,getClassSkillPointsPerLevel :: SkillGain ,getStartingFeats :: [FeatReference] ,getTalents :: [Talent] ,getBonusFeats :: [Feat]} deriving (Show,Generic) class HasClass a where getClass :: a -> ClassTableRow getNumberOfAttacks :: a -> Int getNumberOfAttacks = length . getBaseAttackBonuses . getClass
elkorn/d20
src/D20/Internal/Character/BasicClass.hs
mit
1,051
0
10
253
194
124
70
25
0
module Tree where import Data.Semigroup import Test.QuickCheck import Test.QuickCheck.Checkers (EqProp, eq, (=-=)) data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) deriving (Eq, Show) instance Functor Tree where fmap _ Empty = Empty fmap f (Leaf a) = Leaf (f a) fmap f (Node xs x xs') = Node (fmap f xs) (f x) (fmap f xs') instance Foldable Tree where foldMap _ Empty = mempty foldMap f (Leaf x) = f x foldMap f (Node xs x xs') = foldMap f xs `mappend` f x `mappend` foldMap f xs' -- λ> traverse (Just . (+10)) (Node (Leaf 1) 2 (Leaf 3)) instance Traversable Tree where traverse _ Empty = pure Empty traverse f (Leaf x) = Leaf <$> f x traverse f (Node xs x xs') = Node <$> traverse f xs <*> f x <*> traverse f xs' -- λ> sample (arbitrary :: Gen (Tree Int)) instance Arbitrary a => Arbitrary (Tree a) where arbitrary = do a <- arbitrary b <- arbitrary c <- arbitrary d <- arbitrary frequency [(1, return Empty), (2, return $ Leaf a), (3, return $ Node b c d)] instance Eq a => EqProp (Tree a) where (=-=) = eq
JoshuaGross/haskell-learning-log
Code/Haskellbook/Foldable/src/Tree.hs
mit
1,097
0
12
283
479
246
233
26
0
{-# LANGUAGE NamedFieldPuns #-} module Utils where import Control.Monad.State.Lazy import Crypto.Cipher.AES import Crypto.Cipher.Types import Crypto.Error import Data.Bits import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import Data.Int import Data.Word import System.Entropy import Text.Bytedump import Types processOutputs :: LBS.ByteString -> [Literal] -> [Either KeyType Bool] -> (LBS.ByteString, [Either KeyType Bool]) processOutputs lastState [] accum = (lastState, accum) processOutputs initialState (x:xs) accum = case x of Constant b' -> processOutputs initialState xs (accum ++ [Right b']) Input{keyState} -> let (resultValue, resultState) = runState keyState initialState in processOutputs resultState xs (accum ++ [Left resultValue]) -- In Bytes -- cipherSize :: Int64 cipherSize = 16 --DO NOT CHANGE keyLength :: Int64 keyLength = 15 padLength :: Int64 padLength = cipherSize - keyLength zeros :: BS.ByteString zeros = getFill False ones :: BS.ByteString ones = getFill True getFill :: Bool -> BS.ByteString getFill x = BS.pack $ map (const (toEnum $ fromEnum x :: Word8)) [1 .. padLength] getFills :: Bool -> (BS.ByteString, BS.ByteString) getFills x = (getFill x, getFill $ not x) genFixedKey :: IO BS.ByteString genFixedKey = getEntropy (fromIntegral cipherSize) genRootKey :: IO BS.ByteString genRootKey = do a <- getEntropy (fromIntegral cipherSize) let (Just (as, al)) = BS.unsnoc a return $ BS.snoc as (setBit al 0) mkKeyPairFromKey :: BS.ByteString -> BS.ByteString -> Bool -> (BS.ByteString, BS.ByteString) mkKeyPairFromKey rkey k0 sw = let k1 = BS.pack $ BS.zipWith xor k0 rkey in if sw then (k1, k0) else (k0, k1) genKeyPair :: BS.ByteString -> IO (BS.ByteString, BS.ByteString) genKeyPair rkey = do rnd <- getEntropy (fromIntegral cipherSize) return $ mkKeyPairFromKey rkey rnd False getAESKeys :: BS.ByteString -> BS.ByteString -> (AES128, AES128) getAESKeys a b = (throwCryptoError $ cipherInit a :: AES128, throwCryptoError $ cipherInit b :: AES128) initFixedKey :: BS.ByteString -> AES128 initFixedKey str = throwCryptoError $ cipherInit str hash :: AES128 -> Key -> Key hash = ecbEncrypt hashPair :: AES128 -> Key -> Key -> Key hashPair fkey a b = BS.pack $ BS.zipWith xor (hash fkey a) (hash fkey b) enc :: AES128 -> (Key, Key, Key) -> Key enc fkey (a, b, o) = BS.pack $ BS.zipWith xor o $ hashPair fkey a b keyString :: BS.ByteString -> String keyString = dumpBS printKey :: Maybe Bool -> BS.ByteString -> IO() printKey (Just False) key = putStrLn $ "0:\t" ++ keyString key printKey (Just True) key = putStrLn $ "1:\t" ++ keyString key printKey Nothing key = putStrLn $ "?:\t" ++ keyString key bits2Bools :: FiniteBits a => a -> [Bool] bits2Bools i = reverse $ map (testBit i) [0..(finiteBitSize i - 1) :: Int] bsToBools :: BS.ByteString -> [Bool] bsToBools bs = concatMap bits2Bools $ BS.unpack bs numBytes :: FiniteBits a => a -> Int numBytes n = finiteBitSize n `quot` 8 --
ur-crypto/sec-lib
library/Utils.hs
mit
3,149
0
14
659
1,137
600
537
77
2
{-# LANGUAGE OverloadedStrings, MultiWayIf #-} {-# LANGUAGE RecordWildCards #-} -- | Data structures pertaining to Discord Channels module Network.Discord.Types.Channel where import Control.Monad (mzero) import Data.Text as Text (pack, Text) import Data.Aeson import Data.Aeson.Types (Parser) import Data.Time.Clock import Data.Vector (toList) import qualified Data.HashMap.Strict as HM import qualified Data.Vector as V import Network.Discord.Types.Prelude -- |Represents information about a user. data User = User { userId :: {-# UNPACK #-} !Snowflake -- ^ The user's id. , userName :: String -- ^ The user's username, not unique across -- the platform. , userDiscrim :: String -- ^ The user's 4-digit discord-tag. , userAvatar :: Maybe String -- ^ The user's avatar hash. , userIsBot :: Bool -- ^ Whether the user belongs to an OAuth2 -- application. , userMfa :: Maybe Bool -- ^ Whether the user has two factor -- authentication enabled on the account. , userVerified :: Maybe Bool -- ^ Whether the email on this account has -- been verified. , userEmail :: Maybe String -- ^ The user's email. } | Webhook deriving (Show, Eq) instance FromJSON User where parseJSON (Object o) = User <$> o .: "id" <*> o .: "username" <*> o .: "discriminator" <*> o .:? "avatar" <*> o .:? "bot" .!= False <*> o .:? "mfa_enabled" <*> o .:? "verified" <*> o .:? "email" parseJSON _ = mzero -- | Guild channels represent an isolated set of users and messages in a Guild (Server) data Channel -- | A text channel in a guild. = Text { channelId :: Snowflake -- ^ The id of the channel (Will be equal to -- the guild if it's the "general" channel). , channelGuild :: Snowflake -- ^ The id of the guild. , channelName :: String -- ^ The name of the guild (2 - 1000 characters). , channelPosition :: Integer -- ^ The storing position of the channel. , channelPermissions :: [Overwrite] -- ^ An array of permission 'Overwrite's , channelTopic :: String -- ^ The topic of the channel. (0 - 1024 chars). , channelLastMessage :: Snowflake -- ^ The id of the last message sent in the -- channel } -- |A voice channel in a guild. | Voice { channelId:: Snowflake , channelGuild:: Snowflake , channelName:: String , channelPosition:: Integer , channelPermissions:: [Overwrite] , channelBitRate:: Integer -- ^ The bitrate (in bits) of the channel. , channelUserLimit:: Integer -- ^ The user limit of the voice channel. } -- | DM Channels represent a one-to-one conversation between two users, outside the scope -- of guilds | DirectMessage { channelId :: Snowflake , channelRecipients :: [User] -- ^ The 'User' object(s) of the DM recipient(s). , channelLastMessage :: Snowflake } deriving (Show, Eq) instance FromJSON Channel where parseJSON = withObject "text or voice" $ \o -> do type' <- (o .: "type") :: Parser Int case type' of 0 -> Text <$> o .: "id" <*> o .: "guild_id" <*> o .: "name" <*> o .: "position" <*> o .: "permission_overwrites" <*> o .:? "topic" .!= "" <*> o .:? "last_message_id" .!= 0 1 -> DirectMessage <$> o .: "id" <*> o .: "recipients" <*> o .:? "last_message_id" .!= 0 2 -> Voice <$> o .: "id" <*> o .: "guild_id" <*> o .: "name" <*> o .: "position" <*> o .: "permission_overwrites" <*> o .: "bitrate" <*> o .: "user_limit" _ -> mzero -- | Permission overwrites for a channel. data Overwrite = Overwrite { overwriteId:: {-# UNPACK #-} !Snowflake -- ^ 'Role' or 'User' id , overWriteType:: String -- ^ Either "role" or "member , overwriteAllow:: Integer -- ^ Allowed permission bit set , overwriteDeny:: Integer -- ^ Denied permission bit set } deriving (Show, Eq) instance FromJSON Overwrite where parseJSON (Object o) = Overwrite <$> o .: "id" <*> o .: "type" <*> o .: "allow" <*> o .: "deny" parseJSON _ = mzero -- | Represents information about a message in a Discord channel. data Message = Message { messageId :: {-# UNPACK #-} !Snowflake -- ^ The id of the message , messageChannel :: {-# UNPACK #-} !Snowflake -- ^ Id of the channel the message -- was sent in , messageAuthor :: User -- ^ The 'User' the message was sent -- by , messageContent :: Text -- ^ Contents of the message , messageTimestamp :: UTCTime -- ^ When the message was sent , messageEdited :: Maybe UTCTime -- ^ When/if the message was edited , messageTts :: Bool -- ^ Whether this message was a TTS -- message , messageEveryone :: Bool -- ^ Whether this message mentions -- everyone , messageMentions :: [User] -- ^ 'User's specifically mentioned in -- the message , messageMentionRoles :: [Snowflake] -- ^ 'Role's specifically mentioned in -- the message , messageAttachments :: [Attachment] -- ^ Any attached files , messageEmbeds :: [Embed] -- ^ Any embedded content , messageNonce :: Maybe Snowflake -- ^ Used for validating if a message -- was sent , messagePinned :: Bool -- ^ Whether this message is pinned } deriving (Show, Eq) instance FromJSON Message where parseJSON (Object o) = Message <$> o .: "id" <*> o .: "channel_id" <*> o .:? "author" .!= Webhook <*> o .:? "content" .!= "" <*> o .:? "timestamp" .!= epochTime <*> o .:? "edited_timestamp" <*> o .:? "tts" .!= False <*> o .:? "mention_everyone" .!= False <*> o .:? "mentions" .!= [] <*> o .:? "mention_roles" .!= [] <*> o .:? "attachments" .!= [] <*> o .: "embeds" <*> o .:? "nonce" <*> o .:? "pinned" .!= False parseJSON _ = mzero -- |Represents an attached to a message file. data Attachment = Attachment { attachmentId :: {-# UNPACK #-} !Snowflake -- ^ Attachment id , attachmentFilename :: String -- ^ Name of attached file , attachmentSize :: Integer -- ^ Size of file (in bytes) , attachmentUrl :: String -- ^ Source of file , attachmentProxy :: String -- ^ Proxied url of file , attachmentHeight :: Maybe Integer -- ^ Height of file (if image) , attachmentWidth :: Maybe Integer -- ^ Width of file (if image) } deriving (Show, Eq) instance FromJSON Attachment where parseJSON (Object o) = Attachment <$> o .: "id" <*> o .: "filename" <*> o .: "size" <*> o .: "url" <*> o .: "proxy_url" <*> o .:? "height" <*> o .:? "width" parseJSON _ = mzero -- |An embed attached to a message. data Embed = Embed { embedTitle :: String -- ^ Title of the embed , embedType :: String -- ^ Type of embed (Always "rich" for webhooks) , embedDesc :: String -- ^ Description of embed , embedUrl :: String -- ^ URL of embed , embedTime :: UTCTime -- ^ The time of the embed content , embedColor :: Integer -- ^ The embed color , embedFields ::[SubEmbed] -- ^ Fields of the embed } deriving (Show, Read, Eq) instance FromJSON Embed where parseJSON (Object o) = Embed <$> o .:? "title" .!= "Untitled" <*> o .: "type" <*> o .:? "description" .!= "" <*> o .:? "url" .!= "" <*> o .:? "timestamp" .!= epochTime <*> o .:? "color" .!= 0 <*> sequence (HM.foldrWithKey to_embed [] o) where to_embed k (Object v) a | k == pack "footer" = (Footer <$> v .: "text" <*> v .:? "icon_url" .!= "" <*> v .:? "proxy_icon_url" .!= "") : a | k == pack "image" = (Image <$> v .: "url" <*> v .: "proxy_url" <*> v .: "height" <*> v .: "width") : a | k == pack "thumbnail" = (Thumbnail <$> v .: "url" <*> v .: "proxy_url" <*> v .: "height" <*> v .: "width") : a | k == pack "video" = (Video <$> v .: "url" <*> v .: "height" <*> v .: "width") : a | k == pack "provider" = (Provider <$> v .: "name" <*> v .:? "url" .!= "") : a | k == pack "author" = (Author <$> v .: "name" <*> v .:? "url" .!= "" <*> v .:? "icon_url" .!= "" <*> v .:? "proxy_icon_url" .!= "") : a to_embed k (Array v) a | k == pack "fields" = [Field <$> i .: "name" <*> i .: "value" <*> i .: "inline" | Object i <- toList v] ++ a to_embed _ _ a = a parseJSON _ = mzero instance ToJSON Embed where toJSON (Embed {..}) = object [ "title" .= embedTitle , "type" .= embedType , "description" .= embedDesc , "url" .= embedUrl , "timestamp" .= embedTime , "color" .= embedColor ] |> makeSubEmbeds embedFields where (Object o) |> hm = Object $ HM.union o hm _ |> _ = error "Type mismatch" makeSubEmbeds = foldr embed HM.empty embed (Thumbnail url _ height width) = HM.alter (\_ -> Just $ object [ "url" .= url , "height" .= height , "width" .= width ]) "thumbnail" embed (Image url _ height width) = HM.alter (\_ -> Just $ object [ "url" .= url , "height" .= height , "width" .= width ]) "image" embed (Author name url icon _) = HM.alter (\_ -> Just $ object [ "name" .= name , "url" .= url , "icon_url" .= icon ]) "author" embed (Footer text icon _) = HM.alter (\_ -> Just $ object [ "text" .= text , "icon_url" .= icon ]) "footer" embed (Field name value inline) = HM.alter (\val -> case val of Just (Array a) -> Just . Array $ V.cons (object [ "name" .= name , "value" .= value , "inline" .= inline ]) a _ -> Just $ toJSON [ object [ "name" .= name , "value" .= value , "inline" .= inline ] ] ) "fields" embed _ = id -- |Represents a part of an embed. data SubEmbed = Thumbnail String String Integer Integer | Video String Integer Integer | Image String String Integer Integer | Provider String String | Author String String String String | Footer String String String | Field String String Bool deriving (Show, Read, Eq)
jano017/Discord.hs
src/Network/Discord/Types/Channel.hs
mit
13,073
0
42
5,756
2,507
1,378
1,129
279
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} module Language.Rowling.ValuesSpec (main, spec) where import SpecHelper import Language.Rowling.Definitions.Expressions import Language.Rowling.Definitions.Values main :: IO () main = hspec $ spec >> spec spec :: Spec spec = patternMatchSpec patternMatchSpec :: Spec patternMatchSpec = describe "pattern matching" $ do it "should match literals that equal" $ do match (Int 1) (VInt 1) match (Float 1) (VFloat 1) match "False" (VBool False) match (String "wazzap") (VString "wazzap") it "should not match literals that are not equal" $ do noMatch (Int 1) (VInt 2) noMatch (Float 1) (VFloat 2) noMatch (String "hey") (VString "yo") it "should match variables" $ do let vals :: [Value] = [VInt 1, VFloat 1, VBool True, ["hello", "world"]] forM_ vals $ \val -> matchWith (Variable "x") val [("x", val)] it "should match list patterns" $ do match [Int 1, Int 2] [VInt 1, VInt 2] matchWith ["a", Int 1] [VInt 0, VInt 1] [("a", VInt 0)] noMatch ["a", Int 1] [VInt 0, VInt 2] describe "record patterns" $ do it "should match when keys match" $ do match (Record [("x", Int 1), ("y", Int 3)]) (VRecord [("x", VInt 1), ("y", VInt 3)]) matchWith (Record [("x", "a"), ("y", "b")]) (VRecord [("x", VInt 2), ("y", VFloat 5)]) [("a", VInt 2), ("b", VFloat 5)] it "should match when there are extra keys in the value" $ do match (Record [("x", Int 1), ("y", Int 3)]) (VRecord [("x", VInt 1), ("y", VInt 3), ("z", VInt 0)]) matchWith (Record [("x", "a"), ("y", "b")]) (VRecord [("x", VInt 2), ("y", VFloat 5), ("z", VInt 0)]) [("a", VInt 2), ("b", VFloat 5)] it "should NOT match when there are extra keys in the pattern" $ do noMatch (Record [("x", Int 1), ("y", Int 3)]) (VRecord [("x", VInt 2), ("y", VInt 3)]) noMatch (Record [("x", Int 1), ("y", Int 3)]) (VRecord [("x", VInt 2)]) describe "haskell builtins" $ do it "should use haskell booleans" $ do match "True" (VBool True) match "False" (VBool False) noMatch "False" (VBool True) noMatch "True" (VBool False) it "should use haskell maybes" $ do match "None" (VMaybe Nothing) match (Apply "Some" (Int 3)) (VMaybe (Just $ VInt 3)) noMatch "None" (VMaybe $ Just (VInt 0)) describe "compound expressions" $ do it "should match singleton constructors" $ do match "Foo" (VTagged "Foo" []) it "should match applied constructors" $ do match (Apply "Foo" (Int 1)) (VTagged "Foo" [VInt 1]) it "should assign variables correctly" $ do matchWith (Apply "Foo" "x") (VTagged "Foo" [VInt 1]) [("x", VInt 1)] it "should handle multiple variables" $ do matchWith (Apply (Apply "A" "b") "c") (VTagged "A" [VInt 1, VFloat 2]) [("b", VInt 1), ("c", VFloat 2)] it "should handle a mix of variables and constants" $ do matchWith (Apply (Apply "A" "b") (Int 1)) (VTagged "A" [VInt 1, VInt 1]) [("b", VInt 1)] it "should reject incompatible matches" $ do noMatch (Apply (Apply "A" "b") (Int 1)) (VTagged "A" [VInt 1, VInt 0]) it "should reject when the length isn't correct" $ do noMatch (Apply (Apply "A" "b") (Int 1)) (VTagged "A" [VInt 0]) it "should handle nested compound expressions" $ do -- Pattern: @A (B 1) x@. Value: @A (B 1) "hello"@ matchWith (Apply (Apply "A" (Apply "B" (Int 1))) "x") (VTagged "A" [VTagged "B" [VInt 1], VString "hello"]) [("x", VString "hello")] -- Pattern: @A (B 1) x@. Value: @A (B 2) "hello"@ noMatch (Apply (Apply "A" (Apply "B" (Int 1))) "x") (VTagged "A" [VTagged "B" [VInt 2], VString "hello"]) where matchWith :: Pattern -> Value -> HashMap Name Value -> IO () matchWith p v bs = patternMatch p v `shouldBeJ` bs match :: Pattern -> Value -> IO () match p v = matchWith p v [] noMatch :: Pattern -> Value -> IO () noMatch p v = shouldBeN $ patternMatch p v
thinkpad20/rowling
test/Language/Rowling/ValuesSpec.hs
mit
4,301
0
22
1,127
1,799
898
901
90
1
----------------------------------------------------------------------------- -- -- Module : PhyQ.Quantity -- Copyright : -- License : MIT -- -- Maintainer : - -- Stability : -- Portability : -- -- | -- module PhyQ.Quantity ( module Export , TypesEq(..), type (=~=), type (/~=), TypesOrd(..) ) where import PhysicalQuantities.Definitions as Export import PhyQ.Quantity.Base as Export import PhyQ.Quantity.Derived as Export import TypeNum.TypeFunctions -----------------------------------------------------------------------------
fehu/PhysicalQuantities
src/PhyQ/Quantity.hs
mit
562
0
5
89
81
61
20
-1
-1
-- Copyright: (c) 2013 Gree, Inc. -- License: MIT-style import System.Prefork import System.Posix import System.Exit (exitSuccess) data ServerConfig = ServerConfig data Worker = Worker1 String | Worker2 String deriving (Show, Read, Eq) instance WorkerContext Worker main :: IO () main = defaultMain defaultSettings { psUpdateConfig = updateConfig , psUpdateServer = updateServer , psOnStart = \_ -> do pid <- getProcessID putStrLn $ "Please send SIGHUP to " ++ show pid ++ " to relaunch workers" } $ \w -> case w of Worker1 msg -> putStrLn msg >> exitSuccess Worker2 msg -> putStrLn msg >> exitSuccess updateConfig :: IO (Maybe ServerConfig) updateConfig = do return (Just ServerConfig) updateServer :: ServerConfig -> IO ([ProcessID]) updateServer ServerConfig = do pid1 <- forkWorkerProcess (Worker1 "Hello. I'm a worker 1.") pid2 <- forkWorkerProcess (Worker2 "Hello. I'm a worker 2.") return ([pid1, pid2])
gree/haskell-prefork
sample/various-workers.hs
mit
956
3
14
183
269
140
129
24
2
{-| Module : Web.App.State Copyright : (c) Nathaniel Symer, 2016 License : MIT Maintainer : [email protected] Stability : experimental Portability : POSIX Typeclass all types to be used as state for a WebApp must have an instance of. -} module Web.App.State ( WebAppState(..) ) where -- |Defines a common interface for an app's state. class WebAppState s where -- |Create an app state initState :: IO s -- |Destroy an app state destroyState :: s -- ^ the state to destroy -> IO () instance WebAppState () where initState = return () destroyState _ = return ()
fhsjaagshs/webapp
src/Web/App/State.hs
mit
619
0
9
160
85
47
38
10
0
data StatePoint
Zomega/thesis
Wurm/System/ControlledSystem.hs
mit
16
0
3
2
4
2
2
-1
-1
module GHCJS.DOM.SVGNumberList ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SVGNumberList.hs
mit
43
0
3
7
10
7
3
1
0
{-# LANGUAGE CPP #-} module Tinc.GhcPkgSpec (spec) where import Control.Monad import System.Environment import Helper import Tinc.Facts import Tinc.GhcPkg import Tinc.Package globalPackages :: [String] globalPackages = [ "array" , "base" , "binary" , "bin-package-db" , "bytestring" , "Cabal" , "containers" , "deepseq" , "directory" , "filepath" , "ghc" , "ghc-prim" , "hoopl" , "hpc" , "integer-gmp" , "pretty" , "process" , "rts" , "template-haskell" , "time" , "unix" , "haskeline" , "terminfo" , "transformers" , "xhtml" #if __GLASGOW_HASKELL__ < 710 , "haskell2010" , "haskell98" , "old-locale" , "old-time" #endif ] spec :: Spec spec = do describe "listGlobalPackages" $ before_ (getExecutablePath >>= useNix >>= (`when` pending)) $ do it "lists packages from global package database" $ do packages <- listGlobalPackages map packageName packages `shouldMatchList` globalPackages
robbinch/tinc
test/Tinc/GhcPkgSpec.hs
mit
1,030
0
14
268
217
131
86
45
1
module Main where import NXT -- btBrick = NXTBrick Bluetooth "/dev/tty.NXT-DevB-1" -- -- main = do -- h <- nxtOpen btBrick -- -- reactimate (mkInit h) (mkSense h) (mkActuate h) nxtSF -- -- nxtClose h main = testloop
janv/haskell-nxt
src/test.hs
mit
226
0
4
48
20
16
4
3
1
module Driver where import Data.Monoid ((<>)) import Data.Foldable import Control.Monad import Data.Maybe import Data.Int import Data.Either hiding (fromRight) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Char8 as BS import qualified Data.Vector as V import Test.Tasty import Test.Tasty.HUnit import Database.PostgreSQL.Driver.Connection import Database.PostgreSQL.Driver.StatementStorage import Database.PostgreSQL.Driver.Query import Database.PostgreSQL.Protocol.Types import Database.PostgreSQL.Protocol.DataRows import Database.PostgreSQL.Protocol.Store.Decode import Database.PostgreSQL.Protocol.Decoders import Database.PostgreSQL.Protocol.Codecs.Decoders import Database.PostgreSQL.Protocol.Codecs.Encoders as PE import Connection testDriver :: TestTree testDriver = testGroup "Driver" [ testCase "Single batch" testBatch , testCase "Two batches" testTwoBatches , testCase "Multiple batches" testMultipleBatches , testCase "Empty query" testEmptyQuery , testCase "Query without result" testQueryWithoutResult , testCase "Invalid queries" testInvalidBatch , testCase "Valid after postgres error" testValidAfterError , testCase "Describe statement" testDescribeStatement , testCase "Describe statement with no data" testDescribeStatementNoData , testCase "Describe empty statement" testDescribeStatementEmpty , testCase "SimpleQuery" testSimpleQuery , testCase "PreparedStatementCache" testPreparedStatementCache , testCase "Query with large response" testLargeQuery , testCase "Correct datarows" testCorrectDatarows ] makeQuery1 :: B.ByteString -> Query makeQuery1 n = Query "SELECT $1" [(Oid 23, Just $ PE.bytea n )] Text Text AlwaysCache makeQuery2 :: B.ByteString -> B.ByteString -> Query makeQuery2 n1 n2 = Query "SELECT $1 + $2" [(Oid 23, Just $ PE.bytea n1), (Oid 23, Just $ PE.bytea n2)] Text Text AlwaysCache fromRight :: Either e a -> a fromRight (Right v) = v fromRight _ = error "fromRight" fromMessage :: Either e DataRows -> B.ByteString -- TODO -- 5 bytes -header, 2 bytes -count, 4 bytes - length fromMessage (Right rows) = B.drop 11 $ flattenDataRows rows fromMessage _ = error "from message" -- | Single batch. testBatch :: IO () testBatch = withConnection $ \c -> do let a = "5" b = "3" sendBatchAndSync c [makeQuery1 a, makeQuery1 b] r1 <- readNextData c r2 <- readNextData c waitReadyForQuery c a @=? fromMessage r1 b @=? fromMessage r2 -- | Two batches in single transaction. testTwoBatches :: IO () testTwoBatches = withConnection $ \c -> do let a = 7 b = 2 sendBatchAndFlush c [ makeQuery1 (BS.pack (show a)) , makeQuery1 (BS.pack (show b))] r1 <- fromMessage <$> readNextData c r2 <- fromMessage <$> readNextData c sendBatchAndSync c [makeQuery2 r1 r2] r <- readNextData c waitReadyForQuery c BS.pack (show $ a + b) @=? fromMessage r -- | Multiple batches with individual transactions in single connection. testMultipleBatches :: IO () testMultipleBatches = withConnection $ replicateM_ 10 . assertSingleBatch where assertSingleBatch c = do let a = "5" b = "6" sendBatchAndSync c [ makeQuery1 a, makeQuery1 b] r1 <- readNextData c a @=? fromMessage r1 r2 <- readNextData c b @=? fromMessage r2 waitReadyForQuery c -- | Query is empty string. testEmptyQuery :: IO () testEmptyQuery = assertQueryNoData $ Query "" [] Text Text NeverCache -- | Query than returns no datarows. testQueryWithoutResult :: IO () testQueryWithoutResult = assertQueryNoData $ Query "SET client_encoding TO UTF8" [] Text Text NeverCache -- | Asserts that query returns no data rows. assertQueryNoData :: Query -> IO () assertQueryNoData q = withConnection $ \c -> do sendBatchAndSync c [q] r <- fromRight <$> readNextData c waitReadyForQuery c Empty @=? r -- | Asserts that all the received data messages are in form (Right _) checkRightResult :: Connection -> Int -> Assertion checkRightResult conn 0 = pure () checkRightResult conn n = readNextData conn >>= either (const $ assertFailure "Result is invalid") (const $ checkRightResult conn (n - 1)) -- | Asserts that (Left _) as result exists in the received data messages. checkInvalidResult :: Connection -> Int -> Assertion checkInvalidResult conn 0 = assertFailure "Result is right" checkInvalidResult conn n = readNextData conn >>= either (const $ pure ()) (const $ checkInvalidResult conn (n -1)) -- | Diffirent invalid queries in batches. testInvalidBatch :: IO () testInvalidBatch = do let rightQuery = makeQuery1 "5" q1 = Query "SEL $1" [(Oid 23, Just $ PE.bytea "5")] Text Text NeverCache q2 = Query "SELECT $1" [(Oid 23, Just $ PE.bytea "a")] Text Text NeverCache q4 = Query "SELECT $1" [] Text Text NeverCache assertInvalidBatch "Parse error" [q1] assertInvalidBatch "Invalid param" [ q2] assertInvalidBatch "Missed oid of param" [ q4] assertInvalidBatch "Parse error" [rightQuery, q1] assertInvalidBatch "Invalid param" [rightQuery, q2] assertInvalidBatch "Missed oid of param" [rightQuery, q4] where assertInvalidBatch desc qs = withConnection $ \c -> do sendBatchAndSync c qs checkInvalidResult c $ length qs -- | Connection remains valid even after PostgreSQL returned error on the -- previous query. testValidAfterError :: IO () testValidAfterError = withConnection $ \c -> do let a = "5" rightQuery = makeQuery1 a invalidQuery = Query "SELECT $1" [] Text Text NeverCache sendBatchAndSync c [invalidQuery] checkInvalidResult c 1 waitReadyForQuery c sendBatchAndSync c [rightQuery] r <- readNextData c waitReadyForQuery c a @=? fromMessage r -- | Describes usual statement. testDescribeStatement :: IO () testDescribeStatement = withConnectionCommon $ \c -> do r <- describeStatement c $ "select typname, typnamespace, typowner, typlen, typbyval," <> "typcategory, typispreferred, typisdefined, typdelim, typrelid," <> "typelem, typarray from pg_type where typtypmod = $1 " <> "and typisdefined = $2" assertBool "Should be Right" $ isRight r -- | Describes statement that returns no data. testDescribeStatementNoData :: IO () testDescribeStatementNoData = withConnectionCommon $ \c -> do r <- fromRight <$> describeStatement c "SET client_encoding TO UTF8" assertBool "Should be empty" $ null (fst r) assertBool "Should be empty" $ null (snd r) -- | Describes statement that is empty string. testDescribeStatementEmpty :: IO () testDescribeStatementEmpty = withConnectionCommon $ \c -> do r <- fromRight <$> describeStatement c "" assertBool "Should be empty" $ null (fst r) assertBool "Should be empty" $ null (snd r) -- | Query using simple query protocol. testSimpleQuery :: IO () testSimpleQuery = withConnectionCommon $ \c -> do r <- sendSimpleQuery c $ "DROP TABLE IF EXISTS a;" <> "CREATE TABLE a(v int);" <> "INSERT INTO a VALUES (1), (2), (3);" <> "SELECT * FROM a;" <> "DROP TABLE a;" assertBool "Should be Right" $ isRight r -- | Test that cache of statements works. testPreparedStatementCache :: IO () testPreparedStatementCache = withConnection $ \c -> do let a = 7 b = 2 sendBatchAndSync c [ makeQuery1 (BS.pack (show a)) , makeQuery1 (BS.pack (show b)) , makeQuery2 (BS.pack (show a)) (BS.pack (show b))] r1 <- fromMessage <$> readNextData c r2 <- fromMessage <$> readNextData c r3 <- fromMessage <$> readNextData c waitReadyForQuery c BS.pack (show a) @=? r1 BS.pack (show b) @=? r2 BS.pack (show $ a + b) @=? r3 size <- getCacheSize $ connStatementStorage c -- 2 different statements were send 2 @=? size -- | Test that large responses are properly handled testLargeQuery :: IO () testLargeQuery = withConnection $ \c -> do sendBatchAndSync c [Query largeStmt [] Text Text NeverCache ] r <- readNextData c waitReadyForQuery c assertBool "Should be Right" $ isRight r where largeStmt = "select typname, typnamespace, typowner, typlen, typbyval," <> "typcategory, typispreferred, typisdefined, typdelim," <> "typrelid, typelem, typarray from pg_type " testCorrectDatarows :: IO () testCorrectDatarows = withConnection $ \c -> do let stmt = "SELECT * FROM generate_series(1, 1000)" sendBatchAndSync c [Query stmt [] Text Text NeverCache] r <- readNextData c case r of Left e -> error $ show e Right rows -> do map (BS.pack . show ) [1 .. 1000] @=? V.toList (decodeManyRows decodeDataRow rows) countDataRows rows @=? 1000 where -- TODO Right parser later decodeDataRow :: Decode B.ByteString decodeDataRow = do decodeHeader getInt16BE getByteString . fromIntegral =<< getInt32BE
postgres-haskell/postgres-wire
tests/Driver.hs
mit
9,248
0
18
2,132
2,385
1,182
1,203
203
2
{-# LANGUAGE FlexibleContexts #-} module Data.Functor.Foldable.Extended ( module Data.Functor.Foldable , cataM , paraM ) where import Prelude import Control.Monad import Data.Functor.Foldable import Data.Traversable as T -- from https://github.com/ekmett/recursion-schemes/issues/3 cataM :: (Recursive t, T.Traversable (Base t), Monad m) => (Base t a -> m a) -- ^ a monadic (Base t)-algebra -> t -- ^ fixed point -> m a -- ^ result cataM f = c where c = f <=< T.mapM c <=< (return . project) -- from http://jtobin.ca/monadic-recursion-schemes paraM :: (Monad m, T.Traversable (Base t), Recursive t) => (Base t (t, a) -> m a) -> t -> m a paraM alg = p where p = alg <=< traverse f . project f t = liftM2 (,) (return t) (p t)
imccoy/utopia
src/Data/Functor/Foldable/Extended.hs
mit
786
0
10
186
267
146
121
-1
-1
{-# LANGUAGE TemplateHaskell, CPP #-} module Yesod.Routes.TH.RenderRoute ( -- ** RenderRoute mkRenderRouteInstance , mkRenderRouteInstance' , mkRouteCons , mkRenderRouteClauses ) where import Yesod.Routes.TH.Types #if MIN_VERSION_template_haskell(2,11,0) import Language.Haskell.TH (conT) #endif import Language.Haskell.TH.Syntax import Data.Maybe (maybeToList) import Control.Monad (replicateM) import Data.Text (pack) import Web.PathPieces (PathPiece (..), PathMultiPiece (..)) import Yesod.Routes.Class #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) import Data.Monoid (mconcat) #endif -- | Generate the constructors of a route data type. mkRouteCons :: [ResourceTree Type] -> Q ([Con], [Dec]) mkRouteCons rttypes = mconcat <$> mapM mkRouteCon rttypes where mkRouteCon (ResourceLeaf res) = return ([con], []) where con = NormalC (mkName $ resourceName res) $ map (\x -> (notStrict, x)) $ concat [singles, multi, sub] singles = concatMap toSingle $ resourcePieces res toSingle Static{} = [] toSingle (Dynamic typ) = [typ] multi = maybeToList $ resourceMulti res sub = case resourceDispatch res of Subsite { subsiteType = typ } -> [ConT ''Route `AppT` typ] _ -> [] mkRouteCon (ResourceParent name _check pieces children) = do (cons, decs) <- mkRouteCons children #if MIN_VERSION_template_haskell(2,11,0) dec <- DataD [] (mkName name) [] Nothing cons <$> mapM conT [''Show, ''Read, ''Eq] #else let dec = DataD [] (mkName name) [] cons [''Show, ''Read, ''Eq] #endif return ([con], dec : decs) where con = NormalC (mkName name) $ map (\x -> (notStrict, x)) $ singles ++ [ConT $ mkName name] singles = concatMap toSingle pieces toSingle Static{} = [] toSingle (Dynamic typ) = [typ] -- | Clauses for the 'renderRoute' method. mkRenderRouteClauses :: [ResourceTree Type] -> Q [Clause] mkRenderRouteClauses = mapM go where isDynamic Dynamic{} = True isDynamic _ = False go (ResourceParent name _check pieces children) = do let cnt = length $ filter isDynamic pieces dyns <- replicateM cnt $ newName "dyn" child <- newName "child" let pat = ConP (mkName name) $ map VarP $ dyns ++ [child] pack' <- [|pack|] tsp <- [|toPathPiece|] let piecesSingle = mkPieces (AppE pack' . LitE . StringL) tsp pieces dyns childRender <- newName "childRender" let rr = VarE childRender childClauses <- mkRenderRouteClauses children a <- newName "a" b <- newName "b" colon <- [|(:)|] let cons y ys = InfixE (Just y) colon (Just ys) let pieces' = foldr cons (VarE a) piecesSingle let body = LamE [TupP [VarP a, VarP b]] (TupE [pieces', VarE b]) `AppE` (rr `AppE` VarE child) return $ Clause [pat] (NormalB body) [FunD childRender childClauses] go (ResourceLeaf res) = do let cnt = length (filter isDynamic $ resourcePieces res) + maybe 0 (const 1) (resourceMulti res) dyns <- replicateM cnt $ newName "dyn" sub <- case resourceDispatch res of Subsite{} -> return <$> newName "sub" _ -> return [] let pat = ConP (mkName $ resourceName res) $ map VarP $ dyns ++ sub pack' <- [|pack|] tsp <- [|toPathPiece|] let piecesSingle = mkPieces (AppE pack' . LitE . StringL) tsp (resourcePieces res) dyns piecesMulti <- case resourceMulti res of Nothing -> return $ ListE [] Just{} -> do tmp <- [|toPathMultiPiece|] return $ tmp `AppE` VarE (last dyns) body <- case sub of [x] -> do rr <- [|renderRoute|] a <- newName "a" b <- newName "b" colon <- [|(:)|] let cons y ys = InfixE (Just y) colon (Just ys) let pieces = foldr cons (VarE a) piecesSingle return $ LamE [TupP [VarP a, VarP b]] (TupE [pieces, VarE b]) `AppE` (rr `AppE` VarE x) _ -> do colon <- [|(:)|] let cons a b = InfixE (Just a) colon (Just b) return $ TupE [foldr cons piecesMulti piecesSingle, ListE []] return $ Clause [pat] (NormalB body) [] mkPieces _ _ [] _ = [] mkPieces toText tsp (Static s:ps) dyns = toText s : mkPieces toText tsp ps dyns mkPieces toText tsp (Dynamic{}:ps) (d:dyns) = tsp `AppE` VarE d : mkPieces toText tsp ps dyns mkPieces _ _ (Dynamic _ : _) [] = error "mkPieces 120" -- | Generate the 'RenderRoute' instance. -- -- This includes both the 'Route' associated type and the -- 'renderRoute' method. This function uses both 'mkRouteCons' and -- 'mkRenderRouteClasses'. mkRenderRouteInstance :: Type -> [ResourceTree Type] -> Q [Dec] mkRenderRouteInstance = mkRenderRouteInstance' [] -- | A more general version of 'mkRenderRouteInstance' which takes an -- additional context. mkRenderRouteInstance' :: Cxt -> Type -> [ResourceTree Type] -> Q [Dec] mkRenderRouteInstance' cxt typ ress = do cls <- mkRenderRouteClauses ress (cons, decs) <- mkRouteCons ress #if MIN_VERSION_template_haskell(2,11,0) did <- DataInstD [] ''Route [typ] Nothing cons <$> mapM conT clazzes #else let did = DataInstD [] ''Route [typ] cons clazzes #endif return $ instanceD cxt (ConT ''RenderRoute `AppT` typ) [ did , FunD (mkName "renderRoute") cls ] : decs where clazzes = [''Show, ''Eq, ''Read] #if MIN_VERSION_template_haskell(2,11,0) notStrict :: Bang notStrict = Bang NoSourceUnpackedness NoSourceStrictness #else notStrict :: Strict notStrict = NotStrict #endif instanceD :: Cxt -> Type -> [Dec] -> Dec #if MIN_VERSION_template_haskell(2,11,0) instanceD = InstanceD Nothing #else instanceD = InstanceD #endif
erikd/yesod
yesod-core/Yesod/Routes/TH/RenderRoute.hs
mit
6,126
0
21
1,772
1,972
1,012
960
117
9
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module LiuCourses (runApp, runMigrations) where import Web.Scotty.Trans (middleware, scottyOptsT, json, get, defaultHandler, notFound) import Control.Monad.IO.Class (liftIO) import Control.Monad.Reader (runReaderT) import Database.Persist.Postgresql (runSqlPersistMPool, runMigration) import Config import Db.Model import Api.Course import Api.Core app :: Config -> App () app config = do let env = getEnv config middleware (getLogger env) defaultHandler (getHandler env) get "/courses" getCourses get "/courses/:program" getCoursesByProgram get "/course/:code" getCourse notFound fourOhFour runApp :: Config -> IO () runApp config = do environment <- getEnvironment options <- getOptions environment let reader m = runReaderT (runConfig m) config scottyOptsT options reader $ app config runMigrations :: Config -> IO () runMigrations config = liftIO $ flip runSqlPersistMPool (getPool config) $ runMigration migrateAll
SebastianCallh/liu-courses
src/LiuCourses.hs
mit
1,264
0
12
330
306
156
150
32
1
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell, QuasiQuotes, ScopedTypeVariables, MultiParamTypeClasses, DeriveDataTypeable, TypeSynonymInstances,FlexibleInstances #-} {- ** ********************************************************************* * * * This software is part of the pads package * * Copyright (c) 2005-2011 AT&T Knowledge Ventures * * and is licensed under the * * Common Public License * * by AT&T Knowledge Ventures * * * * A copy of the License is available at * * www.padsproj.org/License.html * * * * This program contains certain software code or other information * * ("AT&T Software") proprietary to AT&T Corp. ("AT&T"). The AT&T * * Software is provided to you "AS IS". YOU ASSUME TOTAL RESPONSIBILITY* * AND RISK FOR USE OF THE AT&T SOFTWARE. AT&T DOES NOT MAKE, AND * * EXPRESSLY DISCLAIMS, ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND * * WHATSOEVER, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF* * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, WARRANTIES OF * * TITLE OR NON-INFRINGEMENT. (c) AT&T Corp. All rights * * reserved. AT&T is a registered trademark of AT&T Corp. * * * * Network Services Research Center * * AT&T Labs Research * * Florham Park NJ * * * * Kathleen Fisher <[email protected]> * * * ************************************************************************ -} module Language.Forest.BaseTypes where import Language.Forest.Generic import Language.Forest.MetaData import Language.Forest.Quote import Language.Pads.Padsc [forest| type Text = File Ptext type Binary = File Pbinary type Any = File Pbinary |]
elitak/forest
Language/Forest/BaseTypes.hs
epl-1.0
2,484
0
4
1,120
40
28
12
7
0
module Main where import Text.ParserCombinators.Parsec import Types import Reader import Eval import Data.Map import Functions import Control.Exception main :: IO () main = do res <- startEval (parseLisp code) initEnv putStrLn res code = "(def x 3) " ++ "(def l '(1 2 3)) " ++ "(def do (fn (arg & args) (if args (do args) arg))) " ++ "(def defn (macro (id args & body) " ++ "'(def ~id ~(cons 'fn (cons args body))))) " ++ "(defn map (f c) " ++ "(if c " ++ "(cons (f (first c)) (map f (rest c))) " ++ "c)) " ++ "(print map) " ++ "(defn reduce (f i c) " ++ "(if c " ++ "(reduce f (f i (first c)) (rest c)) " ++ "i)) " ++ "(print (map (fn (x) (+ 1 x)) l)) " ++ "(print (reduce (fn (x y) (+ x y)) 0 l)) " ++ "(let (a (fn (d e) (+ d e))) (+ x (a 1 2)))" initEnv :: Env initEnv = fromList [("true", Boolean True), ("false", Boolean False), ("+", Fn (stdFn lispAdd)), ("let", Fn lispLet), ("fn", Fn lispFn), ("macro", Fn lispMacro), ("eval", Fn lispEval), ("def", Fn lispDef), ("if", Fn lispIf), ("cons", Fn lispCons), ("first", Fn (stdFn lispFirst)), ("rest", Fn (stdFn lispRest)), ("print", Fn (stdFn lispPrint))] startEval :: Either ParseError [Expression] -> Env -> IO (String) startEval (Left err) _ = return (show err) startEval (Right exps) env = do (exp, env) <- evalBody exps env res <- (realize exp) return (show res)
ckirkendall/hlisp
Main.hs
gpl-2.0
1,789
0
20
717
444
238
206
48
1
module LambdaRay.Helper where import Numeric.LinearAlgebra import Numeric.LinearAlgebra.Util(cross, norm) import qualified Control.Parallel.Strategies as P import qualified Codec.Picture as CI import LambdaRay.Types pmap f as = P.withStrategy (P.parListChunk 1024 P.rpar) $ map f as vec4 :: [Double] -> Vect vec4 = (4 |>) vec3 :: [Double] -> Vect vec3 = (3 |>) mat3 :: [Double] -> Mat mat3 = 3><3 mat4 :: [Double] -> Mat mat4 = 4><4 zeroVec :: Int -> Vect zeroVec = constant 0 zero3 = zeroVec 3 zero4 = zeroVec 4 vectFromF f = fromList $ map f [0..] unitV i = vectFromF (\s -> if s == i then 1 else 0) zeroMat x y = fromColumns $ take x $ repeat $ zeroVec y normalize :: Vect -> Vect normalize v = (1/norm v) `scale` v average :: Fractional a => [a] -> a average l = sum [a/(fromIntegral $ length l) | a <- l] rotationMatrix :: Vect -> Vect -> Mat rotationMatrix up z = inv $ fromColumns [up' `cross` z', up', z', unitV 3] where up' = normalize up z' = normalize z nullSpectrum = CI.PixelRGBF 0 0 0 scaleSpectrum :: Float -> CI.PixelRGBF -> CI.PixelRGBF scaleSpectrum f (CI.PixelRGBF r g b) = CI.PixelRGBF (f*r) (f*g) (f*b)
zombiecalypse/LambdaRay
src/LambdaRay/Helper.hs
gpl-2.0
1,145
0
10
225
519
282
237
33
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE DeriveGeneric #-} module Lib.Makefile.Types ( TargetType(..), targetAllInputs , FilePattern(..), onFilePatternPaths , InputPat(..), onInputPatPaths , Target, onTargetPaths , Pattern, onPatternPaths , VarName, VarValue, Vars , Makefile(..), onMakefilePaths ) where import Prelude.Compat hiding (FilePath) import Control.DeepSeq (NFData(..)) import Control.DeepSeq.Generics (genericRnf) import Data.Binary (Binary) import Data.ByteString (ByteString) import Data.Map (Map) import GHC.Generics (Generic) import Lib.FilePath (FilePath) import Lib.Parsec () -- instance Binary SourcePos import Lib.StringPattern (StringPattern) import qualified Text.Parsec.Pos as ParsecPos data TargetType output input = Target { targetOutputs :: [output] , targetInputs :: [input] , targetOrderOnlyInputs :: [input] , targetCmds :: ByteString , targetPos :: ParsecPos.SourcePos } deriving (Show, Generic) instance (Binary output, Binary input) => Binary (TargetType output input) instance (NFData output, NFData input) => NFData (TargetType output input) where rnf = genericRnf type Target = TargetType FilePath FilePath data FilePattern = FilePattern { filePatternDirectory :: FilePath , filePatternFile :: StringPattern } deriving (Show, Generic) instance Binary FilePattern instance NFData FilePattern where rnf = genericRnf data InputPat = InputPath FilePath | InputPattern FilePattern deriving (Show, Generic) instance Binary InputPat instance NFData InputPat where rnf = genericRnf type Pattern = TargetType FilePattern InputPat type VarName = ByteString type VarValue = ByteString type Vars = Map VarName VarValue data Makefile = Makefile { makefileTargets :: [Target] , makefilePatterns :: [Pattern] , makefilePhonies :: [(ParsecPos.SourcePos, FilePath)] , makefileWeakVars :: Vars } deriving (Show, Generic) instance Binary Makefile instance NFData Makefile where rnf = genericRnf targetAllInputs :: Target -> [FilePath] targetAllInputs target = targetInputs target ++ targetOrderOnlyInputs target -- Filepath lens boilerplate: onTargetPaths :: Applicative f => (FilePath -> f FilePath) -> Target -> f Target onTargetPaths f (Target outputs inputs orderOnlyInputs cmds pos) = Target <$> traverse f outputs <*> traverse f inputs <*> traverse f orderOnlyInputs <*> pure cmds <*> pure pos onFilePatternPaths :: Functor f => (FilePath -> f FilePath) -> FilePattern -> f FilePattern onFilePatternPaths f (FilePattern dir file) = (`FilePattern` file) <$> f dir onInputPatPaths :: Functor f => (FilePath -> f FilePath) -> InputPat -> f InputPat onInputPatPaths f (InputPath x) = InputPath <$> f x onInputPatPaths f (InputPattern x) = InputPattern <$> onFilePatternPaths f x onPatternPaths :: Applicative f => (FilePath -> f FilePath) -> Pattern -> f Pattern onPatternPaths f (Target outputs inputs orderOnlyInputs cmds pos) = Target <$> traverse (onFilePatternPaths f) outputs <*> traverse (onInputPatPaths f) inputs <*> traverse (onInputPatPaths f) orderOnlyInputs <*> pure cmds <*> pure pos _2 :: Functor f => (b -> f c) -> (a, b) -> f (a, c) _2 f (x, y) = (,) x <$> f y onMakefilePaths :: Applicative f => (FilePath -> f FilePath) -> Makefile -> f Makefile onMakefilePaths f (Makefile targets patterns phonies weakVars) = Makefile <$> traverse (onTargetPaths f) targets <*> traverse (onPatternPaths f) patterns <*> (traverse . _2) f phonies <*> pure weakVars
da-x/buildsome
src/Lib/Makefile/Types.hs
gpl-2.0
3,495
0
12
569
1,110
603
507
87
1
-- File: ch3/exB1.hs -- A function that computes the number of elements in a list. length' :: [a] -> Int length' (x:xs) = 1 + (length' xs) length' [] = 0
friedbrice/RealWorldHaskell
ch3/exB1.hs
gpl-2.0
159
0
7
36
50
27
23
3
1
module Network.Tremulous.NameInsensitive ( TI(..), mk, mkColor, mkAlphaNum ) where import Prelude hiding (length, map, filter) import Data.ByteString.Char8 import Data.Char import Data.Ord import Network.Tremulous.ByteStringUtils data TI = TI { original :: !ByteString , cleanedCase :: !ByteString } instance Eq TI where a == b = cleanedCase a == cleanedCase b instance Ord TI where compare = comparing cleanedCase instance Show TI where show = show . original mk :: ByteString -> TI mk xs = TI bs (map toLower bs) where bs = clean xs mkColor :: ByteString -> TI mkColor xs = TI bs (removeColors bs) where bs = clean xs mkAlphaNum :: ByteString -> TI mkAlphaNum xs = TI bs (map toLower $ filter (\x -> isAlphaNum x || isSpace x) bs) where bs = clean xs clean :: ByteString -> ByteString clean = stripw . filter (\c -> c >= '\x20' && c <= '\x7E') removeColors :: ByteString -> ByteString removeColors bss = rebuildC (length bss) f bss where f '^' xs | Just (x2, xs2) <- uncons xs , isAlphaNum x2 , Just (x3, xs3) <- uncons xs2 = f x3 xs3 f x xs = (toLower x, xs)
Cadynum/tremulous-query
Network/Tremulous/NameInsensitive.hs
gpl-3.0
1,169
0
12
299
446
233
213
38
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NamedFieldPuns #-} module Formatter where import Data.Char (intToDigit) import Data.Text (Text) import qualified Data.Text as T import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Set (Set) import qualified Data.Set as Set import Numeric (showIntAtBase) import Model -- | Pad short strings; leave too-long/long-enough strings alone leftpad :: Int -> Char -> String -> String leftpad l c s = replicate (max 0 (l - length s)) c ++ s -- | Converts any (pos/neg) integer to a 16-bit bin-string toBinaryString :: Int -> Text toBinaryString n = T.pack $ leftpad 16 '0' $ showIntAtBase 2 intToDigit (n `mod` 2 ^ 15) "" formatCompExpr :: HackComputation -> Text formatCompExpr expr = T.pack $ case expr of ComputeZero -> "101010" ComputeOne -> "111111" ComputeNegOne -> "111010" ComputeD -> "001100" ComputeR -> "110000" NotD -> "001101" NotR -> "110001" NegD -> "001111" NegR -> "110011" DPlusOne -> "011111" RPlusOne -> "110111" DSubOne -> "001110" RSubOne -> "110010" DPlusR -> "000010" DSubR -> "010011" RSubD -> "000111" DAndR -> "000000" DOrR -> "010101" formatDest :: Set (HackRegister) -> Text formatDest dest = T.pack $ map hot [RegA, RegD, RegM] where hot :: HackRegister -> Char hot reg = if Set.member reg dest then '1' else '0' formatJump :: Set (Ordering) -> Text formatJump jump = T.pack $ map hot [LT, EQ, GT] where hot :: Ordering -> Char hot o = if Set.member o jump then '1' else '0' formatAM :: HackAM -> Text formatAM UseA = "0" formatAM UseM = "1" -- | We can always produce output formatComp :: Set HackRegister -> HackComputation -> HackAM -> Set Ordering -> Text formatComp dest comp am jump = T.concat [ "111" , formatAM am , formatCompExpr comp , formatDest dest , formatJump jump ] -- | We may fail due to symbol-lookup miss formatAddr :: SymbolTable -> AddrInstruction -> Maybe Text formatAddr table (AddrLiteral lit) = Just (toBinaryString lit) formatAddr table (AddrSymbol sym) = do lit <- Map.lookup sym table return (toBinaryString lit)
easoncxz/hack-assembler
src/Formatter.hs
gpl-3.0
2,319
0
11
616
667
354
313
70
18
content <- readFile "/etc/lsb-release" let nChars = length content putStrLn $ "File content = \n" ++ content putStrLn $ "File size (number of chars) = " ++ show nChars putStrLn "--------------------------------" :{ getPassword :: String -> IO () -> IO () -> IO () getPassword password success error = do passwd <- putStr "Enter the password: " >> getLine if passwd == password then success else do error getPassword password success error :} :{ showSecreteFile :: String -> IO () showSecreteFile file = do content <- readFile file putStrLn "Secrete File Content" putStrLn content :} :{ getPassword2 :: String -> Int -> IO () getPassword2 password maxTry = aux (maxTry - 1) where aux counter = do passwd <- putStr "Enter the password: " >> getLine case (counter, passwd) of _ | passwd == password -> showSecreteFile "/etc/shells" _ | counter == 0 -> putStrLn $ "File destroyed after " ++ show maxTry ++ " attempts." _ -> do putStrLn $ "Try again. You only have " ++ show counter ++ " attempts." aux (counter - 1) :} let printLine = putStrLn "-----------------------------------------------" printLine putStrLn "Open secrete vault: " getPassword "guessthepassword" (putStrLn "Vault opened. Ok.") (putStrLn "Error: Wrong password. Try Again") printLine putStrLn "Open secret file: (1)" getPassword2 "xyzVjkmArchp972343asx" 3 printLine putStrLn "Open secret file: (2)" getPassword2 "xyzVjkmArchp972343asx" 3
caiorss/Functional-Programming
haskell/src/script_ghci.hs
unlicense
1,736
13
15
551
421
199
222
-1
-1
{-# LANGUAGE FlexibleInstances #-} import GHC.Arr import Data.Word -- Chapter exercises -- 1. Bool has kind *, hence no Functor instance -- 2. Kind * -> *, can have Functor -- 3. Same -- 4. newtype Mu f = InF { outF :: f (Mu f) } -- Mu :: (* -> *) -> * -- Yes? -- 5. data D = D (Array Word Word) Int Int -- D :: * -- No! -- Rearrange -- 1. data Sum a b = First a | Second b deriving (Eq, Show) instance Functor (Sum e) where fmap f (First a) = First a fmap f (Second b) = Second (f b) -- 2. data Company a b c = DeepBlue a c | Something b instance Functor (Company e e') where fmap _ (Something b) = Something b fmap f (DeepBlue a c) = DeepBlue a (f c) -- 3. data More a b = L b a b | R a b a deriving (Eq, Show) instance Functor (More x) where fmap f (R a b a') = R a (f b) a' fmap f (L b a b') = L (f b) a (f b') -- Write Functor instances -- 1. data Quant a b = Finance | Desk a | Bloor b instance Functor (Quant e) where fmap f Finance = Finance fmap f (Desk a) = Desk a fmap f (Bloor b) = Bloor (f b) -- 2. data K a b = K a instance Functor (K a) where fmap f (K b) = K b -- 3. newtype Flip f a b = Flip (f b a) deriving (Eq, Show) instance Functor (Flip K a) where fmap f (Flip (K b)) = Flip (K (f b)) -- 4. data EvilGoateeConst a b = GoatyConst b deriving (Eq, Show) instance Functor (EvilGoateeConst a) where fmap f (GoatyConst b) = GoatyConst (f b) -- 5. data LiftItOut f a = LiftItOut (f a) deriving (Eq, Show) instance Functor f => Functor (LiftItOut f) where fmap f (LiftItOut fa) = LiftItOut (fmap f fa) -- 6. data Parappa f g a = DaWrappa (f a) (g a) deriving (Eq, Show) instance (Functor f, Functor g) => Functor (Parappa f g) where fmap f (DaWrappa fa ga) = DaWrappa (fmap f fa) (fmap f ga) -- 7. data IgnoreOne f g a b = IgnoringSomething (f a) (g b) instance (Functor f, Functor g) => Functor (IgnoreOne f g a) where fmap f (IgnoringSomething fa gb) = IgnoringSomething fa (fmap f gb) -- 8. data Notorious g o a t = Notorious (g o) (g a) (g t) instance Functor g => Functor (Notorious g o a) where fmap f (Notorious go ga gt) = Notorious go ga (fmap f gt) -- 9. data List a = Nil | Cons a (List a) deriving (Eq, Show) instance Functor List where fmap f Nil = Nil fmap f (Cons a list) = Cons (f a) (fmap f list) -- 10. data GoatLord a = NoGoat | OneGoat a | MoreGoats (GoatLord a) (GoatLord a) (GoatLord a) instance Functor GoatLord where fmap f NoGoat = NoGoat fmap f (OneGoat a) = OneGoat (f a) fmap f (MoreGoats gl gl' gl'') = MoreGoats (fmap f gl) (fmap f gl') (fmap f gl'') -- 11. data TalkToMe a = Halt | Print String a | Read (String -> a) instance Functor TalkToMe where fmap f Halt = Halt fmap f (Print s a) = Print s (f a) fmap f (Read sa) = Read (f . sa)
dmvianna/haskellbook
src/Ch16Ex-Functor.hs
unlicense
2,844
0
10
756
1,336
708
628
63
0
-- Copyright 2015 Google Inc. All Rights Reserved. -- -- Licensed under the Apache License, Version 2.0 (the "License")-- -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. {-# LANGUAGE OverloadedStrings #-} module Algo (otrsToTrs) where import Debug.Trace import Data.List ( intercalate, tails, inits ) import Data.Traversable import qualified Data.Map.Strict as M import qualified Data.Set as S import Datatypes import Signature import Control.Monad.Writer.Strict (Writer, runWriter, tell) import Terms import Maranget isBottom :: Term -> Bool isBottom Bottom = True isBottom _ = False -- interleave abc ABC = Abc, aBc, abC interleave :: [a] -> [a] -> [[a]] interleave [] [] = [] interleave xs ys = zipWith3 glue (inits xs) ys (tails (tail xs)) where glue xs x ys = xs ++ x : ys complement :: Signature -> Term -> Term -> Term complement sig p1 p2 = p1 \\ p2 where appl f ps | any isBottom ps = Bottom | otherwise = Appl f ps plus Bottom u = u plus t Bottom = t plus t u = Plus t u sum = foldr plus Bottom alias x Bottom = Bottom alias x t = Alias x t u \\ (Var _) = Bottom u \\ Bottom = u (Var x) \\ p@(Appl g ps) = alias x (sum [pattern f \\ p | f <- fs]) where fs = ctorsOfSameRange sig g pattern f = Appl f (replicate (arity sig f) (Var "_")) Bottom \\ Appl _ _ = Bottom Appl f ps \\ Appl g qs | f /= g || someUnchanged = appl f ps | otherwise = sum [appl f ps' | ps' <- interleave ps pqs] where pqs = zipWith (\\) ps qs someUnchanged = or (zipWith (==) ps pqs) Plus q1 q2 \\ p@(Appl _ _) = plus (q1 \\ p) (q2 \\ p) Alias x p1 \\ p2 = alias x (p1 \\ p2) p1 \\ Alias x p2 = p1 \\ p2 p \\ (Plus p1 p2) = (p \\ p1) \\ p2 preMinimize :: [Term] -> [Term] preMinimize patterns = filter (not . isMatched) patterns where isMatched p = any (matches' p) patterns matches' p q = not (matches p q) && matches q p minimize :: Signature -> [Term] -> [Term] minimize sig ps = minimize' ps [] where minimize' [] kernel = kernel minimize' (p:ps) kernel = if subsumes sig (ps++kernel) p then shortest (minimize' ps (p:kernel)) (minimize' ps kernel) else minimize' ps (p:kernel) shortest xs ys = if length xs <= length ys then xs else ys removePlusses :: Term -> S.Set Term removePlusses (Plus p1 p2) = removePlusses p1 `S.union` removePlusses p2 removePlusses (Appl f ps) = S.map (Appl f) (traverseSet removePlusses ps) where traverseSet f s = S.fromList (traverse (S.toList . f) s) removePlusses (Alias x p) = S.map (Alias x) (removePlusses p) removePlusses (Var x) = S.singleton (Var x) removePlusses Bottom = S.empty removeAliases :: Rule -> Rule removeAliases (Rule lhs rhs) = Rule lhs' (substitute subst rhs) where (lhs', subst) = collectAliases (renameUnderscores lhs) collectAliases t = runWriter (collect t) collect :: Term -> Writer Substitution Term collect (Appl f ts) = Appl f <$> (mapM collect ts) collect (Var x) = return (Var x) collect (Alias x t) = do t' <- collect t tell (M.singleton x t') return t' expandAnti :: Signature -> Term -> Term expandAnti sig t = expandAnti' t where expandAnti' (Appl f ts) = Appl f (map expandAnti' ts) expandAnti' (Plus t1 t2) = Plus (expandAnti' t1) (expandAnti' t2) expandAnti' (Compl t1 t2) = complement sig (expandAnti' t1) (expandAnti' t2) expandAnti' (Anti t) = complement sig (Var "_") (expandAnti' t) expandAnti' (Var x) = Var x expandAnti' Bottom = Bottom antiTrsToOtrs :: Signature -> [Rule] -> [Rule] antiTrsToOtrs sig rules = [Rule (expandAnti sig lhs) rhs | Rule lhs rhs <- rules] otrsToAdditiveTrs :: Signature -> [Rule] -> [Rule] otrsToAdditiveTrs sig rules = zipWith diff rules (inits patterns) where patterns = [lhs | Rule lhs _ <- rules] diff (Rule lhs rhs) lhss = Rule (complement sig lhs (sum lhss)) rhs sum = foldr Plus Bottom aliasedTrsToTrs :: [Rule] -> [Rule] aliasedTrsToTrs = map removeAliases additiveTrsToAliasedTrs :: Signature -> [Rule] -> [Rule] additiveTrsToAliasedTrs sig rules = concatMap transform rules where transform (Rule lhs rhs) = map (flip Rule rhs) (expand lhs) expand = minimize sig . preMinimize . S.toList . removePlusses otrsToTrs sig = aliasedTrsToTrs . additiveTrsToAliasedTrs sig . otrsToAdditiveTrs sig . antiTrsToOtrs sig
polux/subsume
Algo.hs
apache-2.0
4,959
0
13
1,225
1,865
943
922
99
12
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Web.Pagure.Projects -- Copyright : (C) 2015 Ricky Elrod -- License : BSD2 (see LICENSE file) -- Maintainer : Ricky Elrod <[email protected]> -- Stability : experimental -- Portability : ghc (lens) -- -- Access to the \"Projects\" endpoints of the Pagure API. ---------------------------------------------------------------------------- module Web.Pagure.Projects where import Control.Lens import Data.Aeson.Lens import Data.Maybe (maybeToList) import qualified Data.Text as T import Network.Wreq import Web.Pagure.Internal.Wreq import Web.Pagure.Types import Web.Pagure.Types.Project -- | Access the @/[repo]/git/tags@ endpoint. -- -- Example: -- -- @ -- >>> import Web.Pagure -- >>> let pc = PagureConfig "https://pagure.io" Nothing -- >>> runPagureT (gitTags "pagure") pc -- ["0.1","0.1.1","0.1.10","0.1.2","0.1.3","0.1.4","0.1.5",[...] -- @ gitTags :: Repo -> PagureT [Tag] gitTags r = do resp <- pagureGet (r ++ "/git/tags") return $ resp ^.. responseBody . key "tags" . values . _String -- | Access the @/fork/[username]/[repo]/git/tags@ endpoint. -- -- Example: -- -- @ -- >>> import Web.Pagure -- >>> let pc = PagureConfig "https://pagure.io" Nothing -- >>> runPagureT (gitTagsFork "codeblock" "pagure") pc -- ["0.1","0.1.1","0.1.10","0.1.2","0.1.3","0.1.4","0.1.5",[...] -- @ gitTagsFork :: Username -> Repo -> PagureT [Tag] gitTagsFork u r = gitTags ("fork/" ++ T.unpack u ++ "/" ++ r) -- | Access the @/projects@ endpoint. -- -- Example: -- -- @ -- >>> import Web.Pagure -- >>> let pc = PagureConfig "https://pagure.io" Nothing -- >>> runPagureT (projects Nothing (Just "codeblock") Nothing) pc -- @ projects :: Maybe Tag -- ^ Tags -> Maybe Username -- ^ Username -> Maybe Bool -- ^ Fork -> PagureT ProjectsResponse projects t u f = do opts <- pagureWreqOptions let opts' = opts & param "tags" .~ maybeToList t & param "username" .~ maybeToList u & param "fork" .~ [maybeToBoolString f] resp <- asJSON =<< pagureGetWith opts' ("/projects") return (resp ^. responseBody) where maybeToBoolString (Just True) = "true" maybeToBoolString (Just False) = "false" maybeToBoolString Nothing = "false"
fedora-infra/pagure-haskell
src/Web/Pagure/Projects.hs
bsd-2-clause
2,314
0
16
389
395
223
172
-1
-1
{-# LANGUAGE MagicHash #-} ----------------------------------------------------------------------------- -- | -- Module : Haddock.Interface.AttachInstances -- Copyright : (c) Simon Marlow 2006, -- David Waern 2006-2009, -- Isaac Dupree 2009 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable ----------------------------------------------------------------------------- module Haddock.Interface.AttachInstances (attachInstances) where import Haddock.Types import Haddock.Convert import Control.Arrow import Data.List import qualified Data.Map as Map import GHC import Name import InstEnv import Class #if MIN_VERSION_ghc(7,1,0) import GhcMonad (withSession) #else import HscTypes (withSession) #endif import MonadUtils (liftIO) import TcRnDriver (tcRnGetInfo) import TypeRep hiding (funTyConName) import Var hiding (varName) import TyCon import PrelNames import FastString #define FSLIT(x) (mkFastString# (x#)) attachInstances :: [Interface] -> InstIfaceMap -> Ghc [Interface] attachInstances ifaces instIfaceMap = mapM attach ifaces where -- TODO: take an IfaceMap as input ifaceMap = Map.fromList [ (ifaceMod i, i) | i <- ifaces ] attach iface = do newItems <- mapM (attachToExportItem iface ifaceMap instIfaceMap) (ifaceExportItems iface) return $ iface { ifaceExportItems = newItems } attachToExportItem :: Interface -> IfaceMap -> InstIfaceMap -> ExportItem Name -> Ghc (ExportItem Name) attachToExportItem iface ifaceMap instIfaceMap export = case export of ExportDecl { expItemDecl = L _ (TyClD d) } -> do mb_info <- getAllInfo (unLoc (tcdLName d)) let export' = export { expItemInstances = case mb_info of Just (_, _, instances) -> let insts = map (first synifyInstHead) $ sortImage (first instHead) [ (instanceHead i, getName i) | i <- instances ] in [ (inst, lookupInstDoc name iface ifaceMap instIfaceMap) | (inst, name) <- insts ] Nothing -> [] } return export' _ -> return export lookupInstDoc :: Name -> Interface -> IfaceMap -> InstIfaceMap -> Maybe (Doc Name) -- TODO: capture this pattern in a function (when we have streamlined the -- handling of instances) lookupInstDoc name iface ifaceMap instIfaceMap = case Map.lookup name (ifaceInstanceDocMap iface) of Just doc -> Just doc Nothing -> case Map.lookup modName ifaceMap of Just iface2 -> case Map.lookup name (ifaceInstanceDocMap iface2) of Just doc -> Just doc Nothing -> Nothing Nothing -> case Map.lookup modName instIfaceMap of Just instIface -> case Map.lookup name (instDocMap instIface) of Just (doc, _) -> doc Nothing -> Nothing Nothing -> Nothing where modName = nameModule name -- | Like GHC's getInfo but doesn't cut things out depending on the -- interative context, which we don't set sufficiently anyway. getAllInfo :: GhcMonad m => Name -> m (Maybe (TyThing,Fixity,[Instance])) getAllInfo name = withSession $ \hsc_env -> do (_msgs, r) <- liftIO $ tcRnGetInfo hsc_env name return r -------------------------------------------------------------------------------- -- Collecting and sorting instances -------------------------------------------------------------------------------- -- | Simplified type for sorting types, ignoring qualification (not visible -- in Haddock output) and unifying special tycons with normal ones. -- For the benefit of the user (looks nice and predictable) and the -- tests (which prefer output to be deterministic). data SimpleType = SimpleType Name [SimpleType] deriving (Eq,Ord) -- TODO: should we support PredTy here? instHead :: ([TyVar], [PredType], Class, [Type]) -> ([Int], Name, [SimpleType]) instHead (_, _, cls, args) = (map argCount args, className cls, map simplify args) where argCount (AppTy t _) = argCount t + 1 argCount (TyConApp _ ts) = length ts argCount (FunTy _ _ ) = 2 argCount (ForAllTy _ t) = argCount t argCount _ = 0 simplify (ForAllTy _ t) = simplify t simplify (FunTy t1 t2) = SimpleType funTyConName [simplify t1, simplify t2] simplify (AppTy t1 t2) = SimpleType s (ts ++ [simplify t2]) where (SimpleType s ts) = simplify t1 simplify (TyVarTy v) = SimpleType (tyVarName v) [] simplify (TyConApp tc ts) = SimpleType (tyConName tc) (map simplify ts) simplify _ = error "simplify" -- sortImage f = sortBy (\x y -> compare (f x) (f y)) sortImage :: Ord b => (a -> b) -> [a] -> [a] sortImage f xs = map snd $ sortBy cmp_fst [(f x, x) | x <- xs] where cmp_fst (x,_) (y,_) = compare x y funTyConName :: Name funTyConName = mkWiredInName gHC_PRIM (mkOccNameFS tcName FSLIT("(->)")) funTyConKey (ATyCon funTyCon) -- Relevant TyCon BuiltInSyntax
nominolo/haddock2
src/Haddock/Interface/AttachInstances.hs
bsd-2-clause
5,221
0
26
1,329
1,323
699
624
91
10
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings, RecordWildCards #-} module Network.DBpedia.Spotlight (Client(..), SpotlightResponse(..), SpotlightResource(..), ResourceType, SpotlightCandidatesResponse, SpotlightCandidates (..), CandidateEntity (..), candidates, defaultHost, defaultPort, defaultClient, extractEntities, extractAllEntities, entityNamesFromResponse, extractEntitiesWithOptions) where import Control.Arrow (second) import Control.Monad import Data.Either (lefts) import Data.Function import Data.List import Data.List.Split import Data.Maybe import Data.String import Data.Typeable import Network.HTTP hiding (Done, host, port) import Network.Socket import Network.URI import Text.XML.HaXml import Text.XML.HaXml.Parse (xmlParse') import Text.XML.HaXml.Posn (posInNewCxt) import Text.XML.HaXml.Util data Client = Client { host :: HostName, port :: ServiceName } -- Data types for `annotate` responses data SpotlightResponse = SpotlightResponse { spotlightConfidence :: Double, spotlightSupport :: Int, spotlightResources :: [SpotlightResource] } deriving (Show, Typeable) data SpotlightResource = SpotlightResource { resourceURI :: URI, resourceSupport :: Int, resourceTypes :: [ResourceType], resourceSurfaceForm :: String, resourceOffset :: Int, resourceSimilarityScore :: Double, resourcePercentageOfSecondRank :: Double } deriving (Show, Eq, Typeable) type ResourceType = String -- Data types for `candidates` responses type SpotlightCandidatesResponse = [SpotlightCandidates] data SpotlightCandidates = SpotlightCandidates { candidateSurfaceForm :: String, candidateOffset :: Int, candidateEntities :: [CandidateEntity] } deriving (Show, Eq, Typeable) data CandidateEntity = CandidateEntity { candidateLabel :: String, candidateURI :: String, candidateContextualScore :: Double, candidatePercentageOfSecondRank :: Double, candidateSupport :: Int, candidatePriorScore :: Double, candidateFinalScore :: Double } deriving (Show, Eq, Typeable) extractResourceTypes rs | null rs = [] | otherwise = sepBy "," rs lookup' x xs = join $ lookup x xs stringsForAttValues = second $ \(AttValue l) -> listToMaybe $ lefts l mkContentRoot = docContent (posInNewCxt "" Nothing) mkParseResult xmlString = either (const Nothing) Just $ xmlParse' "" xmlString parseAnnotationsFromXML xmlString = do parseResult <- mkParseResult xmlString let contentRoot = mkContentRoot parseResult sConfidence <- fmap read $ parseConfidence contentRoot sSupport <- fmap read $ parseSupport contentRoot sResources <- parseResources contentRoot return $ SpotlightResponse sConfidence sSupport sResources where rootElem contentRoot = contentElem contentRoot rootAttrs = map stringsForAttValues . attrs . rootElem parseConfidence = lookup' (N "confidence") . rootAttrs parseSupport = lookup' (N "support") . rootAttrs parseResources = mapM parseResource . resources resources = keep /> tag "Resources" /> tag "Resource" parseResource content = do rURI <- parseURI' =<< resourceAttr "URI" rSupport <- fmap read $ resourceAttr "support" rTypes <- fmap extractResourceTypes $ resourceAttr "types" rSurfaceForm <- resourceAttr "surfaceForm" rOffset <- fmap read $ resourceAttr "offset" rSimScore <- fmap read $ resourceAttr "similarityScore" rPercentSecondRank <- fmap read $ resourceAttr "percentageOfSecondRank" return $ SpotlightResource rURI rSupport rTypes rSurfaceForm rOffset rSimScore rPercentSecondRank where resourceAttrs = map stringsForAttValues $ attrs $ contentElem content resourceAttr attr = lookup' (N attr) resourceAttrs parseCandidatesFromXML xmlString = do parseResult <- mkParseResult xmlString let contentRoot = mkContentRoot parseResult mapM parseDetectedSurfaceForm $ detectedSurfaceForms contentRoot where detectedSurfaceForms = keep /> tag "surfaceForm" parseDetectedSurfaceForm content = do cSurfaceForm <- parseSurfaceForm content cOffset <- fmap read $ parseOffset content cEntities <- mapM parseEntities $ (keep /> tag "resource") content return $ SpotlightCandidates cSurfaceForm cOffset cEntities parseEntities content = do eURI <- candidateAttr "uri" eSupport <- fmap read $ candidateAttr "support" eLabel <- candidateAttr "label" eContextualScore <- fmap read $ candidateAttr "contextualScore" ePercentSecondRank <- fmap read $ candidateAttr "percentageOfSecondRank" ePriorScore <- fmap read $ candidateAttr "priorScore" eFinalScore <- fmap read $ candidateAttr "finalScore" return $ CandidateEntity eLabel eURI eContextualScore ePercentSecondRank eSupport ePriorScore eFinalScore where candidateAttr attr = lookup' (N attr) candidateAttrs candidateAttrs = map stringsForAttValues $ attrs $ contentElem content parseSurfaceForm = lookup' (N "name") . sfAttrs parseOffset = lookup' (N "offset") . sfAttrs sfAttrs = map stringsForAttValues . attrs . contentElem parseURI' x = case parseURI x of Nothing -> fail ("URI " ++ x ++ " is unparseable") Just x -> return x defaultHost = "127.0.0.1" defaultPort = "2222" defaultClient = Client { host = defaultHost, port = defaultPort} buildURI client resource = nullURI { uriScheme = "http:", uriAuthority = Just URIAuth { uriUserInfo = "", uriRegName = host client, uriPort = ":" ++ (port client) }, uriPath = "/rest/" ++ resource } -- | Favours the first list as what value ends up in the result mergeAssocLists :: (Eq a) => [(a, b)] -> [(a, b)] -> [(a, b)] mergeAssocLists xs ys = nubBy ((==) `on` fst) (xs ++ ys) thingSubclassSPARQL = "SELECT DISTINCT ?x WHERE { ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Thing> }" entityNamesFromResponse response = map resourceSurfaceForm $ spotlightResources response extractEntities :: Client -> Maybe String -> String -> IO (Either String SpotlightResponse) extractEntities client Nothing text = extractEntitiesWithOptions client [] text extractEntities client (Just sparql) text = extractEntitiesWithOptions client [("sparql", sparql)] text extractAllEntities :: Client -> String -> IO (Either String SpotlightResponse) extractAllEntities client text = extractEntities client Nothing text extractEntitiesWithOptions :: Client -> [(String, String)] -> String -> IO (Either String SpotlightResponse) extractEntitiesWithOptions client options text = requestAndParseResponse client "annotate" parseAnnotationsFromXML options text candidates :: Client -> String -> IO (Either String SpotlightCandidatesResponse) candidates client text = requestAndParseResponse client "candidates" parseCandidatesFromXML [] text requestAndParseResponse client resource parser options text = do let uri = buildURI client resource let requestBody = urlEncodeVars $ mergeAssocLists options [("confidence", "-1"), ("support", "-1"), ("text", text)] let contentLength = length requestBody let headers = [mkHeader HdrContentType "application/x-www-form-urlencoded" ,mkHeader HdrContentLength (show contentLength) ,mkHeader HdrAccept "text/xml"] let request = Request { rqURI = uri, rqMethod = POST, rqHeaders = headers, rqBody = requestBody } result <- simpleHTTP request case result of Left connError -> return $ Left (show connError) Right response -> let responseBody = rspBody response in case parser responseBody of Just sr -> return $ Right sr Nothing -> return $ Left responseBody
ThoughtLeadr/spotlight-client
Network/DBpedia/Spotlight.hs
bsd-3-clause
8,228
0
16
1,912
2,045
1,055
990
164
3
{-# LANGUAGE TypeSynonymInstances #-} module Data.TrieMap.OrdMap.Zippable () where import Data.TrieMap.OrdMap.Base instance Zippable (SNode k) where empty = tip clear (Empty _ path) = rebuild tip path clear (Full _ path l r) = rebuild (l `glue` r) path assign a (Empty k path) = rebuild (single k a) path assign a (Full k path l r) = rebuild (join k a l r) path instance Zippable (OrdMap k) where empty = OrdMap empty clear (Hole hole) = OrdMap (clear hole) assign a (Hole hole) = OrdMap (assign a hole) rebuild :: Sized a => SNode k a -> Path k a -> SNode k a rebuild t Root = t rebuild t (LeftBin kx x path r) = rebuild (balance kx x t r) path rebuild t (RightBin kx x l path) = rebuild (balance kx x l t) path
lowasser/TrieMap
Data/TrieMap/OrdMap/Zippable.hs
bsd-3-clause
735
0
8
162
358
180
178
17
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} module FinalTagless.Deep where import FinalTagless.GoalSyntax import qualified Syntax newtype Deep v = Deep { unDeep :: Syntax.G v } instance Goal v Deep where unif x y = Deep $ (Syntax.:=:) x y conj x y xs = Deep $ Syntax.Conjunction (unDeep x) (unDeep y) (map unDeep xs) disj x y xs = Deep $ Syntax.Disjunction (unDeep x) (unDeep y) (map unDeep xs) fresh x g = Deep $ Syntax.Fresh x (unDeep g) call n args = Deep $ Syntax.Invoke n args program3 :: Syntax.Program program3 = Syntax.Program [] (unDeep g3) program1 :: Syntax.Program program1 = Syntax.Program [Syntax.Def "appendo" ["x", "y", "z"] (unDeep g1)] (unDeep g2)
kajigor/uKanren_transformations
src/FinalTagless/Deep.hs
bsd-3-clause
713
0
9
131
286
150
136
16
1
{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} #include "thyme.h" -- | Calendar months and day-of-months. module Data.Thyme.Calendar.MonthDay ( Month, DayOfMonth , MonthDay (..), _mdMonth, _mdDay , monthDay, monthDayValid, monthLength , module Data.Thyme.Calendar.MonthDay ) where import Prelude import Control.Lens import Data.Thyme.Calendar.Internal -- * Compatibility -- | Predicated on whether or not it is a leap year, convert an ordinal -- 'DayOfYear' to its corresponding 'Month' and 'DayOfMonth'. -- -- @ -- 'dayOfYearToMonthAndDay' leap ('view' ('monthDay' leap) -> 'MonthDay' m d) = (m, d) -- @ {-# INLINE dayOfYearToMonthAndDay #-} dayOfYearToMonthAndDay :: Bool -- ^ 'isLeapYear'? -> DayOfYear -> (Month, DayOfMonth) dayOfYearToMonthAndDay leap (view (monthDay leap) -> MonthDay m d) = (m, d) -- | Predicated on whether or not it is a leap year, convert a 'Month' and -- 'DayOfMonth' to its corresponding ordinal 'DayOfYear'. -- Does not validate the input. -- -- @ -- 'monthAndDayToDayOfYear' leap m d = 'monthDay' leap 'Control.Lens.#' 'MonthDay' m d -- @ {-# INLINE monthAndDayToDayOfYear #-} monthAndDayToDayOfYear :: Bool -- ^ 'isLeapYear'? -> Month -> DayOfMonth -> DayOfYear monthAndDayToDayOfYear leap m d = monthDay leap # MonthDay m d -- | Predicated on whether or not it is a leap year, convert a 'Month' and -- 'DayOfMonth' to its corresponding ordinal 'DayOfYear'. -- Returns 'Nothing' for invalid input. -- -- @ -- 'monthAndDayToDayOfYearValid' leap m d = 'monthDayValid' leap ('MonthDay' m d) -- @ {-# INLINE monthAndDayToDayOfYearValid #-} monthAndDayToDayOfYearValid :: Bool -- ^ 'isLeapYear'? -> Month -> DayOfMonth -> Maybe DayOfYear monthAndDayToDayOfYearValid leap m d = monthDayValid leap (MonthDay m d)
liyang/thyme
src/Data/Thyme/Calendar/MonthDay.hs
bsd-3-clause
1,847
0
10
333
235
146
89
31
1
{-# LANGUAGE OverloadedStrings #-} module Trombone.Middleware.Cors ( cors ) where import Data.ByteString import Data.List.Utils import Database.Persist.Types import Network.HTTP.Types.Header ( HeaderName ) import Network.HTTP.Types.Status import Network.Wai import Network.Wai.Internal -- | The CORS middleware component provides support for accepting cross-domain -- requests. For more information about cross-origin resource sharing, see: -- http://enable-cors.org. cors :: Middleware cors app req cback = do let head = requestHeaders req hdrs = responseHeaders (lookup "Origin" head) (lookup "Access-Control-Request-Headers" head) case (requestMethod req, hasKeyAL "Access-Control-Request-Method" head) of ("OPTIONS", True) -> -- Cross-site preflight request cback $ responseLBS ok200 hdrs "" _ -> -- Add 'Access-Control-Allow-Origin' header app req $ \resp -> cback $ case lookup "Origin" (requestHeaders req) of Nothing -> resp Just org -> addHeader org resp where responseHeaders origin headers = let h = case (origin, headers) of (Just origin', Just headers') -> [ ("Access-Control-Allow-Origin", origin') , ("Access-Control-Allow-Headers", headers') ] _ -> [] allowed = "POST, GET, PUT, PATCH, DELETE, OPTIONS" in [ ("Access-Control-Allow-Methods", allowed) , ("Access-Control-Max-Age", "1728000") , ("Content-Type", "text/plain") ] ++ h addHeader :: ByteString -> Response -> Response addHeader org (ResponseFile s headers fp m) = ResponseFile s (modified headers org) fp m addHeader org (ResponseBuilder s headers b) = ResponseBuilder s (modified headers org) b addHeader org (ResponseStream s headers b) = ResponseStream s (modified headers org) b addHeader org (ResponseRaw s resp) = ResponseRaw s (addHeader org resp) modified :: [(HeaderName, a)] -> a -> [(HeaderName, a)] {-# INLINE modified #-} modified = flip addToAL "Access-Control-Allow-Origin"
johanneshilden/trombone
Trombone/Middleware/Cors.hs
bsd-3-clause
2,364
0
16
745
529
286
243
46
4
module Main where import Test.Tasty import Test.Tasty.QuickCheck as QC import Test.Tasty.HUnit import Data.List import Data.Ord main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [properties, unitTests] properties :: TestTree properties = testGroup "Properties" [qcProps] qcProps = testGroup "(checked by QuickCheck)" [ QC.testProperty "sort == sort . reverse" $ \list -> sort (list :: [Int]) == sort (reverse list) , QC.testProperty "Fermat's little theorem" $ \x -> ((x :: Integer)^7 - x) `mod` 7 == 0 -- the following property does not hold , QC.testProperty "Fermat's last theorem" $ \x y z n -> (n :: Integer) >= 3 QC.==> x^n + y^n /= (z^n :: Integer) ] unitTests = testGroup "Unit tests" [ testCase "List comparison (different length)" $ [1, 2, 3] `compare` [1,2] @?= GT -- the following test does not hold , testCase "List comparison (same length)" $ [1, 2, 3] `compare` [1,2,2] @?= LT ]
creswick/wikicfp-parser
tests/src/Main.hs
bsd-3-clause
977
0
15
214
326
186
140
-1
-1
module Main where import Control.Applicative import Criterion.Main import Data.Maybe (catMaybes) import System.Directory (getDirectoryContents) import System.FilePath import Language.Lua main :: IO () main = defaultMain [ env (loadFiles "lua-5.3.1-tests") $ \files -> bench "Parsing Lua files from 5.3.1 test suite" $ nf (catMaybes . map (either (const Nothing) Just) . map (parseText chunk)) files ] loadFiles :: FilePath -> IO [String] loadFiles root = do luaFiles <- map (root </>) . filter ((==) ".lua" . takeExtension) <$> getDirectoryContents root mapM readFile luaFiles
osa1/language-lua
bench/Main.hs
bsd-3-clause
675
0
18
179
203
105
98
16
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module Stack.PackageDump ( Line , eachSection , eachPair , DumpPackage (..) , conduitDumpPackage , ghcPkgDump , ghcPkgDescribe , InstalledCache , InstalledCacheEntry (..) , newInstalledCache , loadInstalledCache , saveInstalledCache , addProfiling , addHaddock , sinkMatching , pruneDeps ) where import Control.Applicative import Control.Arrow ((&&&)) import Control.Exception.Enclosed (tryIO) import Control.Monad (liftM) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger (MonadLogger) import Control.Monad.Trans.Control import Data.Attoparsec.Args import Data.Attoparsec.Text as P import Data.Binary.VersionTagged import Data.ByteString (ByteString) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import Data.Conduit import qualified Data.Conduit.Binary as CB import qualified Data.Conduit.List as CL import Data.Either (partitionEithers) import Data.IORef import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (catMaybes, listToMaybe) import Data.Maybe.Extra (mapMaybeM) import qualified Data.Set as Set import qualified Data.Text.Encoding as T import Data.Typeable (Typeable) import GHC.Generics (Generic) import Path import Path.IO (createTree) import Prelude -- Fix AMP warning import Stack.GhcPkg import Stack.Types import System.Directory (getDirectoryContents, doesFileExist) import System.Process.Read -- | Cached information on whether package have profiling libraries and haddocks. newtype InstalledCache = InstalledCache (IORef InstalledCacheInner) newtype InstalledCacheInner = InstalledCacheInner (Map GhcPkgId InstalledCacheEntry) deriving (Binary, NFData, Generic) instance HasStructuralInfo InstalledCacheInner instance HasSemanticVersion InstalledCacheInner -- | Cached information on whether a package has profiling libraries and haddocks. data InstalledCacheEntry = InstalledCacheEntry { installedCacheProfiling :: !Bool , installedCacheHaddock :: !Bool , installedCacheIdent :: !PackageIdentifier } deriving (Eq, Generic) instance Binary InstalledCacheEntry instance HasStructuralInfo InstalledCacheEntry instance NFData InstalledCacheEntry -- | Call ghc-pkg dump with appropriate flags and stream to the given @Sink@, for a single database ghcPkgDump :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ if empty, use global -> Sink ByteString IO a -> m a ghcPkgDump = ghcPkgCmdArgs ["dump"] -- | Call ghc-pkg describe with appropriate flags and stream to the given @Sink@, for a single database ghcPkgDescribe :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => PackageName -> EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ if empty, use global -> Sink ByteString IO a -> m a ghcPkgDescribe pkgName = ghcPkgCmdArgs ["describe", "--simple-output", packageNameString pkgName] -- | Call ghc-pkg and stream to the given @Sink@, for a single database ghcPkgCmdArgs :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => [String] -> EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ if empty, use global -> Sink ByteString IO a -> m a ghcPkgCmdArgs cmd menv wc mpkgDbs sink = do case reverse mpkgDbs of (pkgDb:_) -> createDatabase menv wc pkgDb -- TODO maybe use some retry logic instead? _ -> return () sinkProcessStdout Nothing menv (ghcPkgExeName wc) args sink where args = concat [ case mpkgDbs of [] -> ["--global", "--no-user-package-db"] _ -> ["--user", "--no-user-package-db"] ++ concatMap (\pkgDb -> ["--package-db", toFilePath pkgDb]) mpkgDbs , cmd , ["--expand-pkgroot"] ] -- | Create a new, empty @InstalledCache@ newInstalledCache :: MonadIO m => m InstalledCache newInstalledCache = liftIO $ InstalledCache <$> newIORef (InstalledCacheInner Map.empty) -- | Load a @InstalledCache@ from disk, swallowing any errors and returning an -- empty cache. loadInstalledCache :: (MonadLogger m, MonadIO m) => Path Abs File -> m InstalledCache loadInstalledCache path = do m <- taggedDecodeOrLoad path (return $ InstalledCacheInner Map.empty) liftIO $ InstalledCache <$> newIORef m -- | Save a @InstalledCache@ to disk saveInstalledCache :: MonadIO m => Path Abs File -> InstalledCache -> m () saveInstalledCache path (InstalledCache ref) = liftIO $ do createTree (parent path) readIORef ref >>= taggedEncodeFile path -- | Prune a list of possible packages down to those whose dependencies are met. -- -- * id uniquely identifies an item -- -- * There can be multiple items per name pruneDeps :: (Ord name, Ord id) => (id -> name) -- ^ extract the name from an id -> (item -> id) -- ^ the id of an item -> (item -> [id]) -- ^ get the dependencies of an item -> (item -> item -> item) -- ^ choose the desired of two possible items -> [item] -- ^ input items -> Map name item pruneDeps getName getId getDepends chooseBest = Map.fromList . fmap (getName . getId &&& id) . loop Set.empty Set.empty [] where loop foundIds usedNames foundItems dps = case partitionEithers $ map depsMet dps of ([], _) -> foundItems (s', dps') -> let foundIds' = Map.fromListWith chooseBest s' foundIds'' = Set.fromList $ map getId $ Map.elems foundIds' usedNames' = Map.keysSet foundIds' foundItems' = Map.elems foundIds' in loop (Set.union foundIds foundIds'') (Set.union usedNames usedNames') (foundItems ++ foundItems') (catMaybes dps') where depsMet dp | name `Set.member` usedNames = Right Nothing | all (`Set.member` foundIds) (getDepends dp) = Left (name, dp) | otherwise = Right $ Just dp where id' = getId dp name = getName id' -- | Find the package IDs matching the given constraints with all dependencies installed. -- Packages not mentioned in the provided @Map@ are allowed to be present too. sinkMatching :: Monad m => Bool -- ^ require profiling? -> Bool -- ^ require haddock? -> Map PackageName Version -- ^ allowed versions -> Consumer (DumpPackage Bool Bool) m (Map PackageName (DumpPackage Bool Bool)) sinkMatching reqProfiling reqHaddock allowed = do dps <- CL.filter (\dp -> isAllowed (dpPackageIdent dp) && (not reqProfiling || dpProfiling dp) && (not reqHaddock || dpHaddock dp)) =$= CL.consume return $ Map.fromList $ map (packageIdentifierName . dpPackageIdent &&& id) $ Map.elems $ pruneDeps id dpGhcPkgId dpDepends const -- Could consider a better comparison in the future dps where isAllowed (PackageIdentifier name version) = case Map.lookup name allowed of Just version' | version /= version' -> False _ -> True -- | Add profiling information to the stream of @DumpPackage@s addProfiling :: MonadIO m => InstalledCache -> Conduit (DumpPackage a b) m (DumpPackage Bool b) addProfiling (InstalledCache ref) = CL.mapM go where go dp = liftIO $ do InstalledCacheInner m <- readIORef ref let gid = dpGhcPkgId dp p <- case Map.lookup gid m of Just installed -> return (installedCacheProfiling installed) Nothing | null (dpLibraries dp) -> return True Nothing -> do let loop [] = return False loop (dir:dirs) = do econtents <- tryIO $ getDirectoryContents dir let contents = either (const []) id econtents if or [isProfiling content lib | content <- contents , lib <- dpLibraries dp ] && not (null contents) then return True else loop dirs loop $ dpLibDirs dp return dp { dpProfiling = p } isProfiling :: FilePath -- ^ entry in directory -> ByteString -- ^ name of library -> Bool isProfiling content lib = prefix `S.isPrefixOf` S8.pack content where prefix = S.concat ["lib", lib, "_p"] -- | Add haddock information to the stream of @DumpPackage@s addHaddock :: MonadIO m => InstalledCache -> Conduit (DumpPackage a b) m (DumpPackage a Bool) addHaddock (InstalledCache ref) = CL.mapM go where go dp = liftIO $ do InstalledCacheInner m <- readIORef ref let gid = dpGhcPkgId dp h <- case Map.lookup gid m of Just installed -> return (installedCacheHaddock installed) Nothing | not (dpHasExposedModules dp) -> return True Nothing -> do let loop [] = return False loop (ifc:ifcs) = do exists <- doesFileExist ifc if exists then return True else loop ifcs loop $ dpHaddockInterfaces dp return dp { dpHaddock = h } -- | Dump information for a single package data DumpPackage profiling haddock = DumpPackage { dpGhcPkgId :: !GhcPkgId , dpPackageIdent :: !PackageIdentifier , dpLibDirs :: ![FilePath] , dpLibraries :: ![ByteString] , dpHasExposedModules :: !Bool , dpDepends :: ![GhcPkgId] , dpHaddockInterfaces :: ![FilePath] , dpHaddockHtml :: !(Maybe FilePath) , dpProfiling :: !profiling , dpHaddock :: !haddock , dpIsExposed :: !Bool } deriving (Show, Eq, Ord) data PackageDumpException = MissingSingleField ByteString (Map ByteString [Line]) | Couldn'tParseField ByteString [Line] deriving Typeable instance Exception PackageDumpException instance Show PackageDumpException where show (MissingSingleField name values) = unlines $ concat [ return $ concat [ "Expected single value for field name " , show name , " when parsing ghc-pkg dump output:" ] , map (\(k, v) -> " " ++ show (k, v)) (Map.toList values) ] show (Couldn'tParseField name ls) = "Couldn't parse the field " ++ show name ++ " from lines: " ++ show ls -- | Convert a stream of bytes into a stream of @DumpPackage@s conduitDumpPackage :: MonadThrow m => Conduit ByteString m (DumpPackage () ()) conduitDumpPackage = (=$= CL.catMaybes) $ eachSection $ do pairs <- eachPair (\k -> (k, ) <$> CL.consume) =$= CL.consume let m = Map.fromList pairs let parseS k = case Map.lookup k m of Just [v] -> return v _ -> throwM $ MissingSingleField k m -- Can't fail: if not found, same as an empty list. See: -- https://github.com/fpco/stack/issues/182 parseM k = Map.findWithDefault [] k m parseDepend :: MonadThrow m => ByteString -> m (Maybe GhcPkgId) parseDepend "builtin_rts" = return Nothing parseDepend bs = liftM Just $ parseGhcPkgId bs' where (bs', _builtinRts) = case stripSuffixBS " builtin_rts" bs of Nothing -> case stripPrefixBS "builtin_rts " bs of Nothing -> (bs, False) Just x -> (x, True) Just x -> (x, True) case Map.lookup "id" m of Just ["builtin_rts"] -> return Nothing _ -> do name <- parseS "name" >>= parsePackageName version <- parseS "version" >>= parseVersion ghcPkgId <- parseS "id" >>= parseGhcPkgId -- if a package has no modules, these won't exist let libDirKey = "library-dirs" libraries = parseM "hs-libraries" exposedModules = parseM "exposed-modules" exposed = parseM "exposed" depends <- mapMaybeM parseDepend $ parseM "depends" let parseQuoted key = case mapM (P.parseOnly (argsParser NoEscaping) . T.decodeUtf8) val of Left{} -> throwM (Couldn'tParseField key val) Right dirs -> return (concat dirs) where val = parseM key libDirPaths <- parseQuoted libDirKey haddockInterfaces <- parseQuoted "haddock-interfaces" haddockHtml <- parseQuoted "haddock-html" return $ Just DumpPackage { dpGhcPkgId = ghcPkgId , dpPackageIdent = PackageIdentifier name version , dpLibDirs = libDirPaths , dpLibraries = S8.words $ S8.unwords libraries , dpHasExposedModules = not (null libraries || null exposedModules) , dpDepends = depends , dpHaddockInterfaces = haddockInterfaces , dpHaddockHtml = listToMaybe haddockHtml , dpProfiling = () , dpHaddock = () , dpIsExposed = exposed == ["True"] } stripPrefixBS :: ByteString -> ByteString -> Maybe ByteString stripPrefixBS x y | x `S.isPrefixOf` y = Just $ S.drop (S.length x) y | otherwise = Nothing stripSuffixBS :: ByteString -> ByteString -> Maybe ByteString stripSuffixBS x y | x `S.isSuffixOf` y = Just $ S.take (S.length y - S.length x) y | otherwise = Nothing -- | A single line of input, not including line endings type Line = ByteString -- | Apply the given Sink to each section of output, broken by a single line containing --- eachSection :: Monad m => Sink Line m a -> Conduit ByteString m a eachSection inner = CL.map (S.filter (/= _cr)) =$= CB.lines =$= start where _cr = 13 peekBS = await >>= maybe (return Nothing) (\bs -> if S.null bs then peekBS else leftover bs >> return (Just bs)) start = peekBS >>= maybe (return ()) (const go) go = do x <- toConsumer $ takeWhileC (/= "---") =$= inner yield x CL.drop 1 start -- | Grab each key/value pair eachPair :: Monad m => (ByteString -> Sink Line m a) -> Conduit Line m a eachPair inner = start where start = await >>= maybe (return ()) start' _colon = 58 _space = 32 start' bs1 = toConsumer (valSrc =$= inner key) >>= yield >> start where (key, bs2) = S.break (== _colon) bs1 (spaces, bs3) = S.span (== _space) $ S.drop 1 bs2 indent = S.length key + 1 + S.length spaces valSrc | S.null bs3 = noIndent | otherwise = yield bs3 >> loopIndent indent noIndent = do mx <- await case mx of Nothing -> return () Just bs -> do let (spaces, val) = S.span (== _space) bs if S.length spaces == 0 then leftover val else do yield val loopIndent (S.length spaces) loopIndent i = loop where loop = await >>= maybe (return ()) go go bs | S.length spaces == i && S.all (== _space) spaces = yield val >> loop | otherwise = leftover bs where (spaces, val) = S.splitAt i bs -- | General purpose utility takeWhileC :: Monad m => (a -> Bool) -> Conduit a m a takeWhileC f = loop where loop = await >>= maybe (return ()) go go x | f x = yield x >> loop | otherwise = leftover x
vigoo/stack
src/Stack/PackageDump.hs
bsd-3-clause
16,659
0
27
5,385
4,240
2,172
2,068
-1
-1
{-# LANGUAGE DeriveGeneric #-} -- | The type of item aspects and its operations. module Game.LambdaHack.Common.ItemAspect ( AspectRecord(..), KindMean(..) , emptyAspectRecord, addMeanAspect, castAspect, aspectsRandom , aspectRecordToList, rollAspectRecord, getSkill, checkFlag, meanAspect , onlyMinorEffects, itemTrajectory, totalRange, isHumanTrinket , goesIntoEqp, loreFromContainer #ifdef EXPOSE_INTERNAL -- * Internal operations , ceilingMeanDice #endif ) where import Prelude () import Game.LambdaHack.Core.Prelude import qualified Control.Monad.Trans.State.Strict as St import Data.Binary import qualified Data.EnumSet as ES import Data.Hashable (Hashable) import qualified Data.Text as T import GHC.Generics (Generic) import qualified System.Random.SplitMix32 as SM import Game.LambdaHack.Common.Point import Game.LambdaHack.Common.Time import Game.LambdaHack.Common.Types import Game.LambdaHack.Common.Vector import qualified Game.LambdaHack.Content.ItemKind as IK import qualified Game.LambdaHack.Core.Dice as Dice import Game.LambdaHack.Core.Random import qualified Game.LambdaHack.Definition.Ability as Ability import Game.LambdaHack.Definition.Defs -- | Record of skills conferred by an item as well as of item flags -- and other item aspects. data AspectRecord = AspectRecord { aTimeout :: Int , aSkills :: Ability.Skills , aFlags :: Ability.Flags , aELabel :: Text , aToThrow :: IK.ThrowMod , aPresentAs :: Maybe (GroupName IK.ItemKind) , aEqpSlot :: Maybe Ability.EqpSlot } deriving (Show, Eq, Ord, Generic) instance Hashable AspectRecord instance Binary AspectRecord -- | Partial information about an item, deduced from its item kind. -- These are assigned to each 'IK.ItemKind'. The @kmConst@ flag says whether -- the item's aspect record is constant rather than random or dependent -- on item creation dungeon level. data KindMean = KindMean { kmConst :: Bool -- ^ whether the item doesn't need second identification , kmMean :: AspectRecord -- ^ mean value of item's possible aspect records } deriving (Show, Eq, Ord) emptyAspectRecord :: AspectRecord emptyAspectRecord = AspectRecord { aTimeout = 0 , aSkills = Ability.zeroSkills , aFlags = Ability.Flags ES.empty , aELabel = "" , aToThrow = IK.ThrowMod 100 100 1 , aPresentAs = Nothing , aEqpSlot = Nothing } castAspect :: Dice.AbsDepth -> Dice.AbsDepth -> AspectRecord -> IK.Aspect -> Rnd AspectRecord castAspect !ldepth !totalDepth !ar !asp = case asp of IK.Timeout d -> do n <- castDice ldepth totalDepth d return $! assert (aTimeout ar == 0) $ ar {aTimeout = n} IK.AddSkill sk d -> do n <- castDice ldepth totalDepth d return $! if n /= 0 then ar {aSkills = Ability.addSk sk n (aSkills ar)} else ar IK.SetFlag feat -> return $! ar {aFlags = Ability.Flags $ ES.insert feat (Ability.flags $ aFlags ar)} IK.ELabel t -> return $! ar {aELabel = t} IK.ToThrow tt -> return $! ar {aToThrow = tt} IK.PresentAs ha -> return $! ar {aPresentAs = Just ha} IK.EqpSlot slot -> return $! ar {aEqpSlot = Just slot} IK.Odds d aspects1 aspects2 -> do pick1 <- oddsDice ldepth totalDepth d foldlM' (castAspect ldepth totalDepth) ar $ if pick1 then aspects1 else aspects2 -- If @False@, aspects of this kind are most probably fixed, not random -- nor dependent on dungeon level where the item is created. aspectsRandom :: [IK.Aspect] -> Bool aspectsRandom ass = let rollM depth = foldlM' (castAspect (Dice.AbsDepth depth) (Dice.AbsDepth 10)) emptyAspectRecord ass gen = SM.mkSMGen 0 (ar0, gen0) = St.runState (rollM 0) gen (ar1, gen1) = St.runState (rollM 10) gen0 in show gen /= show gen0 || show gen /= show gen1 || ar0 /= ar1 addMeanAspect :: AspectRecord -> IK.Aspect -> AspectRecord addMeanAspect !ar !asp = case asp of IK.Timeout d -> let n = ceilingMeanDice d in assert (aTimeout ar == 0) $ ar {aTimeout = n} IK.AddSkill sk d -> let n = ceilingMeanDice d in if n /= 0 then ar {aSkills = Ability.addSk sk n (aSkills ar)} else ar IK.SetFlag feat -> ar {aFlags = Ability.Flags $ ES.insert feat (Ability.flags $ aFlags ar)} IK.ELabel t -> ar {aELabel = t} IK.ToThrow tt -> ar {aToThrow = tt} IK.PresentAs ha -> ar {aPresentAs = Just ha} IK.EqpSlot slot -> ar {aEqpSlot = Just slot} IK.Odds{} -> ar -- can't tell, especially since we don't know the level ceilingMeanDice :: Dice.Dice -> Int ceilingMeanDice d = ceiling $ Dice.meanDice d aspectRecordToList :: AspectRecord -> [IK.Aspect] aspectRecordToList AspectRecord{..} = [IK.Timeout $ Dice.intToDice aTimeout | aTimeout /= 0] ++ [ IK.AddSkill sk $ Dice.intToDice n | (sk, n) <- Ability.skillsToList aSkills ] ++ [IK.SetFlag feat | feat <- ES.elems $ Ability.flags aFlags] ++ [IK.ELabel aELabel | not $ T.null aELabel] ++ [IK.ToThrow aToThrow | aToThrow /= IK.ThrowMod 100 100 1] ++ maybe [] (\ha -> [IK.PresentAs ha]) aPresentAs ++ maybe [] (\slot -> [IK.EqpSlot slot]) aEqpSlot rollAspectRecord :: [IK.Aspect] -> Dice.AbsDepth -> Dice.AbsDepth -> Rnd AspectRecord rollAspectRecord ass ldepth totalDepth = foldlM' (castAspect ldepth totalDepth) emptyAspectRecord ass getSkill :: Ability.Skill -> AspectRecord -> Int {-# INLINE getSkill #-} getSkill sk ar = Ability.getSk sk $ aSkills ar checkFlag :: Ability.Flag -> AspectRecord -> Bool {-# INLINE checkFlag #-} checkFlag flag ar = Ability.checkFl flag (aFlags ar) meanAspect :: IK.ItemKind -> AspectRecord meanAspect kind = foldl' addMeanAspect emptyAspectRecord (IK.iaspects kind) -- Kinetic damage is not considered major effect, even though it -- identifies an item, when one hits with it. However, it's tedious -- to wait for weapon identification until first hit and also -- if a weapon is periodically activated, the kinetic damage would not apply, -- so we'd need special cases that force identification or warn -- or here not consider kinetic damage a major effect if item is periodic. -- So we opt for KISS and identify effect-less weapons at pick-up, -- not at first hit. onlyMinorEffects :: AspectRecord -> IK.ItemKind -> Bool onlyMinorEffects ar kind = checkFlag Ability.MinorEffects ar -- override || all IK.alwaysDudEffect (IK.ieffects kind) -- exhibits no major effects itemTrajectory :: AspectRecord -> IK.ItemKind -> [Point] -> ([Vector], (Speed, Int)) itemTrajectory ar itemKind path = let IK.ThrowMod{..} = aToThrow ar in computeTrajectory (IK.iweight itemKind) throwVelocity throwLinger path totalRange :: AspectRecord -> IK.ItemKind -> Int totalRange ar itemKind = snd $ snd $ itemTrajectory ar itemKind [] isHumanTrinket :: IK.ItemKind -> Bool isHumanTrinket itemKind = maybe False (> 0) $ lookup IK.VALUABLE $ IK.ifreq itemKind -- risk from treasure hunters goesIntoEqp :: AspectRecord -> Bool goesIntoEqp ar = checkFlag Ability.Equipable ar || checkFlag Ability.Meleeable ar loreFromContainer :: AspectRecord -> Container -> SLore loreFromContainer arItem c = case c of CFloor{} -> SItem CEmbed{} -> SEmbed CActor _ store -> if | checkFlag Ability.Blast arItem -> SBlast | checkFlag Ability.Condition arItem -> SCondition | otherwise -> loreFromMode $ MStore store CTrunk{} -> if checkFlag Ability.Blast arItem then SBlast else STrunk
LambdaHack/LambdaHack
engine-src/Game/LambdaHack/Common/ItemAspect.hs
bsd-3-clause
7,645
0
16
1,671
2,102
1,119
983
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} ------------------------------------------------------------------------------- -- | -- Module : Bart.Departure.Parser -- Copyright : (c) 2012 Paulo Tanimoto -- License : BSD3 -- -- Maintainer : Paulo Tanimoto <[email protected]> -- ------------------------------------------------------------------------------- module Bart.Departure.Parser ( parseDepart , parseStation , parseEtd , parseEstimate ) where ------------------------------------------------------------------------------- -- Imports ------------------------------------------------------------------------------- import Bart.Departure.Types import Control.Applicative (Applicative (..), (<$>)) import Control.Monad (join) import Control.Monad.IO.Class (MonadIO (liftIO)) import Data.Default (Default (..)) import Data.Monoid (Monoid (..), (<>)) import Data.Conduit (Conduit, Pipe, ResourceT, Sink, Source, ($$), ($=), (=$)) import qualified Data.Conduit as C import qualified Data.Conduit.Binary as CB import qualified Data.Conduit.List as CL import qualified Data.Conduit.Text as CT import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Data.Text (Text) import qualified Data.Text as T import Data.XML.Types import Text.XML.Stream.Parse ------------------------------------------------------------------------------- -- Parser ------------------------------------------------------------------------------- ptag :: C.MonadThrow m => Name -> Pipe Event Event o u m a -> Pipe Event Event o u m (Maybe a) ptag name p = tagNoAttr name p text :: C.MonadThrow m => Name -> Pipe Event Event o u m (Maybe Text) text name = ptag name content withDef :: (Monad m, Default a) => m (Maybe a) -> m a withDef f = do may <- f case may of Nothing -> return def Just res -> return res parseDepart :: C.MonadThrow m => Pipe Event Event o u m (Maybe Depart) parseDepart = do withDef $ ptag "root" $ do uri <- text "uri" date <- text "date" time <- text "time" stns <- many parseStation msg <- text "message" return $ Depart <$> uri <*> date <*> time <*> Just stns <*> msg parseStation :: C.MonadThrow m => Pipe Event Event o u m (Maybe Station) parseStation = do withDef $ ptag "station" $ do name <- text "name" abbr <- text "abbr" etds <- many parseEtd return $ Station <$> name <*> abbr <*> Just etds parseEtd :: C.MonadThrow m => Pipe Event Event o u m (Maybe Etd) parseEtd = do withDef $ ptag "etd" $ do dest <- text "destination" abbr <- text "abbreviation" ests <- many parseEstimate return $ Etd <$> dest <*> abbr <*> Just ests parseEstimate :: C.MonadThrow m => Pipe Event Event o u m (Maybe Estimate) parseEstimate = do withDef $ ptag "estimate" $ do minu <- text "minutes" plat <- text "platform" dir <- text "direction" len <- text "length" col <- text "color" hex <- text "hexcolor" bike <- text "bikeflag" return $ Estimate <$> minu <*> plat <*> dir <*> len <*> col <*> hex <*> bike
tanimoto/bart
src/Bart/Departure/Parser.hs
bsd-3-clause
3,634
0
17
1,076
947
497
450
103
2
{-# LANGUAGE RecordWildCards #-} module Codex.Lib.Server.MVar ( Server, ID, Message (..), Event (..), Client (..), initServer, deliverWall, deliverBroadcast, deliverMessage, send'event'connection, send'event'disconnect, send'event'debug ) where import Codex.Lib.Map import Control.Monad import Control.Concurrent import Control.Concurrent.MVar import Control.Concurrent.Chan import qualified Data.Map as M import qualified Data.Vector.Unboxed as V type ID = Int data Message = Wall String | Broadcast [ID] String | Message ID String data Event = Init | Destroy | Connection (MVar (Maybe Client)) | Disconnect ID | Delivery Message | Debug (MVar String) data Client = Client { _id :: ID, _ch :: Chan String } data Server = Server { _mv :: MVar (Event), _clients :: M.Map ID Client, _maxConnections :: Int, _connections :: Int, _counter :: Int } instance Show Client where show (Client a b) = "id: " ++ show a instance Show Server where show (Server a b c d e) = "clients: " ++ M.showTree b ++ ", maxConnections: " ++ show c ++ ", connections: " ++ show d ++ ", counter: " ++ show e initServer :: Int -> IO Server initServer maxConn = do mv <- newEmptyMVar let serv = Server { _mv = mv, _clients = M.empty, _maxConnections = maxConn, _connections = 0, _counter = 0 } forkIO $ dispatchLoop serv return serv dispatchLoop :: Server -> IO () dispatchLoop serv = do e <- takeMVar $ _mv serv putStrLn "got event" serv' <- case e of Init -> do recv'event'id serv "init" Destroy -> do recv'event'id serv "destroy" Connection mv -> do recv'event'connection serv mv Disconnect id' -> do recv'event'disconnect serv id' Delivery _ -> do recv'event'id serv "destroy" Debug mv -> do recv'event'debug serv mv dispatchLoop serv' recv'event'id :: Server -> String -> IO Server recv'event'id serv s = do putStrLn $ "got " ++ s return serv recv'event'connection :: Server -> MVar (Maybe Client) -> IO Server recv'event'connection serv@Server{..} mv = do putStrLn $ "recv'event'connection" case (_connections >= _maxConnections) of False -> recv'event'connection'ok serv mv True-> recv'event'connection'fail serv mv recv'event'connection'fail :: Server -> MVar (Maybe Client) -> IO Server recv'event'connection'fail serv mv = do putMVar mv Nothing return serv recv'event'connection'ok :: Server -> MVar (Maybe Client) -> IO Server recv'event'connection'ok serv@Server{..} mv = do let counter = _counter + 1 let connections = _connections + 1 ch <- newChan let client = Client { _id = counter, _ch = ch } let clients = M.insert counter client _clients putMVar mv (Just client) let serv' = serv { _counter = counter, _connections = connections, _clients = clients } return serv' recv'event'disconnect :: Server -> ID -> IO Server recv'event'disconnect serv@Server{..} id' = do putStrLn $ "recv'event'disconnect: " ++ show id' let connections = _connections - 1 let clients = deleteMaybe id' _clients case clients of Nothing -> return serv (Just clients') -> do let serv' = serv { _connections = connections, _clients = clients' } return serv' recv'event'debug :: Server -> MVar String -> IO Server recv'event'debug serv mv = do putStrLn $ "recv'event'debug" putMVar mv $ show serv return serv send'event'connection :: Server -> IO (Maybe Client) send'event'connection serv = do mv <- newEmptyMVar putMVar (_mv serv) $ Connection mv client <- takeMVar mv case client of Nothing -> return Nothing (Just client') -> do putStrLn $ "new connection: " ++ (show $ _id client') return client send'event'disconnect :: Server -> ID -> IO () send'event'disconnect serv id' = do putMVar (_mv serv) $ Disconnect id' putStrLn $ "disconnect: " ++ show id' return () send'event'debug :: Server -> IO () send'event'debug serv = do mv <- newEmptyMVar putMVar (_mv serv) $ Debug mv msg <- takeMVar mv putStrLn $ "debug info: " ++ msg return () deliverWall :: Server -> String -> IO () deliverWall serv s = do return () deliverBroadcast :: Server -> [ID] -> String -> IO () deliverBroadcast serv ids s = do return () deliverMessage :: Server -> ID -> String -> IO () deliverMessage serv id' s = do putMVar (_mv serv) Init return ()
adarqui/Codex
src/Codex/Lib/Server/MVar.hs
bsd-3-clause
4,228
0
16
803
1,538
761
777
135
6
{-# LANGUAGE OverloadedStrings #-} module ETA.CodeGen.Rts where import Data.Text import Codec.JVM import ETA.Util import Data.Monoid((<>)) import qualified Data.Text as T -- NOTE: If the RTS is refactored, this file must also be updated accordingly -- merge "a" "b" == "a/b" merge :: Text -> Text -> Text merge x y = append x . cons '/' $ y rts, apply, thunk, stg, exception, io, util, stm, par, interp, conc :: Text -> Text rts = merge "eta/runtime" apply = merge (rts "apply") thunk = merge (rts "thunk") stg = merge (rts "stg") exception = merge (rts "exception") io = merge (rts "io") conc = merge (rts "concurrent") util = merge (rts "util") stm = merge (rts "stm") par = merge (rts "parallel") interp = merge (rts "interpreter") closureType, indStaticType, contextType, capabilityType, taskType, funType, tsoType, frameType, rtsFunType, conType, thunkType, rtsConfigType, exitCodeType, rtsOptsEnbledType, stgArrayType, stgByteArrayType, stgMutVarType, stgMVarType, hsResultType, stgTVarType, stgBCOType, stgWeakType :: FieldType closureType = obj stgClosure indStaticType = obj stgIndStatic contextType = obj stgContext capabilityType = obj capability taskType = obj task funType = obj stgFun tsoType = obj stgTSO frameType = obj stackFrame rtsFunType = obj rtsFun conType = obj stgConstr thunkType = obj stgThunk rtsConfigType = obj rtsConfig rtsOptsEnbledType = obj rtsOptsEnbled exitCodeType = obj exitCode stgArrayType = obj stgArray stgMutVarType = obj stgMutVar stgByteArrayType = obj stgByteArray stgMVarType = obj stgMVar stgTVarType = obj stgTVar hsResultType = obj hsResult stgBCOType = obj stgBCO stgWeakType = obj stgWeak stgConstr, stgClosure, stgContext, capability, task, stgInd, stgIndStatic, stgThunk, stgFun, stgTSO, stackFrame, rtsConfig, rtsOptsEnbled, exitCode, stgArray, stgByteArray, rtsUnsigned, stgMutVar, stgMVar, stgTVar, rtsGroup, hsResult, rtsFun, stgBCO, stgWeak :: Text stgConstr = stg "StgConstr" stgClosure = stg "StgClosure" stgContext = stg "StgContext" capability = stg "Capability" task = stg "Task" stgInd = thunk "StgInd" stgIndStatic = thunk "StgIndStatic" stgThunk = thunk "StgThunk" stgFun = apply "StgFun" stgTSO = stg "StgTSO" stackFrame = stg "StackFrame" rtsFun = stg "RtsFun" rtsConfig = rts "RtsConfig" rtsOptsEnbled = rts "RtsFlags$RtsOptsEnabled" exitCode = rts "Rts$ExitCode" stgArray = io "StgArray" stgByteArray = io "StgByteArray" rtsUnsigned = merge "eta/integer" "Utils" stgMutVar = io "StgMutVar" stgMVar = conc "StgMVar" stgTVar = stm "StgTVar" stgBCO = interp "StgBCO" stgWeak = stg "StgWeak" rtsGroup = rts "Rts" hsResult = rts "Rts$HaskellResult" memoryManager :: Text memoryManager = io "MemoryManager" storeR, loadR, storeI, loadI, storeL, loadL, storeF, loadF, storeD, loadD, storeO, loadO :: Code (storeR, loadR) = contextLoadStore "R" closureType (storeI, loadI) = contextLoadStore "I" jint (storeL, loadL) = contextLoadStore "L" jlong (storeF, loadF) = contextLoadStore "F" jfloat (storeD, loadD) = contextLoadStore "D" jdouble (storeO, loadO) = contextLoadStore "O" jobject contextLoadStore :: Text -> FieldType -> (Code, Code) contextLoadStore name ft = ( invokevirtual $ mkMethodRef stgContext name [jint, ft] void , invokevirtual $ mkMethodRef stgContext name [jint] (ret ft)) argPatToFrame :: Text -> Text argPatToFrame patText = append (upperFirst a) (toUpper b) where [a,b] = split (== '_') patText loadContext :: Code loadContext = gload contextType 1 currentTSOField :: Code currentTSOField = getfield (mkFieldRef stgContext "currentTSO" tsoType) spPushMethod :: Code spPushMethod = invokevirtual (mkMethodRef stgTSO "spPush" [frameType] void) spTopIndexMethod :: Code spTopIndexMethod = invokevirtual (mkMethodRef stgContext "stackTopIndex" [] (ret jint)) spTopMethod :: Code spTopMethod = invokevirtual (mkMethodRef stgContext "stackTop" [] (ret frameType)) checkForStackFramesMethod :: Code checkForStackFramesMethod = invokevirtual (mkMethodRef stgContext "checkForStackFrames" [jint, frameType] (ret jbool)) mkApFast :: Text -> Code mkApFast patText = getstatic (mkFieldRef (apply "Apply") fullPat rtsFunType) <> loadContext <> invokevirtual (mkMethodRef rtsFun "enter" [contextType] void) -- TODO: We can do better than rtsFun, but it depends on the -- determinism of javac. where fullPat = append patText "_fast" apUpdName :: Int -> Text apUpdName n = thunk $ T.concat ["Ap", pack $ show n, "Upd"] selectThunkName :: Bool -> Text -> Text selectThunkName updatable repText = thunk $ T.concat ["Selector", repText, updText] where updText = if updatable then "Upd" else "NoUpd" constrField :: Int -> Text constrField = cons 'x' . pack . show constrFieldGetter :: Int -> Text constrFieldGetter = append "get" . pack . show myCapability :: FieldRef myCapability = mkFieldRef stgContext "myCapability" capabilityType contextMyCapability :: Code contextMyCapability = getfield myCapability contextMyCapabilitySet :: Code contextMyCapabilitySet = putfield myCapability suspendThreadMethod :: Bool -> Code suspendThreadMethod interruptible = loadContext <> contextMyCapability -- <> dup capabilityType <> iconst jbool (boolToInt interruptible) <> invokevirtual (mkMethodRef capability "suspendThread" [jbool] (ret taskType)) where boolToInt True = 1 boolToInt False = 0 resumeThreadMethod :: Code resumeThreadMethod = invokestatic (mkMethodRef capability "resumeThread" [taskType] (ret capabilityType)) <> loadContext <> swap capabilityType contextType <> contextMyCapabilitySet stgExceptionGroup, ioGroup, stmGroup, concGroup, parGroup, interpGroup, stgGroup :: Text stgExceptionGroup = exception "StgException" ioGroup = io "IO" stmGroup = stm "STM" concGroup = conc "Concurrent" stgGroup = stg "Stg" parGroup = par "Parallel" interpGroup = interp "Interpreter" mkRtsFunCall :: (Text, Text) -> Code mkRtsFunCall (group, name) = getstatic (mkFieldRef group name rtsFunType) <> loadContext <> invokevirtual (mkMethodRef rtsFun "enter" [contextType] void) -- Types buffer :: Text buffer = "java/nio/Buffer" bufferType :: FieldType bufferType = obj buffer byteBuffer :: Text byteBuffer = "java/nio/ByteBuffer" byteBufferType :: FieldType byteBufferType = obj byteBuffer byteArrayBuf :: Code byteArrayBuf = getfield $ mkFieldRef stgByteArray "buf" byteBufferType byteBufferCapacity :: Code byteBufferCapacity = invokevirtual $ mkMethodRef byteBuffer "capacity" [] (ret jint) byteBufferGet :: FieldType -> Code byteBufferGet ft = invokevirtual $ mkMethodRef byteBuffer name [jint] (ret ft) where name = append "get" $ fieldTypeSuffix ft byteBufferPut :: FieldType -> Code byteBufferPut ft = invokevirtual $ mkMethodRef byteBuffer name [jint, ft] (ret byteBufferType) where name = append "put" $ fieldTypeSuffix ft byteBufferPosGet :: Code byteBufferPosGet = invokevirtual $ mkMethodRef byteBuffer "position" [] (ret jint) byteBufferAddrGet :: Code byteBufferAddrGet = invokestatic $ mkMethodRef memoryManager "getAddress" [byteBufferType] (ret jint) byteBufferPosSet :: Code byteBufferPosSet = invokevirtual $ mkMethodRef byteBuffer "position" [jint] (ret bufferType) byteBufferDup :: Code byteBufferDup = invokevirtual $ mkMethodRef byteBuffer "duplicate" [] (ret byteBufferType) fieldTypeSuffix :: FieldType -> Text fieldTypeSuffix (BaseType prim) = case prim of JBool -> "Int" JChar -> "Char" JFloat -> "Float" JDouble -> "Double" JByte -> "" JShort -> "Short" JInt -> "Int" JLong -> "Long" fieldTypeSuffix ft = error $ "fieldTypeSuffix: " ++ show ft mutVarValue :: Code mutVarValue = getfield $ mkFieldRef stgMutVar "value" closureType mutVarSetValue :: Code mutVarSetValue = putfield $ mkFieldRef stgMutVar "value" closureType mVarValue :: Code mVarValue = getfield $ mkFieldRef stgMVar "value" closureType barf :: Text -> Code barf text = sconst text <> iconst jint (0) <> new arrayFt <> invokestatic (mkMethodRef (rts "RtsMessages") "barf" [jstring, arrayFt] void) where arrayFt = jarray jobject hsResultCap :: Code hsResultCap = getfield $ mkFieldRef hsResult "cap" capabilityType hsResultValue :: Code hsResultValue = getfield $ mkFieldRef hsResult "result" closureType trueClosure :: Code trueClosure = invokestatic . mkMethodRef "ghczmprim/ghc/Types" "DTrue_closure" [] $ Just closureType falseClosure :: Code falseClosure = invokestatic . mkMethodRef "ghczmprim/ghc/Types" "DFalse_closure" [] $ Just closureType getTagMethod :: Code -> Code getTagMethod code = code <> gconv closureType conType <> invokevirtual (mkMethodRef stgConstr "getTag" [] (ret jint)) printStream :: Text printStream = "java/io/PrintStream" printStreamType :: FieldType printStreamType = obj printStream debugPrint :: FieldType -> Code debugPrint ft = dup ft <> getstatic (mkFieldRef "java/lang/System" "out" printStreamType) <> swap ft printStreamType <> invokevirtual (mkMethodRef printStream "println" [genFt ft] void) where genFt (ObjectType _) = jobject genFt (ArrayType _) = jobject genFt ft = ft nullAddr :: Code nullAddr = getstatic $ mkFieldRef memoryManager "nullAddress" byteBufferType
AlexeyRaga/eta
compiler/ETA/CodeGen/Rts.hs
bsd-3-clause
9,559
0
12
1,797
2,608
1,420
1,188
231
8
{-# LANGUAGE OverloadedStrings, TypeFamilies, FlexibleContexts, PackageImports #-} module Retrieve (retrievePln, retrieveEx, retrieveDM5, retrieveSS1) where import "monads-tf" Control.Monad.State import "monads-tf" Control.Monad.Error import qualified Data.ByteString as BS import qualified Network.Sasl as SASL import qualified Network.Sasl.DigestMd5.Server as DM5S import qualified Network.Sasl.ScramSha1.Server as SS1S retrievePln :: ( MonadState m, SASL.SaslState (StateType m), MonadError m, SASL.SaslError (ErrorType m) ) => BS.ByteString -> BS.ByteString -> BS.ByteString -> m () retrievePln "" "yoshikuni" "password" = return () retrievePln _ _ _ = throwError $ SASL.fromSaslError SASL.NotAuthorized "incorrect username or password" retrieveEx :: (MonadError m, SASL.SaslError (ErrorType m)) => BS.ByteString -> m () retrieveEx "" = return () retrieveEx hn = throwError $ SASL.fromSaslError SASL.NotAuthorized hn retrieveDM5 :: ( MonadState m, SASL.SaslState (StateType m), MonadError m, SASL.SaslError (ErrorType m) ) => BS.ByteString -> m BS.ByteString retrieveDM5 "yoshikuni" = return $ DM5S.mkStored "yoshikuni" "localhost" "password" retrieveDM5 _ = throwError $ SASL.fromSaslError SASL.NotAuthorized "incorrect username or password" retrieveSS1 :: ( MonadState m, SASL.SaslState (StateType m), MonadError m, SASL.SaslError (ErrorType m) ) => BS.ByteString -> m (BS.ByteString, BS.ByteString, BS.ByteString, Int) retrieveSS1 "yoshikuni" = return (slt, stk, svk, i) where slt = "pepper"; i = 4492; (stk, svk) = SS1S.salt "password" slt i retrieveSS1 _ = throwError $ SASL.fromSaslError SASL.NotAuthorized "incorrect username or password"
YoshikuniJujo/xmpipe
examples/Retrieve.hs
bsd-3-clause
1,670
24
10
222
534
288
246
33
1
-- | Random-access, streaming sources, which are used to read PDF files -- incrementally. module Graphics.PDF.Source ( -- * Sources Source(..) -- * Construction , handleSource , byteStringSource -- * Parsing , parseStream ) where import Control.Applicative import Control.Monad.State.Strict import Data.Attoparsec import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.Int import Pipes import Pipes.Attoparsec as P import Pipes.ByteString import System.IO -- | A random-access streaming source. data Source m = Source { streamFrom :: Int64 -> Producer B.ByteString m () } -- | Turn a 'Handle' into a 'Source'. The handle must be seekable. handleSource :: MonadIO m => Handle -> Source m handleSource h = Source $ \pos -> do liftIO $ hSeek h AbsoluteSeek (fromIntegral pos) fromHandle h -- | Turn a lazy 'L.ByteString' into a 'Source'. byteStringSource :: Monad m => L.ByteString -> Source m byteStringSource s = Source $ \pos -> fromLazy (L.drop pos s) -- | Parse a stream, returning a result and the rest of the stream. parseStream :: (Functor m, Monad m) => Parser a -> Producer B.ByteString m r -> m (Either P.ParsingError a, Producer B.ByteString m r) parseStream parser = runStateT $ fmap snd <$> P.parse parser
knrafto/pdfkit
Graphics/PDF/Source.hs
bsd-3-clause
1,429
0
12
373
326
180
146
29
1
module Closure where import Control.Applicative import Control.Monad.State import Data.Set (Set, difference, union) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromJust) import Debug.Trace import Id import Type import Syntax hiding (name, args, body) import KNormal hiding (freeVars, name, args, body) import qualified KNormal -- | Type of closure. data Closure = Closure { entry :: LId, actualFV :: [VId] } deriving (Eq, Show) -- Expression after closure transformation type ClosExp = Typed ClosExpT data ClosExpT = CUnit | CInt !Int | CFloat !Float | CNeg !VId | CArithBin !ArithBinOp !VId !VId | CFNeg !VId | CFloatBin !FloatBinOp !VId !VId | CIf !CmpOp !VId !VId !ClosExp !ClosExp -- 比較 + 分岐 | CLet !VId !Type !ClosExp !ClosExp | CVar !VId | CMakeCls !VId !Type !Closure !ClosExp | CAppCls !VId ![VId] | CAppDir !LId ![VId] | CTuple ![VId] | CLetTuple ![(VId, Type)] !VId !ClosExp | CGet !VId !VId | CPut !VId !VId !VId | CExtArray !LId deriving (Eq, Show) data CFundef = CFundef { name :: !(VId, Type) , args :: ![(VId, Type)] , formalFV :: ![(VId, Type)] , body :: !ClosExp } deriving (Eq, Show) data CVardef = CVardef !Id !Type ClosExp deriving (Eq, Show) data Prog = Prog ![CVardef] ![CFundef] !ClosExp freeVars :: ClosExp -> Set VId freeVars (expr :-: _) = case expr of CUnit -> Set.empty (CInt {}) -> Set.empty (CFloat {}) -> Set.empty (CNeg x) -> Set.singleton x (CArithBin _ x y) -> Set.fromList [x, y] (CFNeg x) -> Set.singleton x (CFloatBin _ x y) -> Set.fromList [x, y] (CIf _ x y e1 e2) -> Set.fromList [x, y] `union` freeVars e1 `union` freeVars e2 (CLet x _t e1 e2) -> freeVars e1 `union` Set.delete x (freeVars e2) (CVar x) -> Set.singleton x (CMakeCls x _t (Closure { actualFV = ys }) e) -> Set.delete x (Set.fromList ys `union` freeVars e) (CAppCls x ls) -> Set.fromList (x : ls) (CAppDir _ ls) -> Set.fromList ls (CTuple ls) -> Set.fromList ls (CLetTuple ls x e) -> Set.insert x (freeVars e `difference` Set.fromList (map fst ls)) (CGet x y) -> Set.fromList [x, y] (CPut x y z) -> Set.fromList [x, y, z] (CExtArray {}) -> Set.empty idToVId :: Id -> VId idToVId (Id x) = VId x idToLId :: Id -> LId idToLId (Id x) = LId x transSub :: Map VId Type -> Set Id -> KNormal -> State [CFundef] ClosExp transSub env known (e :-: exprt) = fmap (:-: exprt) $ case e of KUnit -> return CUnit (KInt i) -> return $ CInt i (KFloat f) -> return $ CFloat f (KNeg (Id x)) -> return $ CNeg (VId x) (KArithBin op (Id x) (Id y)) -> return $ CArithBin op (VId x) (VId y) (KFNeg (Id x)) -> return $ CFNeg (VId x) (KFloatBin op (Id x) (Id y)) -> return $ CFloatBin op (VId x) (VId y) KIf cmp (Id x) (Id y) e1 e2 -> CIf cmp (VId x) (VId y) <$> transSub env known e1 <*> transSub env known e2 KLet (Id x) ty e1 e2 -> CLet (VId x) ty <$> transSub env known e1 <*> transSub (Map.insert (VId x) ty env) known e2 KVar (Id x) -> return $ CVar (VId x) KLetRec KFundef{ KNormal.name = (x@(Id n), ty), KNormal.args = yts, KNormal.body = e1 } e2 -> -- 関数定義の場合 {- 関数定義let rec x y1 ... yn = e1 in e2の場合は、 xに自由変数がない(closureを介さずdirectに呼び出せる) と仮定し、knownに追加してe1をクロージャ変換してみる -} do toplevel_backup <- get let env' = Map.insert (VId n) ty env let known' = Set.insert x known let newenv = Map.fromList (map (\(Id y, z) -> (VId y, z)) yts) `Map.union` env' e1' <- transSub newenv known' e1 {- 本当に自由変数がなかったか、変換結果e1'を確認する 注意: e1'にx自身が変数として出現する場合はclosureが必要! (thanks to nuevo-namasute and azounoman; test/cls-bug2.ml参照) -} let zs = freeVars e1' `difference` Set.fromList (map (idToVId . fst) yts) (known'2, e1'2) <- if Set.null zs then return (known', e1') else do {- 駄目だったら状態(toplevelの値)を戻して、クロージャ変換をやり直す -} trace ("free variable(s) " ++ show zs ++ " found in function " ++ show x ++ "@.") $! trace ("function " ++ show x ++ " cannot be directly applied in fact@.") $ return () put toplevel_backup e1'' <- transSub newenv known e1 return (known, e1'') let zs' = Set.toList (freeVars e1' `difference` Set.map idToVId (Set.insert x (Set.fromList (map fst yts)))) -- 自由変数のリスト let zts = map (\z -> (z, fromJust (Map.lookup z env'))) zs' -- ここで自由変数zの型を引くために引数envが必要 modify (CFundef{ name = (idToVId x, ty), args = map (\(Id y, z) -> (VId y, z)) yts, formalFV = zts, body = e1'2 } :) -- トップレベル関数を追加 e2'@(e2'cont :-: _) <- transSub env' known'2 e2 return $! if Set.member (idToVId x) (freeVars e2') then -- xが変数としてe2'に出現するか CMakeCls (idToVId x) ty Closure{ entry = idToLId x, actualFV = zs' } e2' -- 出現していたら削除しない else trace ("eliminating closure(s) " ++ show x ++ "@.") e2'cont -- 出現しなければMakeClsを削除 KApp (Id x) ys | Set.member (Id x) known -> -- 関数適用の場合 return $! trace ("directly applying " ++ x ++ "@.") (CAppDir (LId x) (map idToVId ys)) KApp (Id f) xs -> return $ CAppCls (VId f) (map idToVId xs) KTuple xs -> return $ CTuple (map idToVId xs) KLetTuple xts (Id y) e1 -> let transXts = map (\(Id x, t) -> (VId x, t)) xts in CLetTuple transXts (VId y) <$> transSub (Map.fromList transXts `Map.union` env) known e1 KGet (Id x) (Id y) -> return $ CGet (VId x) (VId y) KPut (Id x) (Id y) (Id z) -> return $ CPut (VId x) (VId y) (VId z) KExtArray (Id x) -> return $ CExtArray (LId x) KExtFunApp (Id x) ys -> return $ CAppDir (LId ("min_caml_" ++ x)) (map idToVId ys) -- add prefix "min_caml_" for external functions trans :: KNormal -> (ClosExp, [CFundef]) trans expr = runState (transSub Map.empty Set.empty expr) []
koba-e964/hayashii-mcc
Closure.hs
bsd-3-clause
6,145
2
23
1,333
2,582
1,318
1,264
209
21
{- | Use GHC to load a ModIface from a .hi file -} module HPack.Iface.LoadIface ( IfaceM , ModName(..) , ModIface , runIfaceM , compileAndLoadIface , showModIface ) where import GHC ( getSessionDynFlags, setSessionDynFlags, workingDirectoryChanged , runGhc, Ghc, GhcMonad , defaultErrorHandler, SuccessFlag(..) , ModIface, mkModuleName, findModule, getModuleInfo, modInfoIface , guessTarget, setTargets, LoadHowMuch(..), load ) import GHC.Paths (libdir) import LoadIface (pprModIface) import BinIface (readBinIface, CheckHiWay(..), TraceBinIFaceReading(..)) import TcRnMonad (initTcRnIf) import HscTypes (HscEnv) import HscMain (newHscEnv) import DynFlags (DynFlags, defaultFatalMessager, defaultFlushOut) import Outputable (Outputable(..), showSDoc, ppr) import System.Directory (setCurrentDirectory) import System.FilePath ((</>)) import Control.Monad (liftM, void) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE, catchE) import Control.Monad.Trans.Class (lift) import HPack.Ghc import HPack.Source (Pkg(..)) type ModName = String type IfaceM = Ghc -- | Run the IfaceM monad runIfaceM :: IfaceM a -> IO a runIfaceM = defaultErrorHandler defaultFatalMessager defaultFlushOut . runGhc (Just libdir) -- | First compile the package, then load the interface compileAndLoadIface :: FilePath -> ModName -> IfaceM ModIface compileAndLoadIface buildDir modName = do liftIO $ putStrLn $ "Loading module: " ++ show modName chdir buildDir initDynFlags loadIface modName -- | Change the working directory and inform GHC chdir :: FilePath -> IfaceM () chdir path = do liftIO (setCurrentDirectory path) workingDirectoryChanged -- | Load the interface information for the given module loadIface :: ModName -> IfaceM ModIface loadIface modName = do let filePath = haskellInterfacePath modName dynflags <- getSessionDynFlags liftIO $ readIface dynflags filePath where -- | Read binary interface (adapted from 'showIface' in GHC's -- iface/LoadIface.hs) readIface :: DynFlags -> FilePath -> IO ModIface readIface dynflags filename = do hscEnv <- newHscEnv dynflags initTcRnIf 's' hscEnv () () $ readBinIface IgnoreHiWay TraceBinIFaceReading filename -- | Determine the path to the .hi file for a given module name "Foo.Bar.Baz" haskellInterfacePath :: ModName -> FilePath haskellInterfacePath modName = [ if c == '.' then '/' else c | c <- modName ] ++ ".hi" --------------------------------------------------------- showModIface :: ModIface -> IfaceM String showModIface modIface = ghcShowSDoc $ pprModIface modIface
markflorisson/hpack
src/HPack/Iface/LoadIface.hs
bsd-3-clause
2,724
0
11
496
632
358
274
59
2
module Types where -- | data World = World { worldCells :: [Cell] -- ^ клетки , worldPlayer :: State -- ^ чей ход , worldTotals :: CountBlackWhite -- ^ кол-во черныз, белых , prevWorld :: Maybe World -- ^ храним предыдущий шаг , mouse :: Point -- ^ считывание позиции мыши , gamestate :: MenuorGame -- ^ меню или игра , savedGame :: (Maybe World, Int) -- ^ сохранённая игра, 0 или 1 , stepsList :: ([World], Int) -- ^ последовательность действий , viewed :: Int -- на каком шаге просмотра мы находимся? , botlevel :: Int --какой бот против нас (или игрок) } deriving Eq -- | собственно "клетка" data Cell = Cell { cellPos :: Pos -- ^ x y координата , cellState :: State -- ^ состояние (пустое, занято(белым\черным), помечено "крестиком") } deriving Eq -- | Состояние клетки игрового поля. data State = Empty -- ^ Пустая клетка. | Player WhichMove -- ^ Клетка игрока. | PossibleMove -- ^ Возможный ход. deriving Eq data MenuorGame = Menu | Game | MenuBot | View deriving Eq -- ^ меню/игра -- ширина и высота клеток cellWidth, cellHeight:: Float cellWidth = 35 -- | ширина cellHeight = 35 -- | высота -- смещение месторасположения initialLocation :: (Float, Float) initialLocation = (-100, -100) -- | ход черных \ белых data WhichMove = BlackMove | WhiteMove deriving Eq -- | кол-во черных \ белых type CountBlackWhite = (CntBlack, CntWhite) -- | x y координата type Pos = (Int, Int) -- | кол-во черных клеток type CntBlack = Int -- | кол-во белых клеток type CntWhite = Int -- | координата курсора мыши type Point = (Float, Float) -- | вещ х y координату -> целочисл x y pointToPos :: (Float, Float) -> (Int, Int) pointToPos (x, y) = (floor(x / cellWidth), floor(y / cellHeight)) -- | целочисл x y -> вещ х y координату posToPoint :: (Int, Int) -> (Float, Float) posToPoint (x, y) = ((a) * cellWidth, (b) * cellHeight) where a = fromIntegral (x) :: Float b = fromIntegral (y) :: Float -- сравнивает координаты areal :: Pos -> Pos -> Bool areal (x1, y1) (x, y) = x1 == x && y1 == y -- сравнивает состояния игроков isEqMove :: WhichMove -> WhichMove -> Bool isEqMove BlackMove BlackMove = True isEqMove WhiteMove WhiteMove = True isEqMove _ _ = False -- State is equal to PossibleMove ? isStatePossibleMove :: State -> Bool isStatePossibleMove PossibleMove = True isStatePossibleMove _ = False unJust :: Maybe a -> a unJust (Just a) = a unJust _ = undefined deleteTail :: [a] -> Int -> Int -> [a] deleteTail lst n k | n == k = [(lst !! n)] | otherwise = (lst !! k) : (deleteTail lst n (k + 1)) deleteHead :: [a] -> Int -> [a] deleteHead (x:xs) n |(length (x:xs)) == n = (x:xs) | otherwise = deleteHead xs n deleteHead [] n = []
cmc-haskell-2016/reversi
src/Types.hs
bsd-3-clause
3,406
0
12
704
780
462
318
59
1
{-# LANGUAGE RankNTypes, TypeOperators, DefaultSignatures #-} module MHask.Impl.Identity ( IdentityT , fmap , extract ) where import Prelude hiding (fmap, return) import MHask.Arrow import Control.Monad.Trans.Identity import Control.Monad.Trans.Class (lift) fmap :: (Monad m, Monad n) => (m ~> n) -> (IdentityT m ~> IdentityT n) fmap f m = IdentityT (f (runIdentityT m)) extract :: (Monad m) => m <~ IdentityT m extract = runIdentityT
DanBurton/MHask
MHask/Impl/Identity.hs
bsd-3-clause
453
0
9
82
150
86
64
15
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Test.Data.SymReg.AST( ) where import Data.SymReg.AST import Data.SymReg.Functions import Test.QuickCheck instance Arbitrary AST where arbitrary = frequency [ (2, literal) , (2, var) , (1, function) ] where literal = do v <- arbitrary return $ Const $ getNonNegative v var = do v <- arbitrary return $ Variable $ getNonNegative v function = do op <- elements operands args <- vectorOf (operandArity op) arbitrary return $ rightTreeToLeft $ Function op args -- | Performs transformation fo AST in such manner: -- Was: Function opa [a, Function opb [b, c]] -- Now: Function opa [Function opb [a, b], c] rightTreeToLeft :: AST -> AST rightTreeToLeft ast@(Const _) = ast rightTreeToLeft ast@(Variable _) = ast rightTreeToLeft ast@(Function opa args) | operandType opa /= InfixOperand = Function opa $ rightTreeToLeft <$> args | otherwise = case args of [a, Function opb [b, c]] | operandArity opa == operandArity opb -> rightTreeToLeft $ Function opa [Function opb [rightTreeToLeft a, rightTreeToLeft b], rightTreeToLeft c] _ -> Function opa $ rightTreeToLeft <$> args
Teaspot-Studio/genmus
test/Test/Data/SymReg/AST.hs
bsd-3-clause
1,225
0
15
288
368
189
179
29
2
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Main (main) where import Data.Text (Text) import qualified Data.Text.Normalize as T import Data.Text.Normalize (NormalizationMode) import Data.Unicode.Internal.Division (quotRem21, quotRem28) import QuickCheckUtils () import Test.Hspec.QuickCheck (modifyMaxSuccess, prop) import Test.Hspec as H import Test.QuickCheck (NonNegative(..)) #ifdef HAS_ICU import Data.Text (pack) import qualified Data.Text.ICU as ICU toICUMode :: NormalizationMode -> ICU.NormalizationMode toICUMode mode = case mode of T.NFD -> ICU.NFD T.NFKD -> ICU.NFKD T.NFC -> ICU.NFC T.NFKC -> ICU.NFKC t_normalizeCompareICU :: NormalizationMode -> Text -> Bool t_normalizeCompareICU mode t = T.normalize mode t == ICU.normalize (toICUMode mode) t #else import qualified Data.Text as T -- WARNING! These tests do not check the correctness of the output they -- only check whether a non empty output is produced. t_nonEmpty :: (Text -> Text) -> Text -> Bool t_nonEmpty f t | T.null t = T.null ft | otherwise = T.length ft > 0 where ft = f t -- Normalization t_normalize :: NormalizationMode -> Text -> Bool t_normalize mode = t_nonEmpty $ T.normalize mode #endif main :: IO () main = hspec $ H.parallel $ modifyMaxSuccess (const 10000) $ do prop "quotRem28" $ \(NonNegative n) -> n `quotRem` 28 == quotRem28 n prop "quotRem28 maxBound" $ \(NonNegative n) -> let n1 = maxBound - n in n1 `quotRem` 28 == quotRem28 n1 prop "quotRem21" $ \(NonNegative n) -> n `quotRem` 21 == quotRem21 n prop "quotRem21 maxBound" $ \(NonNegative n) -> let n1 = maxBound - n in n1 `quotRem` 21 == quotRem21 n1 #ifdef HAS_ICU it "Compare \127340 with ICU" $ t_normalizeCompareICU T.NFKD (pack "\127340") `H.shouldBe` True prop "Comparing random strings with ICU..." t_normalizeCompareICU #else prop "Checking non-empty results for random strings..." t_normalize #endif
harendra-kumar/unicode-transforms
test/Properties.hs
bsd-3-clause
2,110
0
14
479
476
259
217
35
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Control.Functor.Concurrent where import Control.Applicative import Control.Monad import Control.Monad.Base import Control.Monad.Trans.Control import Control.Monad.Trans.Identity import Control.Monad.Trans.Free import Data.Functor.Identity import Test.QuickCheck -- import Pipes -- import Pipes.Internal import Data.Void -- instance (MonadBase b m, Functor f) => MonadBase b (FreeT f m) where -- liftBase = liftBaseDefault -- instance (MonadBaseControl b m, Functor f) -- => MonadBaseControl b (FreeT f m) where -- type StM (FreeT f m) a = StM m (FreeF f a (FreeT f m a)) -- liftBaseWith f = -- FreeT $ liftM Pure $ liftBaseWith $ \runInBase -> -- f $ runInBase . runFreeT -- restoreM = FreeT . restoreM -- instance Arbitrary a => Arbitrary (Identity a) where -- arbitrary = fmap Identity arbitrary -- law1 :: Int -> Bool -- law1 x = (liftBaseWith . const . return) x == -- (return x :: FreeT Identity Identity Int) -- law2 :: Identity Int -> (Int -> Identity Int) -- -> Bool -- law2 m f = -- (liftBaseWith (const (m >>= f)) :: FreeT Identity Identity Int) == -- (liftBaseWith (const m) >>= liftBaseWith . const . f) -- law3 :: Identity Int -> Bool -- law3 m = (liftBaseWith (\runInBase -> runInBase m) >>= restoreM) == m data Command i o r = Send o r | Await (i -> r) deriving Functor newtype DSL i o m a = DSL { runDSL :: FreeT (Command i o) m a } deriving (Functor, Applicative, Monad, MonadFree (Command i o)) -- instance Monad m => MonadFree (Command i o) (DSL i o m) where -- wrap = _ send :: Monad m => o -> DSL i o m () send x = liftF (Send x ()) await :: Monad m => DSL i o m i await = liftF (Await id) -- aws :: Proxy Void () i o m r -- aws = do -- aws (Request x _) = absurd x -- aws (Respond i f) = do -- aws (M m) = m -- aws (Pure r) = return r
jwiegley/functors
Control/Functor/FreeControl.hs
bsd-3-clause
1,985
0
9
458
267
167
100
20
1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} module Control.Distributed.Process.ManagedProcess.Brisk ( handleCallSpec , replySpec , callSpec , defaultProcessSpec , serveSpec , module Control.Distributed.Process.ManagedProcess ) where import Brisk.Annotations as Annot import Control.Distributed.BriskStatic.Internal import Control.Distributed.Process hiding (call) import Control.Distributed.Process.Serializable import Control.Distributed.Process.SymmetricProcess import Control.Distributed.Process.ManagedProcess ( handleCall , serve , reply , defaultProcess , UnhandledMessagePolicy(..) , ProcessDefinition(..) , InitHandler(..) , InitResult(..) ) import Control.Distributed.Process.ManagedProcess.Server import Control.Distributed.Process.ManagedProcess.Client {-# ANN module SpecModule #-} -- 'Emebed' the ProcessReply and Dispatcher types -- as the following: data ProcessReply b s = ReplyMsg b s | NoReply s type Dispatcher s = s -> Process s {-# ANN handleCallSpec (Assume 'handleCall) #-} handleCallSpec :: forall a b s. (Serializable a, Serializable b) => (s -> a -> Process (ProcessReply b s)) -> Dispatcher s handleCallSpec f s0 = do (who,msg) <- expect :: Process (ProcessId, a) reply <- f s0 msg case reply of NoReply s' -> return s' ReplyMsg r s' -> do resp <- selfSign r send who resp return s' {-# ANN replySpec (Assume 'reply) #-} replySpec :: forall r s. Serializable r => r -> s -> Process (ProcessReply r s) replySpec msg st = return (ReplyMsg msg st) {-# ANN defaultProcessSpec (Assume 'defaultProcess) #-} defaultProcessSpec :: ProcessDefinition s defaultProcessSpec = ProcessDefinition { apiHandlers = [] , infoHandlers = [] , exitHandlers = [] , timeoutHandler = Annot.top , shutdownHandler = Annot.top , unhandledMessagePolicy = Terminate } {-# ANN serveSpec (Assume 'serve) #-} serveSpec :: forall goo st. goo -> InitHandler goo st -> ProcessDefinition st -> Process () serveSpec x ih (ProcessDefinition { apiHandlers = [h] }) = do InitOk s0 d0 <- ih x recvLoop s0 where recvLoop :: st -> Process () recvLoop st0 = do s' <- (top `castEffect` h :: st -> Process st) st0 recvLoop s' {-# ANN callSpec (Assume 'call) #-} callSpec :: forall s a b. (Serializable a, Serializable b) => ProcessId -> a -> Process b callSpec p m = do self <- getSelfPid send p (self, m) expectFrom p
abakst/brisk-prelude
src/Control/Distributed/Process/ManagedProcess/Brisk.hs
bsd-3-clause
2,852
0
13
836
676
378
298
72
2
module UnitTests.SimulationConstantsSpec( spec ) where import Test.Hspec import SimulationConstants spec :: Spec spec = parallel $ describe "SimulationConstants" $ do it "dimensionCount is at least 1" $ dimensionCount >= 1 `shouldBe` True it "zeroPhenotypeVec is the right dimension" $ length zeroPhenotypeVec `shouldBe` dimensionCount it "accidentDeathProbability is probability" $ isProbability accidentDeathProbability `shouldBe` True it "probabilityAlleleMutation is probability" $ isProbability probabilityAlleleMutation `shouldBe` True it "maxSteps is positive" $ maxSteps > 0 it "optimumSizeCoefficient is positive" $ optimumSizeCoefficient > 0 it "optimumChangeSizeCoefficient is positive" $ optimumChangeSizeCoefficient > 0 it "nan is NaN" $ nan `shouldSatisfy` isNaN isProbability :: Double -> Bool isProbability p = p >= 0.0 && p <= 1.0
satai/FrozenBeagle
Simulation/Lib/testsuite/UnitTests/SimulationConstantsSpec.hs
bsd-3-clause
1,063
0
11
323
204
101
103
24
1
module Alias where import Data.Word import qualified Data.IntMap as M type BitBoard = Word64 type ZobristKey = Word64 type From = BitBoard type To = BitBoard type PieceMap = BitBoard type EmptyMap = BitBoard type AttackMap = BitBoard type Occupancy = BitBoard type Magic = BitBoard type Depth = Int type Counter = Int type Timeout = Int type Square = Int type TableSize = Int type FromSquare = Square type ToSquare = Square type Evaluation = Int type PieceValue = Evaluation type Alpha = Evaluation type Beta = Evaluation type Lower = Evaluation type Upper = Evaluation type Move = Word16 type Variation = [Move] type Killers = [Move] type Sequence = [Move] type FEN = String
syanidar/Sophy
src/Alias.hs
bsd-3-clause
979
0
5
421
188
126
62
30
0
{-# LINE 1 "GHC.Float.RealFracMethods.hs" #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, MagicHash, UnboxedTuples, NoImplicitPrelude #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Float.RealFracMethods -- Copyright : (c) Daniel Fischer 2010 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- Methods for the RealFrac instances for 'Float' and 'Double', -- with specialised versions for 'Int'. -- -- Moved to their own module to not bloat GHC.Float further. -- ----------------------------------------------------------------------------- module GHC.Float.RealFracMethods ( -- * Double methods -- ** Integer results properFractionDoubleInteger , truncateDoubleInteger , floorDoubleInteger , ceilingDoubleInteger , roundDoubleInteger -- ** Int results , properFractionDoubleInt , floorDoubleInt , ceilingDoubleInt , roundDoubleInt -- * Double/Int conversions, wrapped primops , double2Int , int2Double -- * Float methods -- ** Integer results , properFractionFloatInteger , truncateFloatInteger , floorFloatInteger , ceilingFloatInteger , roundFloatInteger -- ** Int results , properFractionFloatInt , floorFloatInt , ceilingFloatInt , roundFloatInt -- * Float/Int conversions, wrapped primops , float2Int , int2Float ) where import GHC.Integer import GHC.Base import GHC.Num () uncheckedIShiftRA64# :: Int# -> Int# -> Int# uncheckedIShiftRA64# = uncheckedIShiftRA# uncheckedIShiftL64# :: Int# -> Int# -> Int# uncheckedIShiftL64# = uncheckedIShiftL# default () ------------------------------------------------------------------------------ -- Float Methods -- ------------------------------------------------------------------------------ -- Special Functions for Int, nice, easy and fast. -- They should be small enough to be inlined automatically. -- We have to test for ±0.0 to avoid returning -0.0 in the second -- component of the pair. Unfortunately the branching costs a lot -- of performance. properFractionFloatInt :: Float -> (Int, Float) properFractionFloatInt (F# x) = if isTrue# (x `eqFloat#` 0.0#) then (I# 0#, F# 0.0#) else case float2Int# x of n -> (I# n, F# (x `minusFloat#` int2Float# n)) -- truncateFloatInt = float2Int floorFloatInt :: Float -> Int floorFloatInt (F# x) = case float2Int# x of n | isTrue# (x `ltFloat#` int2Float# n) -> I# (n -# 1#) | otherwise -> I# n ceilingFloatInt :: Float -> Int ceilingFloatInt (F# x) = case float2Int# x of n | isTrue# (int2Float# n `ltFloat#` x) -> I# (n +# 1#) | otherwise -> I# n roundFloatInt :: Float -> Int roundFloatInt x = float2Int (c_rintFloat x) -- Functions with Integer results -- With the new code generator in GHC 7, the explicit bit-fiddling is -- slower than the old code for values of small modulus, but when the -- 'Int' range is left, the bit-fiddling quickly wins big, so we use that. -- If the methods are called on smallish values, hopefully people go -- through Int and not larger types. -- Note: For negative exponents, we must check the validity of the shift -- distance for the right shifts of the mantissa. {-# INLINE properFractionFloatInteger #-} properFractionFloatInteger :: Float -> (Integer, Float) properFractionFloatInteger v@(F# x) = case decodeFloat_Int# x of (# m, e #) | isTrue# (e <# 0#) -> case negateInt# e of s | isTrue# (s ># 23#) -> (0, v) | isTrue# (m <# 0#) -> case negateInt# (negateInt# m `uncheckedIShiftRA#` s) of k -> (smallInteger k, case m -# (k `uncheckedIShiftL#` s) of r -> F# (encodeFloatInteger (smallInteger r) e)) | otherwise -> case m `uncheckedIShiftRL#` s of k -> (smallInteger k, case m -# (k `uncheckedIShiftL#` s) of r -> F# (encodeFloatInteger (smallInteger r) e)) | otherwise -> (shiftLInteger (smallInteger m) e, F# 0.0#) {-# INLINE truncateFloatInteger #-} truncateFloatInteger :: Float -> Integer truncateFloatInteger x = case properFractionFloatInteger x of (n, _) -> n -- floor is easier for negative numbers than truncate, so this gets its -- own implementation, it's a little faster. {-# INLINE floorFloatInteger #-} floorFloatInteger :: Float -> Integer floorFloatInteger (F# x) = case decodeFloat_Int# x of (# m, e #) | isTrue# (e <# 0#) -> case negateInt# e of s | isTrue# (s ># 23#) -> if isTrue# (m <# 0#) then (-1) else 0 | otherwise -> smallInteger (m `uncheckedIShiftRA#` s) | otherwise -> shiftLInteger (smallInteger m) e -- ceiling x = -floor (-x) -- If giving this its own implementation is faster at all, -- it's only marginally so, hence we keep it short. {-# INLINE ceilingFloatInteger #-} ceilingFloatInteger :: Float -> Integer ceilingFloatInteger (F# x) = negateInteger (floorFloatInteger (F# (negateFloat# x))) {-# INLINE roundFloatInteger #-} roundFloatInteger :: Float -> Integer roundFloatInteger x = float2Integer (c_rintFloat x) ------------------------------------------------------------------------------ -- Double Methods -- ------------------------------------------------------------------------------ -- Special Functions for Int, nice, easy and fast. -- They should be small enough to be inlined automatically. -- We have to test for ±0.0 to avoid returning -0.0 in the second -- component of the pair. Unfortunately the branching costs a lot -- of performance. properFractionDoubleInt :: Double -> (Int, Double) properFractionDoubleInt (D# x) = if isTrue# (x ==## 0.0##) then (I# 0#, D# 0.0##) else case double2Int# x of n -> (I# n, D# (x -## int2Double# n)) -- truncateDoubleInt = double2Int floorDoubleInt :: Double -> Int floorDoubleInt (D# x) = case double2Int# x of n | isTrue# (x <## int2Double# n) -> I# (n -# 1#) | otherwise -> I# n ceilingDoubleInt :: Double -> Int ceilingDoubleInt (D# x) = case double2Int# x of n | isTrue# (int2Double# n <## x) -> I# (n +# 1#) | otherwise -> I# n roundDoubleInt :: Double -> Int roundDoubleInt x = double2Int (c_rintDouble x) -- Functions with Integer results -- The new Code generator isn't quite as good for the old 'Double' code -- as for the 'Float' code, so for 'Double' the bit-fiddling also wins -- when the values have small modulus. -- When the exponent is negative, all mantissae have less than 64 bits -- and the right shifting of sized types is much faster than that of -- 'Integer's, especially when we can -- Note: For negative exponents, we must check the validity of the shift -- distance for the right shifts of the mantissa. {-# INLINE properFractionDoubleInteger #-} properFractionDoubleInteger :: Double -> (Integer, Double) properFractionDoubleInteger v@(D# x) = case decodeDoubleInteger x of (# m, e #) | isTrue# (e <# 0#) -> case negateInt# e of s | isTrue# (s ># 52#) -> (0, v) | m < 0 -> case integerToInt (negateInteger m) of n -> case n `uncheckedIShiftRA64#` s of k -> (smallInteger (negateInt# k), case ( -# ) n (k `uncheckedIShiftL64#` s) of r -> D# (encodeDoubleInteger (smallInteger (negateInt# r)) e)) | otherwise -> case integerToInt m of n -> case n `uncheckedIShiftRA64#` s of k -> (smallInteger k, case ( -# ) n (k `uncheckedIShiftL64#` s) of r -> D# (encodeDoubleInteger (smallInteger r) e)) | otherwise -> (shiftLInteger m e, D# 0.0##) {-# INLINE truncateDoubleInteger #-} truncateDoubleInteger :: Double -> Integer truncateDoubleInteger x = case properFractionDoubleInteger x of (n, _) -> n -- floor is easier for negative numbers than truncate, so this gets its -- own implementation, it's a little faster. {-# INLINE floorDoubleInteger #-} floorDoubleInteger :: Double -> Integer floorDoubleInteger (D# x) = case decodeDoubleInteger x of (# m, e #) | isTrue# (e <# 0#) -> case negateInt# e of s | isTrue# (s ># 52#) -> if m < 0 then (-1) else 0 | otherwise -> case integerToInt m of n -> smallInteger (n `uncheckedIShiftRA64#` s) | otherwise -> shiftLInteger m e {-# INLINE ceilingDoubleInteger #-} ceilingDoubleInteger :: Double -> Integer ceilingDoubleInteger (D# x) = negateInteger (floorDoubleInteger (D# (negateDouble# x))) {-# INLINE roundDoubleInteger #-} roundDoubleInteger :: Double -> Integer roundDoubleInteger x = double2Integer (c_rintDouble x) -- Wrappers around double2Int#, int2Double#, float2Int# and int2Float#, -- we need them here, so we move them from GHC.Float and re-export them -- explicitly from there. double2Int :: Double -> Int double2Int (D# x) = I# (double2Int# x) int2Double :: Int -> Double int2Double (I# i) = D# (int2Double# i) float2Int :: Float -> Int float2Int (F# x) = I# (float2Int# x) int2Float :: Int -> Float int2Float (I# i) = F# (int2Float# i) -- Quicker conversions from 'Double' and 'Float' to 'Integer', -- assuming the floating point value is integral. -- -- Note: Since the value is integral, the exponent can't be less than -- (-TYP_MANT_DIG), so we need not check the validity of the shift -- distance for the right shfts here. {-# INLINE double2Integer #-} double2Integer :: Double -> Integer double2Integer (D# x) = case decodeDoubleInteger x of (# m, e #) | isTrue# (e <# 0#) -> case integerToInt m of n -> smallInteger (n `uncheckedIShiftRA64#` negateInt# e) | otherwise -> shiftLInteger m e {-# INLINE float2Integer #-} float2Integer :: Float -> Integer float2Integer (F# x) = case decodeFloat_Int# x of (# m, e #) | isTrue# (e <# 0#) -> smallInteger (m `uncheckedIShiftRA#` negateInt# e) | otherwise -> shiftLInteger (smallInteger m) e -- Foreign imports, the rounding is done faster in C when the value -- isn't integral, so we call out for rounding. For values of large -- modulus, calling out to C is slower than staying in Haskell, but -- presumably 'round' is mostly called for values with smaller modulus, -- when calling out to C is a major win. -- For all other functions, calling out to C gives at most a marginal -- speedup for values of small modulus and is much slower than staying -- in Haskell for values of large modulus, so those are done in Haskell. foreign import ccall unsafe "rintDouble" c_rintDouble :: Double -> Double foreign import ccall unsafe "rintFloat" c_rintFloat :: Float -> Float
phischu/fragnix
builtins/base/GHC.Float.RealFracMethods.hs
bsd-3-clause
11,966
0
29
3,506
2,279
1,211
1,068
189
2
{-# OPTIONS_GHC -fno-warn-type-defaults #-} module Math.NumberTheory.ZetaBench ( benchSuite ) where import Gauge.Main import Math.NumberTheory.Zeta benchSuite :: Benchmark benchSuite = bgroup "Zeta" [ bench "riemann zeta" $ nf (sum . take 20 . zetas) (1e-15 :: Double) , bench "dirichlet beta" $ nf (sum . take 20 . betas) (1e-15 :: Double) ]
Bodigrim/arithmoi
benchmark/Math/NumberTheory/ZetaBench.hs
mit
359
0
12
68
109
60
49
9
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module CO4.Unique ( MonadUnique(..), UniqueT, Unique, withUnique, withUniqueT , newName, newNamelike, originalName, liftListen, liftPass) where import Prelude hiding (fail) import Control.Monad.Identity (Identity,runIdentity) import Control.Monad.State.Strict (StateT,modify,get,evalStateT) import qualified Control.Monad.Trans.State.Strict as State import Control.Monad.Reader (ReaderT) import Control.Monad.Writer (WriterT) import Control.Monad.RWS (RWST) import Control.Monad.Signatures (Listen,Pass) import Control.Monad.Fail (MonadFail (fail)) import Control.Monad.IO.Class (MonadIO (liftIO)) import Control.Monad.Trans.Class (MonadTrans (lift)) import Language.Haskell.TH.Syntax (Quasi(..)) import CO4.Names (Namelike,mapName,fromName,readName) import CO4.Language (Name) class (Monad m) => MonadUnique m where newString :: String -> m String newInt :: m Int newtype UniqueT m a = UniqueT { runUniqueT :: StateT Int m a } deriving (Monad, Functor, Applicative, MonadTrans) newtype Unique a = Unique (UniqueT Identity a) deriving (Monad, Functor, Applicative, MonadUnique) instance (Monad m) => MonadUnique (UniqueT m) where newString prefix = UniqueT $ do i <- get modify (+1) return $ concat [prefix, separator:[], show i] newInt = UniqueT $ do i <- get modify (+1) return i separator = '_' withUniqueT :: Monad m => UniqueT m a -> m a withUniqueT (UniqueT u) = evalStateT u 0 withUnique :: Unique a -> a withUnique (Unique u) = runIdentity $ withUniqueT u -- |@newName n@ returns an unique name with prefix @n@ newName :: (MonadUnique m, Namelike n) => n -> m Name newName = newNamelike -- |@newNamelike n@ returns an unique namelike with prefix @n@ newNamelike :: (MonadUnique m, Namelike n, Namelike o) => n -> m o newNamelike prefix = newString (fromName $ originalName prefix) >>= return . readName -- |Gets the original name, i.e. the common prefix of an unique name -- TODO: what about variable names that contain separator originalName :: Namelike n => n -> n originalName = mapName $ takeWhile (/= separator) instance (MonadUnique m) => MonadUnique (ReaderT r m) where newString = lift . newString newInt = lift newInt instance (MonadUnique m, Monoid w) => MonadUnique (WriterT w m) where newString = lift . newString newInt = lift newInt instance (MonadUnique m) => MonadUnique (StateT s m) where newString = lift . newString newInt = lift newInt instance (MonadUnique m, Monoid w) => MonadUnique (RWST r w s m) where newString = lift . newString newInt = lift newInt instance (MonadIO m) => MonadIO (UniqueT m) where liftIO = lift . liftIO instance (MonadFail m) => MonadFail (UniqueT m) where fail = lift . fail instance (Quasi m, Applicative m) => Quasi (UniqueT m) where qNewName = lift . qNewName qReport a b = lift $ qReport a b qRecover a b = qRecover a b qLookupName a b = lift $ qLookupName a b qReify = lift . qReify qReifyInstances a b = lift $ qReifyInstances a b qReifyRoles = lift . qReifyRoles qReifyAnnotations = lift . qReifyAnnotations qReifyModule = lift . qReifyModule qLocation = lift qLocation qRunIO = lift . qRunIO qAddDependentFile = lift . qAddDependentFile qAddTopDecls = lift . qAddTopDecls qAddModFinalizer = lift . qAddModFinalizer qGetQ = lift qGetQ qPutQ = lift . qPutQ qReifyFixity = lift . qReifyFixity qReifyConStrictness = lift . qReifyConStrictness qIsExtEnabled = lift . qIsExtEnabled qExtsEnabled = lift qExtsEnabled qAddForeignFile a b = lift $ qAddForeignFile a b liftListen :: Monad m => Listen w m (a,Int) -> Listen w (UniqueT m) a liftListen listen = UniqueT . State.liftListen listen . runUniqueT liftPass :: Monad m => Pass w m (a,Int) -> Pass w (UniqueT m) a liftPass pass = UniqueT . State.liftPass pass . runUniqueT
apunktbau/co4
src/CO4/Unique.hs
gpl-3.0
4,176
0
13
1,017
1,310
711
599
87
1
{-#LANGUAGE DeriveDataTypeable#-} module Data.P440.Domain.FilenameAst where import Data.Typeable (Typeable) import Data.Text data Message = Message {messagePrefix :: Text ,messageResend :: Text ,messageBIC :: Text ,messageTaxcode :: Text ,messageFiledate :: (Text, Text, Text) ,messageNumber :: Text } deriving (Eq, Show, Typeable) data Reply = Reply {replyPrefix :: Text ,replyResend :: Text ,replyMessage :: Message ,replyDivision :: Text } deriving (Eq, Show, Typeable) data AuxReply = AuxReply {areplyReply :: Reply ,areplyAccountNum :: Text ,areplyFilenum :: Text } deriving (Eq, Show, Typeable) data Transport = Transport {transportPrefix :: Text ,transportSender :: Text ,transportReceiver :: Text ,transportFiledate :: (Text, Text, Text) ,transportFilenum :: Text } deriving (Eq, Show, Typeable) data TransportAck = TransportAck {tackPrefix :: Text ,tackReceiver :: Text ,tackAckTransport :: Transport } deriving (Eq, Show, Typeable) data FNSAck = FNSAck {fackPrefix :: Text ,fackReceiver :: Text ,fackReply :: FNSAckName } deriving (Eq, Show, Typeable) data FNSAckName = Reply' Reply | AuxReply' AuxReply | KOAck1' KOAck1 | KOAck2' KOAck2 deriving (Eq, Show, Typeable) data KOAck1 = KOAck1 {kack1Prefix :: Text ,kack1Message :: Message } deriving (Eq, Show, Typeable) data KOAck2 = KOAck2 {kack2Prefix :: Text ,kack2Message :: Message ,kack2Division :: Text } deriving (Eq, Show, Typeable)
Macil-dev/440P-old
src/Data/P440/Domain/FilenameAst.hs
unlicense
1,911
0
9
703
447
270
177
54
0
{-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RecordWildCards #-} -- | The Config type. module Stack.Types.Config where import Control.Applicative import Control.Exception import Control.Monad (liftM, mzero, forM) import Control.Monad.Catch (MonadThrow, throwM) import Control.Monad.Logger (LogLevel(..)) import Control.Monad.Reader (MonadReader, ask, asks, MonadIO, liftIO) import Data.Aeson.Extended (ToJSON, toJSON, FromJSON, parseJSON, withText, withObject, object, (.=), (.:), (..:), (..:?), (..!=), Value(String, Object), withObjectWarnings, WarningParser, Object, jsonSubWarnings, JSONWarning, jsonSubWarningsMT) import Data.Attoparsec.Args import Data.Binary (Binary) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.Either (partitionEithers) import Data.Hashable (Hashable) import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Map.Strict as M import Data.Maybe import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8, decodeUtf8) import Data.Typeable import Data.Yaml (ParseException) import Distribution.System (Platform) import qualified Distribution.Text import Distribution.Version (anyVersion) import Network.HTTP.Client (parseUrl) import Path import qualified Paths_stack as Meta import Stack.Types.BuildPlan (SnapName, renderSnapName, parseSnapName) import Stack.Types.Compiler import Stack.Types.Docker import Stack.Types.FlagName import Stack.Types.Image import Stack.Types.PackageIdentifier import Stack.Types.PackageName import Stack.Types.Version import System.Process.Read (EnvOverride) -- | The top-level Stackage configuration. data Config = Config {configStackRoot :: !(Path Abs Dir) -- ^ ~/.stack more often than not ,configDocker :: !DockerOpts ,configEnvOverride :: !(EnvSettings -> IO EnvOverride) -- ^ Environment variables to be passed to external tools ,configLocalPrograms :: !(Path Abs Dir) -- ^ Path containing local installations (mainly GHC) ,configConnectionCount :: !Int -- ^ How many concurrent connections are allowed when downloading ,configHideTHLoading :: !Bool -- ^ Hide the Template Haskell "Loading package ..." messages from the -- console ,configPlatform :: !Platform -- ^ The platform we're building for, used in many directory names ,configLatestSnapshotUrl :: !Text -- ^ URL for a JSON file containing information on the latest -- snapshots available. ,configPackageIndices :: ![PackageIndex] -- ^ Information on package indices. This is left biased, meaning that -- packages in an earlier index will shadow those in a later index. -- -- Warning: if you override packages in an index vs what's available -- upstream, you may correct your compiled snapshots, as different -- projects may have different definitions of what pkg-ver means! This -- feature is primarily intended for adding local packages, not -- overriding. Overriding is better accomplished by adding to your -- list of packages. -- -- Note that indices specified in a later config file will override -- previous indices, /not/ extend them. -- -- Using an assoc list instead of a Map to keep track of priority ,configSystemGHC :: !Bool -- ^ Should we use the system-installed GHC (on the PATH) if -- available? Can be overridden by command line options. ,configInstallGHC :: !Bool -- ^ Should we automatically install GHC if missing or the wrong -- version is available? Can be overridden by command line options. ,configSkipGHCCheck :: !Bool -- ^ Don't bother checking the GHC version or architecture. ,configSkipMsys :: !Bool -- ^ On Windows: don't use a locally installed MSYS ,configCompilerCheck :: !VersionCheck -- ^ Specifies which versions of the compiler are acceptable. ,configLocalBin :: !(Path Abs Dir) -- ^ Directory we should install executables into ,configRequireStackVersion :: !VersionRange -- ^ Require a version of stack within this range. ,configJobs :: !Int -- ^ How many concurrent jobs to run, defaults to number of capabilities ,configExtraIncludeDirs :: !(Set Text) -- ^ --extra-include-dirs arguments ,configExtraLibDirs :: !(Set Text) -- ^ --extra-lib-dirs arguments ,configConfigMonoid :: !ConfigMonoid -- ^ @ConfigMonoid@ used to generate this ,configConcurrentTests :: !Bool -- ^ Run test suites concurrently ,configImage :: !ImageOpts ,configTemplateParams :: !(Map Text Text) -- ^ Parameters for templates. ,configScmInit :: !(Maybe SCM) -- ^ Initialize SCM (e.g. git) when creating new projects. ,configGhcOptions :: !(Map (Maybe PackageName) [Text]) -- ^ Additional GHC options to apply to either all packages (Nothing) -- or a specific package (Just). } -- | Information on a single package index data PackageIndex = PackageIndex { indexName :: !IndexName , indexLocation :: !IndexLocation , indexDownloadPrefix :: !Text -- ^ URL prefix for downloading packages , indexGpgVerify :: !Bool -- ^ GPG-verify the package index during download. Only applies to Git -- repositories for now. , indexRequireHashes :: !Bool -- ^ Require that hashes and package size information be available for packages in this index } deriving Show instance FromJSON (PackageIndex, [JSONWarning]) where parseJSON = withObjectWarnings "PackageIndex" $ \o -> do name <- o ..: "name" prefix <- o ..: "download-prefix" mgit <- o ..:? "git" mhttp <- o ..:? "http" loc <- case (mgit, mhttp) of (Nothing, Nothing) -> fail $ "Must provide either Git or HTTP URL for " ++ T.unpack (indexNameText name) (Just git, Nothing) -> return $ ILGit git (Nothing, Just http) -> return $ ILHttp http (Just git, Just http) -> return $ ILGitHttp git http gpgVerify <- o ..:? "gpg-verify" ..!= False reqHashes <- o ..:? "require-hashes" ..!= False return PackageIndex { indexName = name , indexLocation = loc , indexDownloadPrefix = prefix , indexGpgVerify = gpgVerify , indexRequireHashes = reqHashes } -- | Unique name for a package index newtype IndexName = IndexName { unIndexName :: ByteString } deriving (Show, Eq, Ord, Hashable, Binary) indexNameText :: IndexName -> Text indexNameText = decodeUtf8 . unIndexName instance ToJSON IndexName where toJSON = toJSON . indexNameText instance FromJSON IndexName where parseJSON = withText "IndexName" $ \t -> case parseRelDir (T.unpack t) of Left e -> fail $ "Invalid index name: " ++ show e Right _ -> return $ IndexName $ encodeUtf8 t -- | Location of the package index. This ensures that at least one of Git or -- HTTP is available. data IndexLocation = ILGit !Text | ILHttp !Text | ILGitHttp !Text !Text deriving (Show, Eq, Ord) -- | Controls which version of the environment is used data EnvSettings = EnvSettings { esIncludeLocals :: !Bool -- ^ include local project bin directory, GHC_PACKAGE_PATH, etc , esIncludeGhcPackagePath :: !Bool -- ^ include the GHC_PACKAGE_PATH variable , esStackExe :: !Bool -- ^ set the STACK_EXE variable to the current executable name , esLocaleUtf8 :: !Bool -- ^ set the locale to C.UTF-8 } deriving (Show, Eq, Ord) data ExecOpts = ExecOpts { eoCmd :: !(Maybe String) -- ^ Usage of @Maybe@ here is nothing more than a hack, to avoid some weird -- bug in optparse-applicative. See: -- https://github.com/commercialhaskell/stack/issues/806 , eoArgs :: ![String] , eoExtra :: !ExecOptsExtra } data ExecOptsExtra = ExecOptsPlain | ExecOptsEmbellished { eoEnvSettings :: !EnvSettings , eoPackages :: ![String] } -- | Parsed global command-line options. data GlobalOpts = GlobalOpts { globalReExec :: !Bool , globalLogLevel :: !LogLevel -- ^ Log level , globalConfigMonoid :: !ConfigMonoid -- ^ Config monoid, for passing into 'loadConfig' , globalResolver :: !(Maybe AbstractResolver) -- ^ Resolver override , globalTerminal :: !Bool -- ^ We're in a terminal? , globalStackYaml :: !(Maybe FilePath) -- ^ Override project stack.yaml , globalModifyCodePage :: !Bool -- ^ Force the code page to UTF-8 on Windows } deriving (Show) -- | Either an actual resolver value, or an abstract description of one (e.g., -- latest nightly). data AbstractResolver = ARLatestNightly | ARLatestLTS | ARLatestLTSMajor !Int | ARResolver !Resolver | ARGlobal deriving Show -- | Default logging level should be something useful but not crazy. defaultLogLevel :: LogLevel defaultLogLevel = LevelInfo -- | A superset of 'Config' adding information on how to build code. The reason -- for this breakdown is because we will need some of the information from -- 'Config' in order to determine the values here. data BuildConfig = BuildConfig { bcConfig :: !Config , bcResolver :: !Resolver -- ^ How we resolve which dependencies to install given a set of -- packages. , bcWantedCompiler :: !CompilerVersion -- ^ Compiler version wanted for this build , bcPackageEntries :: ![PackageEntry] -- ^ Local packages identified by a path, Bool indicates whether it is -- a non-dependency (the opposite of 'peExtraDep') , bcExtraDeps :: !(Map PackageName Version) -- ^ Extra dependencies specified in configuration. -- -- These dependencies will not be installed to a shared location, and -- will override packages provided by the resolver. , bcStackYaml :: !(Path Abs File) -- ^ Location of the stack.yaml file. -- -- Note: if the STACK_YAML environment variable is used, this may be -- different from bcRoot </> "stack.yaml" , bcFlags :: !(Map PackageName (Map FlagName Bool)) -- ^ Per-package flag overrides , bcImplicitGlobal :: !Bool -- ^ Are we loading from the implicit global stack.yaml? This is useful -- for providing better error messages. } -- | Directory containing the project's stack.yaml file bcRoot :: BuildConfig -> Path Abs Dir bcRoot = parent . bcStackYaml -- | Directory containing the project's stack.yaml file bcWorkDir :: BuildConfig -> Path Abs Dir bcWorkDir = (</> workDirRel) . parent . bcStackYaml -- | Configuration after the environment has been setup. data EnvConfig = EnvConfig {envConfigBuildConfig :: !BuildConfig ,envConfigCabalVersion :: !Version ,envConfigCompilerVersion :: !CompilerVersion ,envConfigPackages :: !(Map (Path Abs Dir) Bool)} instance HasBuildConfig EnvConfig where getBuildConfig = envConfigBuildConfig instance HasConfig EnvConfig instance HasPlatform EnvConfig instance HasStackRoot EnvConfig class HasBuildConfig r => HasEnvConfig r where getEnvConfig :: r -> EnvConfig instance HasEnvConfig EnvConfig where getEnvConfig = id -- | Value returned by 'Stack.Config.loadConfig'. data LoadConfig m = LoadConfig { lcConfig :: !Config -- ^ Top-level Stack configuration. , lcLoadBuildConfig :: !(Maybe AbstractResolver -> m BuildConfig) -- ^ Action to load the remaining 'BuildConfig'. , lcProjectRoot :: !(Maybe (Path Abs Dir)) -- ^ The project root directory, if in a project. } data PackageEntry = PackageEntry { peExtraDepMaybe :: !(Maybe Bool) -- ^ Is this package a dependency? This means the local package will be -- treated just like an extra-deps: it will only be built as a dependency -- for others, and its test suite/benchmarks will not be run. -- -- Useful modifying an upstream package, see: -- https://github.com/commercialhaskell/stack/issues/219 -- https://github.com/commercialhaskell/stack/issues/386 , peValidWanted :: !(Maybe Bool) -- ^ Deprecated name meaning the opposite of peExtraDep. Only present to -- provide deprecation warnings to users. , peLocation :: !PackageLocation , peSubdirs :: ![FilePath] } deriving Show -- | Once peValidWanted is removed, this should just become the field name in PackageEntry. peExtraDep :: PackageEntry -> Bool peExtraDep pe = case peExtraDepMaybe pe of Just x -> x Nothing -> case peValidWanted pe of Just x -> not x Nothing -> False instance ToJSON PackageEntry where toJSON pe | not (peExtraDep pe) && null (peSubdirs pe) = toJSON $ peLocation pe toJSON pe = object [ "extra-dep" .= peExtraDep pe , "location" .= peLocation pe , "subdirs" .= peSubdirs pe ] instance FromJSON (PackageEntry, [JSONWarning]) where parseJSON (String t) = do loc <- parseJSON $ String t return (PackageEntry { peExtraDepMaybe = Nothing , peValidWanted = Nothing , peLocation = loc , peSubdirs = [] }, []) parseJSON v = withObjectWarnings "PackageEntry" (\o -> PackageEntry <$> o ..:? "extra-dep" <*> o ..:? "valid-wanted" <*> o ..: "location" <*> o ..:? "subdirs" ..!= []) v data PackageLocation = PLFilePath FilePath -- ^ Note that we use @FilePath@ and not @Path@s. The goal is: first parse -- the value raw, and then use @canonicalizePath@ and @parseAbsDir@. | PLHttpTarball Text | PLGit Text Text -- ^ URL and commit deriving Show instance ToJSON PackageLocation where toJSON (PLFilePath fp) = toJSON fp toJSON (PLHttpTarball t) = toJSON t toJSON (PLGit x y) = toJSON $ T.unwords ["git", x, y] instance FromJSON PackageLocation where parseJSON v = git v <|> withText "PackageLocation" (\t -> http t <|> file t) v where file t = pure $ PLFilePath $ T.unpack t http t = case parseUrl $ T.unpack t of Left _ -> mzero Right _ -> return $ PLHttpTarball t git = withObject "PackageGitLocation" $ \o -> PLGit <$> o .: "git" <*> o .: "commit" -- | A project is a collection of packages. We can have multiple stack.yaml -- files, but only one of them may contain project information. data Project = Project { projectPackages :: ![PackageEntry] -- ^ Components of the package list , projectExtraDeps :: !(Map PackageName Version) -- ^ Components of the package list referring to package/version combos, -- see: https://github.com/fpco/stack/issues/41 , projectFlags :: !(Map PackageName (Map FlagName Bool)) -- ^ Per-package flag overrides , projectResolver :: !Resolver -- ^ How we resolve which dependencies to use } deriving Show instance ToJSON Project where toJSON p = object [ "packages" .= projectPackages p , "extra-deps" .= map fromTuple (Map.toList $ projectExtraDeps p) , "flags" .= projectFlags p , "resolver" .= projectResolver p ] -- | How we resolve which dependencies to install given a set of packages. data Resolver = ResolverSnapshot SnapName -- ^ Use an official snapshot from the Stackage project, either an LTS -- Haskell or Stackage Nightly | ResolverCompiler !CompilerVersion -- ^ Require a specific compiler version, but otherwise provide no build plan. -- Intended for use cases where end user wishes to specify all upstream -- dependencies manually, such as using a dependency solver. | ResolverCustom !Text !Text -- ^ A custom resolver based on the given name and URL. This file is assumed -- to be completely immutable. deriving (Show) instance ToJSON Resolver where toJSON (ResolverCustom name location) = object [ "name" .= name , "location" .= location ] toJSON x = toJSON $ resolverName x instance FromJSON Resolver where -- Strange structuring is to give consistent error messages parseJSON v@(Object _) = withObject "Resolver" (\o -> ResolverCustom <$> o .: "name" <*> o .: "location") v parseJSON (String t) = either (fail . show) return (parseResolverText t) parseJSON _ = fail $ "Invalid Resolver, must be Object or String" -- | Convert a Resolver into its @Text@ representation, as will be used by -- directory names resolverName :: Resolver -> Text resolverName (ResolverSnapshot name) = renderSnapName name resolverName (ResolverCompiler v) = compilerVersionName v resolverName (ResolverCustom name _) = "custom-" <> name -- | Try to parse a @Resolver@ from a @Text@. Won't work for complex resolvers (like custom). parseResolverText :: MonadThrow m => Text -> m Resolver parseResolverText t | Right x <- parseSnapName t = return $ ResolverSnapshot x | Just v <- parseCompilerVersion t = return $ ResolverCompiler v | otherwise = throwM $ ParseResolverException t -- | Class for environment values which have access to the stack root class HasStackRoot env where getStackRoot :: env -> Path Abs Dir default getStackRoot :: HasConfig env => env -> Path Abs Dir getStackRoot = configStackRoot . getConfig {-# INLINE getStackRoot #-} -- | Class for environment values which have a Platform class HasPlatform env where getPlatform :: env -> Platform default getPlatform :: HasConfig env => env -> Platform getPlatform = configPlatform . getConfig {-# INLINE getPlatform #-} instance HasPlatform Platform where getPlatform = id -- | Class for environment values that can provide a 'Config'. class (HasStackRoot env, HasPlatform env) => HasConfig env where getConfig :: env -> Config default getConfig :: HasBuildConfig env => env -> Config getConfig = bcConfig . getBuildConfig {-# INLINE getConfig #-} instance HasStackRoot Config instance HasPlatform Config instance HasConfig Config where getConfig = id {-# INLINE getConfig #-} -- | Class for environment values that can provide a 'BuildConfig'. class HasConfig env => HasBuildConfig env where getBuildConfig :: env -> BuildConfig instance HasStackRoot BuildConfig instance HasPlatform BuildConfig instance HasConfig BuildConfig instance HasBuildConfig BuildConfig where getBuildConfig = id {-# INLINE getBuildConfig #-} -- An uninterpreted representation of configuration options. -- Configurations may be "cascaded" using mappend (left-biased). data ConfigMonoid = ConfigMonoid { configMonoidDockerOpts :: !DockerOptsMonoid -- ^ Docker options. , configMonoidConnectionCount :: !(Maybe Int) -- ^ See: 'configConnectionCount' , configMonoidHideTHLoading :: !(Maybe Bool) -- ^ See: 'configHideTHLoading' , configMonoidLatestSnapshotUrl :: !(Maybe Text) -- ^ See: 'configLatestSnapshotUrl' , configMonoidPackageIndices :: !(Maybe [PackageIndex]) -- ^ See: 'configPackageIndices' , configMonoidSystemGHC :: !(Maybe Bool) -- ^ See: 'configSystemGHC' ,configMonoidInstallGHC :: !(Maybe Bool) -- ^ See: 'configInstallGHC' ,configMonoidSkipGHCCheck :: !(Maybe Bool) -- ^ See: 'configSkipGHCCheck' ,configMonoidSkipMsys :: !(Maybe Bool) -- ^ See: 'configSkipMsys' ,configMonoidCompilerCheck :: !(Maybe VersionCheck) -- ^ See: 'configCompilerCheck' ,configMonoidRequireStackVersion :: !VersionRange -- ^ See: 'configRequireStackVersion' ,configMonoidOS :: !(Maybe String) -- ^ Used for overriding the platform ,configMonoidArch :: !(Maybe String) -- ^ Used for overriding the platform ,configMonoidJobs :: !(Maybe Int) -- ^ See: 'configJobs' ,configMonoidExtraIncludeDirs :: !(Set Text) -- ^ See: 'configExtraIncludeDirs' ,configMonoidExtraLibDirs :: !(Set Text) -- ^ See: 'configExtraLibDirs' ,configMonoidConcurrentTests :: !(Maybe Bool) -- ^ See: 'configConcurrentTests' ,configMonoidLocalBinPath :: !(Maybe FilePath) -- ^ Used to override the binary installation dir ,configMonoidImageOpts :: !ImageOptsMonoid -- ^ Image creation options. ,configMonoidTemplateParameters :: !(Map Text Text) -- ^ Template parameters. ,configMonoidScmInit :: !(Maybe SCM) -- ^ Initialize SCM (e.g. git init) when making new projects? ,configMonoidGhcOptions :: !(Map (Maybe PackageName) [Text]) -- ^ See 'configGhcOptions' ,configMonoidExtraPath :: ![Path Abs Dir] -- ^ Additional paths to search for executables in } deriving Show instance Monoid ConfigMonoid where mempty = ConfigMonoid { configMonoidDockerOpts = mempty , configMonoidConnectionCount = Nothing , configMonoidHideTHLoading = Nothing , configMonoidLatestSnapshotUrl = Nothing , configMonoidPackageIndices = Nothing , configMonoidSystemGHC = Nothing , configMonoidInstallGHC = Nothing , configMonoidSkipGHCCheck = Nothing , configMonoidSkipMsys = Nothing , configMonoidRequireStackVersion = anyVersion , configMonoidOS = Nothing , configMonoidArch = Nothing , configMonoidJobs = Nothing , configMonoidExtraIncludeDirs = Set.empty , configMonoidExtraLibDirs = Set.empty , configMonoidConcurrentTests = Nothing , configMonoidLocalBinPath = Nothing , configMonoidImageOpts = mempty , configMonoidTemplateParameters = mempty , configMonoidScmInit = Nothing , configMonoidCompilerCheck = Nothing , configMonoidGhcOptions = mempty , configMonoidExtraPath = [] } mappend l r = ConfigMonoid { configMonoidDockerOpts = configMonoidDockerOpts l <> configMonoidDockerOpts r , configMonoidConnectionCount = configMonoidConnectionCount l <|> configMonoidConnectionCount r , configMonoidHideTHLoading = configMonoidHideTHLoading l <|> configMonoidHideTHLoading r , configMonoidLatestSnapshotUrl = configMonoidLatestSnapshotUrl l <|> configMonoidLatestSnapshotUrl r , configMonoidPackageIndices = configMonoidPackageIndices l <|> configMonoidPackageIndices r , configMonoidSystemGHC = configMonoidSystemGHC l <|> configMonoidSystemGHC r , configMonoidInstallGHC = configMonoidInstallGHC l <|> configMonoidInstallGHC r , configMonoidSkipGHCCheck = configMonoidSkipGHCCheck l <|> configMonoidSkipGHCCheck r , configMonoidSkipMsys = configMonoidSkipMsys l <|> configMonoidSkipMsys r , configMonoidRequireStackVersion = intersectVersionRanges (configMonoidRequireStackVersion l) (configMonoidRequireStackVersion r) , configMonoidOS = configMonoidOS l <|> configMonoidOS r , configMonoidArch = configMonoidArch l <|> configMonoidArch r , configMonoidJobs = configMonoidJobs l <|> configMonoidJobs r , configMonoidExtraIncludeDirs = Set.union (configMonoidExtraIncludeDirs l) (configMonoidExtraIncludeDirs r) , configMonoidExtraLibDirs = Set.union (configMonoidExtraLibDirs l) (configMonoidExtraLibDirs r) , configMonoidConcurrentTests = configMonoidConcurrentTests l <|> configMonoidConcurrentTests r , configMonoidLocalBinPath = configMonoidLocalBinPath l <|> configMonoidLocalBinPath r , configMonoidImageOpts = configMonoidImageOpts l <> configMonoidImageOpts r , configMonoidTemplateParameters = configMonoidTemplateParameters l <> configMonoidTemplateParameters r , configMonoidScmInit = configMonoidScmInit l <|> configMonoidScmInit r , configMonoidCompilerCheck = configMonoidCompilerCheck l <|> configMonoidCompilerCheck r , configMonoidGhcOptions = Map.unionWith (++) (configMonoidGhcOptions l) (configMonoidGhcOptions r) , configMonoidExtraPath = configMonoidExtraPath l ++ configMonoidExtraPath r } instance FromJSON (ConfigMonoid, [JSONWarning]) where parseJSON = withObjectWarnings "ConfigMonoid" parseConfigMonoidJSON -- | Parse a partial configuration. Used both to parse both a standalone config -- file and a project file, so that a sub-parser is not required, which would interfere with -- warnings for missing fields. parseConfigMonoidJSON :: Object -> WarningParser ConfigMonoid parseConfigMonoidJSON obj = do configMonoidDockerOpts <- jsonSubWarnings (obj ..:? "docker" ..!= mempty) configMonoidConnectionCount <- obj ..:? "connection-count" configMonoidHideTHLoading <- obj ..:? "hide-th-loading" configMonoidLatestSnapshotUrl <- obj ..:? "latest-snapshot-url" configMonoidPackageIndices <- jsonSubWarningsMT (obj ..:? "package-indices") configMonoidSystemGHC <- obj ..:? "system-ghc" configMonoidInstallGHC <- obj ..:? "install-ghc" configMonoidSkipGHCCheck <- obj ..:? "skip-ghc-check" configMonoidSkipMsys <- obj ..:? "skip-msys" configMonoidRequireStackVersion <- unVersionRangeJSON <$> obj ..:? "require-stack-version" ..!= VersionRangeJSON anyVersion configMonoidOS <- obj ..:? "os" configMonoidArch <- obj ..:? "arch" configMonoidJobs <- obj ..:? "jobs" configMonoidExtraIncludeDirs <- obj ..:? "extra-include-dirs" ..!= Set.empty configMonoidExtraLibDirs <- obj ..:? "extra-lib-dirs" ..!= Set.empty configMonoidConcurrentTests <- obj ..:? "concurrent-tests" configMonoidLocalBinPath <- obj ..:? "local-bin-path" configMonoidImageOpts <- jsonSubWarnings (obj ..:? "image" ..!= mempty) templates <- obj ..:? "templates" (configMonoidScmInit,configMonoidTemplateParameters) <- case templates of Nothing -> return (Nothing,M.empty) Just tobj -> do scmInit <- tobj ..:? "scm-init" params <- tobj ..:? "params" return (scmInit,fromMaybe M.empty params) configMonoidCompilerCheck <- obj ..:? "compiler-check" mghcoptions <- obj ..:? "ghc-options" configMonoidGhcOptions <- case mghcoptions of Nothing -> return mempty Just m -> fmap Map.fromList $ mapM handleGhcOptions $ Map.toList m extraPath <- obj ..:? "extra-path" ..!= [] configMonoidExtraPath <- forM extraPath $ either (fail . show) return . parseAbsDir . T.unpack return ConfigMonoid {..} where handleGhcOptions :: Monad m => (Text, Text) -> m (Maybe PackageName, [Text]) handleGhcOptions (name', vals') = do name <- if name' == "*" then return Nothing else case parsePackageNameFromString $ T.unpack name' of Left e -> fail $ show e Right x -> return $ Just x case parseArgs Escaping vals' of Left e -> fail e Right vals -> return (name, map T.pack vals) -- | Newtype for non-orphan FromJSON instance. newtype VersionRangeJSON = VersionRangeJSON { unVersionRangeJSON :: VersionRange } -- | Parse VersionRange. instance FromJSON VersionRangeJSON where parseJSON = withText "VersionRange" (\s -> maybe (fail ("Invalid cabal-style VersionRange: " ++ T.unpack s)) (return . VersionRangeJSON) (Distribution.Text.simpleParse (T.unpack s))) data ConfigException = ParseConfigFileException (Path Abs File) ParseException | ParseResolverException Text | NoProjectConfigFound (Path Abs Dir) (Maybe Text) | UnexpectedTarballContents [Path Abs Dir] [Path Abs File] | BadStackVersionException VersionRange | NoMatchingSnapshot [SnapName] | NoSuchDirectory FilePath deriving Typeable instance Show ConfigException where show (ParseConfigFileException configFile exception) = concat [ "Could not parse '" , toFilePath configFile , "':\n" , show exception , "\nSee https://github.com/commercialhaskell/stack/wiki/stack.yaml." ] show (ParseResolverException t) = concat [ "Invalid resolver value: " , T.unpack t , ". Possible valid values include lts-2.12, nightly-YYYY-MM-DD, ghc-7.10.2, and ghcjs-0.1.0_ghc-7.10.2. " , "See https://www.stackage.org/snapshots for a complete list." ] show (NoProjectConfigFound dir mcmd) = concat [ "Unable to find a stack.yaml file in the current directory (" , toFilePath dir , ") or its ancestors" , case mcmd of Nothing -> "" Just cmd -> "\nRecommended action: stack " ++ T.unpack cmd ] show (UnexpectedTarballContents dirs files) = concat [ "When unpacking a tarball specified in your stack.yaml file, " , "did not find expected contents. Expected: a single directory. Found: " , show ( map (toFilePath . dirname) dirs , map (toFilePath . filename) files ) ] show (BadStackVersionException requiredRange) = concat [ "The version of stack you are using (" , show (fromCabalVersion Meta.version) , ") is outside the required\n" ,"version range (" , T.unpack (versionRangeText requiredRange) , ") specified in stack.yaml." ] show (NoMatchingSnapshot names) = concat [ "There was no snapshot found that matched the package " , "bounds in your .cabal files.\n" , "Please choose one of the following commands to get started.\n\n" , unlines $ map (\name -> " stack init --resolver " ++ T.unpack (renderSnapName name)) names , "\nYou'll then need to add some extra-deps. See:\n\n" , " https://github.com/commercialhaskell/stack/wiki/stack.yaml#extra-deps" , "\n\nYou can also try falling back to a dependency solver with:\n\n" , " stack init --solver" ] show (NoSuchDirectory dir) = concat ["No directory could be located matching the supplied path: " ,dir ] instance Exception ConfigException -- | Helper function to ask the environment and apply getConfig askConfig :: (MonadReader env m, HasConfig env) => m Config askConfig = liftM getConfig ask -- | Get the URL to request the information on the latest snapshots askLatestSnapshotUrl :: (MonadReader env m, HasConfig env) => m Text askLatestSnapshotUrl = asks (configLatestSnapshotUrl . getConfig) -- | Root for a specific package index configPackageIndexRoot :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs Dir) configPackageIndexRoot (IndexName name) = do config <- asks getConfig dir <- parseRelDir $ S8.unpack name return (configStackRoot config </> $(mkRelDir "indices") </> dir) -- | Location of the 00-index.cache file configPackageIndexCache :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs File) configPackageIndexCache = liftM (</> $(mkRelFile "00-index.cache")) . configPackageIndexRoot -- | Location of the 00-index.tar file configPackageIndex :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs File) configPackageIndex = liftM (</> $(mkRelFile "00-index.tar")) . configPackageIndexRoot -- | Location of the 00-index.tar.gz file configPackageIndexGz :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs File) configPackageIndexGz = liftM (</> $(mkRelFile "00-index.tar.gz")) . configPackageIndexRoot -- | Location of a package tarball configPackageTarball :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> PackageIdentifier -> m (Path Abs File) configPackageTarball iname ident = do root <- configPackageIndexRoot iname name <- parseRelDir $ packageNameString $ packageIdentifierName ident ver <- parseRelDir $ versionString $ packageIdentifierVersion ident base <- parseRelFile $ packageIdentifierString ident ++ ".tar.gz" return (root </> $(mkRelDir "packages") </> name </> ver </> base) workDirRel :: Path Rel Dir workDirRel = $(mkRelDir ".stack-work") -- | Per-project work dir configProjectWorkDir :: (HasBuildConfig env, MonadReader env m) => m (Path Abs Dir) configProjectWorkDir = do bc <- asks getBuildConfig return (bcRoot bc </> workDirRel) -- | File containing the installed cache, see "Stack.PackageDump" configInstalledCache :: (HasBuildConfig env, MonadReader env m) => m (Path Abs File) configInstalledCache = liftM (</> $(mkRelFile "installed-cache.bin")) configProjectWorkDir -- | Relative directory for the platform identifier platformRelDir :: (MonadReader env m, HasPlatform env, MonadThrow m) => m (Path Rel Dir) platformRelDir = asks getPlatform >>= parseRelDir . Distribution.Text.display -- | Path to .shake files. configShakeFilesDir :: (MonadReader env m, HasBuildConfig env) => m (Path Abs Dir) configShakeFilesDir = liftM (</> $(mkRelDir "shake")) configProjectWorkDir -- | Where to unpack packages for local build configLocalUnpackDir :: (MonadReader env m, HasBuildConfig env) => m (Path Abs Dir) configLocalUnpackDir = liftM (</> $(mkRelDir "unpacked")) configProjectWorkDir -- | Directory containing snapshots snapshotsDir :: (MonadReader env m, HasConfig env, MonadThrow m) => m (Path Abs Dir) snapshotsDir = do config <- asks getConfig platform <- platformRelDir return $ configStackRoot config </> $(mkRelDir "snapshots") </> platform -- | Installation root for dependencies installationRootDeps :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) installationRootDeps = do snapshots <- snapshotsDir bc <- asks getBuildConfig name <- parseRelDir $ T.unpack $ resolverName $ bcResolver bc ghc <- compilerVersionDir return $ snapshots </> name </> ghc -- | Installation root for locals installationRootLocal :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) installationRootLocal = do bc <- asks getBuildConfig name <- parseRelDir $ T.unpack $ resolverName $ bcResolver bc ghc <- compilerVersionDir platform <- platformRelDir return $ configProjectWorkDir bc </> $(mkRelDir "install") </> platform </> name </> ghc compilerVersionDir :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Rel Dir) compilerVersionDir = do compilerVersion <- asks (envConfigCompilerVersion . getEnvConfig) parseRelDir $ case compilerVersion of GhcVersion version -> versionString version GhcjsVersion {} -> T.unpack (compilerVersionName compilerVersion) -- | Package database for installing dependencies into packageDatabaseDeps :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) packageDatabaseDeps = do root <- installationRootDeps return $ root </> $(mkRelDir "pkgdb") -- | Package database for installing local packages into packageDatabaseLocal :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) packageDatabaseLocal = do root <- installationRootLocal return $ root </> $(mkRelDir "pkgdb") -- | Directory for holding flag cache information flagCacheLocal :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) flagCacheLocal = do root <- installationRootLocal return $ root </> $(mkRelDir "flag-cache") -- | Where to store mini build plan caches configMiniBuildPlanCache :: (MonadThrow m, MonadReader env m, HasStackRoot env, HasPlatform env) => SnapName -> m (Path Abs File) configMiniBuildPlanCache name = do root <- asks getStackRoot platform <- platformRelDir file <- parseRelFile $ T.unpack (renderSnapName name) ++ ".cache" -- Yes, cached plans differ based on platform return (root </> $(mkRelDir "build-plan-cache") </> platform </> file) -- | Suffix applied to an installation root to get the bin dir bindirSuffix :: Path Rel Dir bindirSuffix = $(mkRelDir "bin") -- | Suffix applied to an installation root to get the doc dir docDirSuffix :: Path Rel Dir docDirSuffix = $(mkRelDir "doc") -- | Suffix applied to an installation root to get the hpc dir hpcDirSuffix :: Path Rel Dir hpcDirSuffix = $(mkRelDir "hpc") -- | Get the extra bin directories (for the PATH). Puts more local first -- -- Bool indicates whether or not to include the locals extraBinDirs :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Bool -> [Path Abs Dir]) extraBinDirs = do deps <- installationRootDeps local <- installationRootLocal return $ \locals -> if locals then [local </> bindirSuffix, deps </> bindirSuffix] else [deps </> bindirSuffix] -- | Get the minimal environment override, useful for just calling external -- processes like git or ghc getMinimalEnvOverride :: (MonadReader env m, HasConfig env, MonadIO m) => m EnvOverride getMinimalEnvOverride = do config <- asks getConfig liftIO $ configEnvOverride config EnvSettings { esIncludeLocals = False , esIncludeGhcPackagePath = False , esStackExe = False , esLocaleUtf8 = False } getWhichCompiler :: (MonadReader env m, HasEnvConfig env) => m WhichCompiler getWhichCompiler = asks (whichCompiler . envConfigCompilerVersion . getEnvConfig) data ProjectAndConfigMonoid = ProjectAndConfigMonoid !Project !ConfigMonoid instance (warnings ~ [JSONWarning]) => FromJSON (ProjectAndConfigMonoid, warnings) where parseJSON = withObjectWarnings "ProjectAndConfigMonoid" $ \o -> do dirs <- jsonSubWarningsMT (o ..:? "packages") ..!= [packageEntryCurrDir] extraDeps' <- o ..:? "extra-deps" ..!= [] extraDeps <- case partitionEithers $ goDeps extraDeps' of ([], x) -> return $ Map.fromList x (errs, _) -> fail $ unlines errs flags <- o ..:? "flags" ..!= mempty resolver <- o ..: "resolver" config <- parseConfigMonoidJSON o let project = Project { projectPackages = dirs , projectExtraDeps = extraDeps , projectFlags = flags , projectResolver = resolver } return $ ProjectAndConfigMonoid project config where goDeps = map toSingle . Map.toList . Map.unionsWith Set.union . map toMap where toMap i = Map.singleton (packageIdentifierName i) (Set.singleton (packageIdentifierVersion i)) toSingle (k, s) = case Set.toList s of [x] -> Right (k, x) xs -> Left $ concat [ "Multiple versions for package " , packageNameString k , ": " , unwords $ map versionString xs ] -- | A PackageEntry for the current directory, used as a default packageEntryCurrDir :: PackageEntry packageEntryCurrDir = PackageEntry { peValidWanted = Nothing , peExtraDepMaybe = Nothing , peLocation = PLFilePath "." , peSubdirs = [] } -- | A software control system. data SCM = Git deriving (Show) instance FromJSON SCM where parseJSON v = do s <- parseJSON v case s of "git" -> return Git _ -> fail ("Unknown or unsupported SCM: " <> s) instance ToJSON SCM where toJSON Git = toJSON ("git" :: Text)
tedkornish/stack
src/Stack/Types/Config.hs
bsd-3-clause
40,760
0
17
10,128
7,887
4,205
3,682
855
6
{-# LANGUAGE OverloadedStrings #-} module ConfigSpec (configSpec) where import TestImport configSpec :: Spec configSpec = ydescribe "postAddConfigureR" $ do yit "Parses an config and insert it into the manager" $ do testNodeConfig <- liftIO $ readTestConf "testConfigs/testAddConfig.yml" postBody AddConfigureR (encode testNodeConfig) printBody >> statusIs 200 ydescribe "getConfigureR" $ yit "Return all the Config Files in the Node Manager" $ do get ConfigureR printBody >> statusIs 200 ydescribe "postEditConfigureR" $ do yit "Return a config using configName, no rewriteRule" $ do postBody EditConfigureR (encode testRetriveRequest) statusIs 200 yit "Return a config using configName, using rewriteRule" $ do postBody EditConfigureR (encode testRetriveRequestWRewrite) bodyContains "why not working.com" statusIs 200 ydescribe "postCopyConfigureR" $ yit "Requests the copies of all the configs from the node manager" $ do postBody CopyConfigureR (encode testCopyRequest) printBody >> statusIs 200 ydescribe "postDeleteConfigureR" $ yit "Delete a configure using a configure name" $ do postBody DeleteConfigureR (encode testDeleteRequest) printBody >> statusIs 200
bitemyapp/node-manager
test/ConfigSpec.hs
bsd-3-clause
1,365
0
16
349
269
115
154
29
1
-- | -- Copyright : (c) Sam Truzjan 2013 -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- module Network.BitTorrent.Exchange ( -- * Manager Options (..) , Manager , Handler , newManager , closeManager -- * Session , Caps , Extension , toCaps , Session , newSession , closeSession -- * Query , waitMetadata , takeMetadata -- * Connections , connect , connectSink ) where import Network.BitTorrent.Exchange.Manager import Network.BitTorrent.Exchange.Message import Network.BitTorrent.Exchange.Session
DavidAlphaFox/bittorrent
src/Network/BitTorrent/Exchange.hs
bsd-3-clause
736
0
5
255
90
65
25
20
0
module Runner ( run ) where import Control.DeepSeq (deepseq) import TAPL.Meow (Meow, meow) import Evaluator (evaluate) import Parser (parseTree) import PPrint (pprint) run :: String -> Meow () run str = do let term = parseTree str let val = term `deepseq` evaluate term meow $ pprint val
foreverbell/unlimited-plt-toys
tapl/untyped/Runner.hs
bsd-3-clause
299
0
11
59
118
64
54
12
1
{-# LANGUAGE CPP, ScopedTypeVariables #-} module TcErrors( reportUnsolved, reportAllUnsolved, warnAllUnsolved, warnDefaulting, solverDepthErrorTcS ) where #include "HsVersions.h" import TcRnTypes import TcRnMonad import TcMType import TcType import TypeRep import Type import Kind ( isKind ) import Unify ( tcMatchTys ) import Module import FamInst import Inst import InstEnv import TyCon import DataCon import TcEvidence import Name import RdrName ( lookupGRE_Name, GlobalRdrEnv ) import Id import Var import VarSet import VarEnv import NameEnv import Bag import ErrUtils ( ErrMsg, pprLocErrMsg ) import BasicTypes import Util import FastString import Outputable import SrcLoc import DynFlags import StaticFlags ( opt_PprStyle_Debug ) import ListSetOps ( equivClasses ) import Control.Monad ( when ) import Data.Maybe import Data.List ( partition, mapAccumL, nub, sortBy ) {- ************************************************************************ * * \section{Errors and contexts} * * ************************************************************************ ToDo: for these error messages, should we note the location as coming from the insts, or just whatever seems to be around in the monad just now? Note [Deferring coercion errors to runtime] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ While developing, sometimes it is desirable to allow compilation to succeed even if there are type errors in the code. Consider the following case: module Main where a :: Int a = 'a' main = print "b" Even though `a` is ill-typed, it is not used in the end, so if all that we're interested in is `main` it is handy to be able to ignore the problems in `a`. Since we treat type equalities as evidence, this is relatively simple. Whenever we run into a type mismatch in TcUnify, we normally just emit an error. But it is always safe to defer the mismatch to the main constraint solver. If we do that, `a` will get transformed into co :: Int ~ Char co = ... a :: Int a = 'a' `cast` co The constraint solver would realize that `co` is an insoluble constraint, and emit an error with `reportUnsolved`. But we can also replace the right-hand side of `co` with `error "Deferred type error: Int ~ Char"`. This allows the program to compile, and it will run fine unless we evaluate `a`. This is what `deferErrorsToRuntime` does. It does this by keeping track of which errors correspond to which coercion in TcErrors. TcErrors.reportTidyWanteds does not print the errors and does not fail if -fdefer-type-errors is on, so that we can continue compilation. The errors are turned into warnings in `reportUnsolved`. -} -- | Report unsolved goals as errors or warnings. We may also turn some into -- deferred run-time errors if `-fdefer-type-errors` is on. reportUnsolved :: WantedConstraints -> TcM (Bag EvBind) reportUnsolved wanted = do { binds_var <- newTcEvBinds ; defer_errs <- goptM Opt_DeferTypeErrors ; defer_holes <- goptM Opt_DeferTypedHoles ; warn_holes <- woptM Opt_WarnTypedHoles ; let expr_holes | not defer_holes = HoleError | warn_holes = HoleWarn | otherwise = HoleDefer ; partial_sigs <- xoptM Opt_PartialTypeSignatures ; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures ; let type_holes | not partial_sigs = HoleError | warn_partial_sigs = HoleWarn | otherwise = HoleDefer ; report_unsolved (Just binds_var) False defer_errs expr_holes type_holes wanted ; getTcEvBinds binds_var } -- | Report *all* unsolved goals as errors, even if -fdefer-type-errors is on -- See Note [Deferring coercion errors to runtime] reportAllUnsolved :: WantedConstraints -> TcM () reportAllUnsolved wanted = report_unsolved Nothing False False HoleError HoleError wanted -- | Report all unsolved goals as warnings (but without deferring any errors to -- run-time). See Note [Safe Haskell Overlapping Instances Implementation] in -- TcSimplify warnAllUnsolved :: WantedConstraints -> TcM () warnAllUnsolved wanted = report_unsolved Nothing True False HoleWarn HoleWarn wanted -- | Report unsolved goals as errors or warnings. report_unsolved :: Maybe EvBindsVar -- cec_binds -> Bool -- Errors as warnings -> Bool -- cec_defer_type_errors -> HoleChoice -- Expression holes -> HoleChoice -- Type holes -> WantedConstraints -> TcM () report_unsolved mb_binds_var err_as_warn defer_errs expr_holes type_holes wanted | isEmptyWC wanted = return () | otherwise = do { traceTc "reportUnsolved (before zonking and tidying)" (ppr wanted) ; wanted <- zonkWC wanted -- Zonk to reveal all information ; env0 <- tcInitTidyEnv -- If we are deferring we are going to need /all/ evidence around, -- including the evidence produced by unflattening (zonkWC) ; let tidy_env = tidyFreeTyVars env0 free_tvs free_tvs = tyVarsOfWC wanted ; traceTc "reportUnsolved (after zonking and tidying):" $ vcat [ pprTvBndrs (varSetElems free_tvs) , ppr wanted ] ; warn_redundant <- woptM Opt_WarnRedundantConstraints ; let err_ctxt = CEC { cec_encl = [] , cec_tidy = tidy_env , cec_defer_type_errors = defer_errs , cec_errors_as_warns = err_as_warn , cec_expr_holes = expr_holes , cec_type_holes = type_holes , cec_suppress = False -- See Note [Suppressing error messages] , cec_warn_redundant = warn_redundant , cec_binds = mb_binds_var } ; reportWanteds err_ctxt wanted } -------------------------------------------- -- Internal functions -------------------------------------------- data HoleChoice = HoleError -- A hole is a compile-time error | HoleWarn -- Defer to runtime, emit a compile-time warning | HoleDefer -- Defer to runtime, no warning data ReportErrCtxt = CEC { cec_encl :: [Implication] -- Enclosing implications -- (innermost first) -- ic_skols and givens are tidied, rest are not , cec_tidy :: TidyEnv , cec_binds :: Maybe EvBindsVar -- Nothinng <=> Report all errors, including holes; no bindings -- Just ev <=> make some errors (depending on cec_defer) -- into warnings, and emit evidence bindings -- into 'ev' for unsolved constraints , cec_errors_as_warns :: Bool -- Turn all errors into warnings -- (except for Holes, which are -- controlled by cec_type_holes and -- cec_expr_holes) , cec_defer_type_errors :: Bool -- True <=> -fdefer-type-errors -- Defer type errors until runtime -- Irrelevant if cec_binds = Nothing , cec_expr_holes :: HoleChoice -- Holes in expressions , cec_type_holes :: HoleChoice -- Holes in types , cec_warn_redundant :: Bool -- True <=> -fwarn-redundant-constraints , cec_suppress :: Bool -- True <=> More important errors have occurred, -- so create bindings if need be, but -- don't issue any more errors/warnings -- See Note [Suppressing error messages] } {- Note [Suppressing error messages] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The cec_suppress flag says "don't report any errors". Instead, just create evidence bindings (as usual). It's used when more important errors have occurred. Specifically (see reportWanteds) * If there are insoluble Givens, then we are in unreachable code and all bets are off. So don't report any further errors. * If there are any insolubles (eg Int~Bool), here or in a nested implication, then suppress errors from the simple constraints here. Sometimes the simple-constraint errors are a knock-on effect of the insolubles. -} reportImplic :: ReportErrCtxt -> Implication -> TcM () reportImplic ctxt implic@(Implic { ic_skols = tvs, ic_given = given , ic_wanted = wanted, ic_binds = evb , ic_status = status, ic_info = info , ic_env = tcl_env }) | BracketSkol <- info , not (isInsolubleStatus status) = return () -- For Template Haskell brackets report only -- definite errors. The whole thing will be re-checked -- later when we plug it in, and meanwhile there may -- certainly be un-satisfied constraints | otherwise = do { reportWanteds ctxt' wanted ; traceTc "reportImplic" (ppr implic) ; when (cec_warn_redundant ctxt) $ warnRedundantConstraints ctxt' tcl_env info' dead_givens } where (env1, tvs') = mapAccumL tidyTyVarBndr (cec_tidy ctxt) tvs (env2, info') = tidySkolemInfo env1 info implic' = implic { ic_skols = tvs' , ic_given = map (tidyEvVar env2) given , ic_info = info' } ctxt' = ctxt { cec_tidy = env2 , cec_encl = implic' : cec_encl ctxt , cec_binds = case cec_binds ctxt of Nothing -> Nothing Just {} -> Just evb } dead_givens = case status of IC_Solved { ics_dead = dead } -> dead _ -> [] warnRedundantConstraints :: ReportErrCtxt -> TcLclEnv -> SkolemInfo -> [EvVar] -> TcM () warnRedundantConstraints ctxt env info ev_vars | null redundant_evs = return () | SigSkol {} <- info = setLclEnv env $ -- We want to add "In the type signature for f" -- to the error context, which is a bit tiresome addErrCtxt (ptext (sLit "In") <+> ppr info) $ do { env <- getLclEnv ; msg <- mkErrorMsg ctxt env doc ; reportWarning msg } | otherwise -- But for InstSkol there already *is* a surrounding -- "In the instance declaration for Eq [a]" context -- and we don't want to say it twice. Seems a bit ad-hoc = do { msg <- mkErrorMsg ctxt env doc ; reportWarning msg } where doc = ptext (sLit "Redundant constraint") <> plural redundant_evs <> colon <+> pprEvVarTheta redundant_evs redundant_evs = case info of -- See Note [Redundant constraints in instance decls] InstSkol -> filterOut improving ev_vars _ -> ev_vars improving ev_var = any isImprovementPred $ transSuperClassesPred (idType ev_var) {- Note [Redundant constraints in instance decls] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For instance declarations, we don't report unused givens if they can give rise to improvement. Example (Trac #10100): class Add a b ab | a b -> ab, a ab -> b instance Add Zero b b instance Add a b ab => Add (Succ a) b (Succ ab) The context (Add a b ab) for the instance is clearly unused in terms of evidence, since the dictionary has no feilds. But it is still needed! With the context, a wanted constraint Add (Succ Zero) beta (Succ Zero) we will reduce to (Add Zero beta Zero), and thence we get beta := Zero. But without the context we won't find beta := Zero. This only matters in instance declarations.. -} reportWanteds :: ReportErrCtxt -> WantedConstraints -> TcM () reportWanteds ctxt (WC { wc_simple = simples, wc_insol = insols, wc_impl = implics }) = do { traceTc "reportWanteds" (vcat [ ptext (sLit "Simples =") <+> ppr simples , ptext (sLit "Suppress =") <+> ppr (cec_suppress ctxt)]) ; let tidy_insols = bagToList (mapBag (tidyCt env) insols) tidy_simples = bagToList (mapBag (tidyCt env) simples) -- First deal with things that are utterly wrong -- Like Int ~ Bool (incl nullary TyCons) -- or Int ~ t a (AppTy on one side) -- Do this first so that we know the ctxt for the nested implications ; (ctxt1, insols1) <- tryReporters ctxt insol_given tidy_insols ; (ctxt2, insols2) <- tryReporters ctxt1 insol_wanted insols1 -- For the simple wanteds, suppress them if there are any -- insolubles in the tree, to avoid unnecessary clutter ; let ctxt2' = ctxt { cec_suppress = cec_suppress ctxt2 || anyBag insolubleImplic implics } ; (_, leftovers) <- tryReporters ctxt2' reporters (insols2 ++ tidy_simples) ; MASSERT2( null leftovers, ppr leftovers ) -- All the Derived ones have been filtered out of simples -- by the constraint solver. This is ok; we don't want -- to report unsolved Derived goals as errors -- See Note [Do not report derived but soluble errors] ; mapBagM_ (reportImplic ctxt1) implics } -- NB ctxt1: don't suppress inner insolubles if there's only a -- wanted insoluble here; but do suppress inner insolubles -- if there's a *given* insoluble here (= inaccessible code) where env = cec_tidy ctxt insol_given = [ ("insoluble1", is_given &&& utterly_wrong, True, mkGroupReporter mkEqErr) , ("insoluble2", is_given &&& is_equality, True, mkSkolReporter) ] insol_wanted = [ ("insoluble3", utterly_wrong, True, mkGroupReporter mkEqErr) , ("insoluble4", is_equality, True, mkSkolReporter) ] reporters = [ ("Holes", is_hole, False, mkHoleReporter) -- Report equalities of form (a~ty). They are usually -- skolem-equalities, and they cause confusing knock-on -- effects in other errors; see test T4093b. , ("Skolem equalities", is_skol_eq, True, mkSkolReporter) -- Other equalities; also confusing knock on effects , ("Equalities", is_equality, True, mkGroupReporter mkEqErr) , ("Implicit params", is_ip, False, mkGroupReporter mkIPErr) , ("Irreds", is_irred, False, mkGroupReporter mkIrredErr) , ("Dicts", is_dict, False, mkGroupReporter mkDictErr) ] (&&&) :: (Ct->PredTree->Bool) -> (Ct->PredTree->Bool) -> (Ct->PredTree->Bool) (&&&) p1 p2 ct pred = p1 ct pred && p2 ct pred is_skol_eq, is_hole, is_dict, is_equality, is_ip, is_irred :: Ct -> PredTree -> Bool utterly_wrong _ (EqPred NomEq ty1 ty2) = isRigid ty1 && isRigid ty2 utterly_wrong _ _ = False is_hole ct _ = isHoleCt ct is_given ct _ = not (isWantedCt ct) -- The Derived ones are actually all from Givens is_equality ct pred = not (isDerivedCt ct) && (case pred of EqPred {} -> True _ -> False) is_skol_eq ct (EqPred NomEq ty1 ty2) = not (isDerivedCt ct) && isRigidOrSkol ty1 && isRigidOrSkol ty2 is_skol_eq _ _ = False is_dict _ (ClassPred {}) = True is_dict _ _ = False is_ip _ (ClassPred cls _) = isIPClass cls is_ip _ _ = False is_irred _ (IrredPred {}) = True is_irred _ _ = False -- isRigidEqPred :: PredTree -> Bool -- isRigidEqPred (EqPred NomEq ty1 ty2) = isRigid ty1 && isRigid ty2 -- isRigidEqPred _ = False --------------- isRigid, isRigidOrSkol :: Type -> Bool isRigid ty | Just (tc,_) <- tcSplitTyConApp_maybe ty = isDecomposableTyCon tc | Just {} <- tcSplitAppTy_maybe ty = True | isForAllTy ty = True | otherwise = False isRigidOrSkol ty | Just tv <- getTyVar_maybe ty = isSkolemTyVar tv | otherwise = isRigid ty isTyFun_maybe :: Type -> Maybe TyCon isTyFun_maybe ty = case tcSplitTyConApp_maybe ty of Just (tc,_) | isTypeFamilyTyCon tc -> Just tc _ -> Nothing -------------------------------------------- -- Reporters -------------------------------------------- type Reporter = ReportErrCtxt -> [Ct] -> TcM () type ReporterSpec = ( String -- Name , Ct -> PredTree -> Bool -- Pick these ones , Bool -- True <=> suppress subsequent reporters , Reporter) -- The reporter itself mkSkolReporter :: Reporter -- Suppress duplicates with the same LHS mkSkolReporter ctxt cts = mapM_ (reportGroup mkEqErr ctxt) (equivClasses cmp_lhs_type cts) where cmp_lhs_type ct1 ct2 = case (classifyPredType (ctPred ct1), classifyPredType (ctPred ct2)) of (EqPred eq_rel1 ty1 _, EqPred eq_rel2 ty2 _) -> (eq_rel1 `compare` eq_rel2) `thenCmp` (ty1 `cmpType` ty2) _ -> pprPanic "mkSkolReporter" (ppr ct1 $$ ppr ct2) mkHoleReporter :: Reporter -- Reports errors one at a time mkHoleReporter ctxt = mapM_ $ \ct -> do { err <- mkHoleError ctxt ct ; maybeReportHoleError ctxt ct err ; maybeAddDeferredHoleBinding ctxt err ct } mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -- Make error message for a group -> Reporter -- Deal with lots of constraints -- Group together errors from same location, -- and report only the first (to avoid a cascade) mkGroupReporter mk_err ctxt cts = mapM_ (reportGroup mk_err ctxt) (equivClasses cmp_loc cts) where cmp_loc ct1 ct2 = ctLocSpan (ctLoc ct1) `compare` ctLocSpan (ctLoc ct2) reportGroup :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -> ReportErrCtxt -> [Ct] -> TcM () reportGroup mk_err ctxt cts = do { err <- mk_err ctxt cts ; maybeReportError ctxt err ; mapM_ (maybeAddDeferredBinding ctxt err) cts } -- Add deferred bindings for all -- But see Note [Always warn with -fdefer-type-errors] maybeReportHoleError :: ReportErrCtxt -> Ct -> ErrMsg -> TcM () maybeReportHoleError ctxt ct err -- When -XPartialTypeSignatures is on, warnings (instead of errors) are -- generated for holes in partial type signatures. Unless -- -fwarn_partial_type_signatures is not on, in which case the messages are -- discarded. | isTypeHoleCt ct = -- For partial type signatures, generate warnings only, and do that -- only if -fwarn_partial_type_signatures is on case cec_type_holes ctxt of HoleError -> reportError err HoleWarn -> reportWarning err HoleDefer -> return () -- Otherwise this is a typed hole in an expression | otherwise = -- If deferring, report a warning only if -fwarn-typed-holds is on case cec_expr_holes ctxt of HoleError -> reportError err HoleWarn -> reportWarning err HoleDefer -> return () maybeReportError :: ReportErrCtxt -> ErrMsg -> TcM () -- Report the error and/or make a deferred binding for it maybeReportError ctxt err -- See Note [Always warn with -fdefer-type-errors] | cec_defer_type_errors ctxt || cec_errors_as_warns ctxt = reportWarning err | cec_suppress ctxt = return () | otherwise = reportError err addDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM () -- See Note [Deferring coercion errors to runtime] addDeferredBinding ctxt err ct | CtWanted { ctev_pred = pred, ctev_evar = ev_id } <- ctEvidence ct -- Only add deferred bindings for Wanted constraints , Just ev_binds_var <- cec_binds ctxt -- We have somewhere to put the bindings = do { dflags <- getDynFlags ; let err_msg = pprLocErrMsg err err_fs = mkFastString $ showSDoc dflags $ err_msg $$ text "(deferred type error)" -- Create the binding ; addTcEvBind ev_binds_var (mkWantedEvBind ev_id (EvDelayedError pred err_fs)) } | otherwise -- Do not set any evidence for Given/Derived = return () maybeAddDeferredHoleBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM () maybeAddDeferredHoleBinding ctxt err ct | isExprHoleCt ct , case cec_expr_holes ctxt of HoleDefer -> True HoleWarn -> True HoleError -> False = addDeferredBinding ctxt err ct -- Only add bindings for holes in expressions | otherwise -- not for holes in partial type signatures = return () maybeAddDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM () maybeAddDeferredBinding ctxt err ct | cec_defer_type_errors ctxt = addDeferredBinding ctxt err ct | otherwise = return () tryReporters :: ReportErrCtxt -> [ReporterSpec] -> [Ct] -> TcM (ReportErrCtxt, [Ct]) -- Use the first reporter in the list whose predicate says True tryReporters ctxt reporters cts = do { traceTc "tryReporters {" (ppr cts) ; (ctxt', cts') <- go ctxt reporters cts ; traceTc "tryReporters }" (ppr cts') ; return (ctxt', cts') } where go ctxt [] cts = return (ctxt, cts) go ctxt (r : rs) cts = do { (ctxt', cts') <- tryReporter ctxt r cts ; go ctxt' rs cts' } -- Carry on with the rest, because we must make -- deferred bindings for them if we have -fdefer-type-errors -- But suppress their error messages tryReporter :: ReportErrCtxt -> ReporterSpec -> [Ct] -> TcM (ReportErrCtxt, [Ct]) tryReporter ctxt (str, keep_me, suppress_after, reporter) cts | null yeses = return (ctxt, cts) | otherwise = do { traceTc "tryReporter:" (text str <+> ppr yeses) ; reporter ctxt yeses ; let ctxt' = ctxt { cec_suppress = suppress_after || cec_suppress ctxt } ; return (ctxt', nos) } where (yeses, nos) = partition (\ct -> keep_me ct (classifyPredType (ctPred ct))) cts -- Add the "arising from..." part to a message about bunch of dicts addArising :: CtOrigin -> SDoc -> SDoc addArising orig msg = hang msg 2 (pprArising orig) pprWithArising :: [Ct] -> (CtLoc, SDoc) -- Print something like -- (Eq a) arising from a use of x at y -- (Show a) arising from a use of p at q -- Also return a location for the error message -- Works for Wanted/Derived only pprWithArising [] = panic "pprWithArising" pprWithArising (ct:cts) | null cts = (loc, addArising (ctLocOrigin loc) (pprTheta [ctPred ct])) | otherwise = (loc, vcat (map ppr_one (ct:cts))) where loc = ctLoc ct ppr_one ct' = hang (parens (pprType (ctPred ct'))) 2 (pprArisingAt (ctLoc ct')) mkErrorMsgFromCt :: ReportErrCtxt -> Ct -> SDoc -> TcM ErrMsg mkErrorMsgFromCt ctxt ct msg = mkErrorMsg ctxt (ctLocEnv (ctLoc ct)) msg mkErrorMsg :: ReportErrCtxt -> TcLclEnv -> SDoc -> TcM ErrMsg mkErrorMsg ctxt tcl_env msg = do { err_info <- mkErrInfo (cec_tidy ctxt) (tcl_ctxt tcl_env) ; mkLongErrAt (RealSrcSpan (tcl_loc tcl_env)) msg err_info } type UserGiven = ([EvVar], SkolemInfo, Bool, RealSrcSpan) getUserGivens :: ReportErrCtxt -> [UserGiven] -- One item for each enclosing implication getUserGivens (CEC {cec_encl = ctxt}) = reverse $ [ (givens, info, no_eqs, tcl_loc env) | Implic { ic_given = givens, ic_env = env , ic_no_eqs = no_eqs, ic_info = info } <- ctxt , not (null givens) ] {- Note [Always warn with -fdefer-type-errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When -fdefer-type-errors is on we warn about *all* type errors, even if cec_suppress is on. This can lead to a lot more warnings than you would get errors without -fdefer-type-errors, but if we suppress any of them you might get a runtime error that wasn't warned about at compile time. This is an easy design choice to change; just flip the order of the first two equations for maybeReportError To be consistent, we should also report multiple warnings from a single location in mkGroupReporter, when -fdefer-type-errors is on. But that is perhaps a bit *over*-consistent! Again, an easy choice to change. Note [Do not report derived but soluble errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The wc_simples include Derived constraints that have not been solved, but are not insoluble (in that case they'd be in wc_insols). We do not want to report these as errors: * Superclass constraints. If we have an unsolved [W] Ord a, we'll also have an unsolved [D] Eq a, and we do not want to report that; it's just noise. * Functional dependencies. For givens, consider class C a b | a -> b data T a where MkT :: C a d => [d] -> T a f :: C a b => T a -> F Int f (MkT xs) = length xs Then we get a [D] b~d. But there *is* a legitimate call to f, namely f (MkT [True]) :: T Bool, in which b=d. So we should not reject the program. For wanteds, something similar data T a where MkT :: C Int b => a -> b -> T a g :: C Int c => c -> () f :: T a -> () f (MkT x y) = g x Here we get [G] C Int b, [W] C Int a, hence [D] a~b. But again f (MkT True True) is a legitimate call. (We leave the Deriveds in wc_simple until reportErrors, so that we don't lose derived superclasses between iterations of the solver.) For functional dependencies, here is a real example, stripped off from libraries/utf8-string/Codec/Binary/UTF8/Generic.hs class C a b | a -> b g :: C a b => a -> b -> () f :: C a b => a -> b -> () f xa xb = let loop = g xa in loop xb We will first try to infer a type for loop, and we will succeed: C a b' => b' -> () Subsequently, we will type check (loop xb) and all is good. But, recall that we have to solve a final implication constraint: C a b => (C a b' => .... cts from body of loop .... )) And now we have a problem as we will generate an equality b ~ b' and fail to solve it. ************************************************************************ * * Irreducible predicate errors * * ************************************************************************ -} mkIrredErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg mkIrredErr ctxt cts = do { (ctxt, binds_msg, _) <- relevantBindings True ctxt ct1 ; mkErrorMsgFromCt ctxt ct1 (msg $$ binds_msg) } where (ct1:_) = cts orig = ctLocOrigin (ctLoc ct1) givens = getUserGivens ctxt msg = couldNotDeduce givens (map ctPred cts, orig) ---------------- mkHoleError :: ReportErrCtxt -> Ct -> TcM ErrMsg mkHoleError ctxt ct@(CHoleCan { cc_occ = occ, cc_hole = hole_sort }) = do { let tyvars = varSetElems (tyVarsOfCt ct) tyvars_msg = map loc_msg tyvars msg = vcat [ hang (ptext (sLit "Found hole") <+> quotes (ppr occ)) 2 (ptext (sLit "with type:") <+> pprType (ctEvPred (ctEvidence ct))) , ppUnless (null tyvars) (ptext (sLit "Where:") <+> vcat tyvars_msg) , hint ] ; (ctxt, binds_doc, _) <- relevantBindings False ctxt ct -- The 'False' means "don't filter the bindings"; see Trac #8191 ; mkErrorMsgFromCt ctxt ct (msg $$ binds_doc) } where hint | TypeHole <- hole_sort , HoleError <- cec_type_holes ctxt = ptext (sLit "To use the inferred type, enable PartialTypeSignatures") | ExprHole <- hole_sort -- Give hint for, say, f x = _x , lengthFS (occNameFS occ) > 1 -- Don't give this hint for plain "_", which isn't legal Haskell = ptext (sLit "Or perhaps") <+> quotes (ppr occ) <+> ptext (sLit "is mis-spelled, or not in scope") | otherwise = empty loc_msg tv = case tcTyVarDetails tv of SkolemTv {} -> quotes (ppr tv) <+> skol_msg MetaTv {} -> quotes (ppr tv) <+> ptext (sLit "is an ambiguous type variable") det -> pprTcTyVarDetails det where skol_msg = pprSkol (getSkolemInfo (cec_encl ctxt) tv) (getSrcLoc tv) mkHoleError _ ct = pprPanic "mkHoleError" (ppr ct) ---------------- mkIPErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg mkIPErr ctxt cts = do { (ctxt, bind_msg, _) <- relevantBindings True ctxt ct1 ; mkErrorMsgFromCt ctxt ct1 (msg $$ bind_msg) } where (ct1:_) = cts orig = ctLocOrigin (ctLoc ct1) preds = map ctPred cts givens = getUserGivens ctxt msg | null givens = addArising orig $ sep [ ptext (sLit "Unbound implicit parameter") <> plural cts , nest 2 (pprTheta preds) ] | otherwise = couldNotDeduce givens (preds, orig) {- ************************************************************************ * * Equality errors * * ************************************************************************ Note [Inaccessible code] ~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T a where T1 :: T a T2 :: T Bool f :: (a ~ Int) => T a -> Int f T1 = 3 f T2 = 4 -- Unreachable code Here the second equation is unreachable. The original constraint (a~Int) from the signature gets rewritten by the pattern-match to (Bool~Int), so the danger is that we report the error as coming from the *signature* (Trac #7293). So, for Given errors we replace the env (and hence src-loc) on its CtLoc with that from the immediately enclosing implication. -} mkEqErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg -- Don't have multiple equality errors from the same location -- E.g. (Int,Bool) ~ (Bool,Int) one error will do! mkEqErr ctxt (ct:_) = mkEqErr1 ctxt ct mkEqErr _ [] = panic "mkEqErr" mkEqErr1 :: ReportErrCtxt -> Ct -> TcM ErrMsg -- Wanted constraints only! mkEqErr1 ctxt ct | isGiven ev = do { (ctxt, binds_msg, _) <- relevantBindings True ctxt ct ; let (given_loc, given_msg) = mk_given (cec_encl ctxt) ; dflags <- getDynFlags ; mkEqErr_help dflags ctxt (given_msg $$ binds_msg) (ct { cc_ev = ev {ctev_loc = given_loc}}) -- Note [Inaccessible code] Nothing ty1 ty2 } | otherwise -- Wanted or derived = do { (ctxt, binds_msg, tidy_orig) <- relevantBindings True ctxt ct ; rdr_env <- getGlobalRdrEnv ; fam_envs <- tcGetFamInstEnvs ; let (is_oriented, wanted_msg) = mk_wanted_extra tidy_orig coercible_msg = case ctEvEqRel ev of NomEq -> empty ReprEq -> mkCoercibleExplanation rdr_env fam_envs ty1 ty2 ; dflags <- getDynFlags ; traceTc "mkEqErr1" (ppr ct $$ pprCtOrigin (ctLocOrigin loc) $$ pprCtOrigin tidy_orig) ; mkEqErr_help dflags ctxt (wanted_msg $$ coercible_msg $$ binds_msg) ct is_oriented ty1 ty2 } where ev = ctEvidence ct loc = ctEvLoc ev (ty1, ty2) = getEqPredTys (ctEvPred ev) mk_given :: [Implication] -> (CtLoc, SDoc) -- For given constraints we overwrite the env (and hence src-loc) -- with one from the implication. See Note [Inaccessible code] mk_given [] = (loc, empty) mk_given (implic : _) = (setCtLocEnv loc (ic_env implic) , hang (ptext (sLit "Inaccessible code in")) 2 (ppr (ic_info implic))) -- If the types in the error message are the same as the types -- we are unifying, don't add the extra expected/actual message mk_wanted_extra orig@(TypeEqOrigin {}) = mkExpectedActualMsg ty1 ty2 orig mk_wanted_extra (KindEqOrigin cty1 cty2 sub_o) = (Nothing, msg1 $$ msg2) where msg1 = hang (ptext (sLit "When matching types")) 2 (vcat [ ppr cty1 <+> dcolon <+> ppr (typeKind cty1) , ppr cty2 <+> dcolon <+> ppr (typeKind cty2) ]) msg2 = case sub_o of TypeEqOrigin {} -> snd (mkExpectedActualMsg cty1 cty2 sub_o) _ -> empty mk_wanted_extra orig@(FunDepOrigin1 {}) = (Nothing, pprArising orig) mk_wanted_extra orig@(FunDepOrigin2 {}) = (Nothing, pprArising orig) mk_wanted_extra orig@(DerivOriginCoerce _ oty1 oty2) = (Nothing, pprArising orig $+$ mkRoleSigs oty1 oty2) mk_wanted_extra orig@(CoercibleOrigin oty1 oty2) -- if the origin types are the same as the final types, don't -- clutter output with repetitive information | not (oty1 `eqType` ty1 && oty2 `eqType` ty2) && not (oty1 `eqType` ty2 && oty2 `eqType` ty1) = (Nothing, pprArising orig $+$ mkRoleSigs oty1 oty2) | otherwise -- still print role sigs even if types line up = (Nothing, mkRoleSigs oty1 oty2) mk_wanted_extra _ = (Nothing, empty) -- | This function tries to reconstruct why a "Coercible ty1 ty2" constraint -- is left over. mkCoercibleExplanation :: GlobalRdrEnv -> FamInstEnvs -> TcType -> TcType -> SDoc mkCoercibleExplanation rdr_env fam_envs ty1 ty2 | Just (tc, tys) <- tcSplitTyConApp_maybe ty1 , (rep_tc, _, _) <- tcLookupDataFamInst fam_envs tc tys , Just msg <- coercible_msg_for_tycon rep_tc = msg | Just (tc, tys) <- splitTyConApp_maybe ty2 , (rep_tc, _, _) <- tcLookupDataFamInst fam_envs tc tys , Just msg <- coercible_msg_for_tycon rep_tc = msg | Just (s1, _) <- tcSplitAppTy_maybe ty1 , Just (s2, _) <- tcSplitAppTy_maybe ty2 , s1 `eqType` s2 , has_unknown_roles s1 = hang (text "NB: We cannot know what roles the parameters to" <+> quotes (ppr s1) <+> text "have;") 2 (text "we must assume that the role is nominal") | otherwise = empty where coercible_msg_for_tycon tc | isAbstractTyCon tc = Just $ hsep [ text "NB: The type constructor" , quotes (pprSourceTyCon tc) , text "is abstract" ] | isNewTyCon tc , [data_con] <- tyConDataCons tc , let dc_name = dataConName data_con , null (lookupGRE_Name rdr_env dc_name) = Just $ hang (text "The data constructor" <+> quotes (ppr dc_name)) 2 (sep [ text "of newtype" <+> quotes (pprSourceTyCon tc) , text "is not in scope" ]) | otherwise = Nothing has_unknown_roles ty | Just (tc, tys) <- tcSplitTyConApp_maybe ty = length tys >= tyConArity tc -- oversaturated tycon | Just (s, _) <- tcSplitAppTy_maybe ty = has_unknown_roles s | isTyVarTy ty = True | otherwise = False -- | Make a listing of role signatures for all the parameterised tycons -- used in the provided types mkRoleSigs :: Type -> Type -> SDoc mkRoleSigs ty1 ty2 = ppUnless (null role_sigs) $ hang (text "Relevant role signatures:") 2 (vcat role_sigs) where tcs = nameEnvElts $ tyConsOfType ty1 `plusNameEnv` tyConsOfType ty2 role_sigs = mapMaybe ppr_role_sig tcs ppr_role_sig tc | null roles -- if there are no parameters, don't bother printing = Nothing | otherwise = Just $ hsep $ [text "type role", ppr tc] ++ map ppr roles where roles = tyConRoles tc mkEqErr_help :: DynFlags -> ReportErrCtxt -> SDoc -> Ct -> Maybe SwapFlag -- Nothing <=> not sure -> TcType -> TcType -> TcM ErrMsg mkEqErr_help dflags ctxt extra ct oriented ty1 ty2 | Just tv1 <- tcGetTyVar_maybe ty1 = mkTyVarEqErr dflags ctxt extra ct oriented tv1 ty2 | Just tv2 <- tcGetTyVar_maybe ty2 = mkTyVarEqErr dflags ctxt extra ct swapped tv2 ty1 | otherwise = reportEqErr ctxt extra ct oriented ty1 ty2 where swapped = fmap flipSwap oriented reportEqErr :: ReportErrCtxt -> SDoc -> Ct -> Maybe SwapFlag -- Nothing <=> not sure -> TcType -> TcType -> TcM ErrMsg reportEqErr ctxt extra1 ct oriented ty1 ty2 = do { let extra2 = mkEqInfoMsg ct ty1 ty2 ; mkErrorMsgFromCt ctxt ct (vcat [ misMatchOrCND ctxt ct oriented ty1 ty2 , extra2, extra1]) } mkTyVarEqErr :: DynFlags -> ReportErrCtxt -> SDoc -> Ct -> Maybe SwapFlag -> TcTyVar -> TcType -> TcM ErrMsg -- tv1 and ty2 are already tidied mkTyVarEqErr dflags ctxt extra ct oriented tv1 ty2 | isUserSkolem ctxt tv1 -- ty2 won't be a meta-tyvar, or else the thing would -- be oriented the other way round; -- see TcCanonical.canEqTyVarTyVar || isSigTyVar tv1 && not (isTyVarTy ty2) = mkErrorMsgFromCt ctxt ct (vcat [ misMatchOrCND ctxt ct oriented ty1 ty2 , extraTyVarInfo ctxt tv1 ty2 , extra ]) -- So tv is a meta tyvar (or started that way before we -- generalised it). So presumably it is an *untouchable* -- meta tyvar or a SigTv, else it'd have been unified | not (k2 `tcIsSubKind` k1) -- Kind error = mkErrorMsgFromCt ctxt ct $ (kindErrorMsg (mkTyVarTy tv1) ty2 $$ extra) | OC_Occurs <- occ_check_expand , NomEq <- ctEqRel ct -- reporting occurs check for Coercible is strange = do { let occCheckMsg = hang (text "Occurs check: cannot construct the infinite type:") 2 (sep [ppr ty1, char '~', ppr ty2]) extra2 = mkEqInfoMsg ct ty1 ty2 ; mkErrorMsgFromCt ctxt ct (occCheckMsg $$ extra2 $$ extra) } | OC_Forall <- occ_check_expand = do { let msg = vcat [ ptext (sLit "Cannot instantiate unification variable") <+> quotes (ppr tv1) , hang (ptext (sLit "with a type involving foralls:")) 2 (ppr ty2) , nest 2 (ptext (sLit "GHC doesn't yet support impredicative polymorphism")) ] ; mkErrorMsgFromCt ctxt ct msg } -- If the immediately-enclosing implication has 'tv' a skolem, and -- we know by now its an InferSkol kind of skolem, then presumably -- it started life as a SigTv, else it'd have been unified, given -- that there's no occurs-check or forall problem | (implic:_) <- cec_encl ctxt , Implic { ic_skols = skols } <- implic , tv1 `elem` skols = mkErrorMsgFromCt ctxt ct (vcat [ misMatchMsg oriented eq_rel ty1 ty2 , extraTyVarInfo ctxt tv1 ty2 , extra ]) -- Check for skolem escape | (implic:_) <- cec_encl ctxt -- Get the innermost context , Implic { ic_env = env, ic_skols = skols, ic_info = skol_info } <- implic , let esc_skols = filter (`elemVarSet` (tyVarsOfType ty2)) skols , not (null esc_skols) = do { let msg = misMatchMsg oriented eq_rel ty1 ty2 esc_doc = sep [ ptext (sLit "because type variable") <> plural esc_skols <+> pprQuotedList esc_skols , ptext (sLit "would escape") <+> if isSingleton esc_skols then ptext (sLit "its scope") else ptext (sLit "their scope") ] tv_extra = vcat [ nest 2 $ esc_doc , sep [ (if isSingleton esc_skols then ptext (sLit "This (rigid, skolem) type variable is") else ptext (sLit "These (rigid, skolem) type variables are")) <+> ptext (sLit "bound by") , nest 2 $ ppr skol_info , nest 2 $ ptext (sLit "at") <+> ppr (tcl_loc env) ] ] ; mkErrorMsgFromCt ctxt ct (msg $$ tv_extra $$ extra) } -- Nastiest case: attempt to unify an untouchable variable | (implic:_) <- cec_encl ctxt -- Get the innermost context , Implic { ic_env = env, ic_given = given, ic_info = skol_info } <- implic = do { let msg = misMatchMsg oriented eq_rel ty1 ty2 tclvl_extra = nest 2 $ sep [ quotes (ppr tv1) <+> ptext (sLit "is untouchable") , nest 2 $ ptext (sLit "inside the constraints:") <+> pprEvVarTheta given , nest 2 $ ptext (sLit "bound by") <+> ppr skol_info , nest 2 $ ptext (sLit "at") <+> ppr (tcl_loc env) ] tv_extra = extraTyVarInfo ctxt tv1 ty2 add_sig = suggestAddSig ctxt ty1 ty2 ; mkErrorMsgFromCt ctxt ct (vcat [msg, tclvl_extra, tv_extra, add_sig, extra]) } | otherwise = reportEqErr ctxt extra ct oriented (mkTyVarTy tv1) ty2 -- This *can* happen (Trac #6123, and test T2627b) -- Consider an ambiguous top-level constraint (a ~ F a) -- Not an occurs check, because F is a type function. where occ_check_expand = occurCheckExpand dflags tv1 ty2 k1 = tyVarKind tv1 k2 = typeKind ty2 ty1 = mkTyVarTy tv1 eq_rel = ctEqRel ct mkEqInfoMsg :: Ct -> TcType -> TcType -> SDoc -- Report (a) ambiguity if either side is a type function application -- e.g. F a0 ~ Int -- (b) warning about injectivity if both sides are the same -- type function application F a ~ F b -- See Note [Non-injective type functions] mkEqInfoMsg ct ty1 ty2 = tyfun_msg $$ ambig_msg where mb_fun1 = isTyFun_maybe ty1 mb_fun2 = isTyFun_maybe ty2 ambig_msg | isJust mb_fun1 || isJust mb_fun2 = snd (mkAmbigMsg ct) | otherwise = empty tyfun_msg | Just tc1 <- mb_fun1 , Just tc2 <- mb_fun2 , tc1 == tc2 = ptext (sLit "NB:") <+> quotes (ppr tc1) <+> ptext (sLit "is a type function, and may not be injective") | otherwise = empty isUserSkolem :: ReportErrCtxt -> TcTyVar -> Bool -- See Note [Reporting occurs-check errors] isUserSkolem ctxt tv = isSkolemTyVar tv && any is_user_skol_tv (cec_encl ctxt) where is_user_skol_tv (Implic { ic_skols = sks, ic_info = skol_info }) = tv `elem` sks && is_user_skol_info skol_info is_user_skol_info (InferSkol {}) = False is_user_skol_info _ = True misMatchOrCND :: ReportErrCtxt -> Ct -> Maybe SwapFlag -> TcType -> TcType -> SDoc -- If oriented then ty1 is actual, ty2 is expected misMatchOrCND ctxt ct oriented ty1 ty2 | null givens || (isRigid ty1 && isRigid ty2) || isGivenCt ct -- If the equality is unconditionally insoluble -- or there is no context, don't report the context = misMatchMsg oriented (ctEqRel ct) ty1 ty2 | otherwise = couldNotDeduce givens ([mkTcEqPred ty1 ty2], orig) where givens = [ given | given@(_, _, no_eqs, _) <- getUserGivens ctxt, not no_eqs] -- Keep only UserGivens that have some equalities orig = TypeEqOrigin { uo_actual = ty1, uo_expected = ty2 } couldNotDeduce :: [UserGiven] -> (ThetaType, CtOrigin) -> SDoc couldNotDeduce givens (wanteds, orig) = vcat [ addArising orig (ptext (sLit "Could not deduce:") <+> pprTheta wanteds) , vcat (pp_givens givens)] pp_givens :: [UserGiven] -> [SDoc] pp_givens givens = case givens of [] -> [] (g:gs) -> ppr_given (ptext (sLit "from the context:")) g : map (ppr_given (ptext (sLit "or from:"))) gs where ppr_given herald (gs, skol_info, _, loc) = hang (herald <+> pprEvVarTheta gs) 2 (sep [ ptext (sLit "bound by") <+> ppr skol_info , ptext (sLit "at") <+> ppr loc]) extraTyVarInfo :: ReportErrCtxt -> TcTyVar -> TcType -> SDoc -- Add on extra info about skolem constants -- NB: The types themselves are already tidied extraTyVarInfo ctxt tv1 ty2 = nest 2 (tv_extra tv1 $$ ty_extra ty2) where implics = cec_encl ctxt ty_extra ty = case tcGetTyVar_maybe ty of Just tv -> tv_extra tv Nothing -> empty tv_extra tv | isTcTyVar tv, isSkolemTyVar tv , let pp_tv = quotes (ppr tv) = case tcTyVarDetails tv of SkolemTv {} -> pp_tv <+> pprSkol (getSkolemInfo implics tv) (getSrcLoc tv) FlatSkol {} -> pp_tv <+> ptext (sLit "is a flattening type variable") RuntimeUnk {} -> pp_tv <+> ptext (sLit "is an interactive-debugger skolem") MetaTv {} -> empty | otherwise -- Normal case = empty suggestAddSig :: ReportErrCtxt -> TcType -> TcType -> SDoc -- See Note [Suggest adding a type signature] suggestAddSig ctxt ty1 ty2 | null inferred_bndrs = empty | [bndr] <- inferred_bndrs = ptext (sLit "Possible fix: add a type signature for") <+> quotes (ppr bndr) | otherwise = ptext (sLit "Possible fix: add type signatures for some or all of") <+> (ppr inferred_bndrs) where inferred_bndrs = nub (get_inf ty1 ++ get_inf ty2) get_inf ty | Just tv <- tcGetTyVar_maybe ty , isTcTyVar tv, isSkolemTyVar tv , InferSkol prs <- getSkolemInfo (cec_encl ctxt) tv = map fst prs | otherwise = [] kindErrorMsg :: TcType -> TcType -> SDoc -- Types are already tidy kindErrorMsg ty1 ty2 = vcat [ ptext (sLit "Kind incompatibility when matching types:") , nest 2 (vcat [ ppr ty1 <+> dcolon <+> ppr k1 , ppr ty2 <+> dcolon <+> ppr k2 ]) ] where k1 = typeKind ty1 k2 = typeKind ty2 -------------------- misMatchMsg :: Maybe SwapFlag -> EqRel -> TcType -> TcType -> SDoc -- Types are already tidy -- If oriented then ty1 is actual, ty2 is expected misMatchMsg oriented eq_rel ty1 ty2 | Just IsSwapped <- oriented = misMatchMsg (Just NotSwapped) eq_rel ty2 ty1 | Just NotSwapped <- oriented = sep [ text "Couldn't match" <+> repr1 <+> text "expected" <+> what <+> quotes (ppr ty2) , nest (12 + extra_space) $ text "with" <+> repr2 <+> text "actual" <+> what <+> quotes (ppr ty1) , sameOccExtra ty2 ty1 ] | otherwise = sep [ text "Couldn't match" <+> repr1 <+> what <+> quotes (ppr ty1) , nest (15 + extra_space) $ text "with" <+> repr2 <+> quotes (ppr ty2) , sameOccExtra ty1 ty2 ] where what | isKind ty1 = ptext (sLit "kind") | otherwise = ptext (sLit "type") (repr1, repr2, extra_space) = case eq_rel of NomEq -> (empty, empty, 0) ReprEq -> (text "representation of", text "that of", 10) mkExpectedActualMsg :: Type -> Type -> CtOrigin -> (Maybe SwapFlag, SDoc) -- NotSwapped means (actual, expected), IsSwapped is the reverse mkExpectedActualMsg ty1 ty2 (TypeEqOrigin { uo_actual = act, uo_expected = exp }) | act `pickyEqType` ty1, exp `pickyEqType` ty2 = (Just NotSwapped, empty) | exp `pickyEqType` ty1, act `pickyEqType` ty2 = (Just IsSwapped, empty) | otherwise = (Nothing, msg) where msg = vcat [ text "Expected type:" <+> ppr exp , text " Actual type:" <+> ppr act ] mkExpectedActualMsg _ _ _ = panic "mkExprectedAcutalMsg" sameOccExtra :: TcType -> TcType -> SDoc -- See Note [Disambiguating (X ~ X) errors] sameOccExtra ty1 ty2 | Just (tc1, _) <- tcSplitTyConApp_maybe ty1 , Just (tc2, _) <- tcSplitTyConApp_maybe ty2 , let n1 = tyConName tc1 n2 = tyConName tc2 same_occ = nameOccName n1 == nameOccName n2 same_pkg = modulePackageKey (nameModule n1) == modulePackageKey (nameModule n2) , n1 /= n2 -- Different Names , same_occ -- but same OccName = ptext (sLit "NB:") <+> (ppr_from same_pkg n1 $$ ppr_from same_pkg n2) | otherwise = empty where ppr_from same_pkg nm | isGoodSrcSpan loc = hang (quotes (ppr nm) <+> ptext (sLit "is defined at")) 2 (ppr loc) | otherwise -- Imported things have an UnhelpfulSrcSpan = hang (quotes (ppr nm)) 2 (sep [ ptext (sLit "is defined in") <+> quotes (ppr (moduleName mod)) , ppUnless (same_pkg || pkg == mainPackageKey) $ nest 4 $ ptext (sLit "in package") <+> quotes (ppr pkg) ]) where pkg = modulePackageKey mod mod = nameModule nm loc = nameSrcSpan nm {- Note [Suggest adding a type signature] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The OutsideIn algorithm rejects GADT programs that don't have a principal type, and indeed some that do. Example: data T a where MkT :: Int -> T Int f (MkT n) = n Does this have type f :: T a -> a, or f :: T a -> Int? The error that shows up tends to be an attempt to unify an untouchable type variable. So suggestAddSig sees if the offending type variable is bound by an *inferred* signature, and suggests adding a declared signature instead. This initially came up in Trac #8968, concerning pattern synonyms. Note [Disambiguating (X ~ X) errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See Trac #8278 Note [Reporting occurs-check errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Given (a ~ [a]), if 'a' is a rigid type variable bound by a user-supplied type signature, then the best thing is to report that we can't unify a with [a], because a is a skolem variable. That avoids the confusing "occur-check" error message. But nowadays when inferring the type of a function with no type signature, even if there are errors inside, we still generalise its signature and carry on. For example f x = x:x Here we will infer somethiing like f :: forall a. a -> [a] with a suspended error of (a ~ [a]). So 'a' is now a skolem, but not one bound by the programmer! Here we really should report an occurs check. So isUserSkolem distinguishes the two. Note [Non-injective type functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's very confusing to get a message like Couldn't match expected type `Depend s' against inferred type `Depend s1' so mkTyFunInfoMsg adds: NB: `Depend' is type function, and hence may not be injective Warn of loopy local equalities that were dropped. ************************************************************************ * * Type-class errors * * ************************************************************************ -} mkDictErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg mkDictErr ctxt cts = ASSERT( not (null cts) ) do { inst_envs <- tcGetInstEnvs ; let (ct1:_) = cts -- ct1 just for its location min_cts = elim_superclasses cts ; lookups <- mapM (lookup_cls_inst inst_envs) min_cts ; let (no_inst_cts, overlap_cts) = partition is_no_inst lookups -- Report definite no-instance errors, -- or (iff there are none) overlap errors -- But we report only one of them (hence 'head') because they all -- have the same source-location origin, to try avoid a cascade -- of error from one location ; (ctxt, err) <- mk_dict_err ctxt (head (no_inst_cts ++ overlap_cts)) ; mkErrorMsgFromCt ctxt ct1 err } where no_givens = null (getUserGivens ctxt) is_no_inst (ct, (matches, unifiers, _)) = no_givens && null matches && (null unifiers || all (not . isAmbiguousTyVar) (varSetElems (tyVarsOfCt ct))) lookup_cls_inst inst_envs ct = do { tys_flat <- mapM quickFlattenTy tys -- Note [Flattening in error message generation] ; return (ct, lookupInstEnv True inst_envs clas tys_flat) } where (clas, tys) = getClassPredTys (ctPred ct) -- When simplifying [W] Ord (Set a), we need -- [W] Eq a, [W] Ord a -- but we really only want to report the latter elim_superclasses cts = filter (\ct -> any (eqPred (ctPred ct)) min_preds) cts where min_preds = mkMinimalBySCs (map ctPred cts) mk_dict_err :: ReportErrCtxt -> (Ct, ClsInstLookupResult) -> TcM (ReportErrCtxt, SDoc) -- Report an overlap error if this class constraint results -- from an overlap (returning Left clas), otherwise return (Right pred) mk_dict_err ctxt (ct, (matches, unifiers, unsafe_overlapped)) | null matches -- No matches but perhaps several unifiers = do { let (is_ambig, ambig_msg) = mkAmbigMsg ct ; (ctxt, binds_msg, _) <- relevantBindings True ctxt ct ; traceTc "mk_dict_err" (ppr ct $$ ppr is_ambig $$ ambig_msg) ; return (ctxt, cannot_resolve_msg is_ambig binds_msg ambig_msg) } | null unsafe_overlapped -- Some matches => overlap errors = return (ctxt, overlap_msg) | otherwise = return (ctxt, safe_haskell_msg) where orig = ctLocOrigin (ctLoc ct) pred = ctPred ct (clas, tys) = getClassPredTys pred ispecs = [ispec | (ispec, _) <- matches] unsafe_ispecs = [ispec | (ispec, _) <- unsafe_overlapped] givens = getUserGivens ctxt all_tyvars = all isTyVarTy tys cannot_resolve_msg has_ambig_tvs binds_msg ambig_msg = vcat [ addArising orig no_inst_msg , vcat (pp_givens givens) , ppWhen (has_ambig_tvs && not (null unifiers && null givens)) (vcat [ ambig_msg, binds_msg, potential_msg ]) , show_fixes (add_to_ctxt_fixes has_ambig_tvs ++ drv_fixes) ] potential_msg = ppWhen (not (null unifiers) && want_potential orig) $ hang (if isSingleton unifiers then ptext (sLit "Note: there is a potential instance available:") else ptext (sLit "Note: there are several potential instances:")) 2 (ppr_insts (sortBy fuzzyClsInstCmp unifiers)) -- Report "potential instances" only when the constraint arises -- directly from the user's use of an overloaded function want_potential (TypeEqOrigin {}) = False want_potential _ = True add_to_ctxt_fixes has_ambig_tvs | not has_ambig_tvs && all_tyvars , (orig:origs) <- usefulContext ctxt pred = [sep [ ptext (sLit "add") <+> pprParendType pred <+> ptext (sLit "to the context of") , nest 2 $ ppr_skol orig $$ vcat [ ptext (sLit "or") <+> ppr_skol orig | orig <- origs ] ] ] | otherwise = [] ppr_skol (PatSkol dc _) = ptext (sLit "the data constructor") <+> quotes (ppr dc) ppr_skol skol_info = ppr skol_info no_inst_msg | null givens && null matches = ptext (sLit "No instance for") <+> pprParendType pred $$ if type_has_arrow pred then nest 2 $ ptext (sLit "(maybe you haven't applied a function to enough arguments?)") else empty | otherwise = ptext (sLit "Could not deduce") <+> pprParendType pred type_has_arrow (TyVarTy _) = False type_has_arrow (AppTy t1 t2) = type_has_arrow t1 || type_has_arrow t2 type_has_arrow (TyConApp _ ts) = or $ map type_has_arrow ts type_has_arrow (FunTy _ _) = True type_has_arrow (ForAllTy _ t) = type_has_arrow t type_has_arrow (LitTy _) = False drv_fixes = case orig of DerivOrigin -> [drv_fix] DerivOriginDC {} -> [drv_fix] DerivOriginCoerce {} -> [drv_fix] _ -> [] drv_fix = hang (ptext (sLit "use a standalone 'deriving instance' declaration,")) 2 (ptext (sLit "so you can specify the instance context yourself")) -- Normal overlap error overlap_msg = ASSERT( not (null matches) ) vcat [ addArising orig (ptext (sLit "Overlapping instances for") <+> pprType (mkClassPred clas tys)) , ppUnless (null matching_givens) $ sep [ptext (sLit "Matching givens (or their superclasses):") , nest 2 (vcat matching_givens)] , sep [ptext (sLit "Matching instances:"), nest 2 (vcat [pprInstances ispecs, pprInstances unifiers])] , ppWhen (null matching_givens && isSingleton matches && null unifiers) $ -- Intuitively, some given matched the wanted in their -- flattened or rewritten (from given equalities) form -- but the matcher can't figure that out because the -- constraints are non-flat and non-rewritten so we -- simply report back the whole given -- context. Accelerate Smart.hs showed this problem. sep [ ptext (sLit "There exists a (perhaps superclass) match:") , nest 2 (vcat (pp_givens givens))] , ppWhen (isSingleton matches) $ parens (vcat [ ptext (sLit "The choice depends on the instantiation of") <+> quotes (pprWithCommas ppr (varSetElems (tyVarsOfTypes tys))) , ppWhen (null (matching_givens)) $ vcat [ ptext (sLit "To pick the first instance above, use IncoherentInstances") , ptext (sLit "when compiling the other instance declarations")] ])] where givens = getUserGivens ctxt matching_givens = mapMaybe matchable givens matchable (evvars,skol_info,_,loc) = case ev_vars_matching of [] -> Nothing _ -> Just $ hang (pprTheta ev_vars_matching) 2 (sep [ ptext (sLit "bound by") <+> ppr skol_info , ptext (sLit "at") <+> ppr loc]) where ev_vars_matching = filter ev_var_matches (map evVarPred evvars) ev_var_matches ty = case getClassPredTys_maybe ty of Just (clas', tys') | clas' == clas , Just _ <- tcMatchTys (tyVarsOfTypes tys) tys tys' -> True | otherwise -> any ev_var_matches (immSuperClasses clas' tys') Nothing -> False -- Overlap error because of Safe Haskell (first -- match should be the most specific match) safe_haskell_msg = ASSERT( length matches == 1 && not (null unsafe_ispecs) ) vcat [ addArising orig (ptext (sLit "Unsafe overlapping instances for") <+> pprType (mkClassPred clas tys)) , sep [ptext (sLit "The matching instance is:"), nest 2 (pprInstance $ head ispecs)] , vcat [ ptext $ sLit "It is compiled in a Safe module and as such can only" , ptext $ sLit "overlap instances from the same module, however it" , ptext $ sLit "overlaps the following instances from different modules:" , nest 2 (vcat [pprInstances $ unsafe_ispecs]) ] ] usefulContext :: ReportErrCtxt -> TcPredType -> [SkolemInfo] usefulContext ctxt pred = go (cec_encl ctxt) where pred_tvs = tyVarsOfType pred go [] = [] go (ic : ics) | implausible ic = rest | otherwise = ic_info ic : rest where -- Stop when the context binds a variable free in the predicate rest | any (`elemVarSet` pred_tvs) (ic_skols ic) = [] | otherwise = go ics implausible ic | null (ic_skols ic) = True | implausible_info (ic_info ic) = True | otherwise = False implausible_info (SigSkol (InfSigCtxt {}) _) = True implausible_info _ = False -- Do not suggest adding constraints to an *inferred* type signature! show_fixes :: [SDoc] -> SDoc show_fixes [] = empty show_fixes (f:fs) = sep [ ptext (sLit "Possible fix:") , nest 2 (vcat (f : map (ptext (sLit "or") <+>) fs))] ppr_insts :: [ClsInst] -> SDoc ppr_insts insts = pprInstances (take 3 insts) $$ dot_dot_message where n_extra = length insts - 3 dot_dot_message | n_extra <= 0 = empty | otherwise = ptext (sLit "...plus") <+> speakNOf n_extra (ptext (sLit "other")) ---------------------- quickFlattenTy :: TcType -> TcM TcType -- See Note [Flattening in error message generation] quickFlattenTy ty | Just ty' <- tcView ty = quickFlattenTy ty' quickFlattenTy ty@(TyVarTy {}) = return ty quickFlattenTy ty@(ForAllTy {}) = return ty -- See quickFlattenTy ty@(LitTy {}) = return ty -- Don't flatten because of the danger or removing a bound variable quickFlattenTy (AppTy ty1 ty2) = do { fy1 <- quickFlattenTy ty1 ; fy2 <- quickFlattenTy ty2 ; return (AppTy fy1 fy2) } quickFlattenTy (FunTy ty1 ty2) = do { fy1 <- quickFlattenTy ty1 ; fy2 <- quickFlattenTy ty2 ; return (FunTy fy1 fy2) } quickFlattenTy (TyConApp tc tys) | not (isTypeFamilyTyCon tc) = do { fys <- mapM quickFlattenTy tys ; return (TyConApp tc fys) } | otherwise = do { let (funtys,resttys) = splitAt (tyConArity tc) tys -- Ignore the arguments of the type family funtys ; v <- newMetaTyVar (TauTv False) (typeKind (TyConApp tc funtys)) ; flat_resttys <- mapM quickFlattenTy resttys ; return (foldl AppTy (mkTyVarTy v) flat_resttys) } {- Note [Flattening in error message generation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider (C (Maybe (F x))), where F is a type function, and we have instances C (Maybe Int) and C (Maybe a) Since (F x) might turn into Int, this is an overlap situation, and indeed (because of flattening) the main solver will have refrained from solving. But by the time we get to error message generation, we've un-flattened the constraint. So we must *re*-flatten it before looking up in the instance environment, lest we only report one matching instance when in fact there are two. Re-flattening is pretty easy, because we don't need to keep track of evidence. We don't re-use the code in TcCanonical because that's in the TcS monad, and we are in TcM here. Note [Quick-flatten polytypes] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we see C (Ix a => blah) or C (forall a. blah) we simply refrain from flattening any further. After all, there can be no instance declarations that match such things. And flattening under a for-all is problematic anyway; consider C (forall a. F a) Note [Suggest -fprint-explicit-kinds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It can be terribly confusing to get an error message like (Trac #9171) Couldn't match expected type ‘GetParam Base (GetParam Base Int)’ with actual type ‘GetParam Base (GetParam Base Int)’ The reason may be that the kinds don't match up. Typically you'll get more useful information, but not when it's as a result of ambiguity. This test suggests -fprint-explicit-kinds when all the ambiguous type variables are kind variables. -} mkAmbigMsg :: Ct -> (Bool, SDoc) mkAmbigMsg ct | null ambig_tkvs = (False, empty) | otherwise = (True, msg) where ambig_tkv_set = filterVarSet isAmbiguousTyVar (tyVarsOfCt ct) ambig_tkvs = varSetElems ambig_tkv_set (ambig_kvs, ambig_tvs) = partition isKindVar ambig_tkvs msg | any isRuntimeUnkSkol ambig_tkvs -- See Note [Runtime skolems] = vcat [ ptext (sLit "Cannot resolve unknown runtime type") <> plural ambig_tvs <+> pprQuotedList ambig_tvs , ptext (sLit "Use :print or :force to determine these types")] | not (null ambig_tvs) = pp_ambig (ptext (sLit "type")) ambig_tvs | otherwise -- All ambiguous kind variabes; suggest -fprint-explicit-kinds = vcat [ pp_ambig (ptext (sLit "kind")) ambig_kvs , sdocWithDynFlags suggest_explicit_kinds ] pp_ambig what tkvs = ptext (sLit "The") <+> what <+> ptext (sLit "variable") <> plural tkvs <+> pprQuotedList tkvs <+> is_or_are tkvs <+> ptext (sLit "ambiguous") is_or_are [_] = text "is" is_or_are _ = text "are" suggest_explicit_kinds dflags -- See Note [Suggest -fprint-explicit-kinds] | gopt Opt_PrintExplicitKinds dflags = empty | otherwise = ptext (sLit "Use -fprint-explicit-kinds to see the kind arguments") pprSkol :: SkolemInfo -> SrcLoc -> SDoc pprSkol UnkSkol _ = ptext (sLit "is an unknown type variable") pprSkol skol_info tv_loc = sep [ ptext (sLit "is a rigid type variable bound by"), sep [ppr skol_info, ptext (sLit "at") <+> ppr tv_loc]] getSkolemInfo :: [Implication] -> TcTyVar -> SkolemInfo -- Get the skolem info for a type variable -- from the implication constraint that binds it getSkolemInfo [] tv = pprPanic "No skolem info:" (ppr tv) getSkolemInfo (implic:implics) tv | tv `elem` ic_skols implic = ic_info implic | otherwise = getSkolemInfo implics tv ----------------------- -- relevantBindings looks at the value environment and finds values whose -- types mention any of the offending type variables. It has to be -- careful to zonk the Id's type first, so it has to be in the monad. -- We must be careful to pass it a zonked type variable, too. -- -- We always remove closed top-level bindings, though, -- since they are never relevant (cf Trac #8233) relevantBindings :: Bool -- True <=> filter by tyvar; False <=> no filtering -- See Trac #8191 -> ReportErrCtxt -> Ct -> TcM (ReportErrCtxt, SDoc, CtOrigin) -- Also returns the zonked and tidied CtOrigin of the constraint relevantBindings want_filtering ctxt ct = do { dflags <- getDynFlags ; (env1, tidy_orig) <- zonkTidyOrigin (cec_tidy ctxt) (ctLocOrigin loc) ; let ct_tvs = tyVarsOfCt ct `unionVarSet` extra_tvs -- For *kind* errors, report the relevant bindings of the -- enclosing *type* equality, because that's more useful for the programmer extra_tvs = case tidy_orig of KindEqOrigin t1 t2 _ -> tyVarsOfTypes [t1,t2] _ -> emptyVarSet ; traceTc "relevantBindings" $ vcat [ ppr ct , pprCtOrigin (ctLocOrigin loc) , ppr ct_tvs , ppr [id | TcIdBndr id _ <- tcl_bndrs lcl_env] ] ; (tidy_env', docs, discards) <- go env1 ct_tvs (maxRelevantBinds dflags) emptyVarSet [] False (tcl_bndrs lcl_env) -- tcl_bndrs has the innermost bindings first, -- which are probably the most relevant ones ; let doc = hang (ptext (sLit "Relevant bindings include")) 2 (vcat docs $$ max_msg) max_msg | discards = ptext (sLit "(Some bindings suppressed; use -fmax-relevant-binds=N or -fno-max-relevant-binds)") | otherwise = empty ; if null docs then return (ctxt, empty, tidy_orig) else return (ctxt { cec_tidy = tidy_env' }, doc, tidy_orig) } where loc = ctLoc ct lcl_env = ctLocEnv loc run_out :: Maybe Int -> Bool run_out Nothing = False run_out (Just n) = n <= 0 dec_max :: Maybe Int -> Maybe Int dec_max = fmap (\n -> n - 1) go :: TidyEnv -> TcTyVarSet -> Maybe Int -> TcTyVarSet -> [SDoc] -> Bool -- True <=> some filtered out due to lack of fuel -> [TcIdBinder] -> TcM (TidyEnv, [SDoc], Bool) -- The bool says if we filtered any out -- because of lack of fuel go tidy_env _ _ _ docs discards [] = return (tidy_env, reverse docs, discards) go tidy_env ct_tvs n_left tvs_seen docs discards (TcIdBndr id top_lvl : tc_bndrs) = do { (tidy_env', tidy_ty) <- zonkTidyTcType tidy_env (idType id) ; traceTc "relevantBindings 1" (ppr id <+> dcolon <+> ppr tidy_ty) ; let id_tvs = tyVarsOfType tidy_ty doc = sep [ pprPrefixOcc id <+> dcolon <+> ppr tidy_ty , nest 2 (parens (ptext (sLit "bound at") <+> ppr (getSrcLoc id)))] new_seen = tvs_seen `unionVarSet` id_tvs ; if (want_filtering && not opt_PprStyle_Debug && id_tvs `disjointVarSet` ct_tvs) -- We want to filter out this binding anyway -- so discard it silently then go tidy_env ct_tvs n_left tvs_seen docs discards tc_bndrs else if isTopLevel top_lvl && not (isNothing n_left) -- It's a top-level binding and we have not specified -- -fno-max-relevant-bindings, so discard it silently then go tidy_env ct_tvs n_left tvs_seen docs discards tc_bndrs else if run_out n_left && id_tvs `subVarSet` tvs_seen -- We've run out of n_left fuel and this binding only -- mentions aleady-seen type variables, so discard it then go tidy_env ct_tvs n_left tvs_seen docs True tc_bndrs -- Keep this binding, decrement fuel else go tidy_env' ct_tvs (dec_max n_left) new_seen (doc:docs) discards tc_bndrs } ----------------------- warnDefaulting :: [Ct] -> Type -> TcM () warnDefaulting wanteds default_ty = do { warn_default <- woptM Opt_WarnTypeDefaults ; env0 <- tcInitTidyEnv ; let tidy_env = tidyFreeTyVars env0 $ foldr (unionVarSet . tyVarsOfCt) emptyVarSet wanteds tidy_wanteds = map (tidyCt tidy_env) wanteds (loc, ppr_wanteds) = pprWithArising tidy_wanteds warn_msg = hang (ptext (sLit "Defaulting the following constraint(s) to type") <+> quotes (ppr default_ty)) 2 ppr_wanteds ; setCtLoc loc $ warnTc warn_default warn_msg } {- Note [Runtime skolems] ~~~~~~~~~~~~~~~~~~~~~~ We want to give a reasonably helpful error message for ambiguity arising from *runtime* skolems in the debugger. These are created by in RtClosureInspect.zonkRTTIType. ************************************************************************ * * Error from the canonicaliser These ones are called *during* constraint simplification * * ************************************************************************ -} solverDepthErrorTcS :: CtLoc -> TcType -> TcM a solverDepthErrorTcS loc ty = setCtLoc loc $ do { ty <- zonkTcType ty ; env0 <- tcInitTidyEnv ; let tidy_env = tidyFreeTyVars env0 (tyVarsOfType ty) tidy_ty = tidyType tidy_env ty msg = vcat [ text "Reduction stack overflow; size =" <+> ppr depth , hang (text "When simplifying the following type:") 2 (ppr tidy_ty) , note ] ; failWithTcM (tidy_env, msg) } where depth = ctLocDepth loc note = vcat [ text "Use -freduction-depth=0 to disable this check" , text "(any upper bound you could choose might fail unpredictably with" , text " minor updates to GHC, so disabling the check is recommended if" , text " you're sure that type checking should terminate)" ]
fmthoma/ghc
compiler/typecheck/TcErrors.hs
bsd-3-clause
72,845
1
21
22,355
15,070
7,671
7,399
-1
-1
{-# LANGUAGE BangPatterns, CPP, ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- -- The register allocator -- -- (c) The University of Glasgow 2004 -- ----------------------------------------------------------------------------- {- The algorithm is roughly: 1) Compute strongly connected components of the basic block list. 2) Compute liveness (mapping from pseudo register to point(s) of death?). 3) Walk instructions in each basic block. We keep track of (a) Free real registers (a bitmap?) (b) Current assignment of temporaries to machine registers and/or spill slots (call this the "assignment"). (c) Partial mapping from basic block ids to a virt-to-loc mapping. When we first encounter a branch to a basic block, we fill in its entry in this table with the current mapping. For each instruction: (a) For each temporary *read* by the instruction: If the temporary does not have a real register allocation: - Allocate a real register from the free list. If the list is empty: - Find a temporary to spill. Pick one that is not used in this instruction (ToDo: not used for a while...) - generate a spill instruction - If the temporary was previously spilled, generate an instruction to read the temp from its spill loc. (optimisation: if we can see that a real register is going to be used soon, then don't use it for allocation). (b) For each real register clobbered by this instruction: If a temporary resides in it, If the temporary is live after this instruction, Move the temporary to another (non-clobbered & free) reg, or spill it to memory. Mark the temporary as residing in both memory and a register if it was spilled (it might need to be read by this instruction). (ToDo: this is wrong for jump instructions?) We do this after step (a), because if we start with movq v1, %rsi which is an instruction that clobbers %rsi, if v1 currently resides in %rsi we want to get movq %rsi, %freereg movq %rsi, %rsi -- will disappear instead of movq %rsi, %freereg movq %freereg, %rsi (c) Update the current assignment (d) If the instruction is a branch: if the destination block already has a register assignment, Generate a new block with fixup code and redirect the jump to the new block. else, Update the block id->assignment mapping with the current assignment. (e) Delete all register assignments for temps which are read (only) and die here. Update the free register list. (f) Mark all registers clobbered by this instruction as not free, and mark temporaries which have been spilled due to clobbering as in memory (step (a) marks then as in both mem & reg). (g) For each temporary *written* by this instruction: Allocate a real register as for (b), spilling something else if necessary. - except when updating the assignment, drop any memory locations that the temporary was previously in, since they will be no longer valid after this instruction. (h) Delete all register assignments for temps which are written and die here (there should rarely be any). Update the free register list. (i) Rewrite the instruction with the new mapping. (j) For each spilled reg known to be now dead, re-add its stack slot to the free list. -} module RegAlloc.Linear.Main ( regAlloc, module RegAlloc.Linear.Base, module RegAlloc.Linear.Stats ) where #include "HsVersions.h" import RegAlloc.Linear.State import RegAlloc.Linear.Base import RegAlloc.Linear.StackMap import RegAlloc.Linear.FreeRegs import RegAlloc.Linear.Stats import RegAlloc.Linear.JoinToTargets import qualified RegAlloc.Linear.PPC.FreeRegs as PPC import qualified RegAlloc.Linear.SPARC.FreeRegs as SPARC import qualified RegAlloc.Linear.X86.FreeRegs as X86 import qualified RegAlloc.Linear.X86_64.FreeRegs as X86_64 import TargetReg import RegAlloc.Liveness import Instruction import Reg import BlockId import Cmm hiding (RegSet) import Digraph import DynFlags import Unique import UniqSet import UniqFM import UniqSupply import Outputable import Platform import Data.Maybe import Data.List import Control.Monad -- ----------------------------------------------------------------------------- -- Top level of the register allocator -- Allocate registers regAlloc :: (Outputable instr, Instruction instr) => DynFlags -> LiveCmmDecl statics instr -> UniqSM ( NatCmmDecl statics instr , Maybe Int -- number of extra stack slots required, -- beyond maxSpillSlots , Maybe RegAllocStats) regAlloc _ (CmmData sec d) = return ( CmmData sec d , Nothing , Nothing ) regAlloc _ (CmmProc (LiveInfo info _ _ _) lbl live []) = return ( CmmProc info lbl live (ListGraph []) , Nothing , Nothing ) regAlloc dflags (CmmProc static lbl live sccs) | LiveInfo info entry_ids@(first_id:_) (Just block_live) _ <- static = do -- do register allocation on each component. (final_blocks, stats, stack_use) <- linearRegAlloc dflags entry_ids block_live sccs -- make sure the block that was first in the input list -- stays at the front of the output let ((first':_), rest') = partition ((== first_id) . blockId) final_blocks let max_spill_slots = maxSpillSlots dflags extra_stack | stack_use > max_spill_slots = Just (stack_use - max_spill_slots) | otherwise = Nothing return ( CmmProc info lbl live (ListGraph (first' : rest')) , extra_stack , Just stats) -- bogus. to make non-exhaustive match warning go away. regAlloc _ (CmmProc _ _ _ _) = panic "RegAllocLinear.regAlloc: no match" -- ----------------------------------------------------------------------------- -- Linear sweep to allocate registers -- | Do register allocation on some basic blocks. -- But be careful to allocate a block in an SCC only if it has -- an entry in the block map or it is the first block. -- linearRegAlloc :: (Outputable instr, Instruction instr) => DynFlags -> [BlockId] -- ^ entry points -> BlockMap RegSet -- ^ live regs on entry to each basic block -> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths" -> UniqSM ([NatBasicBlock instr], RegAllocStats, Int) linearRegAlloc dflags entry_ids block_live sccs = case platformArch platform of ArchX86 -> go $ (frInitFreeRegs platform :: X86.FreeRegs) ArchX86_64 -> go $ (frInitFreeRegs platform :: X86_64.FreeRegs) ArchSPARC -> go $ (frInitFreeRegs platform :: SPARC.FreeRegs) ArchSPARC64 -> panic "linearRegAlloc ArchSPARC64" ArchPPC -> go $ (frInitFreeRegs platform :: PPC.FreeRegs) ArchARM _ _ _ -> panic "linearRegAlloc ArchARM" ArchARM64 -> panic "linearRegAlloc ArchARM64" ArchPPC_64 _ -> go $ (frInitFreeRegs platform :: PPC.FreeRegs) ArchAlpha -> panic "linearRegAlloc ArchAlpha" ArchMipseb -> panic "linearRegAlloc ArchMipseb" ArchMipsel -> panic "linearRegAlloc ArchMipsel" ArchJavaScript -> panic "linearRegAlloc ArchJavaScript" ArchUnknown -> panic "linearRegAlloc ArchUnknown" where go f = linearRegAlloc' dflags f entry_ids block_live sccs platform = targetPlatform dflags linearRegAlloc' :: (FR freeRegs, Outputable instr, Instruction instr) => DynFlags -> freeRegs -> [BlockId] -- ^ entry points -> BlockMap RegSet -- ^ live regs on entry to each basic block -> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths" -> UniqSM ([NatBasicBlock instr], RegAllocStats, Int) linearRegAlloc' dflags initFreeRegs entry_ids block_live sccs = do us <- getUniqueSupplyM let (_, stack, stats, blocks) = runR dflags emptyBlockMap initFreeRegs emptyRegMap (emptyStackMap dflags) us $ linearRA_SCCs entry_ids block_live [] sccs return (blocks, stats, getStackUse stack) linearRA_SCCs :: (FR freeRegs, Instruction instr, Outputable instr) => [BlockId] -> BlockMap RegSet -> [NatBasicBlock instr] -> [SCC (LiveBasicBlock instr)] -> RegM freeRegs [NatBasicBlock instr] linearRA_SCCs _ _ blocksAcc [] = return $ reverse blocksAcc linearRA_SCCs entry_ids block_live blocksAcc (AcyclicSCC block : sccs) = do blocks' <- processBlock block_live block linearRA_SCCs entry_ids block_live ((reverse blocks') ++ blocksAcc) sccs linearRA_SCCs entry_ids block_live blocksAcc (CyclicSCC blocks : sccs) = do blockss' <- process entry_ids block_live blocks [] (return []) False linearRA_SCCs entry_ids block_live (reverse (concat blockss') ++ blocksAcc) sccs {- from John Dias's patch 2008/10/16: The linear-scan allocator sometimes allocates a block before allocating one of its predecessors, which could lead to inconsistent allocations. Make it so a block is only allocated if a predecessor has set the "incoming" assignments for the block, or if it's the procedure's entry block. BL 2009/02: Careful. If the assignment for a block doesn't get set for some reason then this function will loop. We should probably do some more sanity checking to guard against this eventuality. -} process :: (FR freeRegs, Instruction instr, Outputable instr) => [BlockId] -> BlockMap RegSet -> [GenBasicBlock (LiveInstr instr)] -> [GenBasicBlock (LiveInstr instr)] -> [[NatBasicBlock instr]] -> Bool -> RegM freeRegs [[NatBasicBlock instr]] process _ _ [] [] accum _ = return $ reverse accum process entry_ids block_live [] next_round accum madeProgress | not madeProgress {- BUGS: There are so many unreachable blocks in the code the warnings are overwhelming. pprTrace "RegAlloc.Linear.Main.process: no progress made, bailing out." ( text "Unreachable blocks:" $$ vcat (map ppr next_round)) -} = return $ reverse accum | otherwise = process entry_ids block_live next_round [] accum False process entry_ids block_live (b@(BasicBlock id _) : blocks) next_round accum madeProgress = do block_assig <- getBlockAssigR if isJust (mapLookup id block_assig) || id `elem` entry_ids then do b' <- processBlock block_live b process entry_ids block_live blocks next_round (b' : accum) True else process entry_ids block_live blocks (b : next_round) accum madeProgress -- | Do register allocation on this basic block -- processBlock :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ live regs on entry to each basic block -> LiveBasicBlock instr -- ^ block to do register allocation on -> RegM freeRegs [NatBasicBlock instr] -- ^ block with registers allocated processBlock block_live (BasicBlock id instrs) = do initBlock id block_live (instrs', fixups) <- linearRA block_live [] [] id instrs return $ BasicBlock id instrs' : fixups -- | Load the freeregs and current reg assignment into the RegM state -- for the basic block with this BlockId. initBlock :: FR freeRegs => BlockId -> BlockMap RegSet -> RegM freeRegs () initBlock id block_live = do dflags <- getDynFlags let platform = targetPlatform dflags block_assig <- getBlockAssigR case mapLookup id block_assig of -- no prior info about this block: we must consider -- any fixed regs to be allocated, but we can ignore -- virtual regs (presumably this is part of a loop, -- and we'll iterate again). The assignment begins -- empty. Nothing -> do -- pprTrace "initFreeRegs" (text $ show initFreeRegs) (return ()) case mapLookup id block_live of Nothing -> setFreeRegsR (frInitFreeRegs platform) Just live -> setFreeRegsR $ foldr (frAllocateReg platform) (frInitFreeRegs platform) [ r | RegReal r <- nonDetEltsUFM live ] -- See Note [Unique Determinism and code generation] setAssigR emptyRegMap -- load info about register assignments leading into this block. Just (freeregs, assig) -> do setFreeRegsR freeregs setAssigR assig -- | Do allocation for a sequence of instructions. linearRA :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ map of what vregs are live on entry to each block. -> [instr] -- ^ accumulator for instructions already processed. -> [NatBasicBlock instr] -- ^ accumulator for blocks of fixup code. -> BlockId -- ^ id of the current block, for debugging. -> [LiveInstr instr] -- ^ liveness annotated instructions in this block. -> RegM freeRegs ( [instr] -- instructions after register allocation , [NatBasicBlock instr]) -- fresh blocks of fixup code. linearRA _ accInstr accFixup _ [] = return ( reverse accInstr -- instrs need to be returned in the correct order. , accFixup) -- it doesn't matter what order the fixup blocks are returned in. linearRA block_live accInstr accFixups id (instr:instrs) = do (accInstr', new_fixups) <- raInsn block_live accInstr id instr linearRA block_live accInstr' (new_fixups ++ accFixups) id instrs -- | Do allocation for a single instruction. raInsn :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ map of what vregs are love on entry to each block. -> [instr] -- ^ accumulator for instructions already processed. -> BlockId -- ^ the id of the current block, for debugging -> LiveInstr instr -- ^ the instr to have its regs allocated, with liveness info. -> RegM freeRegs ( [instr] -- new instructions , [NatBasicBlock instr]) -- extra fixup blocks raInsn _ new_instrs _ (LiveInstr ii Nothing) | Just n <- takeDeltaInstr ii = do setDeltaR n return (new_instrs, []) raInsn _ new_instrs _ (LiveInstr ii@(Instr i) Nothing) | isMetaInstr ii = return (i : new_instrs, []) raInsn block_live new_instrs id (LiveInstr (Instr instr) (Just live)) = do assig <- getAssigR -- If we have a reg->reg move between virtual registers, where the -- src register is not live after this instruction, and the dst -- register does not already have an assignment, -- and the source register is assigned to a register, not to a spill slot, -- then we can eliminate the instruction. -- (we can't eliminate it if the source register is on the stack, because -- we do not want to use one spill slot for different virtual registers) case takeRegRegMoveInstr instr of Just (src,dst) | src `elementOfUniqSet` (liveDieRead live), isVirtualReg dst, not (dst `elemUFM` assig), isRealReg src || isInReg src assig -> do case src of (RegReal rr) -> setAssigR (addToUFM assig dst (InReg rr)) -- if src is a fixed reg, then we just map dest to this -- reg in the assignment. src must be an allocatable reg, -- otherwise it wouldn't be in r_dying. _virt -> case lookupUFM assig src of Nothing -> panic "raInsn" Just loc -> setAssigR (addToUFM (delFromUFM assig src) dst loc) -- we have eliminated this instruction {- freeregs <- getFreeRegsR assig <- getAssigR pprTrace "raInsn" (text "ELIMINATED: " <> docToSDoc (pprInstr instr) $$ ppr r_dying <+> ppr w_dying $$ text (show freeregs) $$ ppr assig) $ do -} return (new_instrs, []) _ -> genRaInsn block_live new_instrs id instr (nonDetEltsUFM $ liveDieRead live) (nonDetEltsUFM $ liveDieWrite live) -- See Note [Unique Determinism and code generation] raInsn _ _ _ instr = pprPanic "raInsn" (text "no match for:" <> ppr instr) -- ToDo: what can we do about -- -- R1 = x -- jump I64[x] // [R1] -- -- where x is mapped to the same reg as R1. We want to coalesce x and -- R1, but the register allocator doesn't know whether x will be -- assigned to again later, in which case x and R1 should be in -- different registers. Right now we assume the worst, and the -- assignment to R1 will clobber x, so we'll spill x into another reg, -- generating another reg->reg move. isInReg :: Reg -> RegMap Loc -> Bool isInReg src assig | Just (InReg _) <- lookupUFM assig src = True | otherwise = False genRaInsn :: (FR freeRegs, Instruction instr, Outputable instr) => BlockMap RegSet -> [instr] -> BlockId -> instr -> [Reg] -> [Reg] -> RegM freeRegs ([instr], [NatBasicBlock instr]) genRaInsn block_live new_instrs block_id instr r_dying w_dying = do dflags <- getDynFlags let platform = targetPlatform dflags case regUsageOfInstr platform instr of { RU read written -> do let real_written = [ rr | (RegReal rr) <- written ] let virt_written = [ vr | (RegVirtual vr) <- written ] -- we don't need to do anything with real registers that are -- only read by this instr. (the list is typically ~2 elements, -- so using nub isn't a problem). let virt_read = nub [ vr | (RegVirtual vr) <- read ] -- debugging {- freeregs <- getFreeRegsR assig <- getAssigR pprDebugAndThen (defaultDynFlags Settings{ sTargetPlatform=platform }) trace "genRaInsn" (ppr instr $$ text "r_dying = " <+> ppr r_dying $$ text "w_dying = " <+> ppr w_dying $$ text "virt_read = " <+> ppr virt_read $$ text "virt_written = " <+> ppr virt_written $$ text "freeregs = " <+> text (show freeregs) $$ text "assig = " <+> ppr assig) $ do -} -- (a), (b) allocate real regs for all regs read by this instruction. (r_spills, r_allocd) <- allocateRegsAndSpill True{-reading-} virt_read [] [] virt_read -- (c) save any temporaries which will be clobbered by this instruction clobber_saves <- saveClobberedTemps real_written r_dying -- (d) Update block map for new destinations -- NB. do this before removing dead regs from the assignment, because -- these dead regs might in fact be live in the jump targets (they're -- only dead in the code that follows in the current basic block). (fixup_blocks, adjusted_instr) <- joinToTargets block_live block_id instr -- (e) Delete all register assignments for temps which are read -- (only) and die here. Update the free register list. releaseRegs r_dying -- (f) Mark regs which are clobbered as unallocatable clobberRegs real_written -- (g) Allocate registers for temporaries *written* (only) (w_spills, w_allocd) <- allocateRegsAndSpill False{-writing-} virt_written [] [] virt_written -- (h) Release registers for temps which are written here and not -- used again. releaseRegs w_dying let -- (i) Patch the instruction patch_map = listToUFM [ (t, RegReal r) | (t, r) <- zip virt_read r_allocd ++ zip virt_written w_allocd ] patched_instr = patchRegsOfInstr adjusted_instr patchLookup patchLookup x = case lookupUFM patch_map x of Nothing -> x Just y -> y -- (j) free up stack slots for dead spilled regs -- TODO (can't be bothered right now) -- erase reg->reg moves where the source and destination are the same. -- If the src temp didn't die in this instr but happened to be allocated -- to the same real reg as the destination, then we can erase the move anyway. let squashed_instr = case takeRegRegMoveInstr patched_instr of Just (src, dst) | src == dst -> [] _ -> [patched_instr] let code = squashed_instr ++ w_spills ++ reverse r_spills ++ clobber_saves ++ new_instrs -- pprTrace "patched-code" ((vcat $ map (docToSDoc . pprInstr) code)) $ do -- pprTrace "pached-fixup" ((ppr fixup_blocks)) $ do return (code, fixup_blocks) } -- ----------------------------------------------------------------------------- -- releaseRegs releaseRegs :: FR freeRegs => [Reg] -> RegM freeRegs () releaseRegs regs = do dflags <- getDynFlags let platform = targetPlatform dflags assig <- getAssigR free <- getFreeRegsR let loop assig !free [] = do setAssigR assig; setFreeRegsR free; return () loop assig !free (RegReal rr : rs) = loop assig (frReleaseReg platform rr free) rs loop assig !free (r:rs) = case lookupUFM assig r of Just (InBoth real _) -> loop (delFromUFM assig r) (frReleaseReg platform real free) rs Just (InReg real) -> loop (delFromUFM assig r) (frReleaseReg platform real free) rs _ -> loop (delFromUFM assig r) free rs loop assig free regs -- ----------------------------------------------------------------------------- -- Clobber real registers -- For each temp in a register that is going to be clobbered: -- - if the temp dies after this instruction, do nothing -- - otherwise, put it somewhere safe (another reg if possible, -- otherwise spill and record InBoth in the assignment). -- - for allocateRegs on the temps *read*, -- - clobbered regs are allocatable. -- -- for allocateRegs on the temps *written*, -- - clobbered regs are not allocatable. -- saveClobberedTemps :: (Instruction instr, FR freeRegs) => [RealReg] -- real registers clobbered by this instruction -> [Reg] -- registers which are no longer live after this insn -> RegM freeRegs [instr] -- return: instructions to spill any temps that will -- be clobbered. saveClobberedTemps [] _ = return [] saveClobberedTemps clobbered dying = do assig <- getAssigR let to_spill = [ (temp,reg) | (temp, InReg reg) <- nonDetUFMToList assig -- This is non-deterministic but we do not -- currently support deterministic code-generation. -- See Note [Unique Determinism and code generation] , any (realRegsAlias reg) clobbered , temp `notElem` map getUnique dying ] (instrs,assig') <- clobber assig [] to_spill setAssigR assig' return instrs where clobber assig instrs [] = return (instrs, assig) clobber assig instrs ((temp, reg) : rest) = do dflags <- getDynFlags let platform = targetPlatform dflags freeRegs <- getFreeRegsR let regclass = targetClassOfRealReg platform reg freeRegs_thisClass = frGetFreeRegs platform regclass freeRegs case filter (`notElem` clobbered) freeRegs_thisClass of -- (1) we have a free reg of the right class that isn't -- clobbered by this instruction; use it to save the -- clobbered value. (my_reg : _) -> do setFreeRegsR (frAllocateReg platform my_reg freeRegs) let new_assign = addToUFM assig temp (InReg my_reg) let instr = mkRegRegMoveInstr platform (RegReal reg) (RegReal my_reg) clobber new_assign (instr : instrs) rest -- (2) no free registers: spill the value [] -> do (spill, slot) <- spillR (RegReal reg) temp -- record why this reg was spilled for profiling recordSpill (SpillClobber temp) let new_assign = addToUFM assig temp (InBoth reg slot) clobber new_assign (spill : instrs) rest -- | Mark all these real regs as allocated, -- and kick out their vreg assignments. -- clobberRegs :: FR freeRegs => [RealReg] -> RegM freeRegs () clobberRegs [] = return () clobberRegs clobbered = do dflags <- getDynFlags let platform = targetPlatform dflags freeregs <- getFreeRegsR setFreeRegsR $! foldr (frAllocateReg platform) freeregs clobbered assig <- getAssigR setAssigR $! clobber assig (nonDetUFMToList assig) -- This is non-deterministic but we do not -- currently support deterministic code-generation. -- See Note [Unique Determinism and code generation] where -- if the temp was InReg and clobbered, then we will have -- saved it in saveClobberedTemps above. So the only case -- we have to worry about here is InBoth. Note that this -- also catches temps which were loaded up during allocation -- of read registers, not just those saved in saveClobberedTemps. clobber assig [] = assig clobber assig ((temp, InBoth reg slot) : rest) | any (realRegsAlias reg) clobbered = clobber (addToUFM assig temp (InMem slot)) rest clobber assig (_:rest) = clobber assig rest -- ----------------------------------------------------------------------------- -- allocateRegsAndSpill -- Why are we performing a spill? data SpillLoc = ReadMem StackSlot -- reading from register only in memory | WriteNew -- writing to a new variable | WriteMem -- writing to register only in memory -- Note that ReadNew is not valid, since you don't want to be reading -- from an uninitialized register. We also don't need the location of -- the register in memory, since that will be invalidated by the write. -- Technically, we could coalesce WriteNew and WriteMem into a single -- entry as well. -- EZY -- This function does several things: -- For each temporary referred to by this instruction, -- we allocate a real register (spilling another temporary if necessary). -- We load the temporary up from memory if necessary. -- We also update the register assignment in the process, and -- the list of free registers and free stack slots. allocateRegsAndSpill :: (FR freeRegs, Outputable instr, Instruction instr) => Bool -- True <=> reading (load up spilled regs) -> [VirtualReg] -- don't push these out -> [instr] -- spill insns -> [RealReg] -- real registers allocated (accum.) -> [VirtualReg] -- temps to allocate -> RegM freeRegs ( [instr] , [RealReg]) allocateRegsAndSpill _ _ spills alloc [] = return (spills, reverse alloc) allocateRegsAndSpill reading keep spills alloc (r:rs) = do assig <- getAssigR let doSpill = allocRegsAndSpill_spill reading keep spills alloc r rs assig case lookupUFM assig r of -- case (1a): already in a register Just (InReg my_reg) -> allocateRegsAndSpill reading keep spills (my_reg:alloc) rs -- case (1b): already in a register (and memory) -- NB1. if we're writing this register, update its assignment to be -- InReg, because the memory value is no longer valid. -- NB2. This is why we must process written registers here, even if they -- are also read by the same instruction. Just (InBoth my_reg _) -> do when (not reading) (setAssigR (addToUFM assig r (InReg my_reg))) allocateRegsAndSpill reading keep spills (my_reg:alloc) rs -- Not already in a register, so we need to find a free one... Just (InMem slot) | reading -> doSpill (ReadMem slot) | otherwise -> doSpill WriteMem Nothing | reading -> pprPanic "allocateRegsAndSpill: Cannot read from uninitialized register" (ppr r) -- NOTE: if the input to the NCG contains some -- unreachable blocks with junk code, this panic -- might be triggered. Make sure you only feed -- sensible code into the NCG. In CmmPipeline we -- call removeUnreachableBlocks at the end for this -- reason. | otherwise -> doSpill WriteNew -- reading is redundant with reason, but we keep it around because it's -- convenient and it maintains the recursive structure of the allocator. -- EZY allocRegsAndSpill_spill :: (FR freeRegs, Instruction instr, Outputable instr) => Bool -> [VirtualReg] -> [instr] -> [RealReg] -> VirtualReg -> [VirtualReg] -> UniqFM Loc -> SpillLoc -> RegM freeRegs ([instr], [RealReg]) allocRegsAndSpill_spill reading keep spills alloc r rs assig spill_loc = do dflags <- getDynFlags let platform = targetPlatform dflags freeRegs <- getFreeRegsR let freeRegs_thisClass = frGetFreeRegs platform (classOfVirtualReg r) freeRegs case freeRegs_thisClass of -- case (2): we have a free register (my_reg : _) -> do spills' <- loadTemp r spill_loc my_reg spills setAssigR (addToUFM assig r $! newLocation spill_loc my_reg) setFreeRegsR $ frAllocateReg platform my_reg freeRegs allocateRegsAndSpill reading keep spills' (my_reg : alloc) rs -- case (3): we need to push something out to free up a register [] -> do let keep' = map getUnique keep -- the vregs we could kick out that are already in a slot let candidates_inBoth = [ (temp, reg, mem) | (temp, InBoth reg mem) <- nonDetUFMToList assig -- This is non-deterministic but we do not -- currently support deterministic code-generation. -- See Note [Unique Determinism and code generation] , temp `notElem` keep' , targetClassOfRealReg platform reg == classOfVirtualReg r ] -- the vregs we could kick out that are only in a reg -- this would require writing the reg to a new slot before using it. let candidates_inReg = [ (temp, reg) | (temp, InReg reg) <- nonDetUFMToList assig -- This is non-deterministic but we do not -- currently support deterministic code-generation. -- See Note [Unique Determinism and code generation] , temp `notElem` keep' , targetClassOfRealReg platform reg == classOfVirtualReg r ] let result -- we have a temporary that is in both register and mem, -- just free up its register for use. | (temp, my_reg, slot) : _ <- candidates_inBoth = do spills' <- loadTemp r spill_loc my_reg spills let assig1 = addToUFM assig temp (InMem slot) let assig2 = addToUFM assig1 r $! newLocation spill_loc my_reg setAssigR assig2 allocateRegsAndSpill reading keep spills' (my_reg:alloc) rs -- otherwise, we need to spill a temporary that currently -- resides in a register. | (temp_to_push_out, (my_reg :: RealReg)) : _ <- candidates_inReg = do (spill_insn, slot) <- spillR (RegReal my_reg) temp_to_push_out let spill_store = (if reading then id else reverse) [ -- COMMENT (fsLit "spill alloc") spill_insn ] -- record that this temp was spilled recordSpill (SpillAlloc temp_to_push_out) -- update the register assignment let assig1 = addToUFM assig temp_to_push_out (InMem slot) let assig2 = addToUFM assig1 r $! newLocation spill_loc my_reg setAssigR assig2 -- if need be, load up a spilled temp into the reg we've just freed up. spills' <- loadTemp r spill_loc my_reg spills allocateRegsAndSpill reading keep (spill_store ++ spills') (my_reg:alloc) rs -- there wasn't anything to spill, so we're screwed. | otherwise = pprPanic ("RegAllocLinear.allocRegsAndSpill: no spill candidates\n") $ vcat [ text "allocating vreg: " <> text (show r) , text "assignment: " <> ppr assig , text "freeRegs: " <> text (show freeRegs) , text "initFreeRegs: " <> text (show (frInitFreeRegs platform `asTypeOf` freeRegs)) ] result -- | Calculate a new location after a register has been loaded. newLocation :: SpillLoc -> RealReg -> Loc -- if the tmp was read from a slot, then now its in a reg as well newLocation (ReadMem slot) my_reg = InBoth my_reg slot -- writes will always result in only the register being available newLocation _ my_reg = InReg my_reg -- | Load up a spilled temporary if we need to (read from memory). loadTemp :: (Instruction instr) => VirtualReg -- the temp being loaded -> SpillLoc -- the current location of this temp -> RealReg -- the hreg to load the temp into -> [instr] -> RegM freeRegs [instr] loadTemp vreg (ReadMem slot) hreg spills = do insn <- loadR (RegReal hreg) slot recordSpill (SpillLoad $ getUnique vreg) return $ {- COMMENT (fsLit "spill load") : -} insn : spills loadTemp _ _ _ spills = return spills
sgillespie/ghc
compiler/nativeGen/RegAlloc/Linear/Main.hs
bsd-3-clause
37,774
6
25
13,350
5,737
2,935
2,802
459
13
{-# LANGUAGE CPP, MagicHash #-} ----------------------------------------------------------------------------- -- | -- Module : Haddock.Interface.AttachInstances -- Copyright : (c) Simon Marlow 2006, -- David Waern 2006-2009, -- Isaac Dupree 2009 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable ----------------------------------------------------------------------------- module Haddock.Interface.AttachInstances (attachInstances) where import Haddock.Types import Haddock.Convert import Haddock.GhcUtils import Control.Arrow hiding ((<+>)) import Data.List import Data.Ord (comparing) import Data.Function (on) import Data.Maybe ( maybeToList, mapMaybe ) import qualified Data.Map as Map import qualified Data.Set as Set import Class import DynFlags import CoreSyn (isOrphan) import ErrUtils import FamInstEnv import FastString import GHC import GhcMonad (withSession) import InstEnv import MonadUtils (liftIO) import Name import Outputable (text, sep, (<+>)) import PrelNames import SrcLoc import TcRnDriver (tcRnGetInfo) import TyCon import TyCoRep import TysPrim( funTyCon ) import Var hiding (varName) #define FSLIT(x) (mkFastString# (x#)) type ExportedNames = Set.Set Name type Modules = Set.Set Module type ExportInfo = (ExportedNames, Modules) -- Also attaches fixities attachInstances :: ExportInfo -> [Interface] -> InstIfaceMap -> Ghc [Interface] attachInstances expInfo ifaces instIfaceMap = mapM attach ifaces where -- TODO: take an IfaceMap as input ifaceMap = Map.fromList [ (ifaceMod i, i) | i <- ifaces ] attach iface = do newItems <- mapM (attachToExportItem expInfo iface ifaceMap instIfaceMap) (ifaceExportItems iface) let orphanInstances = attachOrphanInstances expInfo iface ifaceMap instIfaceMap (ifaceInstances iface) return $ iface { ifaceExportItems = newItems , ifaceOrphanInstances = orphanInstances } attachOrphanInstances :: ExportInfo -> Interface -> IfaceMap -> InstIfaceMap -> [ClsInst] -> [DocInstance Name] attachOrphanInstances expInfo iface ifaceMap instIfaceMap cls_instances = [ (synifyInstHead i, instLookup instDocMap n iface ifaceMap instIfaceMap, (L (getSrcSpan n) n)) | let is = [ (instanceSig i, getName i) | i <- cls_instances, isOrphan (is_orphan i) ] , (i@(_,_,cls,tys), n) <- sortBy (comparing $ first instHead) is , not $ isInstanceHidden expInfo cls tys ] attachToExportItem :: ExportInfo -> Interface -> IfaceMap -> InstIfaceMap -> ExportItem Name -> Ghc (ExportItem Name) attachToExportItem expInfo iface ifaceMap instIfaceMap export = case attachFixities export of e@ExportDecl { expItemDecl = L eSpan (TyClD d) } -> do mb_info <- getAllInfo (tcdName d) insts <- case mb_info of Just (_, _, cls_instances, fam_instances) -> let fam_insts = [ (synifyFamInst i opaque, doc,spanNameE n (synifyFamInst i opaque) (L eSpan (tcdName d)) ) | i <- sortBy (comparing instFam) fam_instances , let n = getName i , let doc = instLookup instDocMap n iface ifaceMap instIfaceMap , not $ isNameHidden expInfo (fi_fam i) , not $ any (isTypeHidden expInfo) (fi_tys i) , let opaque = isTypeHidden expInfo (fi_rhs i) ] cls_insts = [ (synifyInstHead i, instLookup instDocMap n iface ifaceMap instIfaceMap, spanName n (synifyInstHead i) (L eSpan (tcdName d))) | let is = [ (instanceSig i, getName i) | i <- cls_instances ] , (i@(_,_,cls,tys), n) <- sortBy (comparing $ first instHead) is , not $ isInstanceHidden expInfo cls tys ] -- fam_insts but with failing type fams filtered out cleanFamInsts = [ (fi, n, L l r) | (Right fi, n, L l (Right r)) <- fam_insts ] famInstErrs = [ errm | (Left errm, _, _) <- fam_insts ] in do dfs <- getDynFlags let mkBug = (text "haddock-bug:" <+>) . text liftIO $ putMsg dfs (sep $ map mkBug famInstErrs) return $ cls_insts ++ cleanFamInsts Nothing -> return [] return $ e { expItemInstances = insts } e -> return e where attachFixities e@ExportDecl{ expItemDecl = L _ d } = e { expItemFixities = nubBy ((==) `on` fst) $ expItemFixities e ++ [ (n',f) | n <- getMainDeclBinder d , Just subs <- [instLookup instSubMap n iface ifaceMap instIfaceMap] , n' <- n : subs , Just f <- [instLookup instFixMap n' iface ifaceMap instIfaceMap] ] } attachFixities e = e -- spanName: attach the location to the name that is the same file as the instance location spanName s (InstHead { ihdClsName = clsn }) (L instL instn) = let s1 = getSrcSpan s sn = if srcSpanFileName_maybe s1 == srcSpanFileName_maybe instL then instn else clsn in L (getSrcSpan s) sn -- spanName on Either spanNameE s (Left e) _ = L (getSrcSpan s) (Left e) spanNameE s (Right ok) linst = let L l r = spanName s ok linst in L l (Right r) instLookup :: (InstalledInterface -> Map.Map Name a) -> Name -> Interface -> IfaceMap -> InstIfaceMap -> Maybe a instLookup f name iface ifaceMap instIfaceMap = case Map.lookup name (f $ toInstalledIface iface) of res@(Just _) -> res Nothing -> do let ifaceMaps = Map.union (fmap toInstalledIface ifaceMap) instIfaceMap iface' <- Map.lookup (nameModule name) ifaceMaps Map.lookup name (f iface') -- | Like GHC's getInfo but doesn't cut things out depending on the -- interative context, which we don't set sufficiently anyway. getAllInfo :: GhcMonad m => Name -> m (Maybe (TyThing,Fixity,[ClsInst],[FamInst])) getAllInfo name = withSession $ \hsc_env -> do (_msgs, r) <- liftIO $ tcRnGetInfo hsc_env name return r -------------------------------------------------------------------------------- -- Collecting and sorting instances -------------------------------------------------------------------------------- -- | Simplified type for sorting types, ignoring qualification (not visible -- in Haddock output) and unifying special tycons with normal ones. -- For the benefit of the user (looks nice and predictable) and the -- tests (which prefer output to be deterministic). data SimpleType = SimpleType Name [SimpleType] | SimpleTyLit TyLit deriving (Eq,Ord) instHead :: ([TyVar], [PredType], Class, [Type]) -> ([Int], Name, [SimpleType]) instHead (_, _, cls, args) = (map argCount args, className cls, map simplify args) argCount :: Type -> Int argCount (AppTy t _) = argCount t + 1 argCount (TyConApp _ ts) = length ts argCount (ForAllTy (Anon _) _ ) = 2 argCount (ForAllTy _ t) = argCount t argCount (CastTy t _) = argCount t argCount _ = 0 simplify :: Type -> SimpleType simplify (ForAllTy (Anon t1) t2) = SimpleType funTyConName [simplify t1, simplify t2] simplify (ForAllTy _ t) = simplify t simplify (AppTy t1 t2) = SimpleType s (ts ++ maybeToList (simplify_maybe t2)) where (SimpleType s ts) = simplify t1 simplify (TyVarTy v) = SimpleType (tyVarName v) [] simplify (TyConApp tc ts) = SimpleType (tyConName tc) (mapMaybe simplify_maybe ts) simplify (LitTy l) = SimpleTyLit l simplify (CastTy ty _) = simplify ty simplify (CoercionTy _) = error "simplify:Coercion" simplify_maybe :: Type -> Maybe SimpleType simplify_maybe (CoercionTy {}) = Nothing simplify_maybe ty = Just (simplify ty) -- Used for sorting instFam :: FamInst -> ([Int], Name, [SimpleType], Int, SimpleType) instFam FamInst { fi_fam = n, fi_tys = ts, fi_rhs = t } = (map argCount ts, n, map simplify ts, argCount t, simplify t) funTyConName :: Name funTyConName = mkWiredInName gHC_PRIM (mkOccNameFS tcName FSLIT("(->)")) funTyConKey (ATyCon funTyCon) -- Relevant TyCon BuiltInSyntax -------------------------------------------------------------------------------- -- Filtering hidden instances -------------------------------------------------------------------------------- -- | A class or data type is hidden iff -- -- * it is defined in one of the modules that are being processed -- -- * and it is not exported by any non-hidden module isNameHidden :: ExportInfo -> Name -> Bool isNameHidden (names, modules) name = nameModule name `Set.member` modules && not (name `Set.member` names) -- | We say that an instance is «hidden» iff its class or any (part) -- of its type(s) is hidden. isInstanceHidden :: ExportInfo -> Class -> [Type] -> Bool isInstanceHidden expInfo cls tys = instClassHidden || instTypeHidden where instClassHidden :: Bool instClassHidden = isNameHidden expInfo $ getName cls instTypeHidden :: Bool instTypeHidden = any (isTypeHidden expInfo) tys isTypeHidden :: ExportInfo -> Type -> Bool isTypeHidden expInfo = typeHidden where typeHidden :: Type -> Bool typeHidden t = case t of TyVarTy {} -> False AppTy t1 t2 -> typeHidden t1 || typeHidden t2 TyConApp tcon args -> nameHidden (getName tcon) || any typeHidden args ForAllTy bndr ty -> typeHidden (binderType bndr) || typeHidden ty LitTy _ -> False CastTy ty _ -> typeHidden ty CoercionTy {} -> False nameHidden :: Name -> Bool nameHidden = isNameHidden expInfo
Helkafen/haddock
haddock-api/src/Haddock/Interface/AttachInstances.hs
bsd-2-clause
9,858
106
23
2,499
2,693
1,438
1,255
170
7
-- | Some helpers for dealing with WAI 'Header's. module Network.Wai.Header ( contentLength ) where import qualified Data.ByteString.Char8 as S8 import Network.HTTP.Types as H -- | More useful for a response. A Wai Request already has a requestBodyLength contentLength :: [(HeaderName, S8.ByteString)] -> Maybe Integer contentLength hdrs = lookup H.hContentLength hdrs >>= readInt readInt :: S8.ByteString -> Maybe Integer readInt bs = case S8.readInteger bs of Just (i, "") -> Just i _ -> Nothing
erikd/wai
wai-extra/Network/Wai/Header.hs
mit
530
0
9
107
128
72
56
11
2
{-# LANGUAGE PatternGuards, ExistentialQuantification, CPP #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.Core.Execute (execute) where import Idris.AbsSyntax import Idris.AbsSyntaxTree import IRTS.Lang(FDesc(..), FType(..)) import Idris.Primitives(Prim(..), primitives) import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.CaseTree import Idris.Error import Debug.Trace import Util.DynamicLinker import Util.System import Control.Applicative hiding (Const) import Control.Exception import Control.Monad.Trans import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE) import Control.Monad hiding (forM) import Data.Maybe import Data.Bits import Data.Traversable (forM) import Data.Time.Clock.POSIX (getPOSIXTime) import qualified Data.Map as M #ifdef IDRIS_FFI import Foreign.LibFFI import Foreign.C.String import Foreign.Marshal.Alloc (free) import Foreign.Ptr #endif import System.IO #ifndef IDRIS_FFI execute :: Term -> Idris Term execute tm = fail "libffi not supported, rebuild Idris with -f FFI" #else -- else is rest of file readMay :: (Read a) => String -> Maybe a readMay s = case reads s of [(x, "")] -> Just x _ -> Nothing data Lazy = Delayed ExecEnv Context Term | Forced ExecVal deriving Show data ExecState = ExecState { exec_dynamic_libs :: [DynamicLib] -- ^ Dynamic libs from idris monad , binderNames :: [Name] -- ^ Used to uniquify binders when converting to TT } data ExecVal = EP NameType Name ExecVal | EV Int | EBind Name (Binder ExecVal) (ExecVal -> Exec ExecVal) | EApp ExecVal ExecVal | EType UExp | EUType Universe | EErased | EConstant Const | forall a. EPtr (Ptr a) | EThunk Context ExecEnv Term | EHandle Handle instance Show ExecVal where show (EP _ n _) = show n show (EV i) = "!!V" ++ show i ++ "!!" show (EBind n b body) = "EBind " ++ show b ++ " <<fn>>" show (EApp e1 e2) = show e1 ++ " (" ++ show e2 ++ ")" show (EType _) = "Type" show (EUType _) = "UType" show EErased = "[__]" show (EConstant c) = show c show (EPtr p) = "<<ptr " ++ show p ++ ">>" show (EThunk _ env tm) = "<<thunk " ++ show env ++ "||||" ++ show tm ++ ">>" show (EHandle h) = "<<handle " ++ show h ++ ">>" toTT :: ExecVal -> Exec Term toTT (EP nt n ty) = (P nt n) <$> (toTT ty) toTT (EV i) = return $ V i toTT (EBind n b body) = do n' <- newN n body' <- body $ EP Bound n' EErased b' <- fixBinder b Bind n' b' <$> toTT body' where fixBinder (Lam t) = Lam <$> toTT t fixBinder (Pi i t k) = Pi i <$> toTT t <*> toTT k fixBinder (Let t1 t2) = Let <$> toTT t1 <*> toTT t2 fixBinder (NLet t1 t2) = NLet <$> toTT t1 <*> toTT t2 fixBinder (Hole t) = Hole <$> toTT t fixBinder (GHole i ns t) = GHole i ns <$> toTT t fixBinder (Guess t1 t2) = Guess <$> toTT t1 <*> toTT t2 fixBinder (PVar t) = PVar <$> toTT t fixBinder (PVTy t) = PVTy <$> toTT t newN n = do (ExecState hs ns) <- lift get let n' = uniqueName n ns lift (put (ExecState hs (n':ns))) return n' toTT (EApp e1 e2) = do e1' <- toTT e1 e2' <- toTT e2 return $ App Complete e1' e2' toTT (EType u) = return $ TType u toTT (EUType u) = return $ UType u toTT EErased = return Erased toTT (EConstant c) = return (Constant c) toTT (EThunk ctxt env tm) = do env' <- mapM toBinder env return $ normalise ctxt env' tm where toBinder (n, v) = do v' <- toTT v return (n, Let Erased v') toTT (EHandle _) = execFail $ Msg "Can't convert handles back to TT after execution." toTT (EPtr ptr) = execFail $ Msg "Can't convert pointers back to TT after execution." unApplyV :: ExecVal -> (ExecVal, [ExecVal]) unApplyV tm = ua [] tm where ua args (EApp f a) = ua (a:args) f ua args t = (t, args) mkEApp :: ExecVal -> [ExecVal] -> ExecVal mkEApp f [] = f mkEApp f (a:args) = mkEApp (EApp f a) args initState :: Idris ExecState initState = do ist <- getIState return $ ExecState (idris_dynamic_libs ist) [] type Exec = ExceptT Err (StateT ExecState IO) runExec :: Exec a -> ExecState -> IO (Either Err a) runExec ex st = fst <$> runStateT (runExceptT ex) st getExecState :: Exec ExecState getExecState = lift get putExecState :: ExecState -> Exec () putExecState = lift . put execFail :: Err -> Exec a execFail = throwE execIO :: IO a -> Exec a execIO = lift . lift execute :: Term -> Idris Term execute tm = do est <- initState ctxt <- getContext res <- lift . lift . flip runExec est $ do res <- doExec [] ctxt tm toTT res case res of Left err -> ierror err Right tm' -> return tm' ioWrap :: ExecVal -> ExecVal ioWrap tm = mkEApp (EP (DCon 0 2 False) (sUN "prim__IO") EErased) [EErased, tm] ioUnit :: ExecVal ioUnit = ioWrap (EP Ref unitCon EErased) type ExecEnv = [(Name, ExecVal)] doExec :: ExecEnv -> Context -> Term -> Exec ExecVal doExec env ctxt p@(P Ref n ty) | Just v <- lookup n env = return v doExec env ctxt p@(P Ref n ty) = do let val = lookupDef n ctxt case val of [Function _ tm] -> doExec env ctxt tm [TyDecl _ _] -> return (EP Ref n EErased) -- abstract def [Operator tp arity op] -> return (EP Ref n EErased) -- will be special-cased later [CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun doExec env ctxt tm [CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] -> return (EP Ref n EErased) [] -> execFail . Msg $ "Could not find " ++ show n ++ " in definitions." other | length other > 1 -> execFail . Msg $ "Multiple definitions found for " ++ show n | otherwise -> execFail . Msg . take 500 $ "got to " ++ show other ++ " lookup up " ++ show n doExec env ctxt p@(P Bound n ty) = case lookup n env of Nothing -> execFail . Msg $ "not found" Just tm -> return tm doExec env ctxt (P (DCon a b u) n _) = return (EP (DCon a b u) n EErased) doExec env ctxt (P (TCon a b) n _) = return (EP (TCon a b) n EErased) doExec env ctxt v@(V i) | i < length env = return (snd (env !! i)) | otherwise = execFail . Msg $ "env too small" doExec env ctxt (Bind n (Let t v) body) = do v' <- doExec env ctxt v doExec ((n, v'):env) ctxt body doExec env ctxt (Bind n (NLet t v) body) = trace "NLet" $ undefined doExec env ctxt tm@(Bind n b body) = do b' <- forM b (doExec env ctxt) return $ EBind n b' (\arg -> doExec ((n, arg):env) ctxt body) doExec env ctxt a@(App _ _ _) = do let (f, args) = unApply a f' <- doExec env ctxt f args' <- case f' of (EP _ d _) | d == delay -> case args of [t,a,tm] -> do t' <- doExec env ctxt t a' <- doExec env ctxt a return [t', a', EThunk ctxt env tm] _ -> mapM (doExec env ctxt) args -- partial applications are fine to evaluate fun' -> do mapM (doExec env ctxt) args execApp env ctxt f' args' doExec env ctxt (Constant c) = return (EConstant c) doExec env ctxt (Proj tm i) = let (x, xs) = unApply tm in doExec env ctxt ((x:xs) !! i) doExec env ctxt Erased = return EErased doExec env ctxt Impossible = fail "Tried to execute an impossible case" doExec env ctxt (TType u) = return (EType u) doExec env ctxt (UType u) = return (EUType u) execApp :: ExecEnv -> Context -> ExecVal -> [ExecVal] -> Exec ExecVal execApp env ctxt v [] = return v -- no args is just a constant! can result from function calls execApp env ctxt (EP _ f _) (t:a:delayed:rest) | f == force , (_, [_, _, EThunk tmCtxt tmEnv tm]) <- unApplyV delayed = do tm' <- doExec tmEnv tmCtxt tm execApp env ctxt tm' rest execApp env ctxt (EP _ fp _) (ty:action:rest) | fp == upio, (prim__IO, [_, v]) <- unApplyV action = execApp env ctxt v rest execApp env ctxt (EP _ fp _) args@(_:_:v:k:rest) | fp == piobind, (prim__IO, [_, v']) <- unApplyV v = do res <- execApp env ctxt k [v'] execApp env ctxt res rest execApp env ctxt con@(EP _ fp _) args@(tp:v:rest) | fp == pioret = execApp env ctxt (mkEApp con [tp, v]) rest -- Special cases arising from not having access to the C RTS in the interpreter execApp env ctxt f@(EP _ fp _) args@(xs:_:_:_:args') | fp == mkfprim, (ty : fn : w : rest) <- reverse args' = execForeign env ctxt getArity ty fn rest (mkEApp f args) where getArity = case unEList xs of Just as -> length as _ -> 0 execApp env ctxt c@(EP (DCon _ arity _) n _) args = do let args' = take arity args let restArgs = drop arity args execApp env ctxt (mkEApp c args') restArgs execApp env ctxt c@(EP (TCon _ arity) n _) args = do let args' = take arity args let restArgs = drop arity args execApp env ctxt (mkEApp c args') restArgs execApp env ctxt f@(EP _ n _) args | Just (res, rest) <- getOp n args = do r <- res execApp env ctxt r rest execApp env ctxt f@(EP _ n _) args = do let val = lookupDef n ctxt case val of [Function _ tm] -> fail "should already have been eval'd" [TyDecl nt ty] -> return $ mkEApp f args [Operator tp arity op] -> if length args >= arity then let args' = take arity args in case getOp n args' of Just (res, []) -> do r <- res execApp env ctxt r (drop arity args) _ -> return (mkEApp f args) else return (mkEApp f args) [CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun do rhs <- doExec env ctxt tm execApp env ctxt rhs args [CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] -> do res <- execCase env ctxt ns sc args return $ fromMaybe (mkEApp f args) res thing -> return $ mkEApp f args execApp env ctxt bnd@(EBind n b body) (arg:args) = do ret <- body arg let (f', as) = unApplyV ret execApp env ctxt f' (as ++ args) execApp env ctxt app@(EApp _ _) args2 | (f, args1) <- unApplyV app = execApp env ctxt f (args1 ++ args2) execApp env ctxt f args = return (mkEApp f args) execForeign env ctxt arity ty fn xs onfail | Just (FFun "putStr" [(_, str)] _) <- foreignFromTT arity ty fn xs = case str of EConstant (Str arg) -> do execIO (putStr arg) execApp env ctxt ioUnit (drop arity xs) _ -> execFail . Msg $ "The argument to putStr should be a constant string, but it was " ++ show str ++ ". Are all cases covered?" | Just (FFun "putchar" [(_, ch)] _) <- foreignFromTT arity ty fn xs = case ch of EConstant (Ch c) -> do execIO (putChar c) execApp env ctxt ioUnit (drop arity xs) EConstant (I i) -> do execIO (putChar (toEnum i)) execApp env ctxt ioUnit (drop arity xs) _ -> execFail . Msg $ "The argument to putchar should be a constant character, but it was " ++ show str ++ ". Are all cases covered?" | Just (FFun "idris_readStr" [_, (_, handle)] _) <- foreignFromTT arity ty fn xs = case handle of EHandle h -> do contents <- execIO $ hGetLine h execApp env ctxt (EConstant (Str (contents ++ "\n"))) (drop arity xs) _ -> execFail . Msg $ "The argument to idris_readStr should be a handle, but it was " ++ show handle ++ ". Are all cases covered?" | Just (FFun "getchar" _ _) <- foreignFromTT arity ty fn xs = do -- The C API returns an Int which Idris library code -- converts; thus, we must make an int here. ch <- execIO $ fmap (ioWrap . EConstant . I . fromEnum) getChar execApp env ctxt ch xs | Just (FFun "idris_time" _ _) <- foreignFromTT arity ty fn xs = do execIO $ fmap (ioWrap . EConstant . I . round) getPOSIXTime | Just (FFun "fileOpen" [(_,fileStr), (_,modeStr)] _) <- foreignFromTT arity ty fn xs = case (fileStr, modeStr) of (EConstant (Str f), EConstant (Str mode)) -> do f <- execIO $ catch (do let m = case mode of "r" -> Right ReadMode "w" -> Right WriteMode "a" -> Right AppendMode "rw" -> Right ReadWriteMode "wr" -> Right ReadWriteMode "r+" -> Right ReadWriteMode _ -> Left ("Invalid mode for " ++ f ++ ": " ++ mode) case fmap (openFile f) m of Right h -> do h' <- h hSetBinaryMode h' True return $ Right (ioWrap (EHandle h'), drop arity xs) Left err -> return $ Left err) (\e -> let _ = ( e::SomeException) in return $ Right (ioWrap (EPtr nullPtr), drop arity xs)) case f of Left err -> execFail . Msg $ err Right (res, rest) -> execApp env ctxt res rest _ -> execFail . Msg $ "The arguments to fileOpen should be constant strings, but they were " ++ show fileStr ++ " and " ++ show modeStr ++ ". Are all cases covered?" | Just (FFun "fileEOF" [(_,handle)] _) <- foreignFromTT arity ty fn xs = case handle of EHandle h -> do eofp <- execIO $ hIsEOF h let res = ioWrap (EConstant (I $ if eofp then 1 else 0)) execApp env ctxt res (drop arity xs) _ -> execFail . Msg $ "The argument to fileEOF should be a file handle, but it was " ++ show handle ++ ". Are all cases covered?" | Just (FFun "fileClose" [(_,handle)] _) <- foreignFromTT arity ty fn xs = case handle of EHandle h -> do execIO $ hClose h execApp env ctxt ioUnit (drop arity xs) _ -> execFail . Msg $ "The argument to fileClose should be a file handle, but it was " ++ show handle ++ ". Are all cases covered?" | Just (FFun "isNull" [(_, ptr)] _) <- foreignFromTT arity ty fn xs = case ptr of EPtr p -> let res = ioWrap . EConstant . I $ if p == nullPtr then 1 else 0 in execApp env ctxt res (drop arity xs) -- Handles will be checked as null pointers sometimes - but if we got a -- real Handle, then it's valid, so just return 1. EHandle h -> let res = ioWrap . EConstant . I $ 0 in execApp env ctxt res (drop arity xs) -- A foreign-returned char* has to be tested for NULL sometimes EConstant (Str s) -> let res = ioWrap . EConstant . I $ 0 in execApp env ctxt res (drop arity xs) _ -> execFail . Msg $ "The argument to isNull should be a pointer or file handle or string, but it was " ++ show ptr ++ ". Are all cases covered?" -- Right now, there's no way to send command-line arguments to the executor, -- so just return 0. execForeign env ctxt arity ty fn xs onfail | Just (FFun "idris_numArgs" _ _) <- foreignFromTT arity ty fn xs = let res = ioWrap . EConstant . I $ 0 in execApp env ctxt res (drop arity xs) execForeign env ctxt arity ty fn xs onfail = case foreignFromTT arity ty fn xs of Just ffun@(FFun f argTs retT) | length xs >= arity -> do let (args', xs') = (take arity xs, -- foreign args drop arity xs) -- rest res <- call ffun (map snd argTs) case res of Nothing -> fail $ "Could not call foreign function \"" ++ f ++ "\" with args " ++ show (map snd argTs) Just r -> return (mkEApp r xs') _ -> return onfail splitArg tm | (_, [_,_,l,r]) <- unApplyV tm -- pair, two implicits = Just (toFDesc l, r) splitArg _ = Nothing toFDesc tm | (EP _ n _, []) <- unApplyV tm = FCon (deNS n) | (EP _ n _, as) <- unApplyV tm = FApp (deNS n) (map toFDesc as) toFDesc _ = FUnknown deNS (NS n _) = n deNS n = n prf = sUN "prim__readFile" pwf = sUN "prim__writeFile" prs = sUN "prim__readString" pws = sUN "prim__writeString" pbm = sUN "prim__believe_me" pstdin = sUN "prim__stdin" pstdout = sUN "prim__stdout" mkfprim = sUN "mkForeignPrim" pioret = sUN "prim_io_return" piobind = sUN "prim_io_bind" upio = sUN "unsafePerformPrimIO" delay = sUN "Delay" force = sUN "Force" -- | Look up primitive operations in the global table and transform -- them into ExecVal functions getOp :: Name -> [ExecVal] -> Maybe (Exec ExecVal, [ExecVal]) getOp fn (_ : _ : x : xs) | fn == pbm = Just (return x, xs) getOp fn (_ : EConstant (Str n) : xs) | fn == pws = Just (do execIO $ putStr n return (EConstant (I 0)), xs) getOp fn (_:xs) | fn == prs = Just (do line <- execIO getLine return (EConstant (Str line)), xs) getOp fn (_ : EP _ fn' _ : EConstant (Str n) : xs) | fn == pwf && fn' == pstdout = Just (do execIO $ putStr n return (EConstant (I 0)), xs) getOp fn (_ : EP _ fn' _ : xs) | fn == prf && fn' == pstdin = Just (do line <- execIO getLine return (EConstant (Str line)), xs) getOp fn (_ : EHandle h : EConstant (Str n) : xs) | fn == pwf = Just (do execIO $ hPutStr h n return (EConstant (I 0)), xs) getOp fn (_ : EHandle h : xs) | fn == prf = Just (do contents <- execIO $ hGetLine h return (EConstant (Str (contents ++ "\n"))), xs) getOp fn (_ : arg : xs) | fn == prf = Just $ (execFail (Msg "Can't use prim__readFile on a raw pointer in the executor."), xs) getOp n args = do (arity, prim) <- getPrim n primitives if (length args >= arity) then do res <- applyPrim prim (take arity args) Just (res, drop arity args) else Nothing where getPrim :: Name -> [Prim] -> Maybe (Int, [ExecVal] -> Maybe ExecVal) getPrim n [] = Nothing getPrim n ((Prim pn _ arity def _ _) : prims) | n == pn = Just (arity, execPrim def) | otherwise = getPrim n prims execPrim :: ([Const] -> Maybe Const) -> [ExecVal] -> Maybe ExecVal execPrim f args = EConstant <$> (mapM getConst args >>= f) getConst (EConstant c) = Just c getConst _ = Nothing applyPrim :: ([ExecVal] -> Maybe ExecVal) -> [ExecVal] -> Maybe (Exec ExecVal) applyPrim fn args = return <$> fn args -- | Overall wrapper for case tree execution. If there are enough arguments, it takes them, -- evaluates them, then begins the checks for matching cases. execCase :: ExecEnv -> Context -> [Name] -> SC -> [ExecVal] -> Exec (Maybe ExecVal) execCase env ctxt ns sc args = let arity = length ns in if arity <= length args then do let amap = zip ns args -- trace ("Case " ++ show sc ++ "\n in " ++ show amap ++"\n in env " ++ show env ++ "\n\n" ) $ return () caseRes <- execCase' env ctxt amap sc case caseRes of Just res -> Just <$> execApp (map (\(n, tm) -> (n, tm)) amap ++ env) ctxt res (drop arity args) Nothing -> return Nothing else return Nothing -- | Take bindings and a case tree and examines them, executing the matching case if possible. execCase' :: ExecEnv -> Context -> [(Name, ExecVal)] -> SC -> Exec (Maybe ExecVal) execCase' env ctxt amap (UnmatchedCase _) = return Nothing execCase' env ctxt amap (STerm tm) = Just <$> doExec (map (\(n, v) -> (n, v)) amap ++ env) ctxt tm execCase' env ctxt amap (Case sh n alts) | Just tm <- lookup n amap = case chooseAlt tm alts of Just (newCase, newBindings) -> let amap' = newBindings ++ (filter (\(x,_) -> not (elem x (map fst newBindings))) amap) in execCase' env ctxt amap' newCase Nothing -> return Nothing execCase' _ _ _ cse = fail $ "The impossible happened: tried to exec " ++ show cse chooseAlt :: ExecVal -> [CaseAlt] -> Maybe (SC, [(Name, ExecVal)]) chooseAlt tm (DefaultCase sc : alts) | ok tm = Just (sc, []) | otherwise = Nothing where -- Default cases should only work on applications of constructors or on constants ok (EApp f x) = ok f ok (EP Bound _ _) = False ok (EP Ref _ _) = False ok _ = True chooseAlt (EConstant c) (ConstCase c' sc : alts) | c == c' = Just (sc, []) chooseAlt tm (ConCase n i ns sc : alts) | ((EP _ cn _), args) <- unApplyV tm , cn == n = Just (sc, zip ns args) | otherwise = chooseAlt tm alts chooseAlt tm (_:alts) = chooseAlt tm alts chooseAlt _ [] = Nothing data Foreign = FFun String [(FDesc, ExecVal)] FDesc deriving Show toFType :: FDesc -> FType toFType (FCon c) | c == sUN "C_Str" = FString | c == sUN "C_Float" = FArith ATFloat | c == sUN "C_Ptr" = FPtr | c == sUN "C_MPtr" = FManagedPtr | c == sUN "C_Unit" = FUnit toFType (FApp c [_,ity]) | c == sUN "C_IntT" = FArith (toAType ity) where toAType (FCon i) | i == sUN "C_IntChar" = ATInt ITChar | i == sUN "C_IntNative" = ATInt ITNative | i == sUN "C_IntBits8" = ATInt (ITFixed IT8) | i == sUN "C_IntBits16" = ATInt (ITFixed IT16) | i == sUN "C_IntBits32" = ATInt (ITFixed IT32) | i == sUN "C_IntBits64" = ATInt (ITFixed IT64) toAType t = error (show t ++ " not defined in toAType") toFType (FApp c [_]) | c == sUN "C_Any" = FAny toFType t = error (show t ++ " not defined in toFType") call :: Foreign -> [ExecVal] -> Exec (Maybe ExecVal) call (FFun name argTypes retType) args = do fn <- findForeign name maybe (return Nothing) (\f -> Just . ioWrap <$> call' f args (toFType retType)) fn where call' :: ForeignFun -> [ExecVal] -> FType -> Exec ExecVal call' (Fun _ h) args (FArith (ATInt ITNative)) = do res <- execIO $ callFFI h retCInt (prepArgs args) return (EConstant (I (fromIntegral res))) call' (Fun _ h) args (FArith (ATInt (ITFixed IT8))) = do res <- execIO $ callFFI h retCChar (prepArgs args) return (EConstant (B8 (fromIntegral res))) call' (Fun _ h) args (FArith (ATInt (ITFixed IT16))) = do res <- execIO $ callFFI h retCWchar (prepArgs args) return (EConstant (B16 (fromIntegral res))) call' (Fun _ h) args (FArith (ATInt (ITFixed IT32))) = do res <- execIO $ callFFI h retCInt (prepArgs args) return (EConstant (B32 (fromIntegral res))) call' (Fun _ h) args (FArith (ATInt (ITFixed IT64))) = do res <- execIO $ callFFI h retCLong (prepArgs args) return (EConstant (B64 (fromIntegral res))) call' (Fun _ h) args (FArith ATFloat) = do res <- execIO $ callFFI h retCDouble (prepArgs args) return (EConstant (Fl (realToFrac res))) call' (Fun _ h) args (FArith (ATInt ITChar)) = do res <- execIO $ callFFI h retCChar (prepArgs args) return (EConstant (Ch (castCCharToChar res))) call' (Fun _ h) args FString = do res <- execIO $ callFFI h retCString (prepArgs args) if res == nullPtr then return (EPtr res) else do hStr <- execIO $ peekCString res return (EConstant (Str hStr)) call' (Fun _ h) args FPtr = EPtr <$> (execIO $ callFFI h (retPtr retVoid) (prepArgs args)) call' (Fun _ h) args FUnit = do _ <- execIO $ callFFI h retVoid (prepArgs args) return $ EP Ref unitCon EErased call' _ _ _ = fail "the impossible happened in call' in Execute.hs" prepArgs = map prepArg prepArg (EConstant (I i)) = argCInt (fromIntegral i) prepArg (EConstant (B8 i)) = argCChar (fromIntegral i) prepArg (EConstant (B16 i)) = argCWchar (fromIntegral i) prepArg (EConstant (B32 i)) = argCInt (fromIntegral i) prepArg (EConstant (B64 i)) = argCLong (fromIntegral i) prepArg (EConstant (Fl f)) = argCDouble (realToFrac f) prepArg (EConstant (Ch c)) = argCChar (castCharToCChar c) -- FIXME - castCharToCChar only safe for first 256 chars -- Issue #1720 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1720 prepArg (EConstant (Str s)) = argString s prepArg (EPtr p) = argPtr p prepArg other = trace ("Could not use " ++ take 100 (show other) ++ " as FFI arg.") undefined foreignFromTT :: Int -> ExecVal -> ExecVal -> [ExecVal] -> Maybe Foreign foreignFromTT arity ty (EConstant (Str name)) args = do argFTyVals <- mapM splitArg (take arity args) return $ FFun name argFTyVals (toFDesc ty) foreignFromTT arity ty fn args = trace ("failed to construct ffun from " ++ show (ty,fn,args)) Nothing getFTy :: ExecVal -> Maybe FType getFTy (EApp (EP _ (UN fi) _) (EP _ (UN intTy) _)) | fi == txt "FIntT" = case str intTy of "ITNative" -> Just (FArith (ATInt ITNative)) "ITChar" -> Just (FArith (ATInt ITChar)) "IT8" -> Just (FArith (ATInt (ITFixed IT8))) "IT16" -> Just (FArith (ATInt (ITFixed IT16))) "IT32" -> Just (FArith (ATInt (ITFixed IT32))) "IT64" -> Just (FArith (ATInt (ITFixed IT64))) _ -> Nothing getFTy (EP _ (UN t) _) = case str t of "FFloat" -> Just (FArith ATFloat) "FString" -> Just FString "FPtr" -> Just FPtr "FUnit" -> Just FUnit _ -> Nothing getFTy _ = Nothing unEList :: ExecVal -> Maybe [ExecVal] unEList tm = case unApplyV tm of (nil, [_]) -> Just [] (cons, ([_, x, xs])) -> do rest <- unEList xs return $ x:rest (f, args) -> Nothing toConst :: Term -> Maybe Const toConst (Constant c) = Just c toConst _ = Nothing mapMaybeM :: (Functor m, Monad m) => (a -> m (Maybe b)) -> [a] -> m [b] mapMaybeM f [] = return [] mapMaybeM f (x:xs) = do rest <- mapMaybeM f xs maybe rest (:rest) <$> f x findForeign :: String -> Exec (Maybe ForeignFun) findForeign fn = do est <- getExecState let libs = exec_dynamic_libs est fns <- mapMaybeM getFn libs case fns of [f] -> return (Just f) [] -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" not found" return Nothing fs -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" is ambiguous. Found " ++ show (length fs) ++ " occurrences." return Nothing where getFn lib = execIO $ catchIO (tryLoadFn fn lib) (\_ -> return Nothing) #endif
phaazon/Idris-dev
src/Idris/Core/Execute.hs
bsd-3-clause
29,471
0
6
10,849
259
166
93
28
1
module TreeIn4 where data Tree a = Leaf a | Branch (Tree a) (Tree a) fringe :: Tree a -> [a] fringe (Leaf x) = [x] fringe (Branch left right@(Leaf b_1)) = (fringe left) ++ (fringe right) fringe (Branch left right@(Branch b_1 b_2)) = (fringe left) ++ (fringe right) fringe (Branch left right) = (fringe left) ++ (fringe right)
kmate/HaRe
old/testing/subIntroPattern/TreeIn4_TokOut.hs
bsd-3-clause
341
0
10
74
181
95
86
10
1
{-# LANGUAGE KindSignatures, TypeFamilies, PolyKinds #-} module T7341 where data Proxy a = Proxy class C a where type F (a :: *) :: * op :: Proxy a -> Int instance C [] where op _ = 5
urbanslug/ghc
testsuite/tests/polykinds/T7341.hs
bsd-3-clause
194
0
8
49
65
37
28
8
0
facMod :: Integer -> Integer -> Integer facMod n m = loop n 1 where loop 0 acc = acc loop k f | k >= m = 0 | f == 0 = 0 | otherwise = loop (k - 1) ((f * k) `mod` m) main :: IO () main = print $ 1000000 `facMod` 1001001779
genos/online_problems
prog_praxis/modular_factorial.hs
mit
276
0
12
112
136
69
67
8
2
{-# LANGUAGE LambdaCase #-} module Main where import Language.Haskell.Interpreter import System.Environment import System.Exit import System.IO import Test.Target import Text.Printf main :: IO () main = do [src, binder] <- getArgs r <- runInterpreter $ do loadModules [src] mods <- getLoadedModules -- liftIO $ print mods setImportsQ $ map (\m -> (m,Nothing)) mods ++ [("Test.Target", Nothing), ("Prelude", Nothing)] set [languageExtensions := [TemplateHaskell]] let expr = printf "$(targetResultTH '%s \"%s\")" binder src -- liftIO $ putStrLn expr interpret expr (as :: IO Result) case r of Left e -> hPrint stderr e >> exitWith (ExitFailure 2) Right x -> x >>= \case Errored e -> hPutStrLn stderr e >> exitWith (ExitFailure 2) Failed s -> printf "Found counter-example: %s\n" s >> exitWith (ExitFailure 1) Passed n -> printf "OK! Passed %d tests.\n" n >> exitSuccess
gridaphobe/target
bin/Target.hs
mit
966
0
17
230
311
157
154
25
4
{-# LANGUAGE OverloadedStrings #-} module JoScript.Util.TextTest (tests) where import Prelude (flip, String, ($)) import Data.Word import Test.HUnit import Control.Applicative (pure, (<$>), (<*>)) import JoScript.Util.Text tests = [ TestLabel "JoScript.Util.Text.foldlM" tryFoldM , TestLabel "JoScript.Util.Text.readInt" tryReadInt , TestLabel "JoScript.Util.Text.readFloat" tryReadFloat ] tryFoldM = TestCase $ do let expected = "olleh" :: String let mFold a b = pure (b : a) resulted <- foldlM mFold "" "hello" -- $ foldl (flip (:)) [] "hello" -- > "olleh" assertEqual "reverses the string" expected resulted tryReadInt = TestCase $ do assertEqual "read int works" (readInt "123") 123 tryReadFloat = TestCase $ do assertEqual "read int works" (readFloat "123.234") 123.234
AKST/jo
source/test/JoScript/Util/TextTest.hs
mit
807
0
13
137
215
117
98
20
1
----------------------------------------------------------------------------- -- | -- Module : My.Control.Concurrent -- Copyright : (c) Dmitry Antonyuk 2009 -- License : MIT -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Utilities for multithreading programming. -- ----------------------------------------------------------------------------- module My.Control.Concurrent ( spawn -- :: IO () -> IO ThreadId ) where import Control.Concurrent (ThreadId, forkIO, myThreadId) import Control.Exception (throwTo) -- | 'spawn' runs an IO action in a separate thread. -- If an action throws an exception it will be rethrown to parent thread. spawn :: IO () -> IO ThreadId spawn act = do tId <- myThreadId forkIO $ act `catch` throwTo tId
lomeo/my
src/My/Control/Concurrent.hs
mit
819
0
8
140
102
63
39
8
1
module BlankSpec where import Test.Hspec import Main spec :: Spec spec = do describe "blank test" $ do it "test" $ 3 `shouldBe` (3 :: Int)
mathfur/grep-tree
test/Spec.hs
mit
147
0
12
34
54
30
24
7
1
import Data.Time.Calendar (fromGregorian) import Data.Time.Calendar.WeekDate (toWeekDate) months = [fromGregorian y m d|y<-[1901..2000],m<-[1..12],d<-[1]] sundays = filter sunday months where sunday d = trd (toWeekDate d) == 7 trd (_,_,x) = x answer = length sundays coins = [200,100,50,20,10,5,2,1] ns = [1,0,0,0,0,0,0,0] ts = [1,2,4,10,20,40,100,200] p xs | a==0 = [xs] where a = find downs = xs
yuto-matsum/contest-util-hs
src/Euler/019.hs
mit
412
1
10
70
257
147
110
-1
-1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.CSSStyleRule (js_setSelectorText, setSelectorText, js_getSelectorText, getSelectorText, js_getStyle, getStyle, CSSStyleRule, castToCSSStyleRule, gTypeCSSStyleRule) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"selectorText\"] = $2;" js_setSelectorText :: JSRef CSSStyleRule -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleRule.selectorText Mozilla CSSStyleRule.selectorText documentation> setSelectorText :: (MonadIO m, ToJSString val) => CSSStyleRule -> Maybe val -> m () setSelectorText self val = liftIO (js_setSelectorText (unCSSStyleRule self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"selectorText\"]" js_getSelectorText :: JSRef CSSStyleRule -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleRule.selectorText Mozilla CSSStyleRule.selectorText documentation> getSelectorText :: (MonadIO m, FromJSString result) => CSSStyleRule -> m (Maybe result) getSelectorText self = liftIO (fromMaybeJSString <$> (js_getSelectorText (unCSSStyleRule self))) foreign import javascript unsafe "$1[\"style\"]" js_getStyle :: JSRef CSSStyleRule -> IO (JSRef CSSStyleDeclaration) -- | <https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleRule.style Mozilla CSSStyleRule.style documentation> getStyle :: (MonadIO m) => CSSStyleRule -> m (Maybe CSSStyleDeclaration) getStyle self = liftIO ((js_getStyle (unCSSStyleRule self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/CSSStyleRule.hs
mit
2,451
20
11
372
596
351
245
42
1
{-# LANGUAGE ExistentialQuantification, RankNTypes, ImpredicativeTypes #-} module ConstraintWitness.TcPlugin.Instances where import Prelude hiding (init) import Data.Monoid import Data.List (union) import Data.Traversable (traverse) import Control.Monad (sequence, void) import GhcPlugins () import TcRnTypes (TcPlugin(..), TcPluginResult(..)) -- | Straightforward plugin-result composition instance Monoid TcPluginResult where mempty = TcPluginOk [] [] mappend (TcPluginOk solved1 new1) (TcPluginOk solved2 new2 ) = TcPluginOk (solved1 ++ solved2) (new1 ++ new2) mappend (TcPluginContradiction bad1) (TcPluginOk _ _ ) = TcPluginContradiction bad1 mappend (TcPluginOk _ _) (TcPluginContradiction bad2) = TcPluginContradiction bad2 mappend (TcPluginContradiction bad1) (TcPluginContradiction bad2) = TcPluginContradiction (bad1 ++ bad2) -- | This makes plugins composable. -- plug1 <> plug2 will run both plugins at the same time *not* one after the other. -- If either finds a contradiction, the composed plugin will also result in a contradiction. -- If they both find a contradiction, the result is a contradiction where the bad constraints -- consist of the bad ones for *both* plugins. instance Monoid TcPlugin where mempty = TcPlugin (return ()) (\state given derived wanted -> return $ TcPluginOk [] []) (\() -> return ()) mappend (TcPlugin init1 solve1 stop1) (TcPlugin init2 solve2 stop2) = TcPlugin ((,) <$> (init1) <*> (init2)) (\(s1, s2) given derived wanted -> mappend <$> solve1 s1 given derived wanted <*> solve2 s2 given derived wanted) (\(s1, s2) -> stop1 s1 >> stop2 s2)
Solonarv/constraint-witness
plugin/ConstraintWitness/TcPlugin/Instances.hs
mit
1,807
0
11
439
436
237
199
29
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module Products.DomainTermsAPI ( DomainTermsAPI , CreateDomainTermsAPI , EditDomainTermsAPI , RemoveDomainTermAPI , APIDomainTerm (..) , createDomainTerm , editDomainTerm , removeDomainTerm , productsDomainTerms ) where import App import AppConfig (DBConfig (..), getDBConfig) import Control.Monad.Reader import Data.Aeson import Data.Int (Int64) import qualified Data.Text as T import Data.Time.Clock as Clock import Database.Types (runPool) import qualified DomainTerms.DomainTerm as DT import Models import qualified Products.Product as P import Servant type DomainTermsAPI = "domain-terms" :> Get '[JSON] [APIDomainTerm] type CreateDomainTermsAPI = "domain-terms" :> ReqBody '[JSON] APIDomainTerm :> Post '[JSON] APIDomainTerm type EditDomainTermsAPI = "domain-terms" :> Capture "id" Int64 :> ReqBody '[JSON] APIDomainTerm :> Put '[JSON] APIDomainTerm type RemoveDomainTermAPI = "domain-terms" :> Capture "id" Int64 :> Delete '[JSON] () data APIDomainTerm = APIDomainTerm { domainTermID :: Maybe Int64 , productID :: Maybe ProductId , title :: T.Text , description :: T.Text } deriving (Show) instance ToJSON APIDomainTerm where toJSON (APIDomainTerm termID prodID termTitle termDescription) = object [ "id" .= termID , "productID" .= prodID , "title" .= termTitle , "description" .= termDescription ] instance FromJSON APIDomainTerm where parseJSON (Object v) = APIDomainTerm <$> v .:? "id" <*> v .:? "productID" <*> v .: "title" <*> v .: "description" parseJSON _ = mzero createDomainTerm :: P.ProductID -> APIDomainTerm -> App APIDomainTerm createDomainTerm pID (APIDomainTerm _ _ t d) = do dbConfig <- reader getDBConfig utcTime <- liftIO $ Clock.getCurrentTime termID <- liftIO $ runReaderT (runPool (DT.createDomainTerm (DT.DomainTerm (toKey pID) t d utcTime))) (getPool dbConfig) return $ APIDomainTerm { domainTermID = Just termID , productID = Just (toKey pID) , title = t , description = d } editDomainTerm :: P.ProductID -> Int64 -> APIDomainTerm -> App APIDomainTerm editDomainTerm pID dtID (APIDomainTerm _ _ t d) = do dbConfig <- reader getDBConfig domainTerm <- liftIO $ runReaderT (runPool (DT.findDomainTerm (toKey dtID))) (getPool dbConfig) case domainTerm of Nothing -> lift $ throwError $ err404 (Just dt) -> (liftIO $ runReaderT (runPool (DT.updateDomainTerm (toKey dtID) dt)) (getPool dbConfig)) >> (return $ APIDomainTerm { domainTermID = Just (dtID) , productID = Just (toKey pID) , title = t , description = d }) removeDomainTerm :: P.ProductID -> Int64 -> App () removeDomainTerm pID dtID = do dbConfig <- reader getDBConfig liftIO $ runReaderT (runPool (DT.removeDomainTerm (toKey pID) (toKey dtID))) (getPool dbConfig) productsDomainTerms :: P.ProductID -> App [APIDomainTerm] productsDomainTerms prodID = do dbConfig <- reader getDBConfig domainTerms <- liftIO $ runReaderT (runPool (DT.findByProductId (toKey prodID))) (getPool dbConfig) return $ map toDomainTerm domainTerms where toDomainTerm dbDomainTerm = do let dbTerm = DT.toDomainTerm dbDomainTerm let dbTermID = DT.toDomainTermID dbDomainTerm APIDomainTerm { domainTermID = Just dbTermID , productID = Just $ domainTermProductId dbTerm , title = domainTermTitle dbTerm , description = domainTermDescription dbTerm }
gust/feature-creature
legacy/exe-feature-creature-api/Products/DomainTermsAPI.hs
mit
4,232
0
19
1,288
1,079
570
509
87
2
{- definitions: DayOfWeek is a datatype Mon, Tue are data instances -} -- intro: data DayOfWeek = Mon|Tue|Wed|Thu|Fri|Sat|Sun deriving (Show) data Date = Date DayOfWeek Int deriving (Show) instance Eq DayOfWeek where (==) Mon Mon = True (==) Tue Tue = True (==) Wed Wed = True (==) Thu Thu = True (==) Fri Fri = True (==) Sat Sat = True (==) Sun Sun = True (==) _ _ = False instance Eq Date where (==) (Date weekday dayOfMonth) (Date weekday' dayOfMonth') = weekday == weekday' && dayOfMonth == dayOfMonth' -- 1 data TisAnInteger = TisAn Integer deriving (Show) instance Eq TisAnInteger where (==) (TisAn num) (TisAn num') = num == num' -- 2 data TwoIntegers = Two Integer Integer deriving (Show) instance Eq TwoIntegers where (==) (Two numOne numTwo) (Two numOne' numTwo') = (==) numOne numOne' && (==) numTwo numTwo' -- 3 data StringOrInt = TisAnInt Int | TisAString String instance Eq StringOrInt where (==) (TisAnInt num) (TisAnInt num') = num == num' (==) (TisAString str) (TisAString str') = str == str' (==) _ _ = False -- 4 data Pair a = Pair a a deriving (Show) instance Eq a => Eq (Pair a) where (==) (Pair one two) (Pair one' two') = (==) one one' && (==) two two' -- 5 data Tuple a b = Tuple a b deriving (Show) instance (Eq a, Eq b) => Eq (Tuple a b) where (==) (Tuple a b) (Tuple a' b') = (==) a a' && (==) b b' -- 6 data Which a = ThisOne a | ThatOne a instance Eq a => Eq (Which a) where (==) (ThisOne one) (ThisOne one') = one == one' (==) (ThatOne one) (ThatOne one') = one == one' (==) _ _ = False -- 7 data EitherOr a b = Hello a | Goodbye b deriving (Show) instance (Eq a, Eq b) => Eq (EitherOr a b) where (==) (Hello v) (Hello v') = v == v' (==) (Goodbye v) (Goodbye v') = v == v' (==) _ _ = False
Numberartificial/workflow
haskell-first-principles/haskell-from-first-principles-master/06/06.05.00-writing-typeclass-instancess.hs
mit
1,917
0
8
538
835
462
373
49
0
module Handlers.InfoDiagramBtn where import Control.Lens import Data.Time import Graphics.UI.Gtk as Gtk import Graphics.Rendering.Chart.Easy hiding (label) import Graphics.Rendering.Chart.Gtk as Chart import Types import Utils() import Values --set size of pie and description pitem :: Item -> PieItem pitem item = pitem_value .~ fromIntegral(item^.price) $ pitem_label .~ item^.description $ pitem_offset .~ 0 $ def infoDiagramBtnHandler :: [Item] -> IO () infoDiagramBtnHandler quariedItemList = do windowDiagram <- windowNew Gtk.set windowDiagram [windowTitle := "Статистика", windowDefaultWidth := 500, windowDefaultHeight := 400, containerBorderWidth := 10, windowResizable := False] diagramEdt <- labelNew(Just "Отобразить статистику за период") --ForLeftBox leftEdt <- labelNew(Just "Начиная с") leftCal <- calendarNew calendarSetDisplayOptions leftCal [CalendarShowHeading,CalendarShowDayNames,CalendarWeekStartMonday] leftChosenDayLabel <- labelNew (Just "") miscSetAlignment leftChosenDayLabel 0.0 0.0 -- Hour and minute choosing leftDayTimeBox <- hBoxNew False 0 leftSpinH <- myAddSpinButton leftDayTimeBox "Часы:" 0.0 23.0 0.0 leftSpinM <- myAddSpinButton leftDayTimeBox "Минуты:" 0.0 59.0 0.0 leftConsBtn <- buttonNewWithLabel "Расходов" --ForRightBox rightEdt <- labelNew(Just "Заканчивая") rightCal <- calendarNew calendarSetDisplayOptions rightCal [CalendarShowHeading,CalendarShowDayNames,CalendarWeekStartMonday] rightChosenDayLabel <- labelNew (Just "") miscSetAlignment rightChosenDayLabel 0.0 0.0 -- Hour and minute choosing rightDayTimeBox <- hBoxNew False 0 rightSpinH <- myAddSpinButton rightDayTimeBox "Часы:" 0.0 23.0 23.0 rightSpinM <- myAddSpinButton rightDayTimeBox "Минуты:" 0.0 59.0 59.0 rightIncBtn <- buttonNewWithLabel "Доходов" --Boxing mainBoxDiagram <- vBoxNew False 1 containerAdd windowDiagram mainBoxDiagram mainBoxDiagram1 <- hBoxNew False 1 mainBoxDiagram2 <- hBoxNew False 1 boxPackStart mainBoxDiagram mainBoxDiagram1 PackGrow 1 boxPackStart mainBoxDiagram mainBoxDiagram2 PackGrow 1 leftBox <- vBoxNew False 1 boxPackStart leftBox leftEdt PackGrow 1 boxPackStart leftBox leftCal PackGrow 1 boxPackStart leftBox leftChosenDayLabel PackGrow 1 boxPackStart leftBox leftDayTimeBox PackGrow 1 boxPackEnd leftBox leftConsBtn PackGrow 10 rightBox <- vBoxNew False 1 boxPackStart rightBox rightEdt PackGrow 1 boxPackStart rightBox rightCal PackGrow 1 boxPackStart rightBox rightChosenDayLabel PackGrow 1 boxPackStart rightBox rightDayTimeBox PackGrow 1 boxPackEnd rightBox rightIncBtn PackGrow 10 boxPackStart mainBoxDiagram1 diagramEdt PackGrow 1 boxPackStart mainBoxDiagram2 leftBox PackGrow 1 boxPackStart mainBoxDiagram2 rightBox PackGrow 1 --leftBtn is show consumes _ <- ($) on leftConsBtn buttonActivated $ do --get date (year1, month1, day1) <- calendarGetDate leftCal --get hour and minute hour1 <- Gtk.get leftSpinH spinButtonValue minute1 <- Gtk.get leftSpinM spinButtonValue (year2, month2, day2) <- calendarGetDate rightCal hour2 <- Gtk.get rightSpinH spinButtonValue minute2 <- Gtk.get rightSpinM spinButtonValue Chart.toWindow 640 480 $ do --values is [Item] which suits to date range and typo let values = getValues quariedItemList (UTCTime (fromGregorian (toInteger year1) (month1 + 1) day1) (fromInteger (3600 * round hour1 + 60 * round minute1))) (UTCTime (fromGregorian (toInteger year2) (month2 + 1) day2) (fromInteger (3600 * round hour2 + 60 * round minute2))) "Расход" let title = if null values then "Расходов в выбранном периоде нет" else "Расход" pie_title .= title pie_plot . pie_data .= map pitem values _ <- ($) on rightIncBtn buttonActivated $ do (year1', month1', day1') <- calendarGetDate leftCal hour1' <- Gtk.get leftSpinH spinButtonValue minute1 <- Gtk.get leftSpinM spinButtonValue (year2, month2, day2) <- calendarGetDate rightCal hour2' <- Gtk.get rightSpinH spinButtonValue minute2 <- Gtk.get rightSpinM spinButtonValue Chart.toWindow 640 480 $ do let values = getValues quariedItemList (UTCTime (fromGregorian (toInteger year1') (month1' + 1) day1') (fromInteger (3600 * round hour1' + 60 * round minute1))) (UTCTime (fromGregorian (toInteger year2) (month2 + 1) day2) (fromInteger (3600 * round hour2' + 60 * round minute2))) "Доход" let title = if null values then "Доходов в выбранном периоде нет" else "Доходы" pie_title .= title pie_plot . pie_data .= map pitem values widgetShowAll windowDiagram --creating spinHbox with some settings myAddSpinButton :: HBox -> String -> Double -> Double -> Double -> IO SpinButton myAddSpinButton box name minVal maxVal defaultValue = do vbox <- vBoxNew False 0 boxPackStart box vbox PackRepel 0 label <- labelNew (Just name) miscSetAlignment label 0.0 0.5 boxPackStart vbox label PackNatural 0 spinb <- spinButtonNewWithRange minVal maxVal 1.0 Gtk.set spinb [spinButtonValue := defaultValue] boxPackStart vbox spinb PackNatural 0 return spinb
deynekalex/Money-Haskell-Project-
src/Handlers/InfoDiagramBtn.hs
gpl-2.0
5,941
3
31
1,516
1,480
700
780
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Vim.Ex.Commands.Reload -- License : GPL-2 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable module Yi.Keymap.Vim.Ex.Commands.Reload (parse) where import Data.Text () import Yi.Boot.Internal (reload) import Yi.Keymap import Yi.Keymap.Vim.Common import Yi.Keymap.Vim.Ex.Commands.Common (impureExCommand) import Yi.Keymap.Vim.Ex.Types parse :: EventString -> Maybe ExCommand parse "reload" = Just $ impureExCommand { cmdShow = "reload" , cmdAction = YiA reload } parse _ = Nothing
atsukotakahashi/wi
src/library/Yi/Keymap/Vim/Ex/Commands/Reload.hs
gpl-2.0
655
0
8
104
125
81
44
14
1
-- | A config file will be parsed by 'runConfigParser' into a list of -- @['Config']@. Use 'getTextRoot', 'getHyphens', etc. to get an -- aspect of the configuration from this list. module HTCF.ConfigParser ( Config (..) , runConfigParser , getTextRoot , getHyphens , getLineBreaks , getDroppedTrees , getTcfRootNamespace , getTcfTextCorpusNamespace , getTcfMetadataNamespace , getTcfIdBase , getTcfTokenIdPrefix , getTcfSentenceIdPrefix , getAbbreviations , addAbbreviations , getMonths , abbrev1CharTokenP , singleDigitOrdinalP , getNoBreaks , defaultTcfRootNamespace , defaultTcfTextCorpusNamespace , defaultTcfMetadataNamespace , defaultTcfIdBase , defaultTcfTokenIdPrefix , defaultTcfSentenceIdPrefix , defaultAbbrev1CharToken , defaultSingleDigitOrdinal , parseConfig , pcTextRoot , pcDroppedTreeSimple , pcLinebreak , pcHyphen , pcAbbrev1CharToken , pcSingleDigitOrdinal , pcMonth , pcTcfTextCorpusNamespace , pcTcfIdBase , pcTcfTokenIdPrefix , pcTcfSentenceIdPrefix ) where import Text.XML.HXT.Core import qualified Data.ByteString.Char8 as C import Data.Maybe import System.IO import System.Directory import System.Environment -- * Types data Config = TextRoot QName -- ^ qname of parent node for text | DroppedTree -- ^ xml subtree to be dropped by the parser { qName :: QName } -- ^ qname of element node | LineBreak QName -- ^ qname of element -- resulting in a control sign -- for the tokenizer | Hyphen Char -- ^ hyphen character for tokenizer | TcfRootNamespace String -- ^ the namespace of the root -- node a TCF file | TcfTextCorpusNamespace String -- ^ the namespace of the -- TextCorpus tag of a TCF -- file | TcfMetadataNamespace String -- ^ the namespace of the meta -- data (preamble) of a TCF -- file | TcfIdBase Int -- ^ The base of the IDs used -- in a TCF file | TcfTokenIdPrefix String -- ^ The prefix of the token -- IDs used in a TCF file | TcfSentenceIdPrefix String -- ^ The prefix of the sentence -- IDs used in a TCF file | Abbreviation String -- ^ An abbreviation (string -- without ending dot) | Month String -- ^ A month. Months are -- needed for abbreviation and -- tokenization of days. | Abbrev1CharToken Bool -- ^ Holds a boolean value, -- whether tokens with a -- length of one word followed -- by a punct are treated as a -- abbreviation. | SingleDigitOrdinal Bool -- ^ Holds a boolean value, -- whether single digits -- followed by a punct are -- treated as an ordinal. | NoBreak Char -- ^ A character which by its -- category results in a -- break, i.e. punctuation or -- space, but which is not -- supposed to do so. deriving (Show, Eq) -- * Default configuration values. -- | Default qualified name of the element node containing the text -- that is fed to the tokenizer etc. Defaults to TEI's \"text\" -- element. defaultTextRoot :: QName defaultTextRoot = mkNsName "text" "http://www.tei-c.org/ns/1.0" -- | Default value for the root node <D-Spin> of a TCF file: -- http://www.dspin.de/data defaultTcfRootNamespace :: String defaultTcfRootNamespace = "http://www.dspin.de/data" -- | Default value for the <TextCorpus> element of a TCF file: -- http://www.dspin.de/data/textcorpus defaultTcfTextCorpusNamespace :: String defaultTcfTextCorpusNamespace = "http://www.dspin.de/data/textcorpus" -- | Default value for the <MetaData> element of a TCF file: -- http://www.dspin.de/data/metadata defaultTcfMetadataNamespace :: String defaultTcfMetadataNamespace = "http://www.dspin.de/data/metadata" -- | Default value for the base of the numeric part of the IDs used in -- a TCF file: 10. defaultTcfIdBase :: Int defaultTcfIdBase = 10 -- | Default prefix for token identifiers. defaultTcfTokenIdPrefix :: String defaultTcfTokenIdPrefix = "t_" -- | Default prefix for sentence identifiers. defaultTcfSentenceIdPrefix :: String defaultTcfSentenceIdPrefix = "s_" -- | By default, tokens of the length of 1 character are not treated -- as abbrevs. defaultAbbrev1CharToken :: Bool defaultAbbrev1CharToken = False -- | By default, numbers of the lenght of 1 character are not treated -- as ordinals. defaultSingleDigitOrdinal :: Bool defaultSingleDigitOrdinal = False -- * Getting aspects of the configuration. -- | Returns the maybe qualified named of the text root defined in the -- config. If there where multiple text roots defined in the config -- file, the qualified name of the first definition and only this one -- is returned. getTextRoot :: [Config] -> QName getTextRoot [] = defaultTextRoot getTextRoot ((TextRoot qn):_) = qn getTextRoot (_:xs) = getTextRoot xs -- | Returns a list of hyphen characters defined in the -- config. Cf. 'Hyphen'. getHyphens :: [Config] -> [Char] getHyphens [] = [] getHyphens ((Hyphen c):xs) = c : getHyphens xs getHyphens (_:xs) = getHyphens xs -- | Returns a list of the qualified names of element nodes, that -- produce linebreak control characters for the -- tokenizer. Cf. 'LineBreak'. getLineBreaks :: [Config] -> [QName] getLineBreaks [] = [] getLineBreaks ((LineBreak qn):xs) = qn : getLineBreaks xs getLineBreaks (_:xs) = getLineBreaks xs -- | Returns a list of qualified names of element nodes, that are -- dropped by the parser. Cf. 'DroppedTree'. getDroppedTrees :: [Config] -> [QName] getDroppedTrees [] = [] getDroppedTrees ((DroppedTree qn):xs) = qn : getDroppedTrees xs getDroppedTrees (_:xs) = getDroppedTrees xs -- | Get the namespace of the root node a TCF file. If none is given -- in the config file, this defaults to -- 'defaultTcfRootNamespace'. getTcfRootNamespace :: [Config] -> String getTcfRootNamespace [] = defaultTcfRootNamespace getTcfRootNamespace ((TcfRootNamespace ns):_) = ns getTcfRootNamespace (_:xs) = getTcfRootNamespace xs -- | Get the namespace of the text corpus element of a TCF file. If -- none is given in the config file, this defaults to -- 'defaultTcfTextCorpusNamespace'. getTcfTextCorpusNamespace :: [Config] -> String getTcfTextCorpusNamespace [] = defaultTcfTextCorpusNamespace getTcfTextCorpusNamespace ((TcfTextCorpusNamespace ns):_) = ns getTcfTextCorpusNamespace (_:xs) = getTcfTextCorpusNamespace xs -- | Get the namespace of the <MetaData> element of a TCF file. If -- none is given in the config file, this defaults to -- 'defaultTcfMetadataNamespace'. getTcfMetadataNamespace :: [Config] -> String getTcfMetadataNamespace [] = defaultTcfMetadataNamespace getTcfMetadataNamespace ((TcfMetadataNamespace ns):_) = ns getTcfMetadataNamespace (_:xs) = getTcfMetadataNamespace xs -- | Get the base of the IDs used in a TCF file. Defaults to -- 'defaultTcfIdBase'. getTcfIdBase :: [Config] -> Int getTcfIdBase [] = defaultTcfIdBase getTcfIdBase ((TcfIdBase b):_) = b getTcfIdBase (_:xs) = getTcfIdBase xs -- | Get the prefix of the token IDs in a TCF file. Defaults to -- 'defaultTcfTokenIdPrefix'. getTcfTokenIdPrefix :: [Config] -> String getTcfTokenIdPrefix [] = defaultTcfTokenIdPrefix getTcfTokenIdPrefix ((TcfTokenIdPrefix p):_) = p getTcfTokenIdPrefix (_:xs) = getTcfTokenIdPrefix xs -- | Get the prefix of the sentence IDs in a TCF file. Defaults to -- 'defaultTcfSentenceIdPrefix'. getTcfSentenceIdPrefix :: [Config] -> String getTcfSentenceIdPrefix [] = defaultTcfSentenceIdPrefix getTcfSentenceIdPrefix ((TcfSentenceIdPrefix p):_) = p getTcfSentenceIdPrefix (_:xs) = getTcfSentenceIdPrefix xs -- | Get the list of abbreviation strings from config. getAbbreviations :: [Config] -> [String] getAbbreviations [] = [] getAbbreviations ((Abbreviation abbr):xs) = abbr:getAbbreviations xs getAbbreviations (_:xs) = getAbbreviations xs -- | Get characters from the config which would result in a break -- between two tokens, but which are not supposed to. getNoBreaks :: [Config] -> [Char] getNoBreaks [] = [] getNoBreaks ((NoBreak c):xs) = c : getNoBreaks xs getNoBreaks (_:xs) = getNoBreaks xs -- | Get the list of month names form config. getMonths :: [Config] -> [String] getMonths [] = [] getMonths ((Month m):xs) = m:getMonths xs getMonths (_:xs) = getMonths xs -- | Test if abbreviation of 1 char length tokens is active or not. abbrev1CharTokenP :: [Config] -> Bool abbrev1CharTokenP [] = defaultAbbrev1CharToken abbrev1CharTokenP ((Abbrev1CharToken b):_) = b abbrev1CharTokenP (_:xs) = abbrev1CharTokenP xs -- | Test if one digit numbers are read as ordinals. singleDigitOrdinalP :: [Config] -> Bool singleDigitOrdinalP [] = defaultSingleDigitOrdinal singleDigitOrdinalP ((SingleDigitOrdinal b):_) = b singleDigitOrdinalP (_:xs) = singleDigitOrdinalP xs -- * Setters for aspects of the configuration. -- | Add a list of strings to the known abbreviations -- (cf. 'Abbreviation'). addAbbreviations :: [String] -- ^ the list of abbreviations -> [Config] -- ^ the existing config -> [Config] -- ^ returned config with new abbrevs addAbbreviations abbrevs cfg = cfg ++ (map (Abbreviation) abbrevs) -- * Parsing the xml config file. -- | Returns the config defined in a XML config file. runConfigParser :: FilePath -> IO [Config] runConfigParser fname = do exists <- doesFileExist fname progName <- getProgName if exists then do { results <- runX (readDocument [withValidate no] fname >>> propagateNamespaces //> hasName "config" >>> multi parseConfig) ; return results} else do { hPutStrLn stderr (progName ++ ": No config file found. Using default config") ; return [] } -- | An arrow for parsing the config file. Cf. implementation of -- 'runConfigParser' for usage. parseConfig :: IOSArrow XmlTree Config parseConfig = pcTextRoot <+> pcDroppedTreeSimple <+> pcLinebreak <+> pcHyphen <+> pcNoBreak <+> pcAbbrev1CharToken <+> pcSingleDigitOrdinal <+> pcMonth <+> pcTcfRootNamespace <+> pcTcfTextCorpusNamespace <+> pcTcfMetadataNamespace <+> pcTcfIdBase <+> pcTcfTokenIdPrefix <+> pcTcfSentenceIdPrefix -- | Arrows for parsing special configuration aspects are all prefixed -- with pc which stands for parseConfig. pcTextRoot :: IOSArrow XmlTree Config pcTextRoot = hasName "textRoot" >>> getAttrValue0 "name" &&& getAttrValue0 "namespace" >>> arr (TextRoot . (uncurry mkNsName)) pcDroppedTreeSimple :: IOSArrow XmlTree Config pcDroppedTreeSimple = hasName "droppedTree" >>> getChildren >>> hasName "simpleElement" >>> getAttrValue0 "name" &&& getAttrValue0 "namespace" >>> arr (DroppedTree . (uncurry mkNsName)) pcLinebreak :: IOSArrow XmlTree Config pcLinebreak = hasName "tokenizer" >>> getChildren >>> hasName "linebreak" >>> getAttrValue0 "name" &&& getAttrValue0 "namespace" >>> arr (LineBreak . (uncurry mkNsName)) pcHyphen :: IOSArrow XmlTree Config pcHyphen = hasName "tokenizer" >>> getChildren >>> hasName "hyphen" >>> getAttrValue0 "char" >>> arr (Hyphen . head) pcNoBreak :: (ArrowXml a) => a XmlTree Config pcNoBreak = hasName "tokenizer" >>> getChildren >>> hasName "noBreak" >>> getAttrValue0 "char" >>> arr (NoBreak . head) pcMonth :: IOSArrow XmlTree Config pcMonth = hasName "tokenizer" >>> getChildren >>> hasName "month" >>> getChildren >>> isText >>> getText >>> arr (Month) pcAbbrev1CharToken :: IOSArrow XmlTree Config pcAbbrev1CharToken = hasName "tokenizer" >>> getChildren >>> hasName "abbrev1Char" >>> getAttrValue0 "abbrev" >>> arr (Abbrev1CharToken . (== "True")) pcSingleDigitOrdinal :: (ArrowXml a) => a XmlTree Config pcSingleDigitOrdinal = hasName "tokenizer" >>> getChildren >>> hasName "singleDigitOrdinal" >>> getAttrValue0 "ordinal" >>> arr (SingleDigitOrdinal . (== "True")) pcTcfRootNamespace :: (ArrowXml a) => a XmlTree Config pcTcfRootNamespace = hasName "tcf" >>> getChildren >>> hasName "tcfRootNamespace" >>> getAttrValue "namespace" >>> arr (TcfRootNamespace . defaultOnNull defaultTcfRootNamespace) pcTcfTextCorpusNamespace :: IOSArrow XmlTree Config pcTcfTextCorpusNamespace = hasName "tcf" >>> getChildren >>> hasName "tcfTextCorpusNamespace" >>> getAttrValue "namespace" >>> arr (TcfTextCorpusNamespace . defaultOnNull defaultTcfTextCorpusNamespace) pcTcfMetadataNamespace :: IOSArrow XmlTree Config pcTcfMetadataNamespace = hasName "tcf" >>> getChildren >>> hasName "tcfMetadataNamespace" >>> getAttrValue "namespace" >>> arr (TcfMetadataNamespace . defaultOnNull defaultTcfMetadataNamespace) pcTcfIdBase :: IOSArrow XmlTree Config pcTcfIdBase = hasName "tcf" >>> getChildren >>> hasName "idBase" >>> getAttrValue "base" >>> arr (TcfIdBase . fromMaybe defaultTcfIdBase . fmap fst . C.readInt . C.pack) pcTcfTokenIdPrefix :: IOSArrow XmlTree Config pcTcfTokenIdPrefix = hasName "tcf" >>> getChildren >>> hasName "tokenIdPrefix" >>> getAttrValue "prefix" >>> arr (TcfTokenIdPrefix . defaultOnNull defaultTcfTokenIdPrefix) pcTcfSentenceIdPrefix :: IOSArrow XmlTree Config pcTcfSentenceIdPrefix = hasName "tcf" >>> getChildren >>> hasName "sentenceIdPrefix" >>> getAttrValue "prefix" >>> arr (TcfSentenceIdPrefix . defaultOnNull defaultTcfSentenceIdPrefix) -- | Helper function defaultOnNull :: [a] -> [a] -> [a] defaultOnNull deflt [] = deflt defaultOnNull _ (x:xs) = x:xs
lueck/htcf
src/HTCF/ConfigParser.hs
gpl-3.0
14,441
0
18
3,459
2,546
1,383
1,163
259
2
module Constraint.Strategy.Simple ( SimpleStrategy ) where import Constraint.Strategy import Data.Traversable (sequenceA) data SimpleStrategy = Simple instance ConstraintStrategy SimpleStrategy where feasibleArrangements = feasibleNormalArrangements feasibleNormalArrangements :: ConstraintMap a -> [Arrangement a] feasibleNormalArrangements = filter validArrangement . sequenceA where validArrangement = nodupes . elems nodupes [] = True nodupes (y:ys) = notElem y ys && nodupes ys
recursion-ninja/SecretSanta
Constraint/Strategy/Simple.hs
gpl-3.0
529
0
9
100
125
67
58
13
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleContexts #-} module Sara.Semantic.Checker ( checkWithoutMain , checkWithMain ) where import Text.Parsec.Pos import Control.Monad import Control.Monad.Identity import Control.Monad.Except import Control.Monad.State.Strict import Data.Monoid import qualified Data.Map as M import Sara.Ast.AstUtils import Sara.Ast.Meta import qualified Sara.Ast.Builtins as B import Sara.Ast.Operators import Sara.Ast.Syntax import Sara.Errors import qualified Sara.Ast.Types as T checkWithoutMain :: Program a b c NodeMeta -> ErrorOr () checkWithoutMain = checkProgram checkWithMain :: Program a b c NodeMeta -> ErrorOr () checkWithMain p = checkMain p >> checkProgram p checkMain :: Program a b c NodeMeta -> ErrorOr () checkMain program = unless (hasMain program) noMain hasMain :: Program a b c d -> Bool hasMain = getAny . foldMapSignatures (\s -> Any $ sigName s == "main") checkProgram :: Program a b c NodeMeta -> ErrorOr () checkProgram p = checkSignatures p >> checkAssignments p checkSignatures :: Program a b c NodeMeta -> ErrorOr () checkSignatures = mapMSignatures_ checkSignature where checkSignature Signature{ sigName = "main", args = [], retType = T.Integer } = return () checkSignature s@Signature{ sigName = "main", args = [], retType = t } = invalidMainRetType t (signaturePos s) checkSignature s@Signature{ sigName = "main", args = a } = invalidMainArgs (map varType a) (signaturePos s) checkSignature Signature{..} = checkArgs args $ functionOrMethod isPure sigName checkArgs :: [TypedVariable b NodeMeta] -> FunctionOrMethod -> ErrorOr () checkArgs args functionOrMethod = evalStateT (mapM_ checkArg args) M.empty where checkArg :: TypedVariable b NodeMeta -> StateT (M.Map Name SourcePos) (ExceptT Error Identity) () checkArg var = do let name = varName var let pos = typedVarPos var case B.stringToBuiltinVar name of Just B.Result -> lift $ resultArg pos _ -> return () previousPos <- gets $ M.lookup name case previousPos of Just pos' -> lift $ redeclaredArgument name functionOrMethod pos' pos Nothing -> return () modify $ M.insert name pos return () checkAssignments :: Program a b c NodeMeta -> ErrorOr () checkAssignments = mapMExpressions_ checkAssignment where checkAssignment BinaryOperation{ left = left, binOp = Assign } = checkAssignable left checkAssignment _ = return () checkAssignable Variable{} = return () checkAssignable a = notAssignable $ expressionPos a
Lykos/Sara
src/lib/Sara/Semantic/Checker.hs
gpl-3.0
2,789
0
13
702
844
432
412
55
4
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, RankNTypes#-} ----------------------------------------------------------------------------- -- | -- Module : Numerical.PETSc.Internal.PutGet.SVD -- Copyright : (c) Marco Zocca 2015 -- License : LGPL3 -- Maintainer : zocca . marco . gmail . com -- Stability : experimental -- -- | SVD Mid-level interface -- ----------------------------------------------------------------------------- module Numerical.PETSc.Internal.PutGet.SVD where import Numerical.PETSc.Internal.InlineC import Numerical.PETSc.Internal.Types import Numerical.PETSc.Internal.C2HsGen.TypesC2HsGen import Numerical.PETSc.Internal.Exception import Numerical.PETSc.Internal.Utils import Numerical.PETSc.Internal.PutGet.Vec import Numerical.PETSc.Internal.PutGet.Mat import Control.Exception withSvdCreate :: Comm -> (SVD -> IO a) -> IO a withSvdCreate k = bracket (svdCreate k) svdDestroy where svdCreate cc = chk1 $ svdCreate' cc svdDestroy s = chk0 $ svdDestroy' s withSvdCreateSetup :: Comm -> Mat -> (SVD -> IO a) -> IO a withSvdCreateSetup cc oper act = withSvdCreate cc $ \s -> do chk0 $ svdSetOperator' s oper act s withSvdCreateSetupSolve :: Comm -> Mat -> (SVD -> IO a) -> IO a withSvdCreateSetupSolve cc oper postsolve = withSvdCreateSetup cc oper $ \s -> do chk0 $ svdSolve' s postsolve s
ocramz/petsc-hs
src/Numerical/PETSc/Internal/PutGet/SVD.hs
gpl-3.0
1,356
0
10
200
299
165
134
22
1
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, -- | 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.NotFound import Response.Post import Response.Privacy import Response.Search import Response.Export
pkukulak/courseography
hs/Response.hs
gpl-3.0
887
0
5
272
138
92
46
24
0
import Parsers import Exprs as E import Data.Char import Control.Monad import Control.Applicative number :: Parser Integer number = do ds <- some digit return (read ds :: Integer) constInt :: Parser E.Expr constInt = do n <- token number return $ E.Const (E.IntV n) addExprP :: Parser E.Expr addExprP = do lhs <- constInt token $ literal "+" rhs <- constInt return $ lhs E.:+: rhs lambdaExprP :: Parser E.Expr lambdaExprP = do token $ literal "/" vars <- many rhs <- constInt return $ lhs E.:+: rhs expr :: Parser E.Expr expr = addExprP <|> constInt ifP = do spaces literal "if" `context` "ifP" test s = runParser expr s
2016-Fall-UPT-PLDA/labs
week-04/week-04.hs
gpl-3.0
809
1
11
299
266
128
138
35
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.EC2.GetConsoleOutput -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Gets the console output for the specified instance. -- -- Instances do not have a physical monitor through which you can view their -- console output. They also lack physical controls that allow you to power up, -- reboot, or shut them down. To allow these actions, we provide them through -- the Amazon EC2 API and command line interface. -- -- Instance console output is buffered and posted shortly after instance boot, -- reboot, and termination. Amazon EC2 preserves the most recent 64 KB output -- which is available for at least one hour after the most recent post. -- -- For Linux instances, the instance console output displays the exact console -- output that would normally be displayed on a physical monitor attached to a -- computer. This output is buffered because the instance produces it and then -- posts it to a store where the instance's owner can retrieve it. -- -- For Windows instances, the instance console output includes output from the -- EC2Config service. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-GetConsoleOutput.html> module Network.AWS.EC2.GetConsoleOutput ( -- * Request GetConsoleOutput -- ** Request constructor , getConsoleOutput -- ** Request lenses , gcoDryRun , gcoInstanceId -- * Response , GetConsoleOutputResponse -- ** Response constructor , getConsoleOutputResponse -- ** Response lenses , gcorInstanceId , gcorOutput , gcorTimestamp ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data GetConsoleOutput = GetConsoleOutput { _gcoDryRun :: Maybe Bool , _gcoInstanceId :: Text } deriving (Eq, Ord, Read, Show) -- | 'GetConsoleOutput' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gcoDryRun' @::@ 'Maybe' 'Bool' -- -- * 'gcoInstanceId' @::@ 'Text' -- getConsoleOutput :: Text -- ^ 'gcoInstanceId' -> GetConsoleOutput getConsoleOutput p1 = GetConsoleOutput { _gcoInstanceId = p1 , _gcoDryRun = Nothing } gcoDryRun :: Lens' GetConsoleOutput (Maybe Bool) gcoDryRun = lens _gcoDryRun (\s a -> s { _gcoDryRun = a }) -- | The ID of the instance. gcoInstanceId :: Lens' GetConsoleOutput Text gcoInstanceId = lens _gcoInstanceId (\s a -> s { _gcoInstanceId = a }) data GetConsoleOutputResponse = GetConsoleOutputResponse { _gcorInstanceId :: Maybe Text , _gcorOutput :: Maybe Text , _gcorTimestamp :: Maybe ISO8601 } deriving (Eq, Ord, Read, Show) -- | 'GetConsoleOutputResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gcorInstanceId' @::@ 'Maybe' 'Text' -- -- * 'gcorOutput' @::@ 'Maybe' 'Text' -- -- * 'gcorTimestamp' @::@ 'Maybe' 'UTCTime' -- getConsoleOutputResponse :: GetConsoleOutputResponse getConsoleOutputResponse = GetConsoleOutputResponse { _gcorInstanceId = Nothing , _gcorTimestamp = Nothing , _gcorOutput = Nothing } -- | The ID of the instance. gcorInstanceId :: Lens' GetConsoleOutputResponse (Maybe Text) gcorInstanceId = lens _gcorInstanceId (\s a -> s { _gcorInstanceId = a }) -- | The console output, Base64 encoded. gcorOutput :: Lens' GetConsoleOutputResponse (Maybe Text) gcorOutput = lens _gcorOutput (\s a -> s { _gcorOutput = a }) -- | The time the output was last updated. gcorTimestamp :: Lens' GetConsoleOutputResponse (Maybe UTCTime) gcorTimestamp = lens _gcorTimestamp (\s a -> s { _gcorTimestamp = a }) . mapping _Time instance ToPath GetConsoleOutput where toPath = const "/" instance ToQuery GetConsoleOutput where toQuery GetConsoleOutput{..} = mconcat [ "DryRun" =? _gcoDryRun , "InstanceId" =? _gcoInstanceId ] instance ToHeaders GetConsoleOutput instance AWSRequest GetConsoleOutput where type Sv GetConsoleOutput = EC2 type Rs GetConsoleOutput = GetConsoleOutputResponse request = post "GetConsoleOutput" response = xmlResponse instance FromXML GetConsoleOutputResponse where parseXML x = GetConsoleOutputResponse <$> x .@? "instanceId" <*> x .@? "output" <*> x .@? "timestamp"
kim/amazonka
amazonka-ec2/gen/Network/AWS/EC2/GetConsoleOutput.hs
mpl-2.0
5,243
0
11
1,114
654
396
258
71
1
module Handler.Supplier where import Import import Handler.Common import Data.Maybe getSupplierR :: Handler Html getSupplierR = do sups <- runDB $ selectList [] [Asc SupplierIdent] defaultLayout $ do setTitleI MsgSuppliers $(widgetFile "supplier") getNewSupplierR :: Handler Html getNewSupplierR = do (newSupplierWidget, enctype) <- generateFormPost $ renderBootstrap3 BootstrapBasicForm newSupplierForm defaultLayout $ do setTitleI MsgNewSupplier $(widgetFile "newSupplier") postNewSupplierR :: Handler Html postNewSupplierR = do ((res, _), _) <- runFormPost $ renderBootstrap3 BootstrapBasicForm newSupplierForm case res of FormSuccess sup -> do runDB $ insert_ sup setMessageI MsgSupplierCreated redirect SupplierR _ -> do setMessageI MsgSupplierNotCreated redirect SupplierR newSupplierForm :: AForm Handler Supplier newSupplierForm = Supplier <$> areq textField (bfs MsgName) Nothing <*> areq textareaField (bfs MsgAddress) Nothing <*> areq textField (bfs MsgTelNr) Nothing <*> areq emailField (bfs MsgEmail) Nothing <*> areq textField (bfs MsgCustomerId) Nothing <*> aopt (selectField avatars) (bfs MsgSelectAvatar) Nothing <* bootstrapSubmit (msgToBSSubmit MsgSubmit) where avatars = do ents <- runDB $ selectList [] [Asc AvatarIdent] optionsPairs $ map (\ent -> ((avatarIdent $ entityVal ent), entityKey ent)) ents data SupConf = SupConf { supConfIdent :: Text , supConfAddr :: Textarea , supConfTel :: Text , supConfEmail :: Text , supConfCustomerId :: Text , supConfAvatar :: Maybe AvatarId } getModifySupplierR :: SupplierId -> Handler Html getModifySupplierR sId = do mSup <- runDB $ get sId case mSup of Just sup -> do (modifySupplierWidget, enctype) <- generateFormPost $ renderBootstrap3 BootstrapBasicForm $ modifySupplierForm sup defaultLayout $ do setTitleI MsgEditSupplier $(widgetFile "modifySupplier") Nothing -> do setMessageI MsgSupplierUnknown redirect $ SupplierR postModifySupplierR :: SupplierId -> Handler Html postModifySupplierR sId = do mSup <- runDB $ get sId case mSup of Just sup -> do ((res, _), _) <- runFormPost $ renderBootstrap3 BootstrapBasicForm $ modifySupplierForm sup case res of FormSuccess msup -> do runDB $ update sId [ SupplierIdent =. supConfIdent msup , SupplierAddress =. supConfAddr msup , SupplierTel =. supConfTel msup , SupplierEmail =. supConfEmail msup , SupplierCustomerId =. supConfCustomerId msup , SupplierAvatar =. supConfAvatar msup ] setMessageI MsgSupplierEdited redirect SupplierR _ -> do setMessageI MsgSupplierNotEdited redirect SupplierR Nothing -> do setMessageI MsgSupplierUnknown redirect SupplierR modifySupplierForm :: Supplier -> AForm Handler SupConf modifySupplierForm sup = SupConf <$> areq textField (bfs MsgName) (Just $ supplierIdent sup) <*> areq textareaField (bfs MsgAddress) (Just $ supplierAddress sup) <*> areq textField (bfs MsgTelNr) (Just $ supplierTel sup) <*> areq textField (bfs MsgEmail) (Just $ supplierEmail sup) <*> areq textField (bfs MsgCustomerId) (Just $ supplierCustomerId sup) <*> aopt (selectField avatars) (bfs MsgSelectAvatar) (Just $ supplierAvatar sup) <* bootstrapSubmit (msgToBSSubmit MsgSubmit) where avatars = do ents <- runDB $ selectList [] [Asc AvatarIdent] optionsPairs $ map (\ent -> ((avatarIdent $ entityVal ent), entityKey ent)) ents
nek0/yammat
Handler/Supplier.hs
agpl-3.0
3,688
0
21
863
1,099
526
573
99
3
module School (School, empty, grade, add, sorted) where import qualified Data.Map as M import qualified Data.Set as S import Control.Arrow (second) type Grade = Int type Student = String type School = M.Map Grade (S.Set Student) empty :: School empty = M.empty sorted :: School -> [(Grade, [Student])] sorted = map (second S.toAscList) . M.toAscList grade :: Grade -> School -> [Student] grade gradeNum = S.toAscList . M.findWithDefault S.empty gradeNum add :: Grade -> Student -> School -> School add gradeNum student = M.insertWith S.union gradeNum (S.singleton student)
mscoutermarsh/exercism_coveralls
assignments/haskell/grade-school/example.hs
agpl-3.0
578
0
9
93
220
125
95
15
1
{-# LANGUAGE GADTs #-} -- Calculating exception machine: http://www.cs.nott.ac.uk/~pszgmh/bib.html#machine -- Syntax data Expr = Val Int | Add Expr Expr deriving (Show) -- Semantics: eval :: Expr -> Int eval (Val n) = n eval (Add x y) = eval x + eval y -- Expression e = Add (Val 3) (Val 5) -- > e -- Add (Val 3) (Val 5) -- > eval e -- 8 ----- ~~~~~~~~~~~~~~~ ----- ----- ~~~~~~~~~~~~~~~ ----- -- Step 1 - Add Continuations ------------------------------ -- Make the evaluation order _explicit_, by rewriting the semantics in -- _continuation-passing_ style (CPS) -- -- Def: A continuation is a functino that is applied to the result of -- another computation -- example: (eval x) (+ eval y) -- |_ computtion |___ continuation -- -- Basic idea: Generalize semantics to make the use of continuations explicit {- Define new semantics: eval' :: Expr -> (Int -> Int) -> Int |___ continuation applies to result of calculation such that eval' e c = c (eval e) and hence eval e = eval' e (\n -> n) -} type Cont = Int -> Int -- evaluation order is explicit -- first eval' x -- then eval' y -- thena apply (+) eval' :: Expr -> Cont -> Int eval' (Val n) c = c n eval' (Add x y) c = eval' x (\n -> eval' y (\m -> c (n+m))) -- > eval' e (+100) -- 108 -- > eval' e id -- 8 ----- ~~~~~~~~~~~~~~~ ----- ----- ~~~~~~~~~~~~~~~ ----- -- Step 2 - Defunctionalization -------------------------------- -- Abstract machines are first-order concepts. -- We need to simulate higher orderness -- Basic idea: Represent the continuations we actually need using a datatype eval0 :: Expr -> Int eval0 e = eval' e id -- > eval0 e -- 8 -- Combinators , time: 22:52 c1 :: Cont c1 = id -- \n -> n c2 :: Expr -> Cont -> Cont c2 y c = \n -> eval' y (c3 n c) c3 :: Int -> Cont -> Cont c3 n c = \m -> c (n + m) eval1' :: Expr -> Cont -> Int eval1' (Val n) c = c n eval1' (Add x y) c = eval1' x (c2 y c) eval1 :: Expr -> Int eval1 e = eval1' e c1 -- Now apply defunctionalization -- CONT: abstract machine representation of continuation data CONT = C1 | C2 Expr CONT | C3 Int CONT apply :: CONT -> Cont apply C1 = c1 apply (C2 y c) = c2 y (apply c) apply (C3 n c) = c3 n (apply c) data CONT' where C1' :: CONT' C2' :: Expr -> CONT' -> CONT' C3' :: Int -> CONT' -> CONT' -- Semantics are now 1st order (CONT is not a function type, it is -- representation of continuation) ----------------------------------------------------------------------- eval'' :: Expr -> CONT -> Int --eval'' e c = eval' e (apply c) eval'' (Val n) c = apply c n -- can be apply'' c n eval'' (Add x y) c = eval'' x (C2 y c) apply'' :: CONT -> Int -> Int apply'' C1 n = n apply'' (C2 y c) n = eval'' y (C3 n c) apply'' (C3 n c) m = apply c (n+m) eval2 :: Expr -> Int eval2 e = eval'' e C1 ----- ~~~~~~~~~~~~~~~ ----- ----- ~~~~~~~~~~~~~~~ ----- -- Step 3 : Refactor --------------------- -- Abstract machine -- Control stack type data Contr = STOP | EVAL Expr Contr | ADD Int Contr run :: Expr -> Int run e = evalr e STOP -- used to be called eval'' evalr :: Expr -> Contr -> Int evalr (Val n) c = exec c n evalr (Add x y) c = evalr x (EVAL y c) -- used to be called apply exec :: Contr -> Int -> Int exec STOP n = n exec (EVAL y c) n = evalr y (ADD n c) exec (ADD n c) m = exec c (n+m) {- run (Add (Val 1) (Val 2)) = evalr (Add (Val 1) (Val 2)) STOP = evalr (Val 1) (EVAL (Val 2) STOP) = exec (EVAL (Val 2) STOP) 1 = evalr (Val 2) (ADD 1 STOP) = exec (ADD 1 STOP) 2 = exec 3 STOP = 3 -} -- > run e -- 8 ----- ~~~~~~~~~~~~~~~ ----- ----- ~~~~~~~~~~~~~~~ ----- -- ~~~=== Adding Exceptions ===~~~
egaburov/funstuff
Haskell/exceptions/exceptions0.hs
apache-2.0
3,792
1
13
1,000
960
514
446
58
1