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 Main where
import Math
import Graphics.Gloss
import Data.Maybe (mapMaybe)
(width, height) = (800, 600)
pixelsPerMeter = 100
type World =
( V2 -- start
, V2 -- target
, Scalar -- gravity
, Scalar -- power
)
testWorld :: World
testWorld = ((1, 1), (7, 2), (9.81), 9)
makePaths :: World -> [Path]
makePaths (s@(sx, _), e@(ex, _), g, v) = map (zip xs) $ mapMaybe toHeights as
where
as = requiredToHit s e v g
xs = [sx, (sx + 0.1) .. ex]
toHeights a = sequence
$ map (\x -> heightAt s x a v g) xs
draw w@((startx, starty), (targetx, targety), g, v) =
Translate (width / (-2)) (height / (-2))
$ Scale (pixelsPerMeter) (pixelsPerMeter)
$ Pictures
( [ (Translate startx starty $ Color white (Circle 0.1))
, (Translate targetx targety $ Color red (Circle 0.1))
]
++ zipWith Color [green, blue] (map Line (makePaths w))
)
main = do
putStrLn "Testing shot trajectory solving:"
putStrLn "Should show one or more curves between the circled points"
display
(InWindow "test" (floor width, floor height) (50, 50))
black
(draw testWorld)
| tomcumming/tennis | src/Test/simpleshot.hs | gpl-2.0 | 1,122 | 0 | 14 | 276 | 478 | 268 | 210 | 33 | 1 |
-- | A module to reference work on Stack
module PurelyFunctionalDataStructure.Stack where
-- Exercise 2.1 Write a function suffixes of type a list -» a list list that takes a
-- list xs and returns a list of all the suffixes of xs in decreasing order of length.
--
-- For example:
-- suffixes [1,2,3,4] = [[1,2,3,4], [2,3,4], [3,4], [4], [ ] ]
-- Show that the resulting list of suffixes can be generated in O(n) time and represented in O(n) space.
suffixes :: [a] -> [[a]]
suffixes [] = [[]]
suffixes l@(_:xs) = l:suffixes xs
-- λ> suffixes [1,2,3,4]
-- [[1,2,3,4],[2,3,4],[3,4],[4],[]]
-- time: We walk over the complete sequence of the list of size n so O(n) time.
-- space: We keep the reference of the previous values.
-- The first element of the result is the list itself, no duplication.
-- After that, the second element is the tail of the list, this is shared with the initial list too.
-- And so on and so forth.
-- So O(n) space.
| ardumont/haskell-lab | src/PurelyFunctionalDataStructure/Stack.hs | gpl-2.0 | 948 | 0 | 8 | 178 | 79 | 51 | 28 | 4 | 1 |
module Net.ClientInterface where
import Data.Word(Word16)
import qualified Net.IPv4 as IP
import qualified Net.ARP_Protocol as ARP
import qualified Net.UDP_Client as UC
import qualified Net.TCP_Client as TC
data Config = DHCP
| Fixed { myIP,routerIP,netmask::IP.Addr }
deriving (Show)
fixed myIP routerIP = Fixed myIP routerIP (IP.defaultNetmask myIP)
data Net m
= Net {
ping :: IP.Addr -> Word16 -> Word16 -> m (),
dump :: m ARP.CacheDump,
udp :: UC.Interface m,
tcp :: TC.Interface m
}
| nh2/network-house | Net/ClientInterface.hs | gpl-2.0 | 536 | 2 | 13 | 122 | 174 | 104 | 70 | 16 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Example.Interface where
--import Foreign.Ptr
--import Foreign.C
--import Foreign.Marshal.Array
foreign import ccall unsafe "example_interface.h c_test" runTest :: IO ()
| DanielMe/cpp-example | src/Example/Interface.hs | gpl-3.0 | 222 | 0 | 7 | 27 | 29 | 18 | 11 | 3 | 0 |
module SharedWorld.Argument (
Argument, PeerId(..), startArgument
) where
import SharedWorld.World ( World )
-- | An argument is a way to change your mind about the world.
data Argument w = Argument
{ argMostRecentWorld :: w
, argOtherPeerId :: PeerId
}
-- Synchronization sketch:
--
-- - Both parties start in agreement; they check by exchanging checksums of their states.
--
-- - Each changes their state and sends changes to the other.
--
-- - Changes are always sent with strictly increasing consecutive sequence numbers. The
-- counter is reset at each Resolution.
--
-- - You immediately apply your own changes, but you buffer the other side's changes.
--
-- - One of the peers is Dom, the other is Sub.
--
-- - Dom may initiate Resolution; at the end of which the two sides agree on the world.
--
-- - During Resolution: Dom sends Sub the Resolution.Start; Sub replies with
-- Resolution.Ok; each has implicitly specified the sequence number up to which to
-- resolve; each applies the other's changes in addition to their own; each check
-- agreement by exchanging checksums of the world; each resets their sequence number
-- counter; the world is locked during synchronization.
--
-- | To prevent misunderstandings, peers identify themselves when arguing.
--
-- Celine's Law: Communication can only happen between equals.
data PeerId = PeerId (String, Int)
-- | Start an argument with another peer.
startArgument :: (World w) => w -> PeerId -> IO (Argument w)
startArgument world peerId = do
return (Argument { argMostRecentWorld = world
, argOtherPeerId = peerId
})
| scvalex/shared-world | src/SharedWorld/Argument.hs | gpl-3.0 | 1,684 | 0 | 10 | 374 | 158 | 103 | 55 | 11 | 1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
module Surpasser where
import Test.QuickCheck.Modifiers
import Data.List (sort)
-- In this pearl we solve a small programming exercise of Martin
-- Rem. While Rem's solution uses binary search, our solution is
-- another application of divide and conquer. By definition, a
-- surpasser of an element of an array is a greater element to the
-- right, so x[j] is a surpasser of x[i] if i<j and x[i] , x[j]. The
-- surpasser count of an element is the number of its surpassers.
-- NOTE: solution assumes sorted table version, which allows extended reasoning
msc :: Ord a => [a] -> Int
msc = maximum . map snd . table
table :: Ord a => [a] -> [(a, Int)]
table [x] = [(x,0)]
table xs = join (m-n) (table ys) (table zs)
where m = length xs
n = m `div` 2
(ys,zs) = splitAt n xs
join :: (Eq b, Num b, Ord a) => b -> [(a, b)] -> [(a, b)] -> [(a, b)]
join 0 txs [] = txs
join _ [] tys = tys
join n txs@((x,c) : txs') tys@((y,d) : tys') | x < y = (x,c+n) : join n txs' tys
| x >= y = (y,d) : join (n-1) txs tys'
-- not divide and conquer friendly
msc' :: Ord a => [a] -> Int
msc' xs = maximum [scount z zs | (z:zs) <- tails xs]
scount :: Ord a => a -> [a] -> Int
scount x = length . filter (x <)
scountHead :: Ord a => [a] -> Int
scountHead (x:xs) = scount x xs
-- different from Data.List.tails:
-- Data.List.tails [] = [[]]
-- tails [] = []
tails :: [a] -> [[a]]
tails [] = []
tails (x:xs) = (x:xs) : tails xs
prop_tailsDivideConquer :: Eq a => [a] -> [a] -> Bool
prop_tailsDivideConquer as bs = tails (as ++ bs) == map (++bs) (tails as) ++ tails bs
-- inefficient version
table' :: Ord a => [a] -> [(a, Int)]
table' xs = sort [(z,scount z zs) | z:zs <- tails xs]
{-
table (xs ++ ys)
[(z,scount z zs) | z:zs <- tails (xs ++ ys)]
[(z,scount z zs) | z:zs <- map (++ys) (tails xs) ++ tails ys]
[(z,scount z (zs ++ ys)) | z:zs <- tails xs] ++
[(z,scount z zs) | z:zs <- tails ys]
[(z,scount z zs + scount z ys) | z:zs <- tails xs] ++
[(z,scount z zs) | z:zs <- tails ys]
[(z,c + scount z (map fst (table ys))) | (z,c) <- table xs] ++ table ys
-}
-- inefficient version
join' :: Ord a => [(a, Int)] -> [(a, Int)] -> [(a, Int)]
join' txs tys = [(z,c + tcount z tys) | (z,c) <- txs] `sortedMerge` tys
-- NOTE: own implementation, not mentioned in book
sortedMerge :: Ord a => [a] -> [a] -> [a]
sortedMerge xs [] = xs
sortedMerge [] ys = ys
sortedMerge xxs@(x:xs) yys@(y:ys) =
if x <= y then x : sortedMerge xs yys else y : sortedMerge xxs ys
-- naive inefficient version
tcount' :: Ord a => a -> [(a, b)] -> Int
tcount' z tys = scount z (map fst tys)
-- NOTE: assumes table to be sorted!
tcount :: Ord a => a -> [(a, b)] -> Int
tcount z = length . dropWhile ((z>=) . fst)
prop_SortedMergeCorrect :: Ord a => OrderedList a -> OrderedList a -> Bool
prop_SortedMergeCorrect (Ordered xs) (Ordered ys) =
sortedMerge xs ys == sort (xs ++ ys)
prop_MSCVersionsEquivalent :: Ord a => NonEmptyList a -> Bool
prop_MSCVersionsEquivalent (NonEmpty xs) = msc' xs == msc xs
| markus1189/PearlsFAD | src/Surpasser.hs | gpl-3.0 | 3,096 | 0 | 10 | 719 | 1,159 | 626 | 533 | 46 | 2 |
import System.Random
threeCoins :: StdGen -> (Bool, Bool, Bool)
threeCoins gen =
let (firstCoin, newGen) = random gen
(secondCoin, newGen') = random newGen
(thirdCoin, newGen'') = random newGen'
in (firstCoin, secondCoin, thirdCoin)
lst = take 5 $ randoms (mkStdGen 12) :: [Int]
finiteRandoms :: (RandomGen g, Random a, Num n, Eq n) => n -> g -> ([a], g)
finiteRandoms 0 gen = ([], gen)
finiteRandoms n gen =
let (value, newGen) = random gen
(restOfList, finalGen) = finiteRandoms (n-1) newGen
in (value:restOfList, finalGen)
| lamontu/learning_haskell | random.hs | gpl-3.0 | 570 | 0 | 11 | 128 | 251 | 135 | 116 | 14 | 1 |
{- Compare our custom implementations with those provided by Data.Split -}
module Main where
import Criterion.Main
import qualified Data.List.Split as S
import qualified CustomPrelude as C
list :: [Int]
list = take 1000 $ cycle [1..100]
main = defaultMain [
bench "Data.List.splitWhen: " $ nf (S.splitWhen even) list
, bench "Custom splitWhen: " $ nf (C.splitWhen even) list
, bench "Data.List.splitOn: " $ nf (S.splitOn [10]) list
, bench "Custom splitOn: " $ nf (C.splitOn [10]) list
]
| ajnsit/custom-prelude | Benchmark.hs | gpl-3.0 | 537 | 0 | 11 | 127 | 159 | 86 | 73 | 11 | 1 |
-- drop every k'yh element
p16 :: [a] -> Int -> [a]
p16 xs n = p16' xs n where
p16' [] _ = []
p16' (x:xs) 1 = p16 xs n
p16' (x:xs) n = x : p16' xs (n-1)
| yalpul/CENG242 | H99/11-20/p16.hs | gpl-3.0 | 178 | 0 | 10 | 66 | 107 | 55 | 52 | 5 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DataFusion.Projects.Locations.Instances.Create
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a new Data Fusion instance in the specified project and
-- location.
--
-- /See:/ <https://cloud.google.com/data-fusion/docs Cloud Data Fusion API Reference> for @datafusion.projects.locations.instances.create@.
module Network.Google.Resource.DataFusion.Projects.Locations.Instances.Create
(
-- * REST Resource
ProjectsLocationsInstancesCreateResource
-- * Creating a Request
, projectsLocationsInstancesCreate
, ProjectsLocationsInstancesCreate
-- * Request Lenses
, plicParent
, plicInstanceId
, plicXgafv
, plicUploadProtocol
, plicAccessToken
, plicUploadType
, plicPayload
, plicCallback
) where
import Network.Google.DataFusion.Types
import Network.Google.Prelude
-- | A resource alias for @datafusion.projects.locations.instances.create@ method which the
-- 'ProjectsLocationsInstancesCreate' request conforms to.
type ProjectsLocationsInstancesCreateResource =
"v1" :>
Capture "parent" Text :>
"instances" :>
QueryParam "instanceId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Instance :> Post '[JSON] Operation
-- | Creates a new Data Fusion instance in the specified project and
-- location.
--
-- /See:/ 'projectsLocationsInstancesCreate' smart constructor.
data ProjectsLocationsInstancesCreate =
ProjectsLocationsInstancesCreate'
{ _plicParent :: !Text
, _plicInstanceId :: !(Maybe Text)
, _plicXgafv :: !(Maybe Xgafv)
, _plicUploadProtocol :: !(Maybe Text)
, _plicAccessToken :: !(Maybe Text)
, _plicUploadType :: !(Maybe Text)
, _plicPayload :: !Instance
, _plicCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsInstancesCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plicParent'
--
-- * 'plicInstanceId'
--
-- * 'plicXgafv'
--
-- * 'plicUploadProtocol'
--
-- * 'plicAccessToken'
--
-- * 'plicUploadType'
--
-- * 'plicPayload'
--
-- * 'plicCallback'
projectsLocationsInstancesCreate
:: Text -- ^ 'plicParent'
-> Instance -- ^ 'plicPayload'
-> ProjectsLocationsInstancesCreate
projectsLocationsInstancesCreate pPlicParent_ pPlicPayload_ =
ProjectsLocationsInstancesCreate'
{ _plicParent = pPlicParent_
, _plicInstanceId = Nothing
, _plicXgafv = Nothing
, _plicUploadProtocol = Nothing
, _plicAccessToken = Nothing
, _plicUploadType = Nothing
, _plicPayload = pPlicPayload_
, _plicCallback = Nothing
}
-- | The instance\'s project and location in the format
-- projects\/{project}\/locations\/{location}.
plicParent :: Lens' ProjectsLocationsInstancesCreate Text
plicParent
= lens _plicParent (\ s a -> s{_plicParent = a})
-- | The name of the instance to create.
plicInstanceId :: Lens' ProjectsLocationsInstancesCreate (Maybe Text)
plicInstanceId
= lens _plicInstanceId
(\ s a -> s{_plicInstanceId = a})
-- | V1 error format.
plicXgafv :: Lens' ProjectsLocationsInstancesCreate (Maybe Xgafv)
plicXgafv
= lens _plicXgafv (\ s a -> s{_plicXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plicUploadProtocol :: Lens' ProjectsLocationsInstancesCreate (Maybe Text)
plicUploadProtocol
= lens _plicUploadProtocol
(\ s a -> s{_plicUploadProtocol = a})
-- | OAuth access token.
plicAccessToken :: Lens' ProjectsLocationsInstancesCreate (Maybe Text)
plicAccessToken
= lens _plicAccessToken
(\ s a -> s{_plicAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plicUploadType :: Lens' ProjectsLocationsInstancesCreate (Maybe Text)
plicUploadType
= lens _plicUploadType
(\ s a -> s{_plicUploadType = a})
-- | Multipart request metadata.
plicPayload :: Lens' ProjectsLocationsInstancesCreate Instance
plicPayload
= lens _plicPayload (\ s a -> s{_plicPayload = a})
-- | JSONP
plicCallback :: Lens' ProjectsLocationsInstancesCreate (Maybe Text)
plicCallback
= lens _plicCallback (\ s a -> s{_plicCallback = a})
instance GoogleRequest
ProjectsLocationsInstancesCreate
where
type Rs ProjectsLocationsInstancesCreate = Operation
type Scopes ProjectsLocationsInstancesCreate =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsInstancesCreate'{..}
= go _plicParent _plicInstanceId _plicXgafv
_plicUploadProtocol
_plicAccessToken
_plicUploadType
_plicCallback
(Just AltJSON)
_plicPayload
dataFusionService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsInstancesCreateResource)
mempty
| brendanhay/gogol | gogol-datafusion/gen/Network/Google/Resource/DataFusion/Projects/Locations/Instances/Create.hs | mpl-2.0 | 5,957 | 0 | 18 | 1,323 | 863 | 503 | 360 | 127 | 1 |
{- hcd-expand-hus < pattern.hcd > pattern.hus
hus = Horizontal Uncompressed States
-- Clocks in signals on rising jtg_tck
-- TODO clock outputs on falling tck
-- TODO change timestamp to 200ns
This code doesn't stream because it has to read the last line of input before it
can write the first line of output.
Memory and runtime will suffer with large inputs.
-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Lib
main :: IO ()
main = do
f <- B.getContents
let
hus :: [ByteString]
hus =
B.lines f &
chunksOf 3 &
map expand
expand :: [ByteString] -> ByteString
expand [ pin,lens,states ] =
B.unwords [ pin
, B.concat (zipWith
(\len state -> B.replicate (fst . fromJust $ B.readInt len ) state) (B.words lens ) (B.unpack states ))]
expand x = error $
"expand called without 3 lines"
++ show x
mapM_ B.putStrLn hus
| gitfoxi/vcd-haskell | app/hcd-expand-hus.hs | agpl-3.0 | 1,022 | 0 | 21 | 304 | 211 | 111 | 100 | 22 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
module MT.MonadCont (
MonadCont(..)
) where
import Prelude (($))
import MT.Cont
import Monad
class (Monad m) => MonadCont r m | m -> r where
callCC :: ((a -> ContT r m b) -> ContT r m a) -> ContT r m a
instance (Monad m) => MonadCont r (ContT r m) where
callCC f = ContT $ \c -> runContT (f (\ x -> ContT $ \_ -> c x)) c
| seckcoder/lang-learn | haskell/lambda-calculus/src/MT/MonadCont.hs | unlicense | 480 | 0 | 15 | 124 | 180 | 99 | 81 | 11 | 0 |
{-# LANGUAGE RankNTypes, MultiWayIf #-}
module SSync.DataQueue (
DataQueue
, create
, validate
, firstByteOfBlock
, lastByteOfBlock
, afterBlock
, beforeBlock
, slide
, slideOff
, atEnd
, addBlock
, hashBlock
) where
{-
For the scanning process, we're interested in the following operations:
* "Give me the first byte of the current block and the last byte of the
block offset by 1"
* "Hash the current block"
* "Give me all the bytes after the current block"
So we will represent this as the following:
* If the current block is contained within a single chunk, a constructor
SingleChunk ByteString firstIndex lastIndex
* If the current block is NOT contained within a single chunk, a constructor
PolyChunk ByteString firstIndex possiblyEmptyChunkQueue ByteString lastIndex
Note that both indices are INCLUSIVE, and in the latter case it is relative to
the start of the last chunk.
-}
import Control.Monad (forM_)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Word (Word8)
import SSync.SimpleQueue
import SSync.Hash
-- None of these bytestrings may be empty!
data DataQueue = SingleChunk !ByteString !Int !Int
| PolyChunk !ByteString !Int !(SimpleQueue ByteString) !ByteString !Int
deriving (Show)
-- We'll always initially populate in single-chunk mode. This incurs
-- a little copying, but not too much.
create :: ByteString -> Int -> Int -> DataQueue
create bs a b
| BS.null bs = error "create: empty bytestring"
| a < 0 || a >= BS.length bs = error "create: first position out of range"
| b < a || b >= BS.length bs = error "create: second position out of range"
| otherwise = SingleChunk bs a b
validate :: (Monad m) => String -> DataQueue -> m ()
validate label (SingleChunk bs hd tl)
| hd > tl = error $ label ++ ": single: hd > tl"
| hd < 0 = error $ label ++ ": single: hd < 0"
| tl >= BS.length bs = error $ label ++ ": single: tl > len"
| otherwise = return ()
validate label (PolyChunk bs1 hd _ bs2 tl)
| hd < 0 = error $ label ++ ": poly: hd < 0"
| hd >= BS.length bs1 = error $ label ++ ": poly: hd > len"
| tl < 0 = error $ label ++ ": poly: tl < 0"
| tl >= BS.length bs2 = error $ label ++ ": poly: tl > len"
| otherwise = return ()
firstByteOfBlock :: DataQueue -> Word8
firstByteOfBlock (SingleChunk bs hd _) = BS.index bs hd
firstByteOfBlock (PolyChunk bs hd _ _ _) = BS.index bs hd
lastByteOfBlock :: DataQueue -> Word8
lastByteOfBlock (SingleChunk bs _ tl) = BS.index bs tl
lastByteOfBlock (PolyChunk _ _ _ bs tl) = BS.index bs tl
atEnd :: DataQueue -> Bool
atEnd (SingleChunk bs _ tl) = atEnd' bs tl
atEnd (PolyChunk _ _ _ bs tl) = atEnd' bs tl
atEnd' :: ByteString -> Int -> Bool
atEnd' bs tl = tl == BS.length bs - 1
afterBlock :: DataQueue -> ByteString
afterBlock (SingleChunk bs _ tl) = BS.drop (tl + 1) bs
afterBlock (PolyChunk _ _ _ bs tl) = BS.drop (tl + 1) bs
beforeBlock :: DataQueue -> ByteString
beforeBlock (SingleChunk bs hd _) = BS.take hd bs
beforeBlock (PolyChunk bs hd _ _ _) = BS.take hd bs
slide :: DataQueue -> Maybe (Maybe ByteString, DataQueue)
slide (SingleChunk bs hd tl) | atEnd' bs tl = Nothing
| otherwise = Just (Nothing, SingleChunk bs (hd+1) (tl+1))
slide (PolyChunk bs1 hd q bs2 tl) | atEnd' bs2 tl =
Nothing
| atEnd' bs1 hd =
case deq q of
Just (q', bs1') ->
Just (Just bs1, PolyChunk bs1' 0 q' bs2 (tl+1))
Nothing ->
Just (Just bs1, SingleChunk bs2 0 (tl+1))
| otherwise =
Just (Nothing, PolyChunk bs1 (hd+1) q bs2 (tl+1))
{-# INLINE slide #-}
-- | Slide only the head of the block.
slideOff :: DataQueue -> (Maybe ByteString, Maybe DataQueue)
slideOff (SingleChunk bs hd tl) | atEnd' bs hd = (Just bs, Nothing)
| otherwise = (Nothing, Just $ SingleChunk bs (hd+1) tl)
slideOff (PolyChunk bs1 hd q bs2 tl) | atEnd' bs1 hd =
case deq q of
Just (q', bs1') ->
(Just bs1, Just $ PolyChunk bs1' 0 q' bs2 tl)
Nothing ->
(Just bs1, Just $ SingleChunk bs2 0 tl)
| otherwise =
(Nothing, Just $ PolyChunk bs1 (hd+1) q bs2 tl)
{-# INLINE slideOff #-}
-- | Add a block, sliding too. Behavior is undefined if not 'atEnd'
addBlock :: DataQueue -> ByteString -> (Maybe ByteString, DataQueue)
addBlock (SingleChunk bs hd tl) bs2 | atEnd' bs tl =
if atEnd' bs hd -- this won't ever happen in practice
then (Just bs, SingleChunk bs2 0 0)
else (Nothing, PolyChunk bs (hd+1) empty bs2 0)
| otherwise =
error "Not at end of block"
addBlock (PolyChunk bs1 hd q bs2 tl) bs3 | atEnd' bs2 tl =
if atEnd' bs1 hd
then case deq q of
Nothing ->
(Just bs1, PolyChunk bs2 0 empty bs3 0)
Just (q', bs1') ->
(Just bs1, PolyChunk bs1' 0 (enq q' bs2) bs3 0)
else (Nothing, PolyChunk bs1 (hd+1) (enq q bs2) bs3 0)
| otherwise =
error "Not at end of block"
{-# INLINE addBlock #-}
hashBlock :: (Monad m) => DataQueue -> HashT m ByteString
hashBlock (SingleChunk bs hd tl) = do
updateS $ BS.take (1 + tl - hd) $ BS.drop hd bs
digestS
hashBlock (PolyChunk bs1 hd q bs2 tl) = do
updateS $ BS.drop hd bs1
forM_ (q2list q) updateS
updateS $ BS.take (tl+1) bs2
digestS
| socrata-platform/ssync | src/main/haskell/SSync/DataQueue.hs | apache-2.0 | 6,362 | 0 | 13 | 2,363 | 1,818 | 902 | 916 | 127 | 4 |
module Main where
import Control.Monad
import Control.Monad.IO.Class
import Control.Exception ( bracket )
import Data.Acid
import Data.Acid.Local ( createCheckpointAndClose )
import Happstack.Server
import Happstack.Server.Compression
import Happstack.Server.ClientSession
import Happstack.Server.SimpleHTTPS
import Bindrop.Session
import Bindrop.State
import Bindrop.Routes ( mainRoute )
httpConf :: Conf
httpConf = nullConf { port = 8082 }
httpsConf :: TLSConf
httpsConf = nullTLSConf
{ tlsPort = 8083
, tlsCert = "nils.cc.crt"
, tlsKey = "nils.key"
}
main :: IO ()
main = do
putStrLn "Starting server..."
key <- getDefaultKey
let sessionConf = mkSessionConf key
-- HTTP server
bracket (openLocalState initialBindropState)
(createCheckpointAndClose)
(\acid -> simpleHTTP httpConf $
withClientSessionT sessionConf $ mainRoute acid)
-- HTTPS server
--simpleHTTPS httpsConf mainHttp
mainHttp :: AcidState BindropState
-> ClientSessionT SessionData (ServerPartT IO) Response
mainHttp acid = do
_ <- compressedResponseFilter
mainRoute acid
httpsForward :: ServerPart Response
httpsForward = withHost $ \h -> uriRest $ \r -> do
let url = "https://" ++ takeWhile (':' /=) h ++ ":"
++ show (tlsPort httpsConf)
++ r
seeOther url (toResponse $ "Forwarding to: " ++ url ++ "\n")
| mcmaniac/bindrop | src/Main.hs | apache-2.0 | 1,398 | 0 | 19 | 297 | 363 | 196 | 167 | 40 | 1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleContexts, MagicHash #-}
module Codec.Picture.RGBA8 where
import Codec.Picture
import qualified Data.Vector.Storable as V
import qualified Data.Vector.Storable.Mutable as MV
import Foreign.Marshal.Utils
import Control.Monad
import Foreign.ForeignPtr
import Foreign.Ptr
import System.IO.Unsafe
import Data.Bits
import GHC.Ptr
import GHC.Base
import GHC.Num
class ToPixelRGBA8 a where
toRGBA8 :: a -> PixelRGBA8
instance ToPixelRGBA8 Pixel8 where
toRGBA8 b = PixelRGBA8 b b b 255
instance ToPixelRGBA8 PixelYA8 where
toRGBA8 (PixelYA8 l a) = PixelRGBA8 l l l a
instance ToPixelRGBA8 PixelRGB8 where
toRGBA8 (PixelRGB8 r g b) = PixelRGBA8 r g b 255
instance ToPixelRGBA8 PixelRGBA8 where
toRGBA8 = id
fromColorAndOpacity :: PixelRGB8 -> Image Pixel8 -> Image PixelRGBA8
fromColorAndOpacity (PixelRGB8 r g b) (Image w h vec) = Image w h $ V.generate (w * h * 4) pix where
pix i = if testBit i 0
then if testBit i 1
then vec V.! unsafeShiftR i 2
else b
else if testBit i 1
then g
else r
{-# INLINE pix #-}
-- | Note: Accessing out of the image causes a segfault.
trimImage :: Image PixelRGBA8
-> (Int, Int) -- ^ width, height
-> (Int, Int) -- ^ the left corner point
-> Image PixelRGBA8
trimImage (Image w _ vec) (w', h') (x0, y0) = unsafePerformIO $ V.unsafeWith vec $ \ptr -> do
mv <- MV.unsafeNew $ w' * h' * 4
MV.unsafeWith mv $ \dst -> forM_ [0..h'-1] $ \y ->
copyBytes (plusPtr dst $ y * w' * 4) (plusPtr ptr $ (*4) $ (y + y0) * w + x0) (4 * w')
Image w' h' `fmap` V.unsafeFreeze mv
-- | Note: Accessing out of the image causes a segfault.
patchImage :: Image PixelRGBA8 -> (Int, Int) -> Image PixelRGBA8 -> Image PixelRGBA8
patchImage (Image w h target) (x0, y0) (Image w' h' vec) = unsafePerformIO $ V.unsafeWith vec $ \ptr -> do
mv <- V.thaw target
MV.unsafeWith mv $ \dst -> forM_ [0..h'-1] $ \y ->
copyBytes (plusPtr dst $ (*4) $ (y + y0) * w + x0) (plusPtr ptr $ (*4) $ y * w') (4 * w')
Image w h `fmap` V.unsafeFreeze mv
flipVertically :: Image PixelRGBA8 -> Image PixelRGBA8
flipVertically (Image w h v) = unsafePerformIO $ V.unsafeWith v $ \ptr -> do
mv <- MV.unsafeNew $ w * h * 4
MV.unsafeWith mv $ \dst -> forM_ [0..h-1] $ \y -> copyBytes (plusPtr dst $ y * w * 4) (plusPtr ptr $ (h - y - 1) * w * 4) (4 * w)
Image w h `fmap` V.unsafeFreeze mv
fromDynamicImage :: DynamicImage -> Image PixelRGBA8
fromDynamicImage (ImageY8 img) = pixelMap toRGBA8 img
fromDynamicImage (ImageYA8 img) = pixelMap toRGBA8 img
fromDynamicImage (ImageRGB8 img) = pixelMap toRGBA8 img
fromDynamicImage (ImageRGBA8 img) = img
fromDynamicImage _ = error "Unsupported format"
readImageRGBA8 :: FilePath -> IO (Image PixelRGBA8)
readImageRGBA8 path = readImage path >>= either fail (return . fromDynamicImage)
addrImage :: Image PixelRGBA8 -> IO Int
addrImage (Image _ _ v) = let (fptr, _) = V.unsafeToForeignPtr0 v
in withForeignPtr fptr $ \(Ptr a) -> return $ fromEnum $ wordToInteger (int2Word# (addr2Int# a)) | fumieval/JuicyPixels-util | Codec/Picture/RGBA8.hs | bsd-2-clause | 3,142 | 0 | 20 | 710 | 1,226 | 629 | 597 | 65 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
module Propellor.Types.Chroot where
import Propellor.Types
import Propellor.Types.Empty
import Propellor.Types.Info
import Data.Monoid
import qualified Data.Map as M
data ChrootInfo = ChrootInfo
{ _chroots :: M.Map FilePath Host
, _chrootCfg :: ChrootCfg
}
deriving (Show, Typeable)
instance IsInfo ChrootInfo where
propagateInfo _ = False
instance Monoid ChrootInfo where
mempty = ChrootInfo mempty mempty
mappend old new = ChrootInfo
{ _chroots = M.union (_chroots old) (_chroots new)
, _chrootCfg = _chrootCfg old <> _chrootCfg new
}
instance Empty ChrootInfo where
isEmpty i = and
[ isEmpty (_chroots i)
, isEmpty (_chrootCfg i)
]
data ChrootCfg
= NoChrootCfg
| SystemdNspawnCfg [(String, Bool)]
deriving (Show, Eq)
instance Monoid ChrootCfg where
mempty = NoChrootCfg
mappend v NoChrootCfg = v
mappend NoChrootCfg v = v
mappend (SystemdNspawnCfg l1) (SystemdNspawnCfg l2) =
SystemdNspawnCfg (l1 <> l2)
instance Empty ChrootCfg where
isEmpty c= c == NoChrootCfg
| np/propellor | src/Propellor/Types/Chroot.hs | bsd-2-clause | 1,042 | 20 | 10 | 181 | 344 | 185 | 159 | 34 | 0 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Targets
-- Copyright : (c) Duncan Coutts 2011
-- License : BSD-like
--
-- Maintainer : duncan@community.haskell.org
--
-- Handling for user-specified targets
-----------------------------------------------------------------------------
module Distribution.Client.Targets (
-- * User targets
UserTarget(..),
readUserTargets,
-- * Package specifiers
PackageSpecifier(..),
pkgSpecifierTarget,
pkgSpecifierConstraints,
-- * Resolving user targets to package specifiers
resolveUserTargets,
-- ** Detailed interface
UserTargetProblem(..),
readUserTarget,
reportUserTargetProblems,
expandUserTarget,
PackageTarget(..),
fetchPackageTarget,
readPackageTarget,
PackageTargetProblem(..),
reportPackageTargetProblems,
disambiguatePackageTargets,
disambiguatePackageName,
-- * User constraints
UserConstraint(..),
userConstraintPackageName,
readUserConstraint,
userToPackageConstraint
) where
import Distribution.Package
( Package(..), PackageName(..)
, PackageIdentifier(..), packageName, packageVersion
, Dependency(Dependency) )
import Distribution.Client.Types
( SourcePackage(..), PackageLocation(..), OptionalStanza(..) )
import Distribution.Client.Dependency.Types
( PackageConstraint(..), ConstraintSource(..)
, LabeledPackageConstraint(..) )
import qualified Distribution.Client.World as World
import Distribution.Client.PackageIndex (PackageIndex)
import qualified Distribution.Client.PackageIndex as PackageIndex
import qualified Distribution.Client.Tar as Tar
import Distribution.Client.FetchUtils
import Distribution.Client.HttpUtils ( HttpTransport(..) )
import Distribution.Client.Utils ( tryFindPackageDesc )
import Distribution.PackageDescription
( GenericPackageDescription, FlagName(..), FlagAssignment )
import Distribution.PackageDescription.Parse
( readPackageDescription, parsePackageDescription, ParseResult(..) )
import Distribution.Version
( Version(Version), thisVersion, anyVersion, isAnyVersion
, VersionRange )
import Distribution.Text
( Text(..), display )
import Distribution.Verbosity (Verbosity)
import Distribution.Simple.Utils
( die, warn, intercalate, fromUTF8, lowercase, ignoreBOM )
import Data.List
( find, nub )
import Data.Maybe
( listToMaybe )
import Data.Either
( partitionEithers )
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid
( Monoid(..) )
#endif
import qualified Data.Map as Map
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
import qualified Distribution.Client.GZipUtils as GZipUtils
import Control.Monad (liftM)
import qualified Distribution.Compat.ReadP as Parse
import Distribution.Compat.ReadP
( (+++), (<++) )
import qualified Text.PrettyPrint as Disp
import Text.PrettyPrint
( (<>), (<+>) )
import Data.Char
( isSpace, isAlphaNum )
import System.FilePath
( takeExtension, dropExtension, takeDirectory, splitPath )
import System.Directory
( doesFileExist, doesDirectoryExist )
import Network.URI
( URI(..), URIAuth(..), parseAbsoluteURI )
-- ------------------------------------------------------------
-- * User targets
-- ------------------------------------------------------------
-- | Various ways that a user may specify a package or package collection.
--
data UserTarget =
-- | A partially specified package, identified by name and possibly with
-- an exact version or a version constraint.
--
-- > cabal install foo
-- > cabal install foo-1.0
-- > cabal install 'foo < 2'
--
UserTargetNamed Dependency
-- | A special virtual package that refers to the collection of packages
-- recorded in the world file that the user specifically installed.
--
-- > cabal install world
--
| UserTargetWorld
-- | A specific package that is unpacked in a local directory, often the
-- current directory.
--
-- > cabal install .
-- > cabal install ../lib/other
--
-- * Note: in future, if multiple @.cabal@ files are allowed in a single
-- directory then this will refer to the collection of packages.
--
| UserTargetLocalDir FilePath
-- | A specific local unpacked package, identified by its @.cabal@ file.
--
-- > cabal install foo.cabal
-- > cabal install ../lib/other/bar.cabal
--
| UserTargetLocalCabalFile FilePath
-- | A specific package that is available as a local tarball file
--
-- > cabal install dist/foo-1.0.tar.gz
-- > cabal install ../build/baz-1.0.tar.gz
--
| UserTargetLocalTarball FilePath
-- | A specific package that is available as a remote tarball file
--
-- > cabal install http://code.haskell.org/~user/foo/foo-0.9.tar.gz
--
| UserTargetRemoteTarball URI
deriving (Show,Eq)
-- ------------------------------------------------------------
-- * Package specifier
-- ------------------------------------------------------------
-- | A fully or partially resolved reference to a package.
--
data PackageSpecifier pkg =
-- | A partially specified reference to a package (either source or
-- installed). It is specified by package name and optionally some
-- additional constraints. Use a dependency resolver to pick a specific
-- package satisfying these constraints.
--
NamedPackage PackageName [PackageConstraint]
-- | A fully specified source package.
--
| SpecificSourcePackage pkg
deriving Show
pkgSpecifierTarget :: Package pkg => PackageSpecifier pkg -> PackageName
pkgSpecifierTarget (NamedPackage name _) = name
pkgSpecifierTarget (SpecificSourcePackage pkg) = packageName pkg
pkgSpecifierConstraints :: Package pkg
=> PackageSpecifier pkg -> [LabeledPackageConstraint]
pkgSpecifierConstraints (NamedPackage _ constraints) = map toLpc constraints
where
toLpc pc = LabeledPackageConstraint pc ConstraintSourceUserTarget
pkgSpecifierConstraints (SpecificSourcePackage pkg) =
[LabeledPackageConstraint pc ConstraintSourceUserTarget]
where
pc = PackageConstraintVersion (packageName pkg)
(thisVersion (packageVersion pkg))
-- ------------------------------------------------------------
-- * Parsing and checking user targets
-- ------------------------------------------------------------
readUserTargets :: Verbosity -> [String] -> IO [UserTarget]
readUserTargets _verbosity targetStrs = do
(problems, targets) <- liftM partitionEithers
(mapM readUserTarget targetStrs)
reportUserTargetProblems problems
return targets
data UserTargetProblem
= UserTargetUnexpectedFile String
| UserTargetNonexistantFile String
| UserTargetUnexpectedUriScheme String
| UserTargetUnrecognisedUri String
| UserTargetUnrecognised String
| UserTargetBadWorldPkg
deriving Show
readUserTarget :: String -> IO (Either UserTargetProblem UserTarget)
readUserTarget targetstr =
case testNamedTargets targetstr of
Just (Dependency (PackageName "world") verrange)
| verrange == anyVersion -> return (Right UserTargetWorld)
| otherwise -> return (Left UserTargetBadWorldPkg)
Just dep -> return (Right (UserTargetNamed dep))
Nothing -> do
fileTarget <- testFileTargets targetstr
case fileTarget of
Just target -> return target
Nothing ->
case testUriTargets targetstr of
Just target -> return target
Nothing -> return (Left (UserTargetUnrecognised targetstr))
where
testNamedTargets = readPToMaybe parseDependencyOrPackageId
testFileTargets filename = do
isDir <- doesDirectoryExist filename
isFile <- doesFileExist filename
parentDirExists <- case takeDirectory filename of
[] -> return False
dir -> doesDirectoryExist dir
let result
| isDir
= Just (Right (UserTargetLocalDir filename))
| isFile && extensionIsTarGz filename
= Just (Right (UserTargetLocalTarball filename))
| isFile && takeExtension filename == ".cabal"
= Just (Right (UserTargetLocalCabalFile filename))
| isFile
= Just (Left (UserTargetUnexpectedFile filename))
| parentDirExists
= Just (Left (UserTargetNonexistantFile filename))
| otherwise
= Nothing
return result
testUriTargets str =
case parseAbsoluteURI str of
Just uri@URI {
uriScheme = scheme,
uriAuthority = Just URIAuth { uriRegName = host }
}
| scheme /= "http:" && scheme /= "https:" ->
Just (Left (UserTargetUnexpectedUriScheme targetstr))
| null host ->
Just (Left (UserTargetUnrecognisedUri targetstr))
| otherwise ->
Just (Right (UserTargetRemoteTarball uri))
_ -> Nothing
extensionIsTarGz f = takeExtension f == ".gz"
&& takeExtension (dropExtension f) == ".tar"
parseDependencyOrPackageId :: Parse.ReadP r Dependency
parseDependencyOrPackageId = parse
+++ liftM pkgidToDependency parse
where
pkgidToDependency :: PackageIdentifier -> Dependency
pkgidToDependency p = case packageVersion p of
Version [] _ -> Dependency (packageName p) anyVersion
version -> Dependency (packageName p) (thisVersion version)
readPToMaybe :: Parse.ReadP a a -> String -> Maybe a
readPToMaybe p str = listToMaybe [ r | (r,s) <- Parse.readP_to_S p str
, all isSpace s ]
reportUserTargetProblems :: [UserTargetProblem] -> IO ()
reportUserTargetProblems problems = do
case [ target | UserTargetUnrecognised target <- problems ] of
[] -> return ()
target -> die
$ unlines
[ "Unrecognised target '" ++ name ++ "'."
| name <- target ]
++ "Targets can be:\n"
++ " - package names, e.g. 'pkgname', 'pkgname-1.0.1', 'pkgname < 2.0'\n"
++ " - the special 'world' target\n"
++ " - cabal files 'pkgname.cabal' or package directories 'pkgname/'\n"
++ " - package tarballs 'pkgname.tar.gz' or 'http://example.com/pkgname.tar.gz'"
case [ () | UserTargetBadWorldPkg <- problems ] of
[] -> return ()
_ -> die "The special 'world' target does not take any version."
case [ target | UserTargetNonexistantFile target <- problems ] of
[] -> return ()
target -> die
$ unlines
[ "The file does not exist '" ++ name ++ "'."
| name <- target ]
case [ target | UserTargetUnexpectedFile target <- problems ] of
[] -> return ()
target -> die
$ unlines
[ "Unrecognised file target '" ++ name ++ "'."
| name <- target ]
++ "File targets can be either package tarballs 'pkgname.tar.gz' "
++ "or cabal files 'pkgname.cabal'."
case [ target | UserTargetUnexpectedUriScheme target <- problems ] of
[] -> return ()
target -> die
$ unlines
[ "URL target not supported '" ++ name ++ "'."
| name <- target ]
++ "Only 'http://' and 'https://' URLs are supported."
case [ target | UserTargetUnrecognisedUri target <- problems ] of
[] -> return ()
target -> die
$ unlines
[ "Unrecognise URL target '" ++ name ++ "'."
| name <- target ]
-- ------------------------------------------------------------
-- * Resolving user targets to package specifiers
-- ------------------------------------------------------------
-- | Given a bunch of user-specified targets, try to resolve what it is they
-- refer to. They can either be specific packages (local dirs, tarballs etc)
-- or they can be named packages (with or without version info).
--
resolveUserTargets :: Package pkg
=> Verbosity
-> HttpTransport
-> FilePath
-> PackageIndex pkg
-> [UserTarget]
-> IO [PackageSpecifier SourcePackage]
resolveUserTargets verbosity transport worldFile available userTargets = do
-- given the user targets, get a list of fully or partially resolved
-- package references
packageTargets <- mapM (readPackageTarget verbosity)
=<< mapM (fetchPackageTarget transport verbosity) . concat
=<< mapM (expandUserTarget worldFile) userTargets
-- users are allowed to give package names case-insensitively, so we must
-- disambiguate named package references
let (problems, packageSpecifiers) =
disambiguatePackageTargets available availableExtra packageTargets
-- use any extra specific available packages to help us disambiguate
availableExtra = [ packageName pkg
| PackageTargetLocation pkg <- packageTargets ]
reportPackageTargetProblems verbosity problems
return packageSpecifiers
-- ------------------------------------------------------------
-- * Package targets
-- ------------------------------------------------------------
-- | An intermediate between a 'UserTarget' and a resolved 'PackageSpecifier'.
-- Unlike a 'UserTarget', a 'PackageTarget' refers only to a single package.
--
data PackageTarget pkg =
PackageTargetNamed PackageName [PackageConstraint] UserTarget
-- | A package identified by name, but case insensitively, so it needs
-- to be resolved to the right case-sensitive name.
| PackageTargetNamedFuzzy PackageName [PackageConstraint] UserTarget
| PackageTargetLocation pkg
deriving Show
-- ------------------------------------------------------------
-- * Converting user targets to package targets
-- ------------------------------------------------------------
-- | Given a user-specified target, expand it to a bunch of package targets
-- (each of which refers to only one package).
--
expandUserTarget :: FilePath
-> UserTarget
-> IO [PackageTarget (PackageLocation ())]
expandUserTarget worldFile userTarget = case userTarget of
UserTargetNamed (Dependency name vrange) ->
let constraints = [ PackageConstraintVersion name vrange
| not (isAnyVersion vrange) ]
in return [PackageTargetNamedFuzzy name constraints userTarget]
UserTargetWorld -> do
worldPkgs <- World.getContents worldFile
--TODO: should we warn if there are no world targets?
return [ PackageTargetNamed name constraints userTarget
| World.WorldPkgInfo (Dependency name vrange) flags <- worldPkgs
, let constraints = [ PackageConstraintVersion name vrange
| not (isAnyVersion vrange) ]
++ [ PackageConstraintFlags name flags
| not (null flags) ] ]
UserTargetLocalDir dir ->
return [ PackageTargetLocation (LocalUnpackedPackage dir) ]
UserTargetLocalCabalFile file -> do
let dir = takeDirectory file
_ <- tryFindPackageDesc dir (localPackageError dir) -- just as a check
return [ PackageTargetLocation (LocalUnpackedPackage dir) ]
UserTargetLocalTarball tarballFile ->
return [ PackageTargetLocation (LocalTarballPackage tarballFile) ]
UserTargetRemoteTarball tarballURL ->
return [ PackageTargetLocation (RemoteTarballPackage tarballURL ()) ]
localPackageError :: FilePath -> String
localPackageError dir =
"Error reading local package.\nCouldn't find .cabal file in: " ++ dir
-- ------------------------------------------------------------
-- * Fetching and reading package targets
-- ------------------------------------------------------------
-- | Fetch any remote targets so that they can be read.
--
fetchPackageTarget :: HttpTransport
-> Verbosity
-> PackageTarget (PackageLocation ())
-> IO (PackageTarget (PackageLocation FilePath))
fetchPackageTarget transport verbosity target = case target of
PackageTargetNamed n cs ut -> return (PackageTargetNamed n cs ut)
PackageTargetNamedFuzzy n cs ut -> return (PackageTargetNamedFuzzy n cs ut)
PackageTargetLocation location -> do
location' <- fetchPackage transport verbosity (fmap (const Nothing) location)
return (PackageTargetLocation location')
-- | Given a package target that has been fetched, read the .cabal file.
--
-- This only affects targets given by location, named targets are unaffected.
--
readPackageTarget :: Verbosity
-> PackageTarget (PackageLocation FilePath)
-> IO (PackageTarget SourcePackage)
readPackageTarget verbosity target = case target of
PackageTargetNamed pkgname constraints userTarget ->
return (PackageTargetNamed pkgname constraints userTarget)
PackageTargetNamedFuzzy pkgname constraints userTarget ->
return (PackageTargetNamedFuzzy pkgname constraints userTarget)
PackageTargetLocation location -> case location of
LocalUnpackedPackage dir -> do
pkg <- tryFindPackageDesc dir (localPackageError dir) >>=
readPackageDescription verbosity
return $ PackageTargetLocation $
SourcePackage {
packageInfoId = packageId pkg,
packageDescription = pkg,
packageSource = fmap Just location,
packageDescrOverride = Nothing
}
LocalTarballPackage tarballFile ->
readTarballPackageTarget location tarballFile tarballFile
RemoteTarballPackage tarballURL tarballFile ->
readTarballPackageTarget location tarballFile (show tarballURL)
RepoTarballPackage _repo _pkgid _ ->
error "TODO: readPackageTarget RepoTarballPackage"
-- For repo tarballs this info should be obtained from the index.
where
readTarballPackageTarget location tarballFile tarballOriginalLoc = do
(filename, content) <- extractTarballPackageCabalFile
tarballFile tarballOriginalLoc
case parsePackageDescription' content of
Nothing -> die $ "Could not parse the cabal file "
++ filename ++ " in " ++ tarballFile
Just pkg ->
return $ PackageTargetLocation $
SourcePackage {
packageInfoId = packageId pkg,
packageDescription = pkg,
packageSource = fmap Just location,
packageDescrOverride = Nothing
}
extractTarballPackageCabalFile :: FilePath -> String
-> IO (FilePath, BS.ByteString)
extractTarballPackageCabalFile tarballFile tarballOriginalLoc =
either (die . formatErr) return
. check
. Tar.entriesIndex
. Tar.filterEntries isCabalFile
. Tar.read
. GZipUtils.maybeDecompress
=<< BS.readFile tarballFile
where
formatErr msg = "Error reading " ++ tarballOriginalLoc ++ ": " ++ msg
check (Left e) = Left e
check (Right m) = case Map.elems m of
[] -> Left noCabalFile
[file] -> case Tar.entryContent file of
Tar.NormalFile content _ -> Right (Tar.entryPath file, content)
_ -> Left noCabalFile
_files -> Left multipleCabalFiles
where
noCabalFile = "No cabal file found"
multipleCabalFiles = "Multiple cabal files found"
isCabalFile e = case splitPath (Tar.entryPath e) of
[ _dir, file] -> takeExtension file == ".cabal"
[".", _dir, file] -> takeExtension file == ".cabal"
_ -> False
parsePackageDescription' :: BS.ByteString -> Maybe GenericPackageDescription
parsePackageDescription' content =
case parsePackageDescription . ignoreBOM . fromUTF8 . BS.Char8.unpack $ content of
ParseOk _ pkg -> Just pkg
_ -> Nothing
-- ------------------------------------------------------------
-- * Checking package targets
-- ------------------------------------------------------------
data PackageTargetProblem
= PackageNameUnknown PackageName UserTarget
| PackageNameAmbiguous PackageName [PackageName] UserTarget
deriving Show
-- | Users are allowed to give package names case-insensitively, so we must
-- disambiguate named package references.
--
disambiguatePackageTargets :: Package pkg'
=> PackageIndex pkg'
-> [PackageName]
-> [PackageTarget pkg]
-> ( [PackageTargetProblem]
, [PackageSpecifier pkg] )
disambiguatePackageTargets availablePkgIndex availableExtra targets =
partitionEithers (map disambiguatePackageTarget targets)
where
disambiguatePackageTarget packageTarget = case packageTarget of
PackageTargetLocation pkg -> Right (SpecificSourcePackage pkg)
PackageTargetNamed pkgname constraints userTarget
| null (PackageIndex.lookupPackageName availablePkgIndex pkgname)
-> Left (PackageNameUnknown pkgname userTarget)
| otherwise -> Right (NamedPackage pkgname constraints)
PackageTargetNamedFuzzy pkgname constraints userTarget ->
case disambiguatePackageName packageNameEnv pkgname of
None -> Left (PackageNameUnknown
pkgname userTarget)
Ambiguous pkgnames -> Left (PackageNameAmbiguous
pkgname pkgnames userTarget)
Unambiguous pkgname' -> Right (NamedPackage pkgname' constraints')
where
constraints' = map (renamePackageConstraint pkgname') constraints
-- use any extra specific available packages to help us disambiguate
packageNameEnv :: PackageNameEnv
packageNameEnv = mappend (indexPackageNameEnv availablePkgIndex)
(extraPackageNameEnv availableExtra)
-- | Report problems to the user. That is, if there are any problems
-- then raise an exception.
reportPackageTargetProblems :: Verbosity
-> [PackageTargetProblem] -> IO ()
reportPackageTargetProblems verbosity problems = do
case [ pkg | PackageNameUnknown pkg originalTarget <- problems
, not (isUserTagetWorld originalTarget) ] of
[] -> return ()
pkgs -> die $ unlines
[ "There is no package named '" ++ display name ++ "'. "
| name <- pkgs ]
++ "You may need to run 'cabal update' to get the latest "
++ "list of available packages."
case [ (pkg, matches) | PackageNameAmbiguous pkg matches _ <- problems ] of
[] -> return ()
ambiguities -> die $ unlines
[ "The package name '" ++ display name
++ "' is ambiguous. It could be: "
++ intercalate ", " (map display matches)
| (name, matches) <- ambiguities ]
case [ pkg | PackageNameUnknown pkg UserTargetWorld <- problems ] of
[] -> return ()
pkgs -> warn verbosity $
"The following 'world' packages will be ignored because "
++ "they refer to packages that cannot be found: "
++ intercalate ", " (map display pkgs) ++ "\n"
++ "You can suppress this warning by correcting the world file."
where
isUserTagetWorld UserTargetWorld = True; isUserTagetWorld _ = False
-- ------------------------------------------------------------
-- * Disambiguating package names
-- ------------------------------------------------------------
data MaybeAmbiguous a = None | Unambiguous a | Ambiguous [a]
-- | Given a package name and a list of matching names, figure out which one it
-- might be referring to. If there is an exact case-sensitive match then that's
-- ok. If it matches just one package case-insensitively then that's also ok.
-- The only problem is if it matches multiple packages case-insensitively, in
-- that case it is ambiguous.
--
disambiguatePackageName :: PackageNameEnv
-> PackageName
-> MaybeAmbiguous PackageName
disambiguatePackageName (PackageNameEnv pkgNameLookup) name =
case nub (pkgNameLookup name) of
[] -> None
[name'] -> Unambiguous name'
names -> case find (name==) names of
Just name' -> Unambiguous name'
Nothing -> Ambiguous names
newtype PackageNameEnv = PackageNameEnv (PackageName -> [PackageName])
instance Monoid PackageNameEnv where
mempty = PackageNameEnv (const [])
mappend (PackageNameEnv lookupA) (PackageNameEnv lookupB) =
PackageNameEnv (\name -> lookupA name ++ lookupB name)
indexPackageNameEnv :: PackageIndex pkg -> PackageNameEnv
indexPackageNameEnv pkgIndex = PackageNameEnv pkgNameLookup
where
pkgNameLookup (PackageName name) =
map fst (PackageIndex.searchByName pkgIndex name)
extraPackageNameEnv :: [PackageName] -> PackageNameEnv
extraPackageNameEnv names = PackageNameEnv pkgNameLookup
where
pkgNameLookup (PackageName name) =
[ PackageName name'
| let lname = lowercase name
, PackageName name' <- names
, lowercase name' == lname ]
-- ------------------------------------------------------------
-- * Package constraints
-- ------------------------------------------------------------
data UserConstraint =
UserConstraintVersion PackageName VersionRange
| UserConstraintInstalled PackageName
| UserConstraintSource PackageName
| UserConstraintFlags PackageName FlagAssignment
| UserConstraintStanzas PackageName [OptionalStanza]
deriving (Show,Eq)
userConstraintPackageName :: UserConstraint -> PackageName
userConstraintPackageName uc = case uc of
UserConstraintVersion name _ -> name
UserConstraintInstalled name -> name
UserConstraintSource name -> name
UserConstraintFlags name _ -> name
UserConstraintStanzas name _ -> name
userToPackageConstraint :: UserConstraint -> PackageConstraint
-- At the moment, the types happen to be directly equivalent
userToPackageConstraint uc = case uc of
UserConstraintVersion name ver -> PackageConstraintVersion name ver
UserConstraintInstalled name -> PackageConstraintInstalled name
UserConstraintSource name -> PackageConstraintSource name
UserConstraintFlags name flags -> PackageConstraintFlags name flags
UserConstraintStanzas name stanzas -> PackageConstraintStanzas name stanzas
renamePackageConstraint :: PackageName -> PackageConstraint -> PackageConstraint
renamePackageConstraint name pc = case pc of
PackageConstraintVersion _ ver -> PackageConstraintVersion name ver
PackageConstraintInstalled _ -> PackageConstraintInstalled name
PackageConstraintSource _ -> PackageConstraintSource name
PackageConstraintFlags _ flags -> PackageConstraintFlags name flags
PackageConstraintStanzas _ stanzas -> PackageConstraintStanzas name stanzas
readUserConstraint :: String -> Either String UserConstraint
readUserConstraint str =
case readPToMaybe parse str of
Nothing -> Left msgCannotParse
Just c -> Right c
where
msgCannotParse =
"expected a package name followed by a constraint, which is "
++ "either a version range, 'installed', 'source' or flags"
instance Text UserConstraint where
disp (UserConstraintVersion pkgname verrange) = disp pkgname
<+> disp verrange
disp (UserConstraintInstalled pkgname) = disp pkgname
<+> Disp.text "installed"
disp (UserConstraintSource pkgname) = disp pkgname
<+> Disp.text "source"
disp (UserConstraintFlags pkgname flags) = disp pkgname
<+> dispFlagAssignment flags
where
dispFlagAssignment = Disp.hsep . map dispFlagValue
dispFlagValue (f, True) = Disp.char '+' <> dispFlagName f
dispFlagValue (f, False) = Disp.char '-' <> dispFlagName f
dispFlagName (FlagName f) = Disp.text f
disp (UserConstraintStanzas pkgname stanzas) = disp pkgname
<+> dispStanzas stanzas
where
dispStanzas = Disp.hsep . map dispStanza
dispStanza TestStanzas = Disp.text "test"
dispStanza BenchStanzas = Disp.text "bench"
parse = parse >>= parseConstraint
where
spaces = Parse.satisfy isSpace >> Parse.skipSpaces
parseConstraint pkgname =
((parse >>= return . UserConstraintVersion pkgname)
+++ (do spaces
_ <- Parse.string "installed"
return (UserConstraintInstalled pkgname))
+++ (do spaces
_ <- Parse.string "source"
return (UserConstraintSource pkgname))
+++ (do spaces
_ <- Parse.string "test"
return (UserConstraintStanzas pkgname [TestStanzas]))
+++ (do spaces
_ <- Parse.string "bench"
return (UserConstraintStanzas pkgname [BenchStanzas])))
<++ (parseFlagAssignment >>= (return . UserConstraintFlags pkgname))
parseFlagAssignment = Parse.many1 (spaces >> parseFlagValue)
parseFlagValue =
(do Parse.optional (Parse.char '+')
f <- parseFlagName
return (f, True))
+++ (do _ <- Parse.char '-'
f <- parseFlagName
return (f, False))
parseFlagName = liftM FlagName ident
ident :: Parse.ReadP r String
ident = Parse.munch1 identChar >>= \s -> check s >> return s
where
identChar c = isAlphaNum c || c == '_' || c == '-'
check ('-':_) = Parse.pfail
check _ = return ()
| randen/cabal | cabal-install/Distribution/Client/Targets.hs | bsd-3-clause | 31,048 | 0 | 21 | 8,538 | 5,801 | 2,994 | 2,807 | 512 | 14 |
-- | Various utilities used in generating assembler.
--
-- These are used not only by the native code generator, but also by the
-- "DriverPipeline".
module AsmUtils
( sectionType
) where
import GhcPrelude
import GHC.Platform
import Outputable
-- | Generate a section type (e.g. @\@progbits@). See #13937.
sectionType :: String -- ^ section type
-> SDoc -- ^ pretty assembler fragment
sectionType ty = sdocWithPlatform $ \platform ->
case platformArch platform of
ArchARM{} -> char '%' <> text ty
_ -> char '@' <> text ty
| sdiehl/ghc | compiler/utils/AsmUtils.hs | bsd-3-clause | 571 | 0 | 11 | 136 | 96 | 53 | 43 | 11 | 2 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Prednote.Core.Instances where
import Rainbow.Instances ()
import Test.QuickCheck hiding (Result)
import Control.Monad
import Prednote.Core
instance (CoArbitrary a, Show a) => Arbitrary (Pred a) where
arbitrary = fmap predicate arbitrary
instance Arbitrary Condition where
arbitrary = fmap Condition arbitrary
instance CoArbitrary Condition where
coarbitrary (Condition c) = coarbitrary c
instance Arbitrary Value where
arbitrary = fmap Value arbitrary
instance CoArbitrary Value where
coarbitrary (Value x) = coarbitrary x
instance Arbitrary Label where
arbitrary = fmap Label arbitrary
instance CoArbitrary Label where
coarbitrary (Label x) = coarbitrary x
instance Arbitrary a => Arbitrary (Labeled a) where
arbitrary = liftM2 Labeled arbitrary arbitrary
instance CoArbitrary a => CoArbitrary (Labeled a) where
coarbitrary (Labeled a b) = coarbitrary a . coarbitrary b
instance Arbitrary Passed where
arbitrary = sized f
where
f s | s < 10 = liftM2 PTerminal arbitrary arbitrary
| otherwise = oneof
[ liftM2 PTerminal arbitrary arbitrary
, liftM2 PAnd nestPass nestPass
, fmap POr
(oneof [ fmap Left nestPass,
fmap Right (liftM2 (,) nestFail nestPass)
])
, fmap PNot nestFail
]
where
nestPass = resize (s `div` 4) arbitrary
nestFail = resize (s `div` 4) arbitrary
instance Arbitrary Failed where
arbitrary = sized f
where
f s | s < 10 = liftM2 FTerminal arbitrary arbitrary
| otherwise = oneof
[ liftM2 FTerminal arbitrary arbitrary
, fmap FAnd
(oneof [ fmap Left nestFail
, fmap Right (liftM2 (,) nestPass nestFail)
])
, liftM2 FOr nestFail nestFail
, fmap FNot nestPass
]
where
nestPass = resize (s `div` 4) arbitrary
nestFail = resize (s `div` 4) arbitrary
varInt :: Int -> Gen a -> Gen a
varInt = variant
instance CoArbitrary Passed where
coarbitrary pass = case pass of
PTerminal v c -> varInt 0 . coarbitrary v . coarbitrary c
PAnd y1 y2 -> varInt 1 . coarbitrary y1 . coarbitrary y2
POr e -> varInt 2 . coarbitrary e
PNot n -> varInt 3 . coarbitrary n
instance CoArbitrary Failed where
coarbitrary fll = case fll of
FTerminal v c -> varInt 0 . coarbitrary v . coarbitrary c
FAnd e -> varInt 1 . coarbitrary e
FOr x y -> varInt 2 . coarbitrary x . coarbitrary y
FNot x -> varInt 3 . coarbitrary x
instance Arbitrary Result where
arbitrary = fmap Result arbitrary
instance CoArbitrary Result where
coarbitrary (Result x) = coarbitrary x
| massysett/prednote | tests/Prednote/Core/Instances.hs | bsd-3-clause | 2,896 | 0 | 18 | 847 | 913 | 447 | 466 | 67 | 1 |
{-# LANGUAGE CPP, FlexibleInstances, OverlappingInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS_HADDOCK not-home #-}
module Text.StringTemplate.Instances() where
import Text.StringTemplate.Classes
import qualified Data.Map as M
import Numeric
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.Ratio
import Data.Array
import Data.Maybe
import qualified Data.Foldable as F
import Data.Time
import Data.Void
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
#if !MIN_VERSION_time(1,5,0)
import System.Locale (defaultTimeLocale)
#endif
{--------------------------------------------------------------------
Additional instances for items that may be set as StringTemplate
attributes. The code should provide examples of how to proceed.
--------------------------------------------------------------------}
--Basics
instance ToSElem () where
toSElem _ = STR ""
instance ToSElem Void where
toSElem = absurd
instance ToSElem Char where
toSElem = STR . (:[])
toSElemList = STR
instance ToSElem LB.ByteString where
toSElem = BS
instance ToSElem B.ByteString where
toSElem = BS . LB.fromChunks . (:[])
instance ToSElem LT.Text where
toSElem = TXT
instance ToSElem T.Text where
toSElem = TXT . LT.fromStrict
instance ToSElem Bool where
toSElem True = STR ""
toSElem _ = SNull
instance (ToSElem a) => ToSElem (Maybe a) where
toSElem (Just x) = toSElem x
toSElem _ = SNull
instance (ToSElem a) => ToSElem (M.Map String a) where
toSElem = SM . fmap toSElem
instance (ToSElem a) => ToSElem [a] where
toSElem = toSElemList
instance (ToSElem a, Ix i) => ToSElem (Array i a) where
toSElem = toSElem . elems
instance (ToSElem a, F.Foldable t) => ToSElem (t a) where
toSElem = toSElemList . F.toList
--Numbers
instance StringTemplateShows Float where
stringTemplateShow = flip showFloat ""
stringTemplateFormattedShow = flip flip [] . showGFloat . fmap fst . listToMaybe . reads
instance ToSElem Float where
toSElem = stShowsToSE
instance StringTemplateShows Double where
stringTemplateShow = flip showFloat ""
stringTemplateFormattedShow = flip flip [] . showGFloat . fmap fst . listToMaybe . reads
instance ToSElem Double where
toSElem = stShowsToSE
instance ToSElem Int where
toSElem = STR . show
instance ToSElem Integer where
toSElem = STR . show
instance (Integral a, Show a) => ToSElem (Ratio a) where
toSElem = STR . show
--Dates and Times
instance StringTemplateShows Day where
stringTemplateShow = show
stringTemplateFormattedShow = formatTime defaultTimeLocale
instance ToSElem Day where
toSElem = stShowsToSE
instance StringTemplateShows LocalTime where
stringTemplateShow = show
stringTemplateFormattedShow = formatTime defaultTimeLocale
instance ToSElem LocalTime where
toSElem = stShowsToSE
instance StringTemplateShows TimeOfDay where
stringTemplateShow = show
stringTemplateFormattedShow = formatTime defaultTimeLocale
instance ToSElem TimeOfDay where
toSElem = stShowsToSE
instance StringTemplateShows UTCTime where
stringTemplateShow = show
stringTemplateFormattedShow = formatTime defaultTimeLocale
instance ToSElem UTCTime where
toSElem = stShowsToSE
instance StringTemplateShows TimeZone where
stringTemplateShow = show
stringTemplateFormattedShow = formatTime defaultTimeLocale
instance ToSElem TimeZone where
toSElem = stShowsToSE
instance StringTemplateShows ZonedTime where
stringTemplateShow = show
stringTemplateFormattedShow = formatTime defaultTimeLocale
instance ToSElem ZonedTime where
toSElem = stShowsToSE
t2map :: [SElem a] -> SElem a
t2map = SM . M.fromList . zip (map show [(0::Int)..])
instance (ToSElem a, ToSElem b) => ToSElem (a, b) where
toSElem (a,b) = t2map [toSElem a, toSElem b]
instance (ToSElem a, ToSElem b, ToSElem c) => ToSElem (a, b, c) where
toSElem (a,b,c) = t2map [toSElem a, toSElem b, toSElem c]
instance (ToSElem a, ToSElem b, ToSElem c, ToSElem d) => ToSElem (a, b, c, d) where
toSElem (a,b,c,d) = t2map [toSElem a, toSElem b, toSElem c, toSElem d]
instance (ToSElem a, ToSElem b, ToSElem c, ToSElem d, ToSElem e) => ToSElem (a, b, c, d, e) where
toSElem (a,b,c,d,e) = t2map [toSElem a, toSElem b, toSElem c, toSElem d, toSElem e]
instance (ToSElem a, ToSElem b, ToSElem c, ToSElem d, ToSElem e, ToSElem f) => ToSElem (a, b, c, d, e, f) where
toSElem (a,b,c,d,e, f) = t2map [toSElem a, toSElem b, toSElem c, toSElem d, toSElem e, toSElem f]
instance (ToSElem a, ToSElem b, ToSElem c, ToSElem d, ToSElem e, ToSElem f, ToSElem g) => ToSElem (a, b, c, d, e, f, g) where
toSElem (a,b,c,d,e,f,g) = t2map [toSElem a, toSElem b, toSElem c, toSElem d, toSElem e, toSElem f, toSElem g]
instance (ToSElem a, ToSElem b, ToSElem c, ToSElem d, ToSElem e, ToSElem f, ToSElem g, ToSElem h) => ToSElem (a, b, c, d, e, f, g, h) where
toSElem (a,b,c,d,e,f,g,h) = t2map [toSElem a, toSElem b, toSElem c, toSElem d, toSElem e, toSElem f, toSElem g, toSElem h]
instance (ToSElem a, ToSElem b, ToSElem c, ToSElem d, ToSElem e, ToSElem f, ToSElem g, ToSElem h, ToSElem i) => ToSElem (a, b, c, d, e, f, g, h, i) where
toSElem (a,b,c,d,e,f,g,h,i) = t2map [toSElem a, toSElem b, toSElem c, toSElem d, toSElem e, toSElem f, toSElem g, toSElem h, toSElem i]
instance (ToSElem a, ToSElem b, ToSElem c, ToSElem d, ToSElem e, ToSElem f, ToSElem g, ToSElem h, ToSElem i, ToSElem j) => ToSElem (a, b, c, d, e, f, g, h, i, j) where
toSElem (a,b,c,d,e,f,g,h,i,j) = t2map [toSElem a, toSElem b, toSElem c, toSElem d, toSElem e, toSElem f, toSElem g, toSElem h, toSElem i, toSElem j]
| factisresearch/HStringTemplate | Text/StringTemplate/Instances.hs | bsd-3-clause | 5,711 | 0 | 11 | 1,038 | 2,103 | 1,149 | 954 | 113 | 1 |
module Ambiguous where
import Text.Syntactical
import Text.Syntactical.Data
table :: Table String
table = buildTable
[ [ closed "<" Distfix "|"
, closed "<" Distfix "|" `distfix` ">"
, infx LeftAssociative "?"
, infx LeftAssociative "?" `distfix` ":"
, prefx "!"
, postfx "!"
, prefx "<-" `distfix` "--"
, postfx "<-" `distfix` "++"
, prefx ">-" `distfix` "--"
, prefx ">-" `sexpr` "++"
, prefx ">>" `distfix` "//" `distfix` ".."
, prefx ">>" `distfix` "//" `sexpr` ";;"
]
]
tests :: [(String,Failure String)]
tests =
[ ("< 1 |", Ambiguity MiddleOrLast)
, ("< 1 | 2", Ambiguity MiddleOrLast)
, ("1 ? 2", Ambiguity LoneOrFirst)
, ("! 1", Ambiguity MultipleLone)
, ("<- 1 -- 2", Ambiguity NotSameFirst)
, ("1 <- 2 --", Ambiguity NotSameFirst)
, (">- 1 -- 2", Ambiguity NotSameHole)
, (">- 1 ++ 2", Ambiguity NotSameHole)
, (">> 1 // 2 .. 3", Ambiguity NotSameHole)
, (">> 1 // 2 ;; 3", Ambiguity NotSameHole)
]
| noteed/syntactical | tests/Ambiguous.hs | bsd-3-clause | 973 | 0 | 10 | 220 | 320 | 185 | 135 | 29 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Rules.HE
( rules
) where
import Duckling.Dimensions.Types
import Duckling.Types
import qualified Duckling.Duration.HE.Rules as Duration
import qualified Duckling.Numeral.HE.Rules as Numeral
import qualified Duckling.Ordinal.HE.Rules as Ordinal
import qualified Duckling.TimeGrain.HE.Rules as TimeGrain
import qualified Duckling.Time.HE.Rules as Time
rules :: Some Dimension -> [Rule]
rules (This Distance) = []
rules (This Duration) = Duration.rules
rules (This Numeral) = Numeral.rules
rules (This Email) = []
rules (This AmountOfMoney) = []
rules (This Ordinal) = Ordinal.rules
rules (This PhoneNumber) = []
rules (This Quantity) = []
rules (This RegexMatch) = []
rules (This Temperature) = []
rules (This Time) = Time.rules
rules (This TimeGrain) = TimeGrain.rules
rules (This Url) = []
rules (This Volume) = []
| rfranek/duckling | Duckling/Rules/HE.hs | bsd-3-clause | 1,199 | 0 | 7 | 181 | 320 | 183 | 137 | 26 | 1 |
{-# LANGUAGE ConstraintKinds #-}
module Windows(
hann
, noWindow
, hamming
, tukey
, cosine
, lanczos
, triangular
, cossq
, frameWithWinAndOverlap
, flattenWithOverlapS
) where
import Prelude hiding(splitAt,(++),concat,zipWith,concatMap,null,head,take)
import Common
import Signal
import Internal
import Data.List.Stream
import qualified Data.Vector.Unboxed as U
import Data.Vector.Unboxed((!),Unbox(..))
frameWithWinAndOverlap :: (Unbox a, Num t)
=> Int -- ^ Window size
-> Int -- ^ Overlap in samples
-> (Int -> Int -> a -> a) -- ^ Window function
-> Sampled t a -- ^ Input signal
-> Sampled t (U.Vector a) -- Result and new sampling period
frameWithWinAndOverlap winSize o winF signal =
let r' = (period signal) * fromIntegral (winSize - o)
frame z =
let (ws,r1) = splitAtVectorS (winSize - o) z
(os,r2) = splitAtVectorS o r1
h = toVectorBS $ imapBS (winF winSize) (appendBS ws os)
in
consS h (frame r1)
in
Sampled r' (frame (getSignal signal))
flattenWithOverlapS :: (Unbox a,Num a, Fractional t)
=> Int -- ^ Window size
-> Int -- ^ Overlap
-> Sampled t (U.Vector a) -- ^ Signal
-> Sampled t a -- ^ Result and new sampling period
flattenWithOverlapS winSize o s | null (getSamples . getSignal $ s) = error "A signal can't be empty : in flattenWithOverlapS"
| o == 0 = Sampled r' (concatMapS U.toList . getSignal $ s)
| otherwise =
let h = headS (getSignal s)
n = U.length h
index = U.fromList [0..o-1]
_flatten [] = []
_flatten (a:b:l) = U.toList (U.slice o (n-o) v) : _flatten (b:l)
where
combine b i x | i >= o = x + (b!(i-o))
| otherwise = x
v = U.imap (combine b) a
news = appendListS (take o . U.toList $ h)
(concatS . onSamples _flatten . getSignal $ s)
in
Sampled r' news
where
r' = (period s) / fromIntegral (winSize - o)
cossq m i x = let sq z = z * z
in
x* sq(sin(pi*fromIntegral i / fromIntegral (m-1)))
hann :: (Num a, HasDoubleRepresentation a)
=> Int
-> Int
-> a
-> a
hann m n x = x * (fromDouble $ 0.5 * (1 - cos (2 * pi * fromIntegral n / fromIntegral (m - 1))))
noWindow :: Int -> Int -> a -> a
noWindow _ _ x = x
hamming :: (Num a, HasDoubleRepresentation a)
=> Double -- ^ Alpha
-> Int
-> Int
-> a
-> a
hamming alpha m n x = x * (fromDouble $ alpha - (1 - alpha) * cos(2*pi*fromIntegral n / fromIntegral (m-1)))
tukey :: (Num a, HasDoubleRepresentation a)
=> Double -- ^ Alpha
-> Int
-> Int
-> a
-> a
tukey alpha m n x | n <= floor (alpha * fromIntegral (m-1) / 2.0) =
x * (fromDouble $ 0.5 * (1 + cos(pi * (2*fromIntegral n/alpha/ fromIntegral (m-1) - 1))))
| (floor $ alpha * fromIntegral (m-1) / 2.0) <= n
&& n <= floor (fromIntegral (m-1)*(1 - alpha / 2.0)) = x
| otherwise = x * (fromDouble $ 0.5 *
(1 + cos(pi * (2*fromIntegral n/alpha/ fromIntegral (m-1) - 2 / alpha + 1))))
cosine :: (Num a, HasDoubleRepresentation a)
=> Int
-> Int
-> a
-> a
cosine m n x = x * (fromDouble $ sin (pi * fromIntegral n / fromIntegral (m-1)))
lanczos :: (Num a, HasDoubleRepresentation a)
=> Int
-> Int
-> a
-> a
lanczos m n x = x * (fromDouble $ sinc (2*fromIntegral n / fromIntegral (m-1) - 1))
where
sinc x | x == 0 = 1
| otherwise = sin(pi*x) / (pi*x)
triangular :: (Num a, HasDoubleRepresentation a)
=> Int
-> Int
-> a
-> a
triangular m n x = x * (fromDouble $ 2.0 / fromIntegral (m+1) * (fromIntegral (m+1)/2.0 - abs (fromIntegral n - fromIntegral(m-1)/2.0)))
| alpheccar/Signal | Windows.hs | bsd-3-clause | 4,808 | 0 | 21 | 2,157 | 1,691 | 875 | 816 | 102 | 2 |
module Supervisor
( ChildId
, ChildType(..)
, ChildSpec(..)
, RestartPolicy(..)
, RestartStrategy(..)
, SupervisorMessage(..)
, runSupervisor
) where
import Data.Time.Clock
import qualified Data.Map as M
import Data.Maybe (isNothing)
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad (when)
import Control.Monad.State hiding (state)
import qualified System.Timeout as T
import Server
import Process
data RestartPolicy
= Permanent
| Temporary
| Transient
data RestartStrategy
= OneForOne
| OneForAll
type ChildId = String
data ChildType = Worker | Supervisor
data ChildSpec = ChildSpec
{ csType :: ChildType
, csAction :: IO Reason
, csRestart :: RestartPolicy
, csShutdown :: IO ()
, csShutdownTimeout :: Int
}
data WorkerMessage
= Dead ChildId Reason
data SupervisorMessage
= Add ChildId (IO ChildSpec)
| Stop ChildId
| Delete ChildId
| Restart ChildId
| Terminate
data SupervisorState = SupervisorState
{ sStrategy :: RestartStrategy
, sMaxRestart :: Int
, sMaxRestartTime :: Int
, sCrashTime :: [UTCTime]
, sCommandChan :: TChan SupervisorMessage
, sChildSpec :: M.Map ChildId (IO ChildSpec)
, sChildThread :: M.Map ChildId (ThreadId, TMVar Reason, ChildSpec)
}
mkSupervisor :: RestartStrategy -> Int -> Int
-> TChan SupervisorMessage
-> [(ChildId, IO ChildSpec)]
-> IO SupervisorState
mkSupervisor strategy maxRestart maxRestartTime commandChan specs = do
return $ SupervisorState
{ sStrategy = strategy
, sMaxRestart = maxRestart
, sMaxRestartTime = maxRestartTime
, sCrashTime = []
, sCommandChan = commandChan
, sChildSpec = M.fromList specs
, sChildThread = M.empty
}
runSupervisor :: RestartStrategy -> Int -> Int
-> TChan SupervisorMessage
-> [(ChildId, IO ChildSpec)]
-> IO Reason
runSupervisor strategy maxRestart maxRestartTime chan specs = do
state <- mkSupervisor strategy maxRestart maxRestartTime chan specs
runServer () state startup server
where
server = mkServer wait onMessage terminate
wait :: Process () SupervisorState (Either WorkerMessage SupervisorMessage)
wait = do
threads <- gets sChildThread
commandChan <- gets sCommandChan
let command = readTChan commandChan >>= return . Right
waitMessage = foldl myfold command (M.assocs threads)
liftIO . atomically $ waitMessage
where
myfold stm (cid, (_, stop, _)) = stm `orElse`
(takeTMVar stop >>= return . Left . Dead cid)
onMessage :: Either WorkerMessage SupervisorMessage
-> Process () SupervisorState ()
onMessage message = do
case message of
Left (Dead cid reason) ->
restartChild cid reason
Right (Add cid spec) ->
addChild cid spec
Right Terminate -> stopProcess Shutdown
startup :: Process () SupervisorState ()
startup = do
specs <- gets sChildSpec
forM_ (M.assocs specs) $ \(id, spec) -> startChild id spec
terminate :: Reason -> Process () SupervisorState ()
terminate _reason = do
threads <- gets sChildThread
forM_ (M.keys threads) shutdownChild
startChild :: ChildId -> IO ChildSpec -> Process () SupervisorState ()
startChild cid spec' = do
spec <- liftIO $ spec'
stop <- liftIO $ newEmptyTMVarIO
thId <- liftIO $ forkFinally (csAction spec) (shutdown stop)
modify $ \s -> s { sChildThread = M.insert cid (thId, stop, spec) $ sChildThread s }
where
shutdown stop (Left e) = shutdown stop $ Right (Exception e)
shutdown stop (Right reason) = atomically $ putTMVar stop reason
shutdownChild :: ChildId -> Process () SupervisorState ()
shutdownChild cid = do
specs <- gets sChildSpec
threads <- gets sChildThread
let thread = M.lookup cid threads
shutdownChild' thread
where
shutdownChild' (Just (thread, stop, spec)) = do
timeouted <- liftIO $ T.timeout (csShutdownTimeout spec) (shutdownAttempt spec stop)
when (isNothing timeouted) $
liftIO $ killThread thread
modify $ \s -> s { sChildThread = M.delete cid $ sChildThread s }
shutdownChild' _ = return ()
shutdownAttempt spec stop = do
liftIO $ csShutdown spec
_ <- liftIO . atomically $ takeTMVar stop
return ()
restartChild :: ChildId -> Reason -> Process () SupervisorState ()
restartChild cid reason = do
crashes <- gets sCrashTime
maxRestart <- gets sMaxRestart
maxRestartTime <- gets sMaxRestartTime
curtime <- liftIO getCurrentTime
let crashes' = take (maxRestart + 1) (curtime : crashes)
modify $ \s -> s { sCrashTime = crashes' }
if needRestart maxRestart maxRestartTime crashes'
then restartChild' cid reason
else stopProcess reason
restartChild' :: ChildId -> Reason -> Process () SupervisorState ()
restartChild' cid reason = do
specs <- gets sChildSpec
workers <- gets sChildThread
let spec = M.lookup cid specs
worker = M.lookup cid workers
case (spec, worker) of
(Just spec1, Just (_, _, spec2)) -> do
modify $ \s -> s { sChildThread = M.delete cid $ sChildThread s }
when (applyRestartPolicy (csRestart spec2) reason) $
restartChild'' cid spec1 reason
_ -> return ()
restartChild'' cid spec reason = do
strategy <- gets sStrategy
case strategy of
OneForOne -> startChild cid spec
OneForAll -> terminate reason >> startup
needRestart :: Int -> Int -> [UTCTime] -> Bool
needRestart maxRestart maxRestartTime crashes
| length crashes == 0 = True
| maxRestart >= length crashes = True
| otherwise = let
hi = head crashes
lo = last crashes
in floor (diffUTCTime hi lo) > maxRestartTime
applyRestartPolicy :: RestartPolicy -> Reason -> Bool
applyRestartPolicy policy reason
= case policy of
Permanent -> True
Temporary -> False
Transient -> reason /= Normal
------
addChild :: ChildId -> IO ChildSpec -> Process () SupervisorState ()
addChild cid spec = do
modify $ \s -> s { sChildSpec = M.insert cid spec (sChildSpec s) }
startChild cid spec
| artems/FlashBit | src/Supervisor.hs | bsd-3-clause | 6,328 | 0 | 18 | 1,647 | 1,994 | 1,012 | 982 | 166 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE IncoherentInstances #-}
module Common.Views where
import Text.Blaze.Html5 as H hiding (i, map)
import Text.Blaze.Html5.Attributes as Ha
import Control.Monad (forM_, when)
import Data.List (intersperse)
import Data.Text (Text, unpack)
import User.Links
layout :: String -> Html -> Html
layout = layout' True
layoutNoBanner :: String -> Html -> Html
layoutNoBanner = layout' False
layout' :: Bool -> String -> Html -> Html
layout' showBanner pageTitle pageContents = docTypeHtml $ do
H.head $ do
meta ! charset "utf-8"
meta ! httpEquiv "X-UA-Compatible" ! content "IE=Edge"
H.title (toHtml $ pageTitle ++ " - autotrace")
script ! src "/underscore.js" $ ""
script ! src "/jquery.js" $ ""
script ! src "/jquery-ui.js" $ ""
script ! src "/d3.js" $ ""
link ! rel "stylesheet" ! type_ "text/css" ! href "/jquery-ui.css"
link ! rel "stylesheet" ! type_ "text/css" ! href "/style.css"
H.body $ do
when showBanner banner
H.div ! class_ "page-contents" $ pageContents
banner :: Html
banner = H.div ! class_ "banner" $ do
a ! href "/" $ "autotrace"
H.span ! Ha.style "float:right;" $ do
H.span ! Ha.style "margin:0 10px;" $ do
H.span "Logged in as "
H.span $ H.b ! Ha.id "username-field" $ ""
a ! href "#" ! Ha.id "login-logout-link" $ ""
script $
" var cookies = {}; \
\ document.cookie.split('; ').forEach(function(c) { \
\ var t = c.split('='); \
\ cookies[t[0]]=t[1]; \
\ }); \
\ if (!cookies['username']) { \
\ $('#username-field').text('guest'); \
\ $('#login-logout-link').text('Change user...'); \
\ } else if (cookies['username'] == 'guest') { \
\ $('#username-field').text('guest'); \
\ $('#login-logout-link').text('Change user...'); \
\ } else { \
\ $('#username-field').text(cookies['username']); \
\ $('#login-logout-link').text('Logout'); \
\ } "
script $ toHtml $
" $('#login-logout-link').click(function(e) { \
\ e.preventDefault(); \
\ $.post('" ++ logoutLink' ++ "').success(function() { \
\ window.location.href = '" ++ toLoginLink' True ++ "'; \
\ }); \
\ }); "
editableH2 :: String -> AttributeValue -> Html
editableH2 h2Label editLink = h2 $ do
H.span (toHtml $ h2Label)
H.span ! Ha.style "float:right;" $
a ! href editLink ! Ha.style "text-decoration:none;"
$ preEscapedString "✎"
class ToString a where
toString :: a -> String
instance ToString String where
toString = Prelude.id
instance ToString Text where
toString = unpack
instance Show a => ToString a where
toString = show
field :: ToString b => String -> String -> (a -> b) -> Maybe a -> Html
field fieldLabel fieldName accessor mRecord = H.label $ do
H.span (toHtml fieldLabel)
input ! Ha.name (stringValue fieldName)
! Ha.value (stringValue $ maybe "" (toString . accessor) mRecord)
-- |The field' function additionally accepts id and class
field' :: ToString b
=> String -> String -> Maybe String -> Maybe String
-> (a -> b) -> Maybe a -> Html
field' fieldLabel fieldName mFieldId mFieldClass accessor mRecord = H.label $ do
H.span (toHtml fieldLabel)
let f = case mFieldId of
Nothing -> Prelude.id
Just fieldId -> \ i -> i ! Ha.id (stringValue fieldId)
let g = case mFieldClass of
Nothing -> Prelude.id
Just fieldClass -> \ i -> i ! Ha.class_ (stringValue fieldClass)
f . g $
input ! Ha.name (stringValue fieldName)
! Ha.value (stringValue $ maybe "" (toString . accessor) mRecord)
-- |The largeField' function is a textarea and additionally accepts id and class
largeField' :: ToString b
=> String -> String -> Maybe String -> Maybe String
-> (a -> b) -> Maybe a -> Html
largeField' fieldLabel fieldName mFieldId mFieldClass accessor mRecord =
H.label $ do
H.span (toHtml fieldLabel)
let f = case mFieldId of
Nothing -> Prelude.id
Just fieldId -> \ i -> i ! Ha.id (stringValue fieldId)
let g = case mFieldClass of
Nothing -> Prelude.id
Just fieldClass -> \ i -> i ! Ha.class_ (stringValue fieldClass)
f . g $
textarea ! Ha.name (stringValue fieldName)
! Ha.rows "4"
$ toHtml $ maybe "" (toString . accessor) mRecord
linkField :: String -> String -> AttributeValue-> Html
linkField fieldLabel displayText url = H.label $ do
H.span (toHtml fieldLabel)
a ! class_ "input-link" ! href url $ toHtml displayText
hiddenField :: String -> String -> Html
hiddenField fieldName val =
input ! Ha.name (stringValue fieldName)
! type_ "hidden"
! Ha.value (stringValue val)
selectField :: (Eq b, Show b)
=> String -> String -> (a -> b) -> Maybe a -> [(b, String)]
-> Html
selectField fieldLabel fieldName accessor mRecord options = H.label $ do
H.span (toHtml fieldLabel)
let f sel = if maybe False (((==) sel) . accessor) mRecord
then (! Ha.selected "selected") else (Prelude.id)
select ! Ha.name (stringValue fieldName) $ do
forM_ options (\ (choice, optionLabel) ->
f choice (H.option ! Ha.value (stringValue $ show choice)
$ toHtml optionLabel))
cancelButton :: String -> Html
cancelButton buttonId = do
button ! Ha.id (stringValue buttonId) $ "Cancel"
script $ toHtml $
" $('#"++buttonId++"').click(function(e) { \
\ e.preventDefault(); \
\ window.location.href = document.referrer; \
\ }); "
deleteButton :: String -> String -> Html
deleteButton buttonId url = do
button ! Ha.id (stringValue buttonId) $ "Delete"
script $ toHtml $
" $('#"++buttonId++"').click(function(e) { \
\ e.preventDefault(); \
\ if (confirm('Permanently delete this item?')) { \
\ $.ajax({ \
\ method: 'DELETE', \
\ url: window.location, \
\ success: function() { \
\ window.location.replace('"++ url ++"'); \
\ } \
\ }) \
\ } \
\ }); "
datepicker :: String -> String -> String -> Html
datepicker fieldId fieldName fieldValue = do
input ! Ha.id (stringValue fieldId)
! Ha.name (stringValue fieldName)
! Ha.value (stringValue fieldValue)
script $ toHtml $
" $('#" ++ fieldId ++ "').datepicker({ \
\ dateFormat: 'dd . mm . yy', \
\ maxDate: 0, \
\ });"
navigation :: [(String, AttributeValue)] -> Int -> Html
navigation links choice = ul ! class_ "navigation" $ forM_ (zip [1..] links)
(\ (index, (linkLabel, linkUrl)) -> li $
a ! href linkUrl
! class_ (if choice == index then "selected" else "")
$ toHtml linkLabel)
breadCrumbs :: [(String, Maybe AttributeValue)] -> Html
breadCrumbs links = p ! class_ "breadcrumbs" $ (mconcat pieces)
where pieces = intersperse (H.span " > ") crumbs
crumbs = map toCrumb links
toCrumb (crumb, mLink) = case mLink of
Just l -> a ! href l $ toHtml crumb
Nothing -> H.span (toHtml crumb)
bar :: Real a => String -> a -> a -> String -> Html
bar color val maxVal barContents = let
val' = realToFrac val :: Double
maxVal' = realToFrac maxVal :: Double
percent = if maxVal' == 0 then 0 else val' / maxVal' * 100
tooltip = show (round percent :: Int) ++ " %"
barContents' = if null barContents then tooltip else barContents
in H.div ! class_ "bar"
! Ha.style (stringValue $ "border:1px solid " ++ color ++";")
! Ha.title (stringValue tooltip) $ do
H.div ! class_ "bar-inner"
! Ha.style (stringValue $
"background-color:" ++ color ++ ";"
++ "width:" ++ show percent ++ "%;")
$ ""
H.div ! class_ "bar-inner-text" $ toHtml barContents'
roundTo :: RealFrac a => Int -> a -> Double
roundTo places x = (realToFrac (round (x' * h) :: Int) :: Double) / h
where x' = realToFrac x
h = 10 ^ places
| hectorhon/autotrace2 | app/Common/Views.hs | bsd-3-clause | 9,009 | 0 | 21 | 2,972 | 2,453 | 1,208 | 1,245 | 165 | 3 |
module Data.BitBoard.Values.Private
( rankBB
, fileBB
, neighbourRanksBB'
, neighbourFilesBB'
, largeNeighbourFilesBB'
, aheadBB'
, knightAttackBB'
, kingAttackBB'
, pawnAttackBB'
, lineBB'
, pseudoAttackBB'
) where
import Data.Monoid
import Data.BitBoard.BitBoard
import Data.Square
import Data.ChessTypes
fileBB :: File -> BitBoard
fileBB p = BitBoard $ 0x0101010101010101 `shift` fromEnum p
{-# INLINE fileBB #-}
rankBB :: Rank -> BitBoard
rankBB r = BitBoard $ 0x00000000000000ff `shift` (8 * fromEnum r)
{-# INLINE rankBB #-}
neighbourRanksBB' :: Rank -> BitBoard
neighbourRanksBB' r = BitBoard (0x000000ffffffffff `shift` (8 * (fromEnum r - 2)))
neighbourFilesBB' :: File -> BitBoard
neighbourFilesBB' f =
let p = if f == minBound then mempty else fileBB $ pred f
s = if f == maxBound then mempty else fileBB $ succ f
in p <> fileBB f <> s
largeNeighbourFilesBB' :: File -> BitBoard
largeNeighbourFilesBB' = largeNeighbourFilesBB'' . fromEnum
where
largeNeighbourFilesBB'' 0 = BitBoard 0x0707070707070707
largeNeighbourFilesBB'' 1 = BitBoard 0x0f0f0f0f0f0f0f0f
largeNeighbourFilesBB'' 2 = BitBoard 0x1f1f1f1f1f1f1f1f
largeNeighbourFilesBB'' 3 = BitBoard 0x3e3e3e3e3e3e3e3e
largeNeighbourFilesBB'' 4 = BitBoard 0x7c7c7c7c7c7c7c7c
largeNeighbourFilesBB'' 5 = BitBoard 0xf8f8f8f8f8f8f8f8
largeNeighbourFilesBB'' 6 = BitBoard 0xf0f0f0f0f0f0f0f0
largeNeighbourFilesBB'' 7 = BitBoard 0xe0e0e0e0e0e0e0e0
largeNeighbourFilesBB'' _ = error "file out of range"
aheadBB' :: Rank -> Colour -> BitBoard
aheadBB' r White = mconcat [ rankBB r' | r' <- [r .. eighthRank] ]
aheadBB' r Black = mconcat [ rankBB r' | r' <- [firstRank .. r] ]
e4:: Square
e4 = toSquare eFile fourthRank
knightAttackBB' :: Square -> BitBoard
knightAttackBB' s
| s == e4 = BitBoard 44272527353856
| otherwise = largeNeighbourFilesBB' (file s)
.&. shift (knightAttackBB' e4) (fromEnum s - fromEnum e4)
kingAttackBB' :: Square -> BitBoard
kingAttackBB' s
| s == e4 = BitBoard 241192927232
| otherwise = largeNeighbourFilesBB' (file s)
.&. shift (kingAttackBB' e4) (fromEnum s - fromEnum e4)
pawnAttackBB' :: Square -> Colour -> BitBoard
pawnAttackBB' pos c =
let mask = largeNeighbourFilesBB' (file pos)
in mconcat [ fromSquare (offset pos $ direction c n)
| n <- [7, 9]
] .&. mask
lineBB' :: Square -> Square -> BitBoard
lineBB' a b
| hDist a b == 0 = mconcat [ fromSquare $ toSquare (file a) r | r <- rankList]
| vDist a b == 0 = mconcat [ fromSquare $ toSquare f (rank a) | f <- fileList]
| hDist a b == vDist a b = mconcat $ map fromSquare $ zipWith toSquare fileList rankList
| otherwise = mempty
where fileList = if file a < file b
then [ file a .. file b ]
else reverse [ file b .. file a ]
rankList = if rank a < rank b
then [ rank a .. rank b ]
else reverse [ rank b .. rank a ]
pseudoAttackBB' :: PieceType -> Square -> BitBoard
pseudoAttackBB' Bishop sq = mconcat $ do
flist <- [ reverse [ aFile .. file sq], [ file sq .. hFile ] ]
rlist <- [ reverse [ firstRank .. rank sq ], [ rank sq .. eighthRank ] ]
(f, r) <- zip flist rlist
return $ fromSquare $ toSquare f r
pseudoAttackBB' Rook sq = fileBB (file sq) <> rankBB (rank sq)
pseudoAttackBB' Queen sq = pseudoAttackBB' Bishop sq <> pseudoAttackBB' Rook sq
pseudoAttackBB' King _ = mempty
pseudoAttackBB' Knight _ = mempty
pseudoAttackBB' Pawn _ = mempty
| phaul/chess | Data/BitBoard/Values/Private.hs | bsd-3-clause | 3,682 | 0 | 13 | 944 | 1,192 | 598 | 594 | 84 | 9 |
import qualified Day10.Test as Day10
import qualified Day11.Test as Day11
import qualified Day12.Test as Day12
import qualified Day13.Test as Day13
import qualified Day15.Test as Day15
import qualified Day16.Test as Day16
import qualified Day17.Test as Day17
import qualified Day18.Test as Day18
import qualified Day19.Test as Day19
import qualified Day2.Test as Day2
import qualified Day20.Test as Day20
import qualified Day21.Test as Day21
import qualified Day22.Test as Day22
import qualified Day23.Test as Day23
import qualified Day24.Test as Day24
import qualified Day3.Test as Day3
import qualified Day4.Test as Day4
import qualified Day5.Test as Day5
import qualified Day6.Test as Day6
import qualified Day7.Test as Day7
import qualified Day8.Test as Day8
import qualified Day9.Test as Day9
import Test.Hspec
main :: IO ()
main = hspec Day22.tests
| z0isch/aoc2016 | test/Spec.hs | bsd-3-clause | 875 | 0 | 6 | 140 | 202 | 145 | 57 | 25 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
module Harihara.Monad where
import MonadLib
import qualified Audio.TagLib.Internal as TL (TagLibException(..))
import Control.Applicative
import Control.Exception
import qualified Data.Text.IO as T
import Harihara.DB hiding (io)
import Harihara.Lastfm hiding (io, getLastfmEnv)
import Harihara.Tag hiding (io, getTagEnv)
import Harihara.Log
import Harihara.Options
-- Harihara Monad {{{
newtype Harihara a = Harihara
{ unHarihara :: StateT HariharaEnv IO a
}
instance Functor Harihara where
fmap f (Harihara m) = Harihara $ fmap f m
instance Monad Harihara where
return = Harihara . return
(Harihara m) >>= f = Harihara $ m >>= unHarihara . f
io :: IO a -> Harihara a
io = Harihara . inBase
runHarihara :: HariharaEnv -> Harihara a -> IO (a,HariharaEnv)
runHarihara env = runStateT env . unHarihara
evalHarihara :: HariharaEnv -> Harihara a -> IO a
evalHarihara env = evalStateT env . unHarihara
instance BaseM Harihara IO where
inBase = Harihara . inBase
instance MonadLog Harihara where
getLogLevel = fromHHEnv logLevel
writeLog = io . T.putStrLn
header = return "Main"
catchHarihara :: (Exception e) => Harihara a -> (e -> Harihara a) -> Harihara a
m `catchHarihara` f = do
env <- getHHEnv
io $ catch
(evalHarihara env m)
(evalHarihara env . f)
-- }}}
-- Harihara Exceptions {{{
-- }}}
-- HariharaEnv {{{
data HariharaEnv = HariharaEnv
{ logLevel :: LogLevel
, lastfmEnv :: Maybe LastfmEnv
, tagEnv :: TagEnv
, databaseOpts :: DBOpts
}
onLogLevel :: (LogLevel -> LogLevel) -> HariharaEnv -> HariharaEnv
onLogLevel f e = e { logLevel = f $ logLevel e }
onLastfmEnv :: (LastfmEnv -> LastfmEnv) -> HariharaEnv -> HariharaEnv
onLastfmEnv f e = e { lastfmEnv = f <$> lastfmEnv e }
onTagEnv :: (TagEnv -> TagEnv) -> HariharaEnv -> HariharaEnv
onTagEnv f e = e { tagEnv = f $ tagEnv e }
onDatabaseOpts :: (DBOpts -> DBOpts) -> HariharaEnv -> HariharaEnv
onDatabaseOpts f e = e { databaseOpts = f $ databaseOpts e }
buildEnv :: HariharaOptions -> Maybe LastfmEnv -> TagEnv -> DBOpts -> HariharaEnv
buildEnv = HariharaEnv . optsLogLevel
-- }}}
-- Monadic Operations {{{
getHHEnv :: Harihara HariharaEnv
getHHEnv = Harihara get
fromHHEnv :: (HariharaEnv -> a) -> Harihara a
fromHHEnv = Harihara . gets
modifyHHEnv :: (HariharaEnv -> HariharaEnv) -> Harihara ()
modifyHHEnv = Harihara . modify
getLastfmEnv :: Harihara (Maybe LastfmEnv)
getLastfmEnv = fromHHEnv lastfmEnv
modifyLastfmEnv :: (LastfmEnv -> LastfmEnv) -> Harihara ()
modifyLastfmEnv = modifyHHEnv . onLastfmEnv
getTagEnv :: Harihara TagEnv
getTagEnv = fromHHEnv tagEnv
modifyTagEnv :: (TagEnv -> TagEnv) -> Harihara ()
modifyTagEnv = modifyHHEnv . onTagEnv
getDatabaseOpts :: Harihara DBOpts
getDatabaseOpts = fromHHEnv databaseOpts
gets :: (StateM m s) => (s -> a) -> m a
gets f = do
s <- get
return (f s)
modify :: (StateM m s) => (s -> s) -> m ()
modify f = get >>= set . f
evalStateT :: (Monad m) => s -> StateT s m a -> m a
evalStateT s m = do
(a,_) <- runStateT s m
return a
-- }}}
-- Tag {{{
tag :: FilePath -> (FileId -> Tag a) -> Harihara a
tag fp f = do
logInfo "Entering Tag"
tEnv <- getTagEnv
io $ runTag tEnv $ withFile fp f
-- | Catch the TagLib exceptions associated with an
-- incompatible or unopenable file. Re-throw any other
-- exception encountered.
skipIfFileBad :: Harihara () -> Harihara ()
skipIfFileBad m = catchHarihara m $ \e -> case e of
TL.InvalidFile fp -> do
logWarnData "Invalid TagLib file" $ show fp
logWarn "Skipping."
TL.UnableToOpen fp -> do
logWarnData "TagLib unable to open file" $ show fp
logWarn "Skipping."
_ -> io $ throwIO e
-- }}}
-- Lastfm {{{
lastfm :: Lastfm a -> Harihara a
lastfm m = do
mEnv <- getLastfmEnv
case mEnv of
Nothing -> do
logError "Last.fm API key or Secret are missing from config"
io $ throwIO MissingLastfmConfig
Just env -> do
logInfo "Entering Lastfm"
io $ runLastfm env m
-- }}}
-- DB {{{
db :: DB a -> Harihara a
db m = do
fp <- dbPath <$> getDatabaseOpts
logInfo "Entering DB"
withDB fp m
withDB :: FilePath -> DB a -> Harihara a
withDB fp m = do
ll <- getLogLevel
io $ do
conn <- openDB fp
runDB (DBEnv conn ll) $ do
a <- m
closeDB
return a
-- }}}
| kylcarte/harihara | src/Harihara/Monad.hs | bsd-3-clause | 4,455 | 0 | 13 | 953 | 1,469 | 751 | 718 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Image where
import Data
import DanceView
import DiagramsDesigns
import DiagramsStuff
import Data.List.Split (divvy)
import Diagrams.Prelude hiding (Options)
import Diagrams.Backend.Cairo
-- 35 inches = 3360 px
-- 20 inches = 1920 px
doMontage :: [Frame Person] -> Options -> IO ()
doMontage allFrames opts = do
let frames = sampleFrames (rows' * cols') allFrames
seed = 3
diagrams = zipWith (flip (montageSingle opts)) frames (randColours seed)
Just cols' = columns opts
Just rows' = rows opts
gridded = divvy (cols') (cols') diagrams
joined = vcat (map hcat gridded)
let outSize = mkSizeSpec $ V2 (outWidth opts) (outHeight opts)
diagram = joined
renderCairo (outFile opts) outSize diagram
-- |
doFractal :: [Frame Person] -> Options -> IO ()
doFractal allFrames opts = do
-- let frames = sampleFrames 3 allFrames
let frames = sampleFrames (min 20 (length allFrames)) allFrames
let diagram = fractal opts frames
outSize = mkSizeSpec $ V2 (outWidth opts) (outHeight opts)
renderCairo (outFile opts) outSize diagram
| silky/DanceView | src/Image.hs | bsd-3-clause | 1,668 | 0 | 14 | 510 | 375 | 196 | 179 | 36 | 1 |
module Main where
import TicTacToe
main :: IO [()]
main = do
let f = NoMoves
partWay = (f >>== midCen >>== topLeft >>== bottomLeft)
case partWay of
Unfinished g ->
let undone = undoMove g
in mapM print $ stringifyGame $ (undone >>== bottomCen >>== topCen >>== bottomRight >>== topRight)
Finished g ->
let undone = undoMove g
in mapM print $ stringifyGame $ (undone >>== bottomCen >>== topCen >>== bottomRight >>== topRight)
NoMoves ->
mapM putStrLn ["invalid move"]
| steveshogren/haskell-katas | src/Main.hs | bsd-3-clause | 520 | 0 | 17 | 134 | 181 | 90 | 91 | 15 | 3 |
module UI.PlaybackStatus where
import Graphics.Vty
import Graphics.Vty.Widgets.All
import Data.IORef (IORef,newIORef,readIORef,writeIORef)
data PlaybackStatus = PlaybackStatus
{ playbackWidget :: Widget ProgressBar
, playbackArtist :: IORef String
, playbackTitle :: IORef String
}
newPlaybackStatus :: Attr -> Attr -> IO (PlaybackStatus, Widget ProgressBar)
newPlaybackStatus comp incomp = do
bar <- newProgressBar comp incomp
setProgressTextAlignment bar AlignLeft
aref <- newIORef ""
tref <- newIORef ""
let play = PlaybackStatus
{ playbackWidget = bar
, playbackArtist = aref
, playbackTitle = tref
}
return (play,bar)
setPlaybackArtist :: PlaybackStatus -> String -> IO ()
setPlaybackArtist p artist = do
writeIORef (playbackArtist p) artist
title <- readIORef (playbackTitle p)
setProgressText (playbackWidget p) (artist ++ " - " ++ title)
setPlaybackTitle :: PlaybackStatus -> String -> IO ()
setPlaybackTitle p title = do
writeIORef (playbackTitle p) title
artist <- readIORef (playbackArtist p)
setProgressText (playbackWidget p) (artist ++ " - " ++ title)
setPlaybackProgress :: PlaybackStatus -> Int -> IO ()
setPlaybackProgress p = setProgress (playbackWidget p)
| elliottt/din | src/UI/PlaybackStatus.hs | bsd-3-clause | 1,260 | 0 | 11 | 243 | 390 | 196 | 194 | 31 | 1 |
module GameOfHaskell.Core where
--------------------------------------------------------------------------------
import Control.Monad.State
import Data.List
--------------------------------------------------------------------------------
type Cell = (Int, Int)
type Board = [Cell]
--------------------------------------------------------------------------------
isAlive :: Board -> Cell -> Bool
isAlive board cell = cell `elem` board
--------------------------------------------------------------------------------
neighbors :: Cell -> [Cell]
neighbors (x,y) = [(x',y') | x' <- [x-1..x+1], y' <- [y-1..y+1], (x',y') /= (x,y)]
--------------------------------------------------------------------------------
aliveNeighborCount :: Board -> Cell -> Int
aliveNeighborCount board = length . filter (isAlive board) . neighbors
--------------------------------------------------------------------------------
liveOrDie :: Board -> Cell -> Bool
liveOrDie board cell
| alive && ns == 2 = True
| alive && ns == 3 = True
| not alive && ns == 3 = True
| otherwise = False
where
alive = isAlive board cell
ns = aliveNeighborCount board cell
--------------------------------------------------------------------------------
generation :: State Board Board
generation = do
board <- get
let deadNeighbors = nub $ filter (not . isAlive board) $ concatMap neighbors board
put $ filter (liveOrDie board) $ board ++ deadNeighbors
return board
--------------------------------------------------------------------------------
generations :: State Board [Board]
generations = do
board <- generation
future <- generations
return (board : future)
| stesta/GameOfLife | src/GameOfHaskell/Core.hs | bsd-3-clause | 1,739 | 0 | 15 | 296 | 447 | 235 | 212 | 30 | 1 |
module Data.Indexed where
import Data.Semigroup as S
import Data.Comonad
import Pipes
data Indexed i a = Ind i (i -> a)
instance (Show a, Show s) => Show (Indexed s a) where
show (Ind s f) = "Ind: " ++ show s ++ " looking at: " ++ show (f s)
instance Functor (Indexed s) where
fmap f (Ind s g) = Ind s (f . g)
instance Comonad (Indexed s) where
leave (Ind s f) = f s
duplicate (Ind s f) = Ind s (flip Ind $ f)
loosen s f = fmap f $ duplicate s
look :: Indexed s a -> a
look = leave
seek :: (s -> s) -> Indexed s a -> Indexed s a
seek f (Ind s g) = (Ind (f s) g)
set = seek . const
peek :: (s -> s) -> Indexed s a -> a
peek f = leave . seek f
peek' = peek . const
index' :: (s -> i -> a) -> i -> (s -> Indexed i a)
index' f i = \x -> Ind i (f x)
index :: Monoid i => (s -> i -> a) -> (s -> Indexed i a)
index f = \x -> Ind mempty (f x)
-- Indexed is a non-commutative semigroup
instance Monoid i => S.Semigroup (Indexed i a) where
(Ind i f) <> (Ind i' f') = Ind (i `mappend` i') f | onomatic/sigmund | src/Data/Indexed.hs | bsd-3-clause | 1,025 | 0 | 9 | 283 | 571 | 292 | 279 | 27 | 1 |
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Quaternions
module Data.Quaternion (
QuaternionG(..)
, Quaternion
, scaleQuat
, conjugate
, realQuat
, quaternionNorm
, quaternionNormSq
-- * Vector rotation
, rotation
, rotX
, rotY
, rotZ
, rotateVector
) where
import qualified Data.Vector.Fixed as F
import Data.Vector.Fixed (Dim,Vector,N3,N4)
import Data.Vector.Fixed.Unboxed (Vec4)
-- | Wrapper new for any 4-element vector.
newtype QuaternionG v a = QuaternionG (v a)
-- | Quaternions wrapping unboxed vectors.
type Quaternion = QuaternionG Vec4
type instance Dim (QuaternionG v) = N4
instance (Vector v a, Dim v ~ N4) => Vector (QuaternionG v) a where
inspect (QuaternionG v) f = F.inspect v f
construct = fmap QuaternionG F.construct
{-# INLINE inspect #-}
{-# INLINE construct #-}
instance (Vector v a, Dim v ~ N4, Floating a) => Num (QuaternionG v a) where
(+) = F.zipWith (+)
(-) = F.zipWith (-)
(F.convert -> (w1,x1,y1,z1)) * (F.convert -> (w2,x2,y2,z2))
= F.mk4 (w1*w2 - x1*x2 - y1*y2 - z1*z2)
(w1*x2 + x1*w2 + y1*z2 - z1*y2)
(w1*y2 - x1*z2 + y1*w2 + z1*x2)
(w1*z2 + x1*y2 - y1*x2 + z1*w2)
{-# INLINE (+) #-}
{-# INLINE (-) #-}
{-# INLINE (*) #-}
abs = realQuat . quaternionNorm
signum = realQuat . signum . F.head
{-# INLINE abs #-}
{-# INLINE signum #-}
fromInteger i = realQuat (fromInteger i)
{-# INLINE fromInteger #-}
instance (Vector v a, Dim v ~ N4, Floating a) => Fractional (QuaternionG v a) where
v / u = recip (quaternionNormSq v) `scaleQuat` v * conjugate u
recip v = recip (quaternionNormSq v) `scaleQuat` conjugate v
{-# INLINE (/) #-}
{-# INLINE recip #-}
fromRational = realQuat . fromRational
{-# INLINE fromRational #-}
-- | Conjugate quaternion
conjugate :: (Vector v a, Dim v ~ N4, Num a) => QuaternionG v a -> QuaternionG v a
conjugate = F.imap (\i a -> if i == 0 then a else negate a)
{-# INLINE conjugate #-}
-- | Scale quaternion
scaleQuat :: (Vector v a, Dim v ~ N4, Num a) => a -> QuaternionG v a -> QuaternionG v a
scaleQuat a = F.map (* a)
{-# INLINE scaleQuat #-}
-- | Construct quaternion from real part
realQuat :: (Vector v a, Dim v ~ N4, Num a) => a -> QuaternionG v a
realQuat x = F.mk4 x 0 0 0
{-# INLINE realQuat #-}
-- | Norm of quaternion
quaternionNorm :: (Vector v a, Dim v ~ N4, Floating a) => QuaternionG v a -> a
quaternionNorm = sqrt . quaternionNormSq
{-# INLINE quaternionNorm #-}
-- | Square of quaternion's norm
quaternionNormSq :: (Vector v a, Dim v ~ N4, Num a) => QuaternionG v a -> a
quaternionNormSq = F.sum . F.map (\x -> x*x)
{-# INLINE quaternionNormSq #-}
----------------------------------------------------------------
-- Rotations
----------------------------------------------------------------
rotation :: (Vector v a, Dim v ~ N3, Vector q a, Dim q ~ N4, RealFloat a)
=> a -> v a -> QuaternionG q a
{-# INLINE rotation #-}
rotation a axis
= F.mk4 c (s * x) (s * y) (s * z)
where
c = cos $ a / 2
s = sin $ a / 2
(x,y,z) = F.convert axis
rotX :: (Vector q a, Dim q ~ N4, RealFloat a)
=> a -> QuaternionG q a
{-# INLINE rotX #-}
rotX a = rotation a (1,0,0)
rotY :: (Vector q a, Dim q ~ N4, RealFloat a)
=> a -> QuaternionG q a
{-# INLINE rotY #-}
rotY a = rotation a (0,1,0)
rotZ :: (Vector q a, Dim q ~ N4, RealFloat a)
=> a -> QuaternionG q a
{-# INLINE rotZ #-}
rotZ a = rotation a (0,0,1)
-- | Rotate vector using quaternion assuming that it have unit norm.
rotateVector :: (Vector q a, Dim q ~ N4, Vector v a, Dim v ~ N3, Floating a)
=> QuaternionG q a -> v a -> v a
{-# INLINE rotateVector #-}
rotateVector q v
= F.tail $ q * F.cons 0 v * recip q
| Shimuuar/quaternion | Data/Quaternion.hs | bsd-3-clause | 3,880 | 0 | 14 | 938 | 1,442 | 774 | 668 | 92 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE Rank2Types #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.List.Lens
-- Copyright : (C) 2012 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : provisional
-- Portability : portable
--
-- Traversals for manipulating parts of a list.
--
----------------------------------------------------------------------------
module Data.List.Lens
(
_head
, _tail
, _last
, _init
, strippingPrefix
) where
import Control.Applicative
import Control.Lens
import Data.List
-- $setup
-- >>> import Debug.SimpleReflect.Expr
-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)
-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f
-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g
-- | A 'Traversal' reading and writing to the 'head' of a /non-empty/ list.
--
-- >>> [a,b,c]^? _head
-- Just a
--
-- >>> [a,b,c] & _head .~ d
-- [d,b,c]
--
-- >>> [a,b,c] & _head %~ f
-- [f a,b,c]
--
-- >>> [] & _head %~ f
-- []
--
-- >>> [1,2,3]^?!_head
-- 1
--
-- >>> []^?_head
-- Nothing
--
-- >>> [1,2]^?_head
-- Just 1
--
-- >>> [] & _head .~ 1
-- []
--
-- >>> [0] & _head .~ 2
-- [2]
--
-- >>> [0,1] & _head .~ 2
-- [2,1]
--
--
_head :: IndexedTraversal' Int [a] a
_head _ [] = pure []
_head f (a:as) = (:as) <$> indexed f (0 :: Int) a
{-# INLINE _head #-}
-- | A 'Traversal' reading and writing to the 'tail' of a /non-empty/ list
--
-- >>> [a,b] & _tail .~ [c,d,e]
-- [a,c,d,e]
--
-- >>> [] & _tail .~ [a,b]
-- []
--
-- >>> [a,b,c,d,e] & _tail.traverse %~ f
-- [a,f b,f c,f d,f e]
--
-- >>> [1,2] & _tail .~ [3,4,5]
-- [1,3,4,5]
--
-- >>> [] & _tail .~ [1,2]
-- []
--
-- >>> [a,b,c]^?_tail
-- Just [b,c]
--
-- >>> [1,2]^?!_tail
-- [2]
--
-- >>> "hello"^._tail
-- "ello"
--
-- >>> ""^._tail
-- ""
_tail :: Traversal' [a] [a]
_tail f (a:as) = (a:) <$> f as
_tail _ as = pure as
{-# INLINE _tail #-}
-- | A 'Traversal' reading and writing to the last element of a /non-empty/ list
--
-- >>> [a,b,c]^?!_last
-- c
--
-- >>> []^?_last
-- Nothing
--
-- >>> [a,b,c] & _last %~ f
-- [a,b,f c]
--
-- >>> [1,2]^?_last
-- Just 2
--
-- >>> [] & _last .~ 1
-- []
--
-- >>> [0] & _last .~ 2
-- [2]
--
-- >>> [0,1] & _last .~ 2
-- [0,2]
_last :: IndexedTraversal' Int [a] a
_last _ [] = pure []
_last f (a:as) = go (0 :: Int) a as where
go n b [] = return <$> indexed f n b
go n b (c:cs) = (b:) <$> (go $! n + 1) c cs
{-# INLINE _last #-}
-- | A 'Traversal' reading and replacing all but the a last element of a /non-empty/ list
--
-- >>> [a,b,c,d]^?_init
-- Just [a,b,c]
--
-- >>> []^?_init
-- Nothing
--
-- >>> [a,b] & _init .~ [c,d,e]
-- [c,d,e,b]
--
-- >>> [] & _init .~ [a,b]
-- []
--
-- >>> [a,b,c,d] & _init.traverse %~ f
-- [f a,f b,f c,d]
--
-- >>> [1,2,3]^?_init
-- Just [1,2]
--
-- >>> [1,2,3,4]^?!_init
-- [1,2,3]
--
-- >>> "hello"^._init
-- "hell"
--
-- >>> ""^._init
-- ""
_init :: Traversal' [a] [a]
_init _ [] = pure []
_init f as = (++ [Prelude.last as]) <$> f (Prelude.init as)
{-# INLINE _init #-}
-- | A 'Prism' stripping a prefix from a list when used as a 'Traversal', or
-- prepending that prefix when run backwards:
--
-- >>> "preview" ^? strippingPrefix "pre"
-- Just "view"
--
-- >>> "review" ^? strippingPrefix "pre"
-- Nothing
--
-- >>> "amble"^.remit (strippingPrefix "pre")
-- "preamble"
strippingPrefix :: Eq a => [a] -> Prism' [a] [a]
strippingPrefix ps = prism (ps ++) $ \xs -> case stripPrefix ps xs of
Nothing -> Left xs
Just xs' -> Right xs'
| np/lens | src/Data/List/Lens.hs | bsd-3-clause | 3,595 | 0 | 11 | 745 | 597 | 383 | 214 | 34 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE CPP #-}
-- | HTTP over TLS support for Warp via the TLS package.
--
-- If HTTP\/2 is negotiated by ALPN, HTTP\/2 over TLS is used.
-- Otherwise HTTP\/1.1 over TLS is used.
--
-- Support for SSL is now obsoleted.
module Network.Wai.Handler.WarpTLS (
-- * Settings
TLSSettings
, defaultTlsSettings
-- * Smart constructors
, tlsSettings
, tlsSettingsMemory
, tlsSettingsChain
, tlsSettingsChainMemory
-- * Accessors
, certFile
, keyFile
, tlsLogging
, tlsAllowedVersions
, tlsCiphers
, tlsWantClientCert
, tlsServerHooks
, onInsecure
, OnInsecure (..)
-- * Runner
, runTLS
, runTLSSocket
-- * Exception
, WarpTLSException (..)
) where
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative ((<$>))
#endif
import Control.Exception (Exception, throwIO, bracket, finally, handle, fromException, try, IOException, onException)
import Control.Monad (void)
import qualified Crypto.Random.AESCtr
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Default.Class (def)
import qualified Data.IORef as I
import Data.Streaming.Network (bindPortTCP, safeRecv)
import Data.Typeable (Typeable)
import Network.Socket (Socket, sClose, withSocketsDo, SockAddr, accept)
import Network.Socket.ByteString (sendAll)
import qualified Network.TLS as TLS
import qualified Network.TLS.Extra as TLSExtra
import Network.Wai (Application)
import Network.Wai.Handler.Warp
import Network.Wai.Handler.Warp.Internal
import System.IO.Error (isEOFError)
----------------------------------------------------------------
-- | Settings for WarpTLS.
data TLSSettings = TLSSettings {
certFile :: FilePath
-- ^ File containing the certificate.
, chainCertFiles :: [FilePath]
-- ^ Files containing chain certificates.
, keyFile :: FilePath
-- ^ File containing the key
, certMemory :: Maybe S.ByteString
, chainCertsMemory :: [S.ByteString]
, keyMemory :: Maybe S.ByteString
, onInsecure :: OnInsecure
-- ^ Do we allow insecure connections with this server as well?
--
-- >>> onInsecure defaultTlsSettings
-- DenyInsecure "This server only accepts secure HTTPS connections."
--
-- Since 1.4.0
, tlsLogging :: TLS.Logging
-- ^ The level of logging to turn on.
--
-- Default: 'TLS.defaultLogging'.
--
-- Since 1.4.0
, tlsAllowedVersions :: [TLS.Version]
-- ^ The TLS versions this server accepts.
--
-- >>> tlsAllowedVersions defaultTlsSettings
-- [TLS12,TLS11,TLS10]
--
-- Since 1.4.2
, tlsCiphers :: [TLS.Cipher]
-- ^ The TLS ciphers this server accepts.
--
-- >>> tlsCiphers defaultTlsSettings
-- [ECDHE-RSA-AES128GCM-SHA256,DHE-RSA-AES128GCM-SHA256,DHE-RSA-AES256-SHA256,DHE-RSA-AES128-SHA256,DHE-RSA-AES256-SHA1,DHE-RSA-AES128-SHA1,DHE-DSA-AES128-SHA1,DHE-DSA-AES256-SHA1,RSA-aes128-sha1,RSA-aes256-sha1]
--
-- Since 1.4.2
, tlsWantClientCert :: Bool
-- ^ Whether or not to demand a certificate from the client. If this
-- is set to True, you must handle received certificates in a server hook
-- or all connections will fail.
--
-- >>> tlsWantClientCert defaultTlsSettings
-- False
--
-- Since 3.0.2
, tlsServerHooks :: TLS.ServerHooks
-- ^ The server-side hooks called by the tls package, including actions
-- to take when a client certificate is received. See the "Network.TLS"
-- module for details.
--
-- Default: def
--
-- Since 3.0.2
}
-- | Default 'TLSSettings'. Use this to create 'TLSSettings' with the field record name (aka accessors).
defaultTlsSettings :: TLSSettings
defaultTlsSettings = TLSSettings {
certFile = "certificate.pem"
, chainCertFiles = []
, keyFile = "key.pem"
, certMemory = Nothing
, chainCertsMemory = []
, keyMemory = Nothing
, onInsecure = DenyInsecure "This server only accepts secure HTTPS connections."
, tlsLogging = def
, tlsAllowedVersions = [TLS.TLS12,TLS.TLS11,TLS.TLS10]
, tlsCiphers = ciphers
, tlsWantClientCert = False
, tlsServerHooks = def
}
-- taken from stunnel example in tls-extra
ciphers :: [TLS.Cipher]
ciphers =
[ TLSExtra.cipher_ECDHE_RSA_AES128GCM_SHA256
, TLSExtra.cipher_DHE_RSA_AES128GCM_SHA256
, TLSExtra.cipher_DHE_RSA_AES256_SHA256
, TLSExtra.cipher_DHE_RSA_AES128_SHA256
, TLSExtra.cipher_DHE_RSA_AES256_SHA1
, TLSExtra.cipher_DHE_RSA_AES128_SHA1
, TLSExtra.cipher_DHE_DSS_AES128_SHA1
, TLSExtra.cipher_DHE_DSS_AES256_SHA1
, TLSExtra.cipher_AES128_SHA1
, TLSExtra.cipher_AES256_SHA1
]
----------------------------------------------------------------
-- | An action when a plain HTTP comes to HTTP over TLS/SSL port.
data OnInsecure = DenyInsecure L.ByteString
| AllowInsecure
deriving (Show)
----------------------------------------------------------------
-- | A smart constructor for 'TLSSettings' based on 'defaultTlsSettings'.
tlsSettings :: FilePath -- ^ Certificate file
-> FilePath -- ^ Key file
-> TLSSettings
tlsSettings cert key = defaultTlsSettings {
certFile = cert
, keyFile = key
}
-- | A smart constructor for 'TLSSettings' that allows specifying
-- chain certificates based on 'defaultTlsSettings'.
--
-- Since 3.0.3
tlsSettingsChain
:: FilePath -- ^ Certificate file
-> [FilePath] -- ^ Chain certificate files
-> FilePath -- ^ Key file
-> TLSSettings
tlsSettingsChain cert chainCerts key = defaultTlsSettings {
certFile = cert
, chainCertFiles = chainCerts
, keyFile = key
}
-- | A smart constructor for 'TLSSettings', but uses in-memory representations
-- of the certificate and key based on 'defaultTlsSettings'.
--
-- Since 3.0.1
tlsSettingsMemory
:: S.ByteString -- ^ Certificate bytes
-> S.ByteString -- ^ Key bytes
-> TLSSettings
tlsSettingsMemory cert key = defaultTlsSettings
{ certMemory = Just cert
, keyMemory = Just key
}
-- | A smart constructor for 'TLSSettings', but uses in-memory representations
-- of the certificate and key based on 'defaultTlsSettings'.
--
-- Since 3.0.3
tlsSettingsChainMemory
:: S.ByteString -- ^ Certificate bytes
-> [S.ByteString] -- ^ Chain certificate bytes
-> S.ByteString -- ^ Key bytes
-> TLSSettings
tlsSettingsChainMemory cert chainCerts key = defaultTlsSettings
{ certMemory = Just cert
, chainCertsMemory = chainCerts
, keyMemory = Just key
}
----------------------------------------------------------------
-- | Running 'Application' with 'TLSSettings' and 'Settings'.
runTLS :: TLSSettings -> Settings -> Application -> IO ()
runTLS tset set app = withSocketsDo $
bracket
(bindPortTCP (getPort set) (getHost set))
sClose
(\sock -> runTLSSocket tset set sock app)
----------------------------------------------------------------
-- | Running 'Application' with 'TLSSettings' and 'Settings' using
-- specified 'Socket'.
runTLSSocket :: TLSSettings -> Settings -> Socket -> Application -> IO ()
runTLSSocket tlsset@TLSSettings{..} set sock app = do
credential <- case (certMemory, keyMemory) of
(Nothing, Nothing) ->
either error id <$>
TLS.credentialLoadX509Chain certFile chainCertFiles keyFile
(mcert, mkey) -> do
cert <- maybe (S.readFile certFile) return mcert
key <- maybe (S.readFile keyFile) return mkey
either error return $
TLS.credentialLoadX509ChainFromMemory cert chainCertsMemory key
runTLSSocket' tlsset set credential sock app
runTLSSocket' :: TLSSettings -> Settings -> TLS.Credential -> Socket -> Application -> IO ()
runTLSSocket' tlsset@TLSSettings{..} set credential sock app =
runSettingsConnectionMakerSecure set get app
where
get = getter tlsset sock params
params = TLS.ServerParams {
TLS.serverWantClientCert = tlsWantClientCert
, TLS.serverCACertificates = []
, TLS.serverDHEParams = Nothing
, TLS.serverHooks = hooks
, TLS.serverShared = shared
, TLS.serverSupported = supported
}
-- Adding alpn to user's tlsServerHooks.
hooks = tlsServerHooks {
TLS.onALPNClientSuggest = Just alpn
}
shared = def {
TLS.sharedCredentials = TLS.Credentials [credential]
}
supported = TLS.Supported {
TLS.supportedVersions = tlsAllowedVersions
, TLS.supportedCiphers = tlsCiphers
, TLS.supportedCompressions = [TLS.nullCompression]
, TLS.supportedHashSignatures = [
(TLS.HashSHA512, TLS.SignatureRSA)
, (TLS.HashSHA384, TLS.SignatureRSA)
, (TLS.HashSHA256, TLS.SignatureRSA)
, (TLS.HashSHA224, TLS.SignatureRSA)
, (TLS.HashSHA1, TLS.SignatureRSA)
, (TLS.HashSHA1, TLS.SignatureDSS)
]
, TLS.supportedSecureRenegotiation = True
, TLS.supportedSession = True
}
alpn :: [S.ByteString] -> IO S.ByteString
alpn xs
| "h2" `elem` xs = return "h2"
| "h2-16" `elem` xs = return "h2-16"
| "h2-15" `elem` xs = return "h2-15"
| "h2-14" `elem` xs = return "h2-14"
| otherwise = return "http/1.1"
----------------------------------------------------------------
getter :: TLS.TLSParams params => TLSSettings -> Socket -> params -> IO (IO (Connection, Transport), SockAddr)
getter tlsset@TLSSettings{..} sock params = do
(s, sa) <- accept sock
return (mkConn tlsset s params, sa)
mkConn :: TLS.TLSParams params => TLSSettings -> Socket -> params -> IO (Connection, Transport)
mkConn tlsset s params = do
firstBS <- safeRecv s 4096
(if not (S.null firstBS) && S.head firstBS == 0x16 then
httpOverTls tlsset s firstBS params
else
plainHTTP tlsset s firstBS) `onException` sClose s
----------------------------------------------------------------
httpOverTls :: TLS.TLSParams params => TLSSettings -> Socket -> S.ByteString -> params -> IO (Connection, Transport)
httpOverTls TLSSettings{..} s bs0 params = do
recvN <- makePlainReceiveN s bs0
#if MIN_VERSION_tls(1,3,0)
ctx <- TLS.contextNew (backend recvN) params
#else
gen <- Crypto.Random.AESCtr.makeSystem
ctx <- TLS.contextNew (backend recvN) params gen
#endif
TLS.contextHookSetLogging ctx tlsLogging
TLS.handshake ctx
writeBuf <- allocateBuffer bufferSize
-- Creating a cache for leftover input data.
ref <- I.newIORef ""
tls <- getTLSinfo ctx
return (conn ctx writeBuf ref, tls)
where
backend recvN = TLS.Backend {
TLS.backendFlush = return ()
, TLS.backendClose = sClose s
, TLS.backendSend = sendAll s
, TLS.backendRecv = recvN
}
conn ctx writeBuf ref = Connection {
connSendMany = TLS.sendData ctx . L.fromChunks
, connSendAll = sendall
, connSendFile = sendfile
, connClose = close
, connRecv = recv ref
, connRecvBuf = recvBuf ref
, connWriteBuffer = writeBuf
, connBufferSize = bufferSize
}
where
sendall = TLS.sendData ctx . L.fromChunks . return
sendfile fid offset len hook headers =
readSendFile writeBuf bufferSize sendall fid offset len hook headers
close = freeBuffer writeBuf `finally`
void (tryIO $ TLS.bye ctx) `finally`
TLS.contextClose ctx
-- TLS version of recv with a cache for leftover input data.
-- The cache is shared with recvBuf.
recv cref = do
cached <- I.readIORef cref
if cached /= "" then do
I.writeIORef cref ""
return cached
else
recv'
-- TLS version of recv (decrypting) without a cache.
recv' = handle onEOF go
where
onEOF e
| Just TLS.Error_EOF <- fromException e = return S.empty
| Just ioe <- fromException e, isEOFError ioe = return S.empty | otherwise = throwIO e
go = do
x <- TLS.recvData ctx
if S.null x then
go
else
return x
-- TLS version of recvBuf with a cache for leftover input data.
recvBuf cref buf siz = do
cached <- I.readIORef cref
(ret, leftover) <- fill cached buf siz recv'
I.writeIORef cref leftover
return ret
fill :: S.ByteString -> Buffer -> BufSize -> Recv -> IO (Bool,S.ByteString)
fill bs0 buf0 siz0 recv
| siz0 <= len0 = do
let (bs, leftover) = S.splitAt siz0 bs0
void $ copy buf0 bs
return (True, leftover)
| otherwise = do
buf <- copy buf0 bs0
loop buf (siz0 - len0)
where
len0 = S.length bs0
loop _ 0 = return (True, "")
loop buf siz = do
bs <- recv
let len = S.length bs
if len == 0 then return (False, "")
else if (len <= siz) then do
buf' <- copy buf bs
loop buf' (siz - len)
else do
let (bs1,bs2) = S.splitAt siz bs
void $ copy buf bs1
return (True, bs2)
getTLSinfo :: TLS.Context -> IO Transport
getTLSinfo ctx = do
proto <- TLS.getNegotiatedProtocol ctx
minfo <- TLS.contextGetInformation ctx
case minfo of
Nothing -> return TCP
Just TLS.Information{..} -> do
let (major, minor) = case infoVersion of
TLS.SSL2 -> (2,0)
TLS.SSL3 -> (3,0)
TLS.TLS10 -> (3,1)
TLS.TLS11 -> (3,2)
TLS.TLS12 -> (3,3)
return TLS {
tlsMajorVersion = major
, tlsMinorVersion = minor
, tlsNegotiatedProtocol = proto
, tlsChiperID = TLS.cipherID infoCipher
}
tryIO :: IO a -> IO (Either IOException a)
tryIO = try
----------------------------------------------------------------
plainHTTP :: TLSSettings -> Socket -> S.ByteString -> IO (Connection, Transport)
plainHTTP TLSSettings{..} s bs0 = case onInsecure of
AllowInsecure -> do
conn' <- socketConnection s
cachedRef <- I.newIORef bs0
let conn'' = conn'
{ connRecv = recvPlain cachedRef (connRecv conn')
}
return (conn'', TCP)
DenyInsecure lbs -> do
sendAll s "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n"
mapM_ (sendAll s) $ L.toChunks lbs
sClose s
throwIO InsecureConnectionDenied
----------------------------------------------------------------
-- | Modify the given receive function to first check the given @IORef@ for a
-- chunk of data. If present, takes the chunk of data from the @IORef@ and
-- empties out the @IORef@. Otherwise, calls the supplied receive function.
recvPlain :: I.IORef S.ByteString -> IO S.ByteString -> IO S.ByteString
recvPlain ref fallback = do
bs <- I.readIORef ref
if S.null bs
then fallback
else do
I.writeIORef ref S.empty
return bs
----------------------------------------------------------------
data WarpTLSException = InsecureConnectionDenied
deriving (Show, Typeable)
instance Exception WarpTLSException
| AndrewRademacher/wai | warp-tls/Network/Wai/Handler/WarpTLS.hs | mit | 15,670 | 0 | 18 | 4,094 | 3,273 | 1,789 | 1,484 | 297 | 6 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.RDS.DescribeDBEngineVersions
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a list of the available DB engines.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DescribeDBEngineVersions.html AWS API Reference> for DescribeDBEngineVersions.
--
-- This operation returns paginated results.
module Network.AWS.RDS.DescribeDBEngineVersions
(
-- * Creating a Request
describeDBEngineVersions
, DescribeDBEngineVersions
-- * Request Lenses
, ddevEngineVersion
, ddevDefaultOnly
, ddevFilters
, ddevEngine
, ddevDBParameterGroupFamily
, ddevListSupportedCharacterSets
, ddevMarker
, ddevMaxRecords
-- * Destructuring the Response
, describeDBEngineVersionsResponse
, DescribeDBEngineVersionsResponse
-- * Response Lenses
, ddevrsMarker
, ddevrsDBEngineVersions
, ddevrsResponseStatus
) where
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.RDS.Types
import Network.AWS.RDS.Types.Product
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'describeDBEngineVersions' smart constructor.
data DescribeDBEngineVersions = DescribeDBEngineVersions'
{ _ddevEngineVersion :: !(Maybe Text)
, _ddevDefaultOnly :: !(Maybe Bool)
, _ddevFilters :: !(Maybe [Filter])
, _ddevEngine :: !(Maybe Text)
, _ddevDBParameterGroupFamily :: !(Maybe Text)
, _ddevListSupportedCharacterSets :: !(Maybe Bool)
, _ddevMarker :: !(Maybe Text)
, _ddevMaxRecords :: !(Maybe Int)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeDBEngineVersions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ddevEngineVersion'
--
-- * 'ddevDefaultOnly'
--
-- * 'ddevFilters'
--
-- * 'ddevEngine'
--
-- * 'ddevDBParameterGroupFamily'
--
-- * 'ddevListSupportedCharacterSets'
--
-- * 'ddevMarker'
--
-- * 'ddevMaxRecords'
describeDBEngineVersions
:: DescribeDBEngineVersions
describeDBEngineVersions =
DescribeDBEngineVersions'
{ _ddevEngineVersion = Nothing
, _ddevDefaultOnly = Nothing
, _ddevFilters = Nothing
, _ddevEngine = Nothing
, _ddevDBParameterGroupFamily = Nothing
, _ddevListSupportedCharacterSets = Nothing
, _ddevMarker = Nothing
, _ddevMaxRecords = Nothing
}
-- | The database engine version to return.
--
-- Example: '5.1.49'
ddevEngineVersion :: Lens' DescribeDBEngineVersions (Maybe Text)
ddevEngineVersion = lens _ddevEngineVersion (\ s a -> s{_ddevEngineVersion = a});
-- | Indicates that only the default version of the specified engine or
-- engine and major version combination is returned.
ddevDefaultOnly :: Lens' DescribeDBEngineVersions (Maybe Bool)
ddevDefaultOnly = lens _ddevDefaultOnly (\ s a -> s{_ddevDefaultOnly = a});
-- | Not currently supported.
ddevFilters :: Lens' DescribeDBEngineVersions [Filter]
ddevFilters = lens _ddevFilters (\ s a -> s{_ddevFilters = a}) . _Default . _Coerce;
-- | The database engine to return.
ddevEngine :: Lens' DescribeDBEngineVersions (Maybe Text)
ddevEngine = lens _ddevEngine (\ s a -> s{_ddevEngine = a});
-- | The name of a specific DB parameter group family to return details for.
--
-- Constraints:
--
-- - Must be 1 to 255 alphanumeric characters
-- - First character must be a letter
-- - Cannot end with a hyphen or contain two consecutive hyphens
ddevDBParameterGroupFamily :: Lens' DescribeDBEngineVersions (Maybe Text)
ddevDBParameterGroupFamily = lens _ddevDBParameterGroupFamily (\ s a -> s{_ddevDBParameterGroupFamily = a});
-- | If this parameter is specified, and if the requested engine supports the
-- CharacterSetName parameter for CreateDBInstance, the response includes a
-- list of supported character sets for each engine version.
ddevListSupportedCharacterSets :: Lens' DescribeDBEngineVersions (Maybe Bool)
ddevListSupportedCharacterSets = lens _ddevListSupportedCharacterSets (\ s a -> s{_ddevListSupportedCharacterSets = a});
-- | An optional pagination token provided by a previous request. If this
-- parameter is specified, the response includes only records beyond the
-- marker, up to the value specified by 'MaxRecords'.
ddevMarker :: Lens' DescribeDBEngineVersions (Maybe Text)
ddevMarker = lens _ddevMarker (\ s a -> s{_ddevMarker = a});
-- | The maximum number of records to include in the response. If more than
-- the 'MaxRecords' value is available, a pagination token called a marker
-- is included in the response so that the following results can be
-- retrieved.
--
-- Default: 100
--
-- Constraints: Minimum 20, maximum 100.
ddevMaxRecords :: Lens' DescribeDBEngineVersions (Maybe Int)
ddevMaxRecords = lens _ddevMaxRecords (\ s a -> s{_ddevMaxRecords = a});
instance AWSPager DescribeDBEngineVersions where
page rq rs
| stop (rs ^. ddevrsMarker) = Nothing
| stop (rs ^. ddevrsDBEngineVersions) = Nothing
| otherwise =
Just $ rq & ddevMarker .~ rs ^. ddevrsMarker
instance AWSRequest DescribeDBEngineVersions where
type Rs DescribeDBEngineVersions =
DescribeDBEngineVersionsResponse
request = postQuery rDS
response
= receiveXMLWrapper "DescribeDBEngineVersionsResult"
(\ s h x ->
DescribeDBEngineVersionsResponse' <$>
(x .@? "Marker") <*>
(x .@? "DBEngineVersions" .!@ mempty >>=
may (parseXMLList "DBEngineVersion"))
<*> (pure (fromEnum s)))
instance ToHeaders DescribeDBEngineVersions where
toHeaders = const mempty
instance ToPath DescribeDBEngineVersions where
toPath = const "/"
instance ToQuery DescribeDBEngineVersions where
toQuery DescribeDBEngineVersions'{..}
= mconcat
["Action" =:
("DescribeDBEngineVersions" :: ByteString),
"Version" =: ("2014-10-31" :: ByteString),
"EngineVersion" =: _ddevEngineVersion,
"DefaultOnly" =: _ddevDefaultOnly,
"Filters" =:
toQuery (toQueryList "Filter" <$> _ddevFilters),
"Engine" =: _ddevEngine,
"DBParameterGroupFamily" =:
_ddevDBParameterGroupFamily,
"ListSupportedCharacterSets" =:
_ddevListSupportedCharacterSets,
"Marker" =: _ddevMarker,
"MaxRecords" =: _ddevMaxRecords]
-- | Contains the result of a successful invocation of the
-- DescribeDBEngineVersions action.
--
-- /See:/ 'describeDBEngineVersionsResponse' smart constructor.
data DescribeDBEngineVersionsResponse = DescribeDBEngineVersionsResponse'
{ _ddevrsMarker :: !(Maybe Text)
, _ddevrsDBEngineVersions :: !(Maybe [DBEngineVersion])
, _ddevrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeDBEngineVersionsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ddevrsMarker'
--
-- * 'ddevrsDBEngineVersions'
--
-- * 'ddevrsResponseStatus'
describeDBEngineVersionsResponse
:: Int -- ^ 'ddevrsResponseStatus'
-> DescribeDBEngineVersionsResponse
describeDBEngineVersionsResponse pResponseStatus_ =
DescribeDBEngineVersionsResponse'
{ _ddevrsMarker = Nothing
, _ddevrsDBEngineVersions = Nothing
, _ddevrsResponseStatus = pResponseStatus_
}
-- | An optional pagination token provided by a previous request. If this
-- parameter is specified, the response includes only records beyond the
-- marker, up to the value specified by 'MaxRecords'.
ddevrsMarker :: Lens' DescribeDBEngineVersionsResponse (Maybe Text)
ddevrsMarker = lens _ddevrsMarker (\ s a -> s{_ddevrsMarker = a});
-- | A list of 'DBEngineVersion' elements.
ddevrsDBEngineVersions :: Lens' DescribeDBEngineVersionsResponse [DBEngineVersion]
ddevrsDBEngineVersions = lens _ddevrsDBEngineVersions (\ s a -> s{_ddevrsDBEngineVersions = a}) . _Default . _Coerce;
-- | The response status code.
ddevrsResponseStatus :: Lens' DescribeDBEngineVersionsResponse Int
ddevrsResponseStatus = lens _ddevrsResponseStatus (\ s a -> s{_ddevrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-rds/gen/Network/AWS/RDS/DescribeDBEngineVersions.hs | mpl-2.0 | 9,101 | 0 | 15 | 1,932 | 1,330 | 784 | 546 | 149 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module SimpleRecord where
import qualified GHC.Generics
import System.Console.GetOpt.Generics
data Options
= Options {
port :: Int,
daemonize :: Bool,
config :: Maybe FilePath
}
deriving (Show, GHC.Generics.Generic)
instance Generic Options
instance HasDatatypeInfo Options
instance HasArguments Options
main :: IO ()
main = withCli run
run :: Options -> IO ()
run = print
| kosmikus/getopt-generics | docs/SimpleRecord.hs | bsd-3-clause | 438 | 0 | 9 | 91 | 120 | 67 | 53 | 17 | 1 |
-- | These graph traversal functions mirror the ones in Cabal, but work with
-- the more complete (and fine-grained) set of dependencies provided by
-- PackageFixedDeps rather than only the library dependencies provided by
-- PackageInstalled.
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE CPP #-}
module Distribution.Client.PlanIndex (
-- * FakeMap and related operations
FakeMap
, fakeDepends
, fakeLookupInstalledPackageId
-- * Graph traversal functions
, brokenPackages
, dependencyClosure
, dependencyCycles
, dependencyGraph
, dependencyInconsistencies
, reverseDependencyClosure
, reverseTopologicalOrder
, topologicalOrder
) where
import Prelude hiding (lookup)
import qualified Data.Map as Map
import qualified Data.Tree as Tree
import qualified Data.Graph as Graph
import Data.Array ((!))
import Data.Map (Map)
import Data.Maybe (isNothing, fromMaybe, fromJust)
import Data.Either (lefts)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (Monoid(..))
#endif
import Distribution.Package
( PackageName(..), PackageIdentifier(..), InstalledPackageId(..)
, Package(..), packageName, packageVersion
)
import Distribution.Version
( Version )
import Distribution.Client.ComponentDeps (ComponentDeps)
import qualified Distribution.Client.ComponentDeps as CD
import Distribution.Client.PackageIndex
( PackageFixedDeps(..) )
import Distribution.Simple.PackageIndex
( PackageIndex, allPackages, insert, lookupInstalledPackageId )
import Distribution.Package
( HasInstalledPackageId(..), PackageId )
-- Note [FakeMap]
-----------------
-- We'd like to use the PackageIndex defined in this module for
-- cabal-install's InstallPlan. However, at the moment, this
-- data structure is indexed by InstalledPackageId, which we don't
-- know until after we've compiled a package (whereas InstallPlan
-- needs to store not-compiled packages in the index.) Eventually,
-- an InstalledPackageId will be calculatable prior to actually
-- building the package (making it something of a misnomer), but
-- at the moment, the "fake installed package ID map" is a workaround
-- to solve this problem while reusing PackageIndex. The basic idea
-- is that, since we don't know what an InstalledPackageId is
-- beforehand, we just fake up one based on the package ID (it only
-- needs to be unique for the particular install plan), and fill
-- it out with the actual generated InstalledPackageId after the
-- package is successfully compiled.
--
-- However, there is a problem: in the index there may be
-- references using the old package ID, which are now dangling if
-- we update the InstalledPackageId. We could map over the entire
-- index to update these pointers as well (a costly operation), but
-- instead, we've chosen to parametrize a variety of important functions
-- by a FakeMap, which records what a fake installed package ID was
-- actually resolved to post-compilation. If we do a lookup, we first
-- check and see if it's a fake ID in the FakeMap.
--
-- It's a bit grungy, but we expect this to only be temporary anyway.
-- (Another possible workaround would have been to *not* update
-- the installed package ID, but I decided this would be hard to
-- understand.)
-- | Map from fake installed package IDs to real ones. See Note [FakeMap]
type FakeMap = Map InstalledPackageId InstalledPackageId
-- | Variant of `depends` which accepts a `FakeMap`
--
-- Analogous to `fakeInstalledDepends`. See Note [FakeMap].
fakeDepends :: PackageFixedDeps pkg => FakeMap -> pkg -> ComponentDeps [InstalledPackageId]
fakeDepends fakeMap = fmap (map resolveFakeId) . depends
where
resolveFakeId :: InstalledPackageId -> InstalledPackageId
resolveFakeId ipid = Map.findWithDefault ipid ipid fakeMap
--- | Variant of 'lookupInstalledPackageId' which accepts a 'FakeMap'. See Note
--- [FakeMap].
fakeLookupInstalledPackageId :: FakeMap -> PackageIndex a -> InstalledPackageId
-> Maybe a
fakeLookupInstalledPackageId fakeMap index pkg =
lookupInstalledPackageId index (Map.findWithDefault pkg pkg fakeMap)
-- | All packages that have dependencies that are not in the index.
--
-- Returns such packages along with the dependencies that they're missing.
--
brokenPackages :: (PackageFixedDeps pkg)
=> FakeMap
-> PackageIndex pkg
-> [(pkg, [InstalledPackageId])]
brokenPackages fakeMap index =
[ (pkg, missing)
| pkg <- allPackages index
, let missing =
[ pkg' | pkg' <- CD.nonSetupDeps (depends pkg)
, isNothing (fakeLookupInstalledPackageId fakeMap index pkg') ]
, not (null missing) ]
dependencyInconsistencies :: forall pkg. (PackageFixedDeps pkg, HasInstalledPackageId pkg)
=> FakeMap
-> Bool
-> PackageIndex pkg
-> [(PackageName, [(PackageIdentifier, Version)])]
dependencyInconsistencies fakeMap indepGoals index =
concatMap (dependencyInconsistencies' fakeMap) subplans
where
subplans :: [PackageIndex pkg]
subplans = lefts $
map (dependencyClosure fakeMap index)
(rootSets fakeMap indepGoals index)
-- | Compute the root sets of a plan
--
-- A root set is a set of packages whose dependency closure must be consistent.
-- This is the set of all top-level library roots (taken together normally, or
-- as singletons sets if we are considering them as independent goals), along
-- with all setup dependencies of all packages.
rootSets :: (PackageFixedDeps pkg, HasInstalledPackageId pkg)
=> FakeMap -> Bool -> PackageIndex pkg -> [[InstalledPackageId]]
rootSets fakeMap indepGoals index =
if indepGoals then map (:[]) libRoots else [libRoots]
++ setupRoots index
where
libRoots = libraryRoots fakeMap index
-- | Compute the library roots of a plan
--
-- The library roots are the set of packages with no reverse dependencies
-- (no reverse library dependencies but also no reverse setup dependencies).
libraryRoots :: (PackageFixedDeps pkg, HasInstalledPackageId pkg)
=> FakeMap -> PackageIndex pkg -> [InstalledPackageId]
libraryRoots fakeMap index =
map (installedPackageId . toPkgId) roots
where
(graph, toPkgId, _) = dependencyGraph fakeMap index
indegree = Graph.indegree graph
roots = filter isRoot (Graph.vertices graph)
isRoot v = indegree ! v == 0
-- | The setup dependencies of each package in the plan
setupRoots :: PackageFixedDeps pkg => PackageIndex pkg -> [[InstalledPackageId]]
setupRoots = filter (not . null)
. map (CD.setupDeps . depends)
. allPackages
-- | Given a package index where we assume we want to use all the packages
-- (use 'dependencyClosure' if you need to get such a index subset) find out
-- if the dependencies within it use consistent versions of each package.
-- Return all cases where multiple packages depend on different versions of
-- some other package.
--
-- Each element in the result is a package name along with the packages that
-- depend on it and the versions they require. These are guaranteed to be
-- distinct.
--
dependencyInconsistencies' :: forall pkg.
(PackageFixedDeps pkg, HasInstalledPackageId pkg)
=> FakeMap
-> PackageIndex pkg
-> [(PackageName, [(PackageIdentifier, Version)])]
dependencyInconsistencies' fakeMap index =
[ (name, [ (pid,packageVersion dep) | (dep,pids) <- uses, pid <- pids])
| (name, ipid_map) <- Map.toList inverseIndex
, let uses = Map.elems ipid_map
, reallyIsInconsistent (map fst uses)
]
where
-- For each package name (of a dependency, somewhere)
-- and each installed ID of that that package
-- the associated package instance
-- and a list of reverse dependencies (as source IDs)
inverseIndex :: Map PackageName (Map InstalledPackageId (pkg, [PackageId]))
inverseIndex = Map.fromListWith (Map.unionWith (\(a,b) (_,b') -> (a,b++b')))
[ (packageName dep, Map.fromList [(ipid,(dep,[packageId pkg]))])
| -- For each package @pkg@
pkg <- allPackages index
-- Find out which @ipid@ @pkg@ depends on
, ipid <- CD.nonSetupDeps (fakeDepends fakeMap pkg)
-- And look up those @ipid@ (i.e., @ipid@ is the ID of @dep@)
, Just dep <- [fakeLookupInstalledPackageId fakeMap index ipid]
]
-- If, in a single install plan, we depend on more than one version of a
-- package, then this is ONLY okay in the (rather special) case that we
-- depend on precisely two versions of that package, and one of them
-- depends on the other. This is necessary for example for the base where
-- we have base-3 depending on base-4.
reallyIsInconsistent :: [pkg] -> Bool
reallyIsInconsistent [] = False
reallyIsInconsistent [_p] = False
reallyIsInconsistent [p1, p2] =
let pid1 = installedPackageId p1
pid2 = installedPackageId p2
in Map.findWithDefault pid1 pid1 fakeMap `notElem` CD.nonSetupDeps (fakeDepends fakeMap p2)
&& Map.findWithDefault pid2 pid2 fakeMap `notElem` CD.nonSetupDeps (fakeDepends fakeMap p1)
reallyIsInconsistent _ = True
-- | Find if there are any cycles in the dependency graph. If there are no
-- cycles the result is @[]@.
--
-- This actually computes the strongly connected components. So it gives us a
-- list of groups of packages where within each group they all depend on each
-- other, directly or indirectly.
--
dependencyCycles :: (PackageFixedDeps pkg, HasInstalledPackageId pkg)
=> FakeMap
-> PackageIndex pkg
-> [[pkg]]
dependencyCycles fakeMap index =
[ vs | Graph.CyclicSCC vs <- Graph.stronglyConnComp adjacencyList ]
where
adjacencyList = [ (pkg, installedPackageId pkg, CD.nonSetupDeps (fakeDepends fakeMap pkg))
| pkg <- allPackages index ]
-- | Tries to take the transitive closure of the package dependencies.
--
-- If the transitive closure is complete then it returns that subset of the
-- index. Otherwise it returns the broken packages as in 'brokenPackages'.
--
-- * Note that if the result is @Right []@ it is because at least one of
-- the original given 'PackageIdentifier's do not occur in the index.
dependencyClosure :: (PackageFixedDeps pkg, HasInstalledPackageId pkg)
=> FakeMap
-> PackageIndex pkg
-> [InstalledPackageId]
-> Either (PackageIndex pkg)
[(pkg, [InstalledPackageId])]
dependencyClosure fakeMap index pkgids0 = case closure mempty [] pkgids0 of
(completed, []) -> Left completed
(completed, _) -> Right (brokenPackages fakeMap completed)
where
closure completed failed [] = (completed, failed)
closure completed failed (pkgid:pkgids) =
case fakeLookupInstalledPackageId fakeMap index pkgid of
Nothing -> closure completed (pkgid:failed) pkgids
Just pkg ->
case fakeLookupInstalledPackageId fakeMap completed
(installedPackageId pkg) of
Just _ -> closure completed failed pkgids
Nothing -> closure completed' failed pkgids'
where completed' = insert pkg completed
pkgids' = CD.nonSetupDeps (depends pkg) ++ pkgids
topologicalOrder :: (PackageFixedDeps pkg, HasInstalledPackageId pkg)
=> FakeMap -> PackageIndex pkg -> [pkg]
topologicalOrder fakeMap index = map toPkgId
. Graph.topSort
$ graph
where (graph, toPkgId, _) = dependencyGraph fakeMap index
reverseTopologicalOrder :: (PackageFixedDeps pkg, HasInstalledPackageId pkg)
=> FakeMap -> PackageIndex pkg -> [pkg]
reverseTopologicalOrder fakeMap index = map toPkgId
. Graph.topSort
. Graph.transposeG
$ graph
where (graph, toPkgId, _) = dependencyGraph fakeMap index
-- | Takes the transitive closure of the packages reverse dependencies.
--
-- * The given 'PackageIdentifier's must be in the index.
--
reverseDependencyClosure :: (PackageFixedDeps pkg, HasInstalledPackageId pkg)
=> FakeMap
-> PackageIndex pkg
-> [InstalledPackageId]
-> [pkg]
reverseDependencyClosure fakeMap index =
map vertexToPkg
. concatMap Tree.flatten
. Graph.dfs reverseDepGraph
. map (fromMaybe noSuchPkgId . pkgIdToVertex)
where
(depGraph, vertexToPkg, pkgIdToVertex) = dependencyGraph fakeMap index
reverseDepGraph = Graph.transposeG depGraph
noSuchPkgId = error "reverseDependencyClosure: package is not in the graph"
-- | Builds a graph of the package dependencies.
--
-- Dependencies on other packages that are not in the index are discarded.
-- You can check if there are any such dependencies with 'brokenPackages'.
--
dependencyGraph :: (PackageFixedDeps pkg, HasInstalledPackageId pkg)
=> FakeMap
-> PackageIndex pkg
-> (Graph.Graph,
Graph.Vertex -> pkg,
InstalledPackageId -> Maybe Graph.Vertex)
dependencyGraph fakeMap index = (graph, vertexToPkg, idToVertex)
where
(graph, vertexToPkg', idToVertex) = Graph.graphFromEdges edges
vertexToPkg = fromJust
. (\((), key, _targets) -> lookupInstalledPackageId index key)
. vertexToPkg'
pkgs = allPackages index
edges = map edgesFrom pkgs
resolve pid = Map.findWithDefault pid pid fakeMap
edgesFrom pkg = ( ()
, resolve (installedPackageId pkg)
, CD.nonSetupDeps (fakeDepends fakeMap pkg)
)
| Helkafen/cabal | cabal-install/Distribution/Client/PlanIndex.hs | bsd-3-clause | 14,064 | 0 | 18 | 3,444 | 2,403 | 1,338 | 1,065 | 181 | 5 |
{-# LANGUAGE CPP, OverloadedStrings #-}
module Haste.PrimOps (genOp) where
import Prelude hiding (LT, GT)
import PrimOp
import Data.JSTarget
import Haste.Config
-- | Dummy State# RealWorld value for where one is needed.
defState :: Exp
defState = litN 0
-- | Generate primops.
-- Many of these ops return lifted Bool values; however, no thunk is
-- generated for them in order to conserve space and CPU time. This relies
-- on the evaluation operation in the RTS being able to handle plain values
-- as though they were thunks. If this were to change, all those ops MUST
-- be changed to return thunks!
genOp :: Config -> PrimOp -> [Exp] -> Either String (Exp)
genOp cfg op xs =
case op of
-- negations
IntNegOp -> Right $ binOp Sub (litN 0) (head xs)
DoubleNegOp -> Right $ binOp Sub (litN 0) (head xs)
FloatNegOp -> Right $ binOp Sub (litN 0) (head xs)
NotOp -> Right $ not_ (head xs) -- bitwise
-- Conversions
ChrOp -> Right $ head xs
OrdOp -> Right $ head xs
Word2IntOp -> Right $ binOp BitAnd (head xs) (litN 0xffffffff)
Int2WordOp -> Right $ binOp ShrL (head xs) (litN 0)
Int2FloatOp -> Right $ head xs
Int2DoubleOp -> Right $ head xs
Double2IntOp -> Right $ binOp (BitAnd) (head xs) (litN 0xffffffff)
Double2FloatOp -> Right $ head xs
Float2IntOp -> Right $ binOp (BitAnd) (head xs) (litN 0xffffffff)
Float2DoubleOp -> Right $ head xs
-- Narrowing ops
Narrow8IntOp -> Right $ binOp BitAnd (head xs) (lit (0xff :: Double))
Narrow16IntOp -> Right $ binOp BitAnd (head xs) (lit (0xffff :: Double))
Narrow32IntOp -> Right $ binOp BitAnd (head xs) (lit (0xffffffff :: Double))
Narrow8WordOp -> Right $ binOp BitAnd (head xs) (lit (0xff :: Double))
Narrow16WordOp -> Right $ binOp BitAnd (head xs) (lit (0xffff :: Double))
Narrow32WordOp -> Right $ binOp ShrL (binOp BitAnd (head xs) (lit (0xffffffff :: Double))) (litN 0)
-- Char ops
CharGtOp -> bOp GT
CharGeOp -> bOp GTE
CharEqOp -> bOp Eq
CharNeOp -> bOp Neq
CharLtOp -> bOp LT
CharLeOp -> bOp LTE
-- Int ops
IntAddOp -> intMath $ bOp Add
IntSubOp -> intMath $ bOp Sub
IntMulOp -> intMath $ Right $ multiplyIntOp cfg (xs !! 0) (xs !! 1)
-- FIXME: this is correct but slow!
IntMulMayOfloOp -> intMath $ Right $ multiplyIntOp cfg (xs !! 0) (xs !! 1)
IntQuotOp -> callF "quot"
IntQuotRemOp -> callF "quotRemI"
IntRemOp -> bOp Mod -- JS % operator is actually rem, not mod!
IntAddCOp -> callF "addC"
IntSubCOp -> callF "subC"
ISllOp -> bOp Shl
ISraOp -> bOp ShrA
ISrlOp -> bOp ShrL
IntGtOp -> bOp GT
IntGeOp -> bOp GTE
IntLtOp -> bOp LT
IntLeOp -> bOp LTE
IntEqOp -> bOp Eq
IntNeOp -> bOp Neq
-- Word ops
WordAddOp -> wordMath $ bOp Add
WordSubOp -> wordMath $ bOp Sub
WordMulOp -> wordMath $ callF "imul"
WordQuotOp -> callF "quot"
WordQuotRemOp -> callF "quotRemI"
WordRemOp -> bOp Mod
AndOp -> wordMath $ bOp BitAnd
OrOp -> wordMath $ bOp BitOr
XorOp -> wordMath $ bOp BitXor
SllOp -> wordMath $ bOp Shl
SrlOp -> bOp ShrL
WordGtOp -> bOp GT
WordGeOp -> bOp GTE
WordEqOp -> bOp Eq
WordNeOp -> bOp Neq
WordLtOp -> bOp LT
WordLeOp -> bOp LTE
-- Double ops
DoubleExpOp -> Right $ callForeign "Math.exp" xs
DoubleLogOp -> Right $ callForeign "Math.log" xs
DoubleSqrtOp -> Right $ callForeign "Math.sqrt" xs
DoubleCosOp -> Right $ callForeign "Math.cos" xs
DoubleSinOp -> Right $ callForeign "Math.sin" xs
DoubleTanOp -> Right $ callForeign "Math.tan" xs
DoubleAcosOp -> Right $ callForeign "Math.acos" xs
DoubleAsinOp -> Right $ callForeign "Math.asin" xs
DoubleAtanOp -> Right $ callForeign "Math.atan" xs
DoubleCoshOp -> Right $ callForeign "cosh" xs
DoubleSinhOp -> Right $ callForeign "sinh" xs
DoubleTanhOp -> Right $ callForeign "tanh" xs
DoubleDecode_2IntOp -> Right $ callForeign "decodeDouble" xs
DoubleGtOp -> bOp GT
DoubleGeOp -> bOp GTE
DoubleEqOp -> bOp Eq
DoubleNeOp -> bOp Neq
DoubleLtOp -> bOp LT
DoubleLeOp -> bOp LTE
DoubleAddOp -> bOp Add
DoubleSubOp -> bOp Sub
DoubleMulOp -> bOp Mul
DoubleDivOp -> bOp Div
DoublePowerOp -> callF "Math.pow"
-- Float ops
FloatExpOp -> Right $ callForeign "Math.exp" xs
FloatLogOp -> Right $ callForeign "Math.log" xs
FloatSqrtOp -> Right $ callForeign "Math.sqrt" xs
FloatCosOp -> Right $ callForeign "Math.cos" xs
FloatSinOp -> Right $ callForeign "Math.sin" xs
FloatTanOp -> Right $ callForeign "Math.tan" xs
FloatAcosOp -> Right $ callForeign "Math.acos" xs
FloatAsinOp -> Right $ callForeign "Math.asin" xs
FloatAtanOp -> Right $ callForeign "Math.atan" xs
FloatCoshOp -> Right $ callForeign "cosh" xs
FloatSinhOp -> Right $ callForeign "sinh" xs
FloatTanhOp -> Right $ callForeign "tanh" xs
FloatDecode_IntOp -> Right $ callForeign "decodeFloat" xs
FloatGtOp -> bOp GT
FloatGeOp -> bOp GTE
FloatEqOp -> bOp Eq
FloatNeOp -> bOp Neq
FloatLtOp -> bOp LT
FloatLeOp -> bOp LTE
FloatAddOp -> bOp Add
FloatSubOp -> bOp Sub
FloatMulOp -> bOp Mul
FloatDivOp -> bOp Div
FloatPowerOp -> callF "Math.pow"
-- Array ops
NewArrayOp -> callF "newArr"
SameMutableArrayOp -> fmap (thunk True . ret) $ bOp Eq
ReadArrayOp -> Right $ index arr ix
WriteArrayOp -> Right $ assignEx (index arr ix) rhs
where (_arr:_ix:rhs:_) = xs
SizeofArrayOp -> Right $ index (head xs) (litS "length")
SizeofMutableArrayOp -> Right $ index (head xs) (litS "length")
IndexArrayOp -> Right $ index arr ix
UnsafeFreezeArrayOp -> Right $ head xs
UnsafeThawArrayOp -> Right $ head xs
-- TODO: copy, clone, freeze, thaw
-- Byte Array ops
NewByteArrayOp_Char -> callF "newByteArr"
NewPinnedByteArrayOp_Char-> callF "newByteArr"
SameMutableByteArrayOp -> fmap (thunk True . ret) $ bOp Eq
IndexByteArrayOp_Char -> readArr xs "i8"
IndexByteArrayOp_Int -> readArr xs "i32"
IndexByteArrayOp_Int8 -> readArr xs "i8"
IndexByteArrayOp_Int16 -> readArr xs "i16"
IndexByteArrayOp_Int32 -> readArr xs "i32"
IndexByteArrayOp_Word -> readArr xs "w32"
IndexByteArrayOp_Word8 -> readArr xs "w8"
IndexByteArrayOp_Word16 -> readArr xs "w16"
IndexByteArrayOp_Word32 -> readArr xs "w32"
IndexByteArrayOp_WideChar-> readArr xs "w32"
IndexByteArrayOp_Float -> readArr xs "f32"
IndexByteArrayOp_Double -> readArr xs "f64"
ReadByteArrayOp_Char -> readArr xs "i8"
ReadByteArrayOp_Int -> readArr xs "i32"
ReadByteArrayOp_Int8 -> readArr xs "i8"
ReadByteArrayOp_Int16 -> readArr xs "i16"
ReadByteArrayOp_Int32 -> readArr xs "i32"
ReadByteArrayOp_Word -> readArr xs "w32"
ReadByteArrayOp_Word8 -> readArr xs "w8"
ReadByteArrayOp_Word16 -> readArr xs "w16"
ReadByteArrayOp_Word32 -> readArr xs "w32"
ReadByteArrayOp_WideChar -> readArr xs "w32"
ReadByteArrayOp_Float -> readArr xs "f32"
ReadByteArrayOp_Double -> readArr xs "f64"
WriteByteArrayOp_Char -> writeArr xs "i8"
WriteByteArrayOp_Int -> writeArr xs "i32"
WriteByteArrayOp_Int8 -> writeArr xs "i8"
WriteByteArrayOp_Int16 -> writeArr xs "i16"
WriteByteArrayOp_Int32 -> writeArr xs "i32"
WriteByteArrayOp_Word -> writeArr xs "w32"
WriteByteArrayOp_Word8 -> writeArr xs "w8"
WriteByteArrayOp_Word16 -> writeArr xs "w16"
WriteByteArrayOp_Word32 -> writeArr xs "w32"
WriteByteArrayOp_WideChar-> writeArr xs "w32"
WriteByteArrayOp_Float -> writeArr xs "f32"
WriteByteArrayOp_Double -> writeArr xs "f64"
SizeofByteArrayOp -> Right $ index (head xs) (litS "byteLength")
SizeofMutableByteArrayOp -> Right $ index (head xs) (litS "byteLength")
NewAlignedPinnedByteArrayOp_Char -> Right $ callForeign "newByteArr" [xs!!0]
UnsafeFreezeByteArrayOp -> Right $ head xs
ByteArrayContents_Char -> Right $ head xs
-- Mutable variables
NewMutVarOp -> callF "nMV"
ReadMutVarOp -> callF "rMV"
WriteMutVarOp -> callF "wMV"
SameMutVarOp -> bOp Eq
AtomicModifyMutVarOp -> callF "mMV"
-- TVars - since there's no parallelism and no preemption, TVars behave
-- just like normal IORefs.
NewTVarOp -> callF "nMV"
ReadTVarOp -> callF "rMV"
WriteTVarOp -> callF "wMV"
SameTVarOp -> bOp Eq
-- Pointer ops
ReallyUnsafePtrEqualityOp -> bOp Eq
WriteOffAddrOp_Char -> writeOffAddr xs "i8" 1
WriteOffAddrOp_Int -> writeOffAddr xs "i32" 4
WriteOffAddrOp_Int8 -> writeOffAddr xs "i8" 1
WriteOffAddrOp_Int16 -> writeOffAddr xs "i16" 2
WriteOffAddrOp_Int32 -> writeOffAddr xs "i32" 4
WriteOffAddrOp_Word -> writeOffAddr xs "w32" 4
WriteOffAddrOp_Word8 -> writeOffAddr xs "w8" 1
WriteOffAddrOp_Word16 -> writeOffAddr xs "w16" 2
WriteOffAddrOp_Word32 -> writeOffAddr xs "w32" 4
WriteOffAddrOp_WideChar-> writeOffAddr xs "w32" 4
WriteOffAddrOp_Float -> writeOffAddr xs "f32" 4
WriteOffAddrOp_Double -> writeOffAddr xs "f64" 8
ReadOffAddrOp_Char -> readOffAddr xs "i8" 1
ReadOffAddrOp_Int -> readOffAddr xs "i32" 4
ReadOffAddrOp_Int8 -> readOffAddr xs "i8" 1
ReadOffAddrOp_Int16 -> readOffAddr xs "i16" 2
ReadOffAddrOp_Int32 -> readOffAddr xs "i32" 4
ReadOffAddrOp_Word -> readOffAddr xs "w32" 4
ReadOffAddrOp_Word8 -> readOffAddr xs "w8" 1
ReadOffAddrOp_Word16 -> readOffAddr xs "w16" 2
ReadOffAddrOp_Word32 -> readOffAddr xs "w32" 4
ReadOffAddrOp_WideChar -> readOffAddr xs "w32" 4
ReadOffAddrOp_Float -> readOffAddr xs "f32" 4
ReadOffAddrOp_Double -> readOffAddr xs "f64" 8
AddrAddOp -> callF "plusAddr"
AddrSubOp ->
Right $ callForeign "plusAddr" [addr, binOp Sub (litN 0) off]
where (addr:off:_) = xs
AddrEqOp -> callF "addrEq"
AddrNeOp ->
Right $ binOp Sub (litN 0) $ callForeign "addrEq" [a, b]
where (a:b:_) = xs
AddrLtOp -> callF "addrLT"
AddrGtOp -> callF "addrGT"
AddrLeOp ->
Right $ binOp Sub (litN 0) $ callForeign "addrGT" [a, b]
where (a:b:_) = xs
AddrGeOp ->
Right $ binOp Sub (litN 0) $ callForeign "addrLT" [a, b]
where (a:b:_) = xs
Addr2IntOp ->
Right $ index x (litS "off")
where
(x:_) = xs
-- MVars
NewMVarOp -> callF "newMVar"
TakeMVarOp -> callF "takeMVar"
TryTakeMVarOp -> callF "tryTakeMVar"
PutMVarOp -> callF "putMVar"
TryPutMVarOp -> callF "tryPutMVar"
SameMVarOp -> callF "sameMVar"
IsEmptyMVarOp -> callF "isEmptyMVar"
-- Stable names
MakeStableNameOp -> callF "makeStableName"
EqStableNameOp -> callF "eqStableName"
StableNameToIntOp -> Right $ head xs
-- Stable pointers - all pointers are stable in JS!
MakeStablePtrOp -> Right $ head xs
EqStablePtrOp -> bOp Eq
DeRefStablePtrOp -> Right $ head xs
-- Weak pointers - no concern of GC in JS
MkWeakOp -> callF "mkWeak"
MkWeakNoFinalizerOp -> callF "mkWeak"
DeRefWeakOp -> callF "derefWeak"
FinalizeWeakOp -> callF "finalizeWeak"
-- Exception masking
-- There's only one thread anyway, so async exceptions can't happen.
MaskAsyncExceptionsOp -> Right $ callSaturated (head xs) []
UnmaskAsyncExceptionsOp -> Right $ callSaturated (head xs) []
MaskStatus -> Right $ litN 0
-- Misc. ops
PopCntOp -> Right $ callForeign "popCnt" [head xs]
PopCnt8Op -> Right $ callForeign "popCnt" [head xs]
PopCnt16Op -> Right $ callForeign "popCnt" [head xs]
PopCnt32Op -> Right $ callForeign "popCnt" [head xs]
DelayOp -> Right $ defState
SeqOp -> Right $ eval $ head xs
AtomicallyOp -> Right $ callSaturated (xs !! 0) []
-- Get the data constructor tag from a value.
DataToTagOp -> callF "dataToTag"
-- Basically unsafeCoerce :: Int# -> <enumeration type>
TagToEnumOp -> Right $ head xs
TouchOp -> Right $ defState
RaiseOp -> callF "die"
RaiseIOOp -> callF "die"
-- noDuplicate is only relevant in a threaded environment.
NoDuplicateOp -> Right $ defState
CatchOp -> callF "jsCatch"
x -> Left $ "Unsupported PrimOp: " ++ showOutputable cfg x
where
(arr:ix:_) = xs
writeArr (a:i:rhs:_) etype =
Right $ assignEx (index (index (index a (litS "v")) (litS etype)) i) rhs
writeArr _ _ =
error "writeArray primop with too few arguments!"
readArr (a:i:_) elemtype =
Right $ index (index (index a (litS "v")) (litS elemtype)) i
readArr _ _ =
error "writeArray primop with too few arguments!"
writeOffAddr (addr:off:rhs:_) etype esize =
Right $ callForeign "writeOffAddr" [litS etype,litN esize,addr,off,rhs]
writeOffAddr _ _ _ =
error "writeOffAddr primop with too few arguments!"
readOffAddr (addr:off:_) etype esize =
Right $ callForeign "readOffAddr" [litS etype,litN esize,addr,off]
readOffAddr _ _ _ =
error "readOffAddr primop with too few arguments!"
callF f = Right $ callForeign f xs
bOp bop =
case xs of
[x, y] -> Right $ binOp bop x y
_ -> error $ "PrimOps.binOp failed! op is " ++ show bop
-- Bitwise ops on words need to be unsigned; exploit the fact that >>> is!
wordMath = fmap (\oper -> binOp ShrL oper (litN 0))
intMath = fmap (wrapIntMath cfg)
| akru/haste-compiler | src/Haste/PrimOps.hs | bsd-3-clause | 14,150 | 0 | 16 | 3,960 | 4,001 | 1,922 | 2,079 | 286 | 245 |
import Test.Hspec
import Test.QuickCheck
import Test.QuickCheck.Modifiers(NonEmptyList (..))
-- import Data.Ord
import Data.Char
import Data.List
--
import Debug.Trace
binary :: Int -> String
binary 0=""
binary n|(d,r)<-divMod n 2=binary d++["01"!!r]
substrings :: String -> [String]
substrings xs = nub$inits xs>>=tails
properSubstrings :: String -> [String]
properSubstrings xs = substrings xs\\[xs]
sb=substrings.binary
psb=properSubstrings.binary
g = scanl step (1,[]) [1..]
where step (_,l) x | psb x\\l/=[]=(x,l++sb x)
| otherwise=(0,l)
f=filter(>1)$fst<$>g
main = hspec $ do
it "does something interesting" $ do
take 40 f `shouldBe` [2, 4, 5, 6, 8, 9, 10, 11, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 50, 54, 56, 58]
| clupascu/codegolf | 139335-generate-unseen-numbers/139335-generate-unseen-numbers.hs | mit | 836 | 0 | 12 | 164 | 437 | 248 | 189 | 22 | 1 |
{-
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 PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Control.Monad.ST.Lazy (module M) where
import "base" Control.Monad.ST.Lazy as M
| Ye-Yong-Chi/codeworld | codeworld-base/src/Control/Monad/ST/Lazy.hs | apache-2.0 | 757 | 0 | 4 | 136 | 27 | 21 | 6 | 4 | 0 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2015 Galois, Inc.
-- License : BSD3
-- Maintainer : cryptol@galois.com
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE RecordWildCards, CPP, Safe #-}
#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE RecursiveDo #-}
#else
{-# LANGUAGE DoRec #-}
#endif
{-# LANGUAGE DeriveGeneric #-}
module Cryptol.TypeCheck.Monad
( module Cryptol.TypeCheck.Monad
, module Cryptol.TypeCheck.InferTypes
) where
import Cryptol.Parser.Position
import qualified Cryptol.Parser.AST as P
import Cryptol.TypeCheck.AST
import Cryptol.TypeCheck.Subst
import Cryptol.TypeCheck.Unify(mgu, Result(..), UnificationError(..))
import Cryptol.TypeCheck.InferTypes
import Cryptol.Utils.PP(pp, (<+>), Doc, text, quotes)
import Cryptol.Utils.Panic(panic)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Map (Map)
import Data.Set (Set)
import Data.List(find, minimumBy, groupBy, sortBy)
import Data.Maybe(mapMaybe)
import Data.Function(on)
import MonadLib
import qualified Control.Applicative as A
import Control.Monad.Fix(MonadFix(..))
import GHC.Generics (Generic)
import Control.DeepSeq
#if __GLASGOW_HASKELL__ < 710
import Data.Functor
#endif
-- | Information needed for type inference.
data InferInput = InferInput
{ inpRange :: Range -- ^ Location of program source
, inpVars :: Map QName Schema -- ^ Variables that are in scope
, inpTSyns :: Map QName TySyn -- ^ Type synonyms that are in scope
, inpNewtypes :: Map QName Newtype -- ^ Newtypes in scope
, inpNameSeeds :: NameSeeds -- ^ Private state of type-checker
, inpMonoBinds :: Bool -- ^ Should local bindings without
-- signatures be monomorphized?
, inpSolverConfig :: SolverConfig -- ^ Options for the constraint solver
} deriving Show
-- | This is used for generating various names.
data NameSeeds = NameSeeds
{ seedTVar :: !Int
, seedGoal :: !Int
} deriving (Show, Generic)
instance NFData NameSeeds
-- | The initial seeds, used when checking a fresh program.
nameSeeds :: NameSeeds
nameSeeds = NameSeeds { seedTVar = 10, seedGoal = 0 }
-- | The results of type inference.
data InferOutput a
= InferFailed [(Range,Warning)] [(Range,Error)]
-- ^ We found some errors
| InferOK [(Range,Warning)] NameSeeds a
-- ^ Type inference was successful.
deriving Show
runInferM :: TVars a => InferInput -> InferM a -> IO (InferOutput a)
runInferM info (IM m) =
do rec ro <- return RO { iRange = inpRange info
, iVars = Map.map ExtVar (inpVars info)
, iTVars = []
, iTSyns = fmap mkExternal (inpTSyns info)
, iNewtypes = fmap mkExternal (inpNewtypes info)
, iSolvedHasLazy = iSolvedHas finalRW -- RECURSION
, iMonoBinds = inpMonoBinds info
, iSolverConfig = inpSolverConfig info
}
(result, finalRW) <- runStateT rw $ runReaderT ro m -- RECURSION
let theSu = iSubst finalRW
defSu = defaultingSubst theSu
warns = [(r,apSubst theSu w) | (r,w) <- iWarnings finalRW ]
case iErrors finalRW of
[] ->
case (iCts finalRW, iHasCts finalRW) of
(cts,[])
| nullGoals cts
-> return $ InferOK warns
(iNameSeeds finalRW)
(apSubst defSu result)
(cts,has) -> return $ InferFailed warns
$ dropErrorsFromSameLoc
[ ( goalRange g
, UnsolvedGoal False (apSubst theSu g)
) | g <- fromGoals cts ++ map hasGoal has
]
errs -> return $ InferFailed warns
$ dropErrorsFromSameLoc
[(r,apSubst theSu e) | (r,e) <- errs]
where
mkExternal x = (IsExternal, x)
rw = RW { iErrors = []
, iWarnings = []
, iSubst = emptySubst
, iExistTVars = []
, iNameSeeds = inpNameSeeds info
, iCts = emptyGoals
, iHasCts = []
, iSolvedHas = Map.empty
}
dropErrorsFromSameLoc = map chooseBestError . groupBy ((==) `on` fst)
. sortBy (cmpRange `on` fst)
addErrorSize (r,e) = (length (show (pp e)), (r,e))
chooseBestError = snd . minimumBy (compare `on` fst) . map addErrorSize
-- The actual order does not matter
cmpRange (Range x y z) (Range a b c) = compare (x,y,z) (a,b,c)
newtype InferM a = IM { unIM :: ReaderT RO (StateT RW IO) a }
data DefLoc = IsLocal | IsExternal
-- | Read-only component of the monad.
data RO = RO
{ iRange :: Range -- ^ Source code being analysed
, iVars :: Map QName VarType -- ^ Type of variable that are in scope
{- NOTE: We assume no shadowing between these two, so it does not matter
where we look first. Similarly, we assume no shadowing with
the existential type variable (in RW). See `checkTShadowing`. -}
, iTVars :: [TParam] -- ^ Type variable that are in scope
, iTSyns :: Map QName (DefLoc, TySyn) -- ^ Type synonyms that are in scope
, iNewtypes :: Map QName (DefLoc, Newtype)
-- ^ Newtype declarations in scope
--
-- NOTE: type synonyms take precedence over newtype. The reason is
-- that we can define local type synonyms, but not local newtypes.
-- So, either a type-synonym shadows a newtype, or it was declared
-- at the top-level, but then there can't be a newtype with the
-- same name (this should be caught by the renamer).
, iSolvedHasLazy :: Map Int (Expr -> Expr)
-- ^ NOTE: This field is lazy in an important way! It is the
-- final version of `iSolvedHas` in `RW`, and the two are tied
-- together through recursion. The field is here so that we can
-- look thing up before they are defined, which is OK because we
-- don't need to know the results until everything is done.
, iMonoBinds :: Bool
-- ^ When this flag is set to true, bindings that lack signatures
-- in where-blocks will never be generalized. Bindings with type
-- signatures, and all bindings at top level are unaffected.
, iSolverConfig :: SolverConfig
}
-- | Read-write component of the monad.
data RW = RW
{ iErrors :: ![(Range,Error)] -- ^ Collected errors
, iWarnings :: ![(Range,Warning)] -- ^ Collected warnings
, iSubst :: !Subst -- ^ Accumulated substitution
, iExistTVars :: [Map QName Type]
-- ^ These keeps track of what existential type variables are available.
-- When we start checking a function, we push a new scope for
-- its arguments, and we pop it when we are done checking the function
-- body. The front element of the list is the current scope, which is
-- the only thing that will be modified, as follows. When we encounter
-- a existential type variable:
-- 1. we look in all scopes to see if it is already defined.
-- 2. if it was not defined, we create a fresh type variable,
-- and we add it to the current scope.
-- 3. it is an error if we encounter an existential variable but we
-- have no current scope.
, iSolvedHas :: Map Int (Expr -> Expr)
-- ^ Selector constraints that have been solved (ref. iSolvedSelectorsLazy)
-- Generating names
, iNameSeeds :: !NameSeeds
-- Constraints that need solving
, iCts :: !Goals -- ^ Ordinary constraints
, iHasCts :: ![HasGoal]
{- ^ Tuple/record projection constraints. The `Int` is the "name"
of the constraint, used so that we can name it solution properly. -}
}
instance Functor InferM where
fmap f (IM m) = IM (fmap f m)
instance A.Applicative InferM where
pure = return
(<*>) = ap
instance Monad InferM where
return x = IM (return x)
fail x = IM (fail x)
IM m >>= f = IM (m >>= unIM . f)
instance MonadFix InferM where
mfix f = IM (mfix (unIM . f))
io :: IO a -> InferM a
io m = IM $ inBase m
-- | The monadic computation is about the given range of source code.
-- This is useful for error reporting.
inRange :: Range -> InferM a -> InferM a
inRange r (IM m) = IM $ mapReader (\ro -> ro { iRange = r }) m
inRangeMb :: Maybe Range -> InferM a -> InferM a
inRangeMb Nothing m = m
inRangeMb (Just r) m = inRange r m
-- | This is the current range that we are working on.
curRange :: InferM Range
curRange = IM $ asks iRange
-- | Report an error.
recordError :: Error -> InferM ()
recordError e =
do r <- curRange
IM $ sets_ $ \s -> s { iErrors = (r,e) : iErrors s }
recordWarning :: Warning -> InferM ()
recordWarning w =
do r <- curRange
IM $ sets_ $ \s -> s { iWarnings = (r,w) : iWarnings s }
getSolverConfig :: InferM SolverConfig
getSolverConfig =
do RO { .. } <- IM ask
return iSolverConfig
--------------------------------------------------------------------------------
newGoal :: ConstraintSource -> Prop -> InferM Goal
newGoal goalSource goal =
do goalRange <- curRange
return Goal { .. }
-- | Record some constraints that need to be solved.
-- The string explains where the constraints came from.
newGoals :: ConstraintSource -> [Prop] -> InferM ()
newGoals src ps = addGoals =<< mapM (newGoal src) ps
{- | The constraints are removed, and returned to the caller.
The substitution IS applied to them. -}
getGoals :: InferM [Goal]
getGoals =
do goals <- applySubst =<< IM (sets $ \s -> (iCts s, s { iCts = emptyGoals }))
return (fromGoals goals)
-- | Add a bunch of goals that need solving.
addGoals :: [Goal] -> InferM ()
addGoals gs = IM $ sets_ $ \s -> s { iCts = foldl (flip insertGoal) (iCts s) gs }
-- | Collect the goals emitted by the given sub-computation.
-- Does not emit any new goals.
collectGoals :: InferM a -> InferM (a, [Goal])
collectGoals m =
do origGs <- applySubst =<< getGoals'
a <- m
newGs <- getGoals
setGoals' origGs
return (a, newGs)
where
-- retrieve the type map only
getGoals' = IM $ sets $ \ RW { .. } -> (iCts, RW { iCts = emptyGoals, .. })
-- set the type map directly
setGoals' gs = IM $ sets $ \ RW { .. } -> ((), RW { iCts = gs, .. })
{- | Record a constraint that when we select from the first type,
we should get a value of the second type.
The returned function should be used to wrap the expression from
which we are selecting (i.e., the record or tuple). Plese note
that the resulting expression should not be forced before the
constraint is solved.
-}
newHasGoal :: P.Selector -> Type -> Type -> InferM (Expr -> Expr)
newHasGoal l ty f =
do goalName <- newGoalName
g <- newGoal CtSelector (pHas l ty f)
IM $ sets_ $ \s -> s { iHasCts = HasGoal goalName g : iHasCts s }
solns <- IM $ fmap iSolvedHasLazy ask
return $ case Map.lookup goalName solns of
Just e1 -> e1
Nothing -> panic "newHasGoal" ["Unsolved has goal in result"]
-- | Add a previously generate has constrained
addHasGoal :: HasGoal -> InferM ()
addHasGoal g = IM $ sets_ $ \s -> s { iHasCts = g : iHasCts s }
-- | Get the `Has` constraints. Each of this should either be solved,
-- or added back using `addHasGoal`.
getHasGoals :: InferM [HasGoal]
getHasGoals = do gs <- IM $ sets $ \s -> (iHasCts s, s { iHasCts = [] })
applySubst gs
-- | Specify the solution (`Expr -> Expr`) for the given constraint (`Int`).
solveHasGoal :: Int -> (Expr -> Expr) -> InferM ()
solveHasGoal n e =
IM $ sets_ $ \s -> s { iSolvedHas = Map.insert n e (iSolvedHas s) }
--------------------------------------------------------------------------------
newName :: (NameSeeds -> (a , NameSeeds)) -> InferM a
newName upd = IM $ sets $ \s -> let (x,seeds) = upd (iNameSeeds s)
in (x, s { iNameSeeds = seeds })
-- | Generate a new name for a goal.
newGoalName :: InferM Int
newGoalName = newName $ \s -> let x = seedGoal s
in (x, s { seedGoal = x + 1})
-- | Generate a new free type variable.
newTVar :: Doc -> Kind -> InferM TVar
newTVar src k = newTVar' src Set.empty k
-- | Generate a new free type variable that depends on these additional
-- type parameters.
newTVar' :: Doc -> Set TVar -> Kind -> InferM TVar
newTVar' src extraBound k =
do bound <- getBoundInScope
let vs = Set.union extraBound bound
newName $ \s -> let x = seedTVar s
in (TVFree x k vs src, s { seedTVar = x + 1 })
-- | Generate a new free type variable.
newTParam :: Maybe QName -> Kind -> InferM TParam
newTParam nm k = newName $ \s -> let x = seedTVar s
in (TParam { tpUnique = x
, tpKind = k
, tpName = nm
}
, s { seedTVar = x + 1 })
-- | Generate an unknown type. The doc is a note about what is this type about.
newType :: Doc -> Kind -> InferM Type
newType src k = TVar `fmap` newTVar src k
--------------------------------------------------------------------------------
-- | Record that the two types should be syntactically equal.
unify :: Type -> Type -> InferM [Prop]
unify t1 t2 =
do t1' <- applySubst t1
t2' <- applySubst t2
case mgu t1' t2' of
OK (su1,ps) -> extendSubst su1 >> return ps
Error err ->
do case err of
UniTypeLenMismatch _ _ -> recordError (TypeMismatch t1' t2')
UniTypeMismatch s1 s2 -> recordError (TypeMismatch s1 s2)
UniKindMismatch k1 k2 -> recordError (KindMismatch k1 k2)
UniRecursive x t -> recordError (RecursiveType (TVar x) t)
UniNonPolyDepends x vs -> recordError
(TypeVariableEscaped (TVar x) vs)
UniNonPoly x t -> recordError (NotForAll x t)
return []
-- | Apply the accumulated substitution to something with free type variables.
applySubst :: TVars t => t -> InferM t
applySubst t =
do su <- getSubst
return (apSubst su t)
-- | Get the substitution that we have accumulated so far.
getSubst :: InferM Subst
getSubst = IM $ fmap iSubst get
-- | Add to the accumulated substitution.
extendSubst :: Subst -> InferM ()
extendSubst su = IM $ sets_ $ \s -> s { iSubst = su @@ iSubst s }
-- | Variables that are either mentioned in the environment or in
-- a selector constraint.
varsWithAsmps :: InferM (Set TVar)
varsWithAsmps =
do env <- IM $ fmap (Map.elems . iVars) ask
fromEnv <- forM env $ \v ->
case v of
ExtVar sch -> getVars sch
CurSCC _ t -> getVars t
sels <- IM $ fmap (map (goal . hasGoal) . iHasCts) get
fromSels <- mapM getVars sels
fromEx <- (getVars . concatMap Map.elems) =<< IM (fmap iExistTVars get)
return (Set.unions fromEnv `Set.union` Set.unions fromSels
`Set.union` fromEx)
where
getVars x = fvs `fmap` applySubst x
--------------------------------------------------------------------------------
-- | Lookup the type of a variable.
lookupVar :: QName -> InferM VarType
lookupVar x =
do mb <- IM $ asks $ Map.lookup x . iVars
case mb of
Just t -> return t
Nothing ->
do mbNT <- lookupNewtype x
case mbNT of
Just nt -> return (ExtVar (newtypeConType nt))
Nothing -> do recordError $ UndefinedVariable x
a <- newType (text "type of" <+> pp x) KType
return $ ExtVar $ Forall [] [] a
-- | Lookup a type variable. Return `Nothing` if there is no such variable
-- in scope, in which case we must be dealing with a type constant.
lookupTVar :: QName -> InferM (Maybe Type)
lookupTVar x = IM $ asks $ fmap (TVar . tpVar) . find this . iTVars
where this tp = tpName tp == Just x
-- | Lookup the definition of a type synonym.
lookupTSyn :: QName -> InferM (Maybe TySyn)
lookupTSyn x = fmap (fmap snd . Map.lookup x) getTSyns
-- | Lookup the definition of a newtype
lookupNewtype :: QName -> InferM (Maybe Newtype)
lookupNewtype x = fmap (fmap snd . Map.lookup x) getNewtypes
-- | Check if we already have a name for this existential type variable and,
-- if so, return the definition. If not, try to create a new definition,
-- if this is allowed. If not, returns nothing.
existVar :: QName -> Kind -> InferM Type
existVar x k =
do scopes <- iExistTVars <$> IM get
case msum (map (Map.lookup x) scopes) of
Just ty -> return ty
Nothing ->
case scopes of
[] ->
do recordError $ ErrorMsg $
text "Undefined type" <+> quotes (pp x)
newType (text "undefined existential type varible" <+>
quotes (pp x)) k
sc : more ->
do ty <- newType (text "existential type variable"
<+> quotes (pp x)) k
IM $ sets_ $ \s -> s{ iExistTVars = Map.insert x ty sc : more }
return ty
-- | Returns the type synonyms that are currently in scope.
getTSyns :: InferM (Map QName (DefLoc,TySyn))
getTSyns = IM $ asks iTSyns
-- | Returns the newtype declarations that are in scope.
getNewtypes :: InferM (Map QName (DefLoc,Newtype))
getNewtypes = IM $ asks iNewtypes
-- | Get the set of bound type variables that are in scope.
getTVars :: InferM (Set QName)
getTVars = IM $ asks $ Set.fromList . mapMaybe tpName . iTVars
-- | Return the keys of the bound variables that are in scope.
getBoundInScope :: InferM (Set TVar)
getBoundInScope = IM $ asks $ Set.fromList . map tpVar . iTVars
-- | Retrieve the value of the `mono-binds` option.
getMonoBinds :: InferM Bool
getMonoBinds = IM (asks iMonoBinds)
{- | We disallow shadowing between type synonyms and type variables
because it is confusing. As a bonus, in the implementation we don't
need to worry about where we lookup things (i.e., in the variable or
type synonym environment. -}
checkTShadowing :: String -> QName -> InferM ()
checkTShadowing this new =
do ro <- IM ask
rw <- IM get
let shadowed =
do _ <- Map.lookup new (iTSyns ro)
return "type synonym"
`mplus`
do guard (new `elem` mapMaybe tpName (iTVars ro))
return "type variable"
`mplus`
do _ <- msum (map (Map.lookup new) (iExistTVars rw))
return "type"
case shadowed of
Nothing -> return ()
Just that ->
recordError $ ErrorMsg $
text "Type" <+> text this <+> quotes (pp new) <+>
text "shadows an existing" <+>
text that <+> text "with the same name."
-- | The sub-computation is performed with the given type parameter in scope.
withTParam :: TParam -> InferM a -> InferM a
withTParam p (IM m) =
do case tpName p of
Just x -> checkTShadowing "variable" x
Nothing -> return ()
IM $ mapReader (\r -> r { iTVars = p : iTVars r }) m
withTParams :: [TParam] -> InferM a -> InferM a
withTParams ps m = foldr withTParam m ps
-- | The sub-computation is performed with the given type-synonym in scope.
withTySyn :: TySyn -> InferM a -> InferM a
withTySyn t (IM m) =
do let x = tsName t
checkTShadowing "synonym" x
IM $ mapReader (\r -> r { iTSyns = Map.insert x (IsLocal,t) (iTSyns r) }) m
withNewtype :: Newtype -> InferM a -> InferM a
withNewtype t (IM m) =
IM $ mapReader
(\r -> r { iNewtypes = Map.insert (ntName t) (IsLocal,t)
(iNewtypes r) }) m
-- | The sub-computation is performed with the given variable in scope.
withVarType :: QName -> VarType -> InferM a -> InferM a
withVarType x s (IM m) =
IM $ mapReader (\r -> r { iVars = Map.insert x s (iVars r) }) m
withVarTypes :: [(QName,VarType)] -> InferM a -> InferM a
withVarTypes xs m = foldr (uncurry withVarType) m xs
withVar :: QName -> Schema -> InferM a -> InferM a
withVar x s = withVarType x (ExtVar s)
-- | The sub-computation is performed with the given variables in scope.
withMonoType :: (QName,Located Type) -> InferM a -> InferM a
withMonoType (x,lt) = withVar x (Forall [] [] (thing lt))
-- | The sub-computation is performed with the given variables in scope.
withMonoTypes :: Map QName (Located Type) -> InferM a -> InferM a
withMonoTypes xs m = foldr withMonoType m (Map.toList xs)
-- | The sub-computation is performed with the given type synonyms
-- and variables in scope.
withDecls :: ([TySyn], Map QName Schema) -> InferM a -> InferM a
withDecls (ts,vs) m = foldr withTySyn (foldr add m (Map.toList vs)) ts
where
add (x,t) = withVar x t
-- | Perform the given computation in a new scope (i.e., the subcomputation
-- may use existential type variables).
inNewScope :: InferM a -> InferM a
inNewScope m =
do curScopes <- iExistTVars <$> IM get
IM $ sets_ $ \s -> s { iExistTVars = Map.empty : curScopes }
a <- m
IM $ sets_ $ \s -> s { iExistTVars = curScopes }
return a
--------------------------------------------------------------------------------
-- Kind checking
newtype KindM a = KM { unKM :: ReaderT KRO (StateT KRW InferM) a }
data KRO = KRO { lazyTVars :: Map QName Type -- ^ lazy map, with tyvars.
, allowWild :: Bool -- ^ are type-wild cards allowed?
}
data KRW = KRW { typeParams :: Map QName Kind -- ^ kinds of (known) vars.
}
instance Functor KindM where
fmap f (KM m) = KM (fmap f m)
instance A.Applicative KindM where
pure = return
(<*>) = ap
instance Monad KindM where
return x = KM (return x)
fail x = KM (fail x)
KM m >>= k = KM (m >>= unKM . k)
{- | The arguments to this function are as follows:
(type param. name, kind signature (opt.), a type representing the param)
The type representing the parameter is just a thunk that we should not force.
The reason is that the type depnds on the kind of parameter, that we are
in the process of computing.
As a result we return the value of the sub-computation and the computed
kinds of the type parameters. -}
runKindM :: Bool -- Are type-wild cards allowed?
-> [(QName, Maybe Kind, Type)] -- ^ See comment
-> KindM a -> InferM (a, Map QName Kind)
runKindM wildOK vs (KM m) =
do (a,kw) <- runStateT krw (runReaderT kro m)
return (a, typeParams kw)
where
tys = Map.fromList [ (x,t) | (x,_,t) <- vs ]
kro = KRO { allowWild = wildOK, lazyTVars = tys }
krw = KRW { typeParams = Map.fromList [ (x,k) | (x,Just k,_) <- vs ] }
-- | This is what's returned when we lookup variables during kind checking.
data LkpTyVar = TLocalVar Type (Maybe Kind) -- ^ Locally bound variable.
| TOuterVar Type -- ^ An outer binding.
-- | Check if a name refers to a type variable.
kLookupTyVar :: QName -> KindM (Maybe LkpTyVar)
kLookupTyVar x = KM $
do vs <- lazyTVars `fmap` ask
ss <- get
case Map.lookup x vs of
Just t -> return $ Just $ TLocalVar t $ Map.lookup x $ typeParams ss
Nothing -> lift $ lift $ do t <- lookupTVar x
return (fmap TOuterVar t)
-- | Are type wild-cards OK in this context?
kWildOK :: KindM Bool
kWildOK = KM $ fmap allowWild ask
-- | Reports an error.
kRecordError :: Error -> KindM ()
kRecordError e = kInInferM $ recordError e
kRecordWarning :: Warning -> KindM ()
kRecordWarning w = kInInferM $ recordWarning w
-- | Generate a fresh unification variable of the given kind.
kNewType :: Doc -> Kind -> KindM Type
kNewType src k =
do tps <- KM $ do vs <- asks lazyTVars
return $ Set.fromList [ tv | TVar tv <- Map.elems vs ]
kInInferM $ TVar `fmap` newTVar' src tps k
-- | Lookup the definition of a type synonym.
kLookupTSyn :: QName -> KindM (Maybe TySyn)
kLookupTSyn x = kInInferM $ lookupTSyn x
-- | Lookup the definition of a newtype.
kLookupNewtype :: QName -> KindM (Maybe Newtype)
kLookupNewtype x = kInInferM $ lookupNewtype x
kExistTVar :: QName -> Kind -> KindM Type
kExistTVar x k = kInInferM $ existVar x k
-- | Replace the given bound variables with concrete types.
kInstantiateT :: Type -> [(TParam,Type)] -> KindM Type
kInstantiateT t as = return (apSubst su t)
where su = listSubst [ (tpVar x, t1) | (x,t1) <- as ]
{- | Record the kind for a local type variable.
This assumes that we already checked that there was no other valid
kind for the variable (if there was one, it gets over-written). -}
kSetKind :: QName -> Kind -> KindM ()
kSetKind v k = KM $ sets_ $ \s -> s{ typeParams = Map.insert v k (typeParams s)}
-- | The sub-computation is about the given range of the source code.
kInRange :: Range -> KindM a -> KindM a
kInRange r (KM m) = KM $
do e <- ask
s <- get
(a,s1) <- lift $ lift $ inRange r $ runStateT s $ runReaderT e m
set s1
return a
kNewGoals :: ConstraintSource -> [Prop] -> KindM ()
kNewGoals c ps = kInInferM $ newGoals c ps
kInInferM :: InferM a -> KindM a
kInInferM m = KM $ lift $ lift m
| iblumenfeld/cryptol | src/Cryptol/TypeCheck/Monad.hs | bsd-3-clause | 25,709 | 0 | 21 | 7,397 | 6,740 | 3,513 | 3,227 | 426 | 7 |
-- | Uncurrying test.
--
-- So:
--
-- _(_(foo)(x))(y)
--
-- should become:
--
-- foo$uncurried(x,y)
--
module Main where
main = print (foo () ())
foo a b = ()
| beni55/fay | tests/codegen/uncurry.hs | bsd-3-clause | 162 | 0 | 8 | 35 | 46 | 29 | 17 | 3 | 1 |
--
-- Copyright (c) 2012 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
{-# LANGUAGE PatternGuards #-}
module AppInventory
(
AppState (..)
, enumAppliances
, findAppliance
, findVmAppliances
, applianceOwnedFiles
, applianceOwnedVms
, haveAppliance
, registerAppliance
, registerApplianceOwnedFile
, registerApplianceOwnedVm
, registerApplianceVmDisk
, unregisterAppliance
, getSystemID
, appDBPath
, changeApplianceState
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Error
import Data.String
import Tools.Db
import Tools.IfM
import Tools.Text
import Tools.File
import System.Directory
import Rpc.Core
import Rpc.Autogen.XenmgrVmClient
import Rpc.Autogen.XenmgrClient
import Core.Types
import Appliance
import VirtualSystem
import Util
data AppState =
AppInstalling
| AppUninstalling
| AppInstalled
deriving (Eq, Show)
instance EnumMarshall AppState where
enumMarshallMap = [ (AppInstalling , "installing" )
, (AppUninstalling, "uninstalling" )
, (AppInstalled, "installed") ]
instance Marshall AppState where {dbRead = dbReadEnum; dbWrite = dbWriteEnum}
xenmgrObj = "/"
xenmgrSrv = "com.citrix.xenclient.xenmgr"
withXenmgr f = f xenmgrSrv xenmgrObj
withXenmgrVmUuid uuid f = f xenmgrSrv vmpath where
vmpath = "/vm/" ++ uuidStrUnderscore uuid
appDBPath (AppID name _) = "/appliance/" ++ name
appFilesDBPath app = appDBPath app ++ "/file"
appStateDBPath app = appDBPath app ++ "/state"
appVmsDBPath app = appDBPath app ++ "/vm"
appSystemIDDBPath app vmuuid = appVmsDBPath app ++ "/" ++ show vmuuid ++ "/id"
enumAppliances :: MonadRpc e m => m [AppID]
enumAppliances = mapM makeAppID =<< dbList "/appliance" where
makeAppID name =
AppID name <$> (read <$> dbReadWithDefault "1" ("/appliance/"++name++"/version"))
applianceOwnedFiles :: MonadRpc e m => AppID -> m [FilePath]
applianceOwnedFiles app = dbRead (appFilesDBPath app)
applianceOwnedVms :: MonadRpc e m => AppID -> m [Uuid]
applianceOwnedVms app = map fromString <$> dbList (appVmsDBPath app)
haveAppliance :: MonadRpc e m => AppID -> m Bool
haveAppliance id = dbExists (appDBPath id)
registerAppliance :: MonadRpc e m => AppID -> m ()
registerAppliance id@(AppID _ version) = do
whenM (haveAppliance id) $ error ("appliance " ++ show id ++ " already registered")
dbWrite (appDBPath id ++ "/version") version
changeApplianceState id AppInstalling
registerApplianceOwnedFile :: MonadRpc e m => AppID -> FilePath -> m ()
registerApplianceOwnedFile app p =
dbWrite (appFilesDBPath app) =<< ((++ [p]) <$> applianceOwnedFiles app)
registerApplianceOwnedVm :: MonadRpc e m => AppID -> Uuid -> VirtualSystemID -> m ()
registerApplianceOwnedVm app uuid (VirtualSystemID sysid) = do
dbWrite (appSystemIDDBPath app uuid) sysid
registerApplianceVmDisk :: MonadRpc e m => AppID -> Disk -> String -> m ()
registerApplianceVmDisk app disk diskObj
| Just im <- diskImage disk = dbWrite (appDBPath app ++ "/disk/" ++ sysidstr ++ "/" ++ imageid im) diskObj
| otherwise = return ()
where
VirtualSystemID sysidstr = sysid
DiskID sysid index = diskID disk
imageid im = let DiskImageID id = diID im in id
-- FIXME: app db locking
unregisterAppliance :: MonadRpc e m => AppID -> Bool -> Bool -> m ()
unregisterAppliance app removeVms removeAssets =
whenM (haveAppliance app) $ do
changeApplianceState app AppUninstalling
vms <- applianceOwnedVms app
running <- runningVms vms
when removeVms $ when (not . null $ running) $ error ("cannot remove appliance because vms are running: " ++ show running)
when removeVms $ mapM_ removeAppVm vms
when removeAssets $ do
-- only remove files not reused by other appliances
other_apps <- filter (/= app) <$> enumAppliances
other_app_files <- concat <$> mapM applianceOwnedFiles other_apps
mapM_ (removeAppFile other_app_files) =<< applianceOwnedFiles app
-- liftIO $ rmDirRec (appStoragePath app)
dbRm (appDBPath app)
where
runningVms vms = filterM (\uuid -> (/= eVM_STATE_STOPPED) <$> withXenmgrVmUuid uuid comCitrixXenclientXenmgrVmGetState) vms
removeAppVm uuid = withXenmgrVmUuid uuid comCitrixXenclientXenmgrVmDelete
removeAppFile exclude f
| not (f `elem` exclude) = liftIO $ whenM (doesFileExist f) (removeFile f)
| otherwise = return ()
changeApplianceState :: MonadRpc e m => AppID -> AppState -> m ()
changeApplianceState app = dbWrite (appStateDBPath app)
findAppliance :: MonadRpc e m => String -> m (Maybe AppID)
findAppliance id = unlist . filter matches <$> enumAppliances where
matches (AppID id' _) = id == id'
unlist (app:_) = Just app
unlist _ = Nothing
findVmAppliances :: MonadRpc e m => Uuid -> m [AppID]
findVmAppliances vm_uuid = filterM matches =<< enumAppliances where
matches app = (vm_uuid `elem`) <$> applianceOwnedVms app
getSystemID :: MonadRpc e m => AppID -> Uuid -> m VirtualSystemID
getSystemID app vm =
VirtualSystemID <$> dbRead (appSystemIDDBPath app vm)
| crogers1/manager | apptool/AppInventory.hs | gpl-2.0 | 5,862 | 0 | 14 | 1,177 | 1,549 | 781 | 768 | 113 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.TwoD.Path.Turtle.Aliases
-- Copyright : (c) 2011 Michael Sloan
-- License : BSD-style (see LICENSE)
-- Maintainer : Michael Sloan <mgsloan at gmail>
--
-- Adds compact aliases for turtle operations, to write code that looks even
-- more Turtle-y.
--
-----------------------------------------------------------------------------
module Diagrams.TwoD.Path.Turtle.Aliases where
import Diagrams.TwoD.Path.Turtle
fd, bk, lt, rt :: (Floating n, Ord n) => n -> Turtle n ()
fd = forward
bk = backward
lt = left
rt = right
pu, pd :: (Floating n, Ord n) => Turtle n ()
pu = penUp
pd = penDown
| wherkendell/diagrams-contrib | src/Diagrams/TwoD/Path/Turtle/Aliases.hs | bsd-3-clause | 719 | 0 | 8 | 128 | 123 | 79 | 44 | 10 | 1 |
module E.Rules(
ARules,
Rule(Rule,ruleHead,ruleBinds,ruleArgs,ruleBody,ruleUniq,ruleName),
RuleType(..),
Rules(..),
applyRules,
arules,
builtinRule,
dropArguments,
fromRules,
ruleUpdate,
mapRBodyArgs,
makeRule,
mapBodies,
printRules,
rulesFromARules
)where
import Control.Monad.Writer(execWriterT,liftM,tell)
import Data.Maybe
import Data.Monoid(Monoid(..))
import qualified Data.Traversable as T
import Data.Binary
import Doc.DocLike
import Doc.PPrint
import Doc.Pretty
import E.Binary()
import E.E
import E.Show()
import E.Subst
import E.Values
import GenUtil
import Info.Types
import Name.Id
import Name.Name
import Name.Names
import Options
import Stats
import StringTable.Atom(toAtom)
import Support.CanType
import Support.FreeVars
import Support.MapBinaryInstance()
import Util.HasSize
import Util.SetLike as S
import qualified Util.Seq as Seq
instance Show Rule where
showsPrec _ r = shows $ ruleName r
emptyRule :: Rule
emptyRule = Rule {
ruleHead = error "ruleHead undefined",
ruleArgs = [],
ruleNArgs = 0,
ruleBinds = [],
ruleType = RuleUser,
ruleBody = error "ruleBody undefined",
ruleName = error "ruleName undefined",
ruleUniq = error "ruleUniq undefined"
}
-- a collection of rules
newtype Rules = Rules (IdMap [Rule])
deriving(HasSize,IsEmpty)
instance Eq Rule where
r1 == r2 = ruleUniq r1 == ruleUniq r2
instance Binary Rules where
put (Rules mp) = put (concat $ values mp)
get = do
rs <- get
return $ fromRules rs
mapBodies :: Monad m => (E -> m E) -> Rules -> m Rules
mapBodies g (Rules mp) = do
let f rule = do
b <- g (ruleBody rule)
return rule { ruleBody = b }
mp' <- T.mapM (mapM f) mp
return $ Rules mp'
--mp' <- sequence [ do rs' <- mapM f rs; return (k,rs') | (k,rs) <- Map.toAscList mp ]
--return $ Rules $ Map.fromAscList mp'
instance FreeVars Rule [Id] where
freeVars rule = idSetToList $ freeVars rule
{-# NOINLINE printRules #-}
printRules ty (Rules rules) = mapM_ (\r -> printRule r >> putChar '\n') [ r | r <- concat $ values rules, ruleType r == ty ]
putDocMLn' :: Monad m => (String -> m ()) -> Doc -> m ()
putDocMLn' putStr d = displayM putStr (renderPretty 0.80 (optColumns options) d) >> putStr "\n"
printRule Rule {ruleName = n, ruleBinds = vs, ruleBody = e2, ruleHead = head, ruleArgs = args } = do
let e1 = foldl EAp (EVar head) args
let p v = parens $ pprint v <> text "::" <> pprint (getType v)
putDocMLn' putStr $ (tshow n) <+> text "forall" <+> hsep (map p vs) <+> text "."
let ty = pprint $ getType e1 -- case inferType dataTable [] e1 of
-- ty2 = pprint $ getType e2
putDocMLn' putStr (indent 2 (pprint e1) <+> text "::" <+> ty )
putDocMLn' putStr $ text " ==>" <+> pprint e2
--putDocMLn CharIO.putStr (indent 2 (pprint e2))
--putDocMLn CharIO.putStr (indent 2 (text "::" <+> ty2))
combineRules as bs = map head $ sortGroupUnder ruleUniq (as ++ bs)
instance Monoid Rules where
mempty = Rules mempty
mappend (Rules x) (Rules y) = Rules $ unionWith combineRules x y
fromRules :: [Rule] -> Rules
fromRules rs = Rules $ fmap snds $ fromList $ sortGroupUnderF fst [ (tvrIdent $ ruleHead r,ruleUpdate r) | r <- rs ]
mapRBodyArgs :: Monad m => (E -> m E) -> Rule -> m Rule
mapRBodyArgs g r = do
let f rule = do
b <- g (ruleBody rule)
as <- mapM g (ruleArgs rule)
return rule { ruleArgs = as, ruleBody = b }
f r
rulesFromARules :: ARules -> [Rule]
rulesFromARules = aruleRules
-- replace the given arguments with the E values, dropping impossible rules
dropArguments :: [(Int,E)] -> [Rule] -> [Rule]
dropArguments os rs = catMaybes $ map f rs where
f r = do
let g (i,a) | Just v <- lookup i os = do
rs <- match (const Nothing) (ruleBinds r) a v
return (Right rs)
g (i,a) = return (Left a)
as' <- mapM g $ zip naturals (ruleArgs r)
let sb = substLet (concat $ rights as')
sa = substMap $ fromList [ (tvrIdent t,v) | Right ds <- as', (t,v) <- ds ]
return r { ruleArgs = map sa (lefts as'), ruleBody = sb (ruleBody r) }
-- | ARules contains a set of rules for a single id, optimized for fast application
--
-- invarients for ARules
-- sorted by number of arguments rule takes
-- all hidden rule fields filled in
-- free variables are up to date
instance Show ARules where
showsPrec n a = showsPrec n (aruleRules a)
arules xs = ARules { aruleFreeVars = freeVars rs, aruleRules = rs } where
rs = sortUnder ruleNArgs (map f xs)
f rule = rule {
ruleNArgs = length (ruleArgs rule),
ruleBinds = bs,
ruleBody = g (ruleBody rule),
ruleArgs = map g (ruleArgs rule)
} where
bs = map (setProperty prop_RULEBINDER) (ruleBinds rule)
g e = substMap (fromList [ (tvrIdent t, EVar t) | t <- bs ]) e
instance Monoid ARules where
mempty = ARules { aruleFreeVars = mempty, aruleRules = [] }
mappend = joinARules
ruleUpdate rule = rule {
ruleNArgs = length (ruleArgs rule),
ruleBinds = bs,
ruleBody = g (ruleBody rule),
ruleArgs = map g (ruleArgs rule)
} where
bs = map (setProperty prop_RULEBINDER) (ruleBinds rule)
g e = substMap (fromList [ (tvrIdent t, EVar t) | t <- bs ]) e
joinARules ar@(ARules fvsa a) br@(ARules fvsb b)
| [] <- rs = ARules mempty []
| all (== r) rs = ARules (fvsa `mappend` fvsb) (sortUnder (\r -> (ruleNArgs r,ruleUniq r)) (snubUnder ruleUniq $ a ++ b))
| otherwise = error $ "mixing rules!" ++ show (ar,br) where
rs@(r:_) = map ruleHead a ++ map ruleHead b
rsubstMap :: IdMap E -> E -> E
rsubstMap im e = doSubst False True (fmap ( (`mlookup` im) . tvrIdent) (unions $ (freeVars e :: IdMap TVr):map freeVars (values im))) e
applyRules :: MonadStats m => (Id -> Maybe E) -> ARules -> [E] -> m (Maybe (E,[E]))
applyRules lup (ARules _ rs) xs = f rs where
lxs = length xs
f [] = return Nothing
f (r:_) | ruleNArgs r > lxs = return Nothing
f (r:rs) = case sequence (zipWith (match lup (ruleBinds r)) (ruleArgs r) xs) of
Just ss -> do
mtick (ruleName r)
let b = rsubstMap (fromList [ (i,x) | (TVr { tvrIdent = i },x) <- concat ss ]) (ruleBody r)
return $ Just (b,drop (ruleNArgs r) xs)
Nothing -> do f rs
preludeError = toId v_error
ruleError = toAtom "Rule.error/EError"
builtinRule TVr { tvrIdent = n } (ty:s:rs)
| n == preludeError, Just s' <- toString s = do
mtick ruleError
return $ Just ((EError ("Prelude.error: " ++ s') ty),rs)
builtinRule _ _ = return Nothing
makeRule ::
String -- ^ the rule name
-> (Module,Int) -- ^ a unique name for this rule
-> RuleType -- ^ type of rule
-> [TVr] -- ^ the free variables
-> TVr -- ^ the head
-> [E] -- ^ the args
-> E -- ^ the body
-> Rule
makeRule name uniq ruleType fvs head args body = rule where
rule = emptyRule {
ruleHead = head,
ruleBinds = fvs,
ruleArgs = args,
ruleType = ruleType,
ruleNArgs = length args,
ruleBody = body,
ruleUniq = uniq,
ruleName = toAtom $ "Rule.User." ++ name
}
-- | find substitution that will transform the left term into the right one,
-- only substituting for the vars in the list
match :: Monad m =>
(Id -> Maybe E) -- ^ function to look up values in the environment
-> [TVr] -- ^ vars which may be substituted
-> E -- ^ pattern to match
-> E -- ^ input expression
-> m [(TVr,E)]
match lup vs = \e1 e2 -> liftM Seq.toList $ execWriterT (un e1 e2 () etherealIds) where
bvs :: IdSet
bvs = fromList (map tvrIdent vs)
un _ _ _ c | c `seq` False = undefined
un (EAp a b) (EAp a' b') mm c = do
un a a' mm c
un b b' mm c
un (ELam va ea) (ELam vb eb) mm c = lam va ea vb eb mm c
un (EPi va ea) (EPi vb eb) mm c = lam va ea vb eb mm c
un (EPrim s xs t) (EPrim s' ys t') mm c | length xs == length ys = do
sequence_ [ un x y mm c | x <- xs | y <- ys]
un t t' mm c
un (ESort x) (ESort y) mm c | x == y = return ()
un (ELit (LitInt x t1)) (ELit (LitInt y t2)) mm c | x == y = un t1 t2 mm c
un (ELit LitCons { litName = n, litArgs = xs, litType = t }) (ELit LitCons { litName = n', litArgs = ys, litType = t'}) mm c | n == n' && length xs == length ys = do
sequence_ [ un x y mm c | x <- xs | y <- ys]
un t t' mm c
un (EVar TVr { tvrIdent = i, tvrType = t}) (EVar TVr {tvrIdent = j, tvrType = u}) mm c | i == j = un t u mm c
un (EVar TVr { tvrIdent = i, tvrType = t}) (EVar TVr {tvrIdent = j, tvrType = u}) mm c | isEtherealId i || isEtherealId j = fail "Expressions don't match"
un (EVar tvr@TVr { tvrIdent = i, tvrType = t}) b mm c
| i `member` bvs = tell (Seq.singleton (tvr,b))
| otherwise = fail $ "Expressions do not unify: " ++ show tvr ++ show b
un a (EVar tvr) mm c | Just b <- lup (tvrIdent tvr), not $ isEVar b = un a b mm c
un a b _ _ = fail $ "Expressions do not unify: " ++ show a ++ show b
lam va ea vb eb mm ~(c:cs) = do
un (tvrType va) (tvrType vb) mm (c:cs)
un (subst va (EVar va { tvrIdent = c }) ea) (subst vb (EVar vb { tvrIdent = c }) eb) mm cs
| m-alvarez/jhc | src/E/Rules.hs | mit | 9,475 | 2 | 24 | 2,656 | 3,842 | 1,974 | 1,868 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fr-FR">
<title>Tips and Tricks | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Indice</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Rechercher</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/tips/src/main/javahelp/org/zaproxy/zap/extension/tips/resources/help_fr_FR/helpset_fr_FR.hs | apache-2.0 | 981 | 78 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
module RefacRmCon(refacRmCon) where
import PrettyPrint
import PosSyntax
import AbstractIO
import Data.Maybe
import TypedIds
import UniqueNames hiding (srcLoc)
import PNT
import TiPNT
import Data.List
import RefacUtils hiding (getParams)
import PFE0 (findFile)
import MUtils (( # ))
import RefacLocUtils
-- import System
import System.IO
{- This refactoring removes a user selected constructor from a data type and resolves all pattern matching.
When a constructor is removed, all equations over that value will be commented out; all references to that value within an expression will be replaced with a call to error.
Copyright : (c) Christopher Brown 2008
Maintainer : cmb21@kent.ac.uk
Stability : provisional
Portability : portable
-}
data Decls = PatBind HsDeclP | MatchBind HsMatchP deriving (Read, Show, Eq)
refacRmCon args
= do let fileName = ghead "filename" args
--fileName'= moduleName fileName
--modName = Module fileName'
row = read (args!!1)::Int
col = read (args!!2)::Int
modName <-fileNameToModName fileName
(inscps, exps, mod, tokList)<-parseSourceFile fileName
case checkCursor fileName row col mod of
Left errMsg -> do error errMsg
Right dat ->
do
let pnt = locToPNT fileName (row, col) mod
if (pnt /= defaultPNT)
then
if isDataCon pnt
then do
let (pnts, defDecl) = pntsToBeRemoved pnt mod
if isExported (declToPNT defDecl) exps
then do
clients <- clientModsAndFiles modName
info <- mapM parseSourceFile $ map snd clients
((_,m), (newToks, newMod))<-applyRefac (doRemoving pnt defDecl modName)
(Just (inscps, exps, mod, tokList)) fileName
refactoredClients<-mapM (removeInClientMod pnt defDecl modName) $ zip info (map snd clients)
writeRefactoredFiles False $ ((fileName,m),(newToks,newMod)):refactoredClients
AbstractIO.putStrLn "\nCompleted.\n"
else do
((_,m), (newToks, newMod))<-applyRefac (doRemoving pnt defDecl modName)
(Just (inscps, exps, mod, tokList)) fileName
writeRefactoredFiles False [((fileName,m), (newToks,newMod))]
AbstractIO.putStrLn "\nCompleted.\n"
else error "Please select a constructor!"
else
error "\nInvalid cursor position!"
checkCursor :: String -> Int -> Int -> HsModuleP -> Either String HsDeclP
checkCursor fileName row col mod
= case locToTypeDecl of
Nothing -> Left ("Invalid cursor position. Please place cursor at the beginning of the constructor name!")
Just decl@(Dec (HsDataDecl loc c tp xs _)) -> Right decl
where
locToTypeDecl = find (definesTypeCon (locToPNT fileName (row, col) mod)) (hsModDecls mod)
-- definesTypeCon pnt (Dec (HsDataDecl loc c tp xs _))
-- = isDataCon pnt && (findPNT pnt tp)
definesTypeCon pnt (Dec (HsDataDecl _ _ _ i _))
= isDataCon pnt && (findPNT pnt i)
definesTypeCon pnt _ = False
removeInClientMod pnt defDecl modName ((inscps, exps, mod,ts), fileName)
= do
((_,m), (newToks, newMod))<-applyRefac (doRemoving2 pnt defDecl modName)
(Just (inscps, exps, mod, ts)) fileName
return ((fileName, m), (newToks, newMod))
doRemoving2 pnt defDecl modName (_, exps, t)
= do
mod'' <- removePatEquation pnt defDecl modName exps t
mod''' <- replaceOrdPats pnt defDecl mod''
return mod'''
doRemoving pnt defDecl modName (_, exps, t)
= do mod' <- removeConstr pnt defDecl t
mod'' <- removePatEquation pnt defDecl modName exps mod'
mod''' <- replaceOrdPats pnt defDecl mod''
return mod'''
createError :: String -> String -> Int -> HsExpP
createError newE typeName line
= (Exp (HsApp (nameToExp "error") (nameToExp ("\""++newE++" no longer defined for "++typeName++" at line: "++(show line)++"\""))))
pntToLine pnt = let (SrcLoc fileName _ row col) = (useLoc pnt) in row
-- replace normal expression patterns with call to error
replaceOrdPats pnt defDecl t
= applyTP (stop_tdTP (failTP `adhocTP` rmInExp)) t
where
rmInExp e@(Exp (HsId (HsCon x)))
| defineLoc x == defineLoc pnt
= do
let newE = (render.ppi) e
let typeName = declToName defDecl
let line = pntToLine pnt
update e (Exp (HsParen (createError newE typeName line))) e
rmInExp e@(Exp (HsInfixApp e1 o@(HsCon x) e2 ))
| defineLoc x == defineLoc pnt
= do
let newE = (render.ppi) e
let typeName = declToName defDecl
let line = pntToLine pnt
update e (Exp (HsParen (createError newE typeName line))) e
rmInExp x = mzero
-- comment out all equations referencing removed
-- constructor
removePatEquation pnt defDecl modName exps t
= applyTP (full_buTP (idTP `adhocTP` rmInMod
`adhocTP` rmInMatch
`adhocTP` rmInPat
`adhocTP` rmInLet
`adhocTP` rmInAlt
`adhocTP` rmInLetStmt
`adhocTP` rmInMonad
)) t
where
-- 1. the equation to comment out is on the top level of a definition...
rmInMod (mod@(HsModule loc name exps imps ds):: HsModuleP)
| canBeRemoved pnt mod
=do
let declsToRemove = whatCanBeRemoved pnt mod
ds' <- rmDecls declsToRemove ds
-- do we need to comment out the type signature
-- of any entities?
dsCommented <- comTypeSigs ds' (HsModule loc name exps imps ds') ds'
-- check for calls to deleted definitions
let removedElems = ds \\\ dsCommented
dsReplacedCall <- checkCalls removedElems dsCommented
-- check that deleted defintion is not exported...
return (HsModule loc name exps imps dsReplacedCall)
rmInMod x = return x
--2. The definition to be removed is a local declaration in a match
rmInMatch (match@(HsMatch loc name pats rhs ds)::HsMatchP)
| canBeRemoved pnt match
=do
let declsToRemove = whatCanBeRemoved pnt match
ds'<-rmDecls declsToRemove ds
dsCommented <- comTypeSigs ds' (HsMatch loc name pats rhs ds') ds'
let removedElems = ds \\\ dsCommented
rhsReplacedCall <- checkCalls removedElems rhs
return (HsMatch loc name pats rhsReplacedCall dsCommented)
rmInMatch x =return x
--3. The definition to be removed is a local declaration in a pattern binding
rmInPat (pat@(Dec (HsPatBind loc p rhs ds))::HsDeclP)
| canBeRemoved pnt pat
=do
let declsToRemove = whatCanBeRemoved pnt pat
ds'<- rmDecls declsToRemove ds
dsCommented <- comTypeSigs ds' (Dec (HsPatBind loc p rhs ds')) ds'
let removedElems = ds \\\ dsCommented
rhsReplacedCall <- checkCalls removedElems rhs
return (Dec (HsPatBind loc p rhsReplacedCall dsCommented))
rmInPat x =return x
--4.The definition to be removed is a local declaration in a let expression
rmInLet (letExp@(Exp (HsLet ds e))::HsExpP)
| canBeRemoved pnt letExp
= do
let declsToRemove = whatCanBeRemoved pnt letExp
ds'<- rmDecls declsToRemove ds
if ds'==[] then return e
else do dsCommented <- comTypeSigs ds' (Exp (HsLet ds' e)) ds'
let removedElems = ds \\\ dsCommented
eReplacedCall <- checkCalls removedElems e
return (Exp (HsLet dsCommented eReplacedCall))
rmInLet (letExp@(Exp (HsListComp (HsLetStmt ds stmts)))) -- e.g. [0|z=1] => [0]
| canBeRemoved pnt letExp
=do
let declsToRemove = whatCanBeRemoved pnt letExp
ds'<- rmDecls declsToRemove ds
dsCommented <- comTypeSigs ds' (Exp (HsListComp (HsLetStmt ds' stmts))) ds'
let removedElems = ds \\\ dsCommented
sReplacedCall <- checkCalls removedElems stmts
if ds'/=[]
then return (Exp (HsListComp (HsLetStmt dsCommented sReplacedCall)))
else if isLast stmts
then return (Exp (HsList [fromJust (expInLast sReplacedCall)]))
else return (Exp (HsListComp sReplacedCall))
rmInLet x = return x
--5. The defintion to be removed is a local decl in a case alternative.
rmInAlt (alt@(HsAlt loc p rhs ds)::HsAltP)
|canBeRemoved pnt alt
=do
let declsToRemove = whatCanBeRemoved pnt alt
ds'<- rmDecls declsToRemove ds
dsCommented <- comTypeSigs ds' (HsAlt loc p rhs ds') ds'
let removedElems = ds \\\ dsCommented
rhsReplacedCall <- checkCalls removedElems rhs
return (HsAlt loc p rhsReplacedCall dsCommented)
rmInAlt x = return x
--6. The definition to be removed is a local decl in a let statement.
rmInLetStmt (letStmt@(HsLetStmt ds stmts)::(HsStmt (HsExpP) (HsPatP) [HsDeclP]))
|canBeRemoved pnt letStmt
=do
let declsToRemove = whatCanBeRemoved pnt letStmt
ds'<- rmDecls declsToRemove ds
dsCommenting <- comTypeSigs ds' (HsLetStmt ds' stmts) ds'
let removedElems = ds \\\ dsCommenting
sReplacedCall <- checkCalls removedElems stmts
if ds'==[] then return sReplacedCall
else return (HsLetStmt dsCommenting sReplacedCall)
rmInLetStmt x = return x
--7. If the definition occurs within a pattern binding in a monadic expression
-- give an error.
rmInMonad (letStmt@(HsLetStmt ds stmts)::HsStmtP)
|canBeRemoved pnt letStmt
=do
let declsToRemove = whatCanBeRemoved pnt letStmt
ds'<- rmDecls declsToRemove ds
dsCommenting <- comTypeSigs ds' (HsLetStmt ds' stmts) ds'
let removedElems = ds \\\ dsCommenting
sReplacedCall <- checkCalls removedElems stmts
if ds'==[] then return sReplacedCall
else return (HsLetStmt dsCommenting sReplacedCall)
rmInMonad (mon@(HsGenerator s p e stmts)::HsStmtP)
| (defineLoc pnt) `elem` flatternPat p
= error "Refactoring cannot be performed as constructor is used in a pattern binding!" -- [decl]
rmInMonad x = return x
-- list1 minus list2
(\\\) :: [HsDeclP] -> [HsDeclP] -> [HsDeclP]
(\\\) list1 list2 = convertMatches list1 \\\\ convertMatches list2
(\\\\) [] _ = []
(\\\\) (d@(Dec (HsFunBind loc [HsMatch loc2 name _ _ _])):ls) list2
| name `elem2` list2 = ls \\\\ list2
| otherwise = d : ls \\\\ list2
where
elem2 _ [] = False
elem2 name (d@(Dec (HsFunBind loc [HsMatch loc2 name2 _ _ _])):ds)
| name == name2 = True
| otherwise = name `elem2` ds
elem2 name (d:ds) = name `elem2` ds
(\\\\) (d:ds) list2
| d `elem` list2 = ds \\\\ list2
| otherwise = d : ds \\\\ list2
convertMatches :: [HsDeclP] -> [HsDeclP]
convertMatches [] = []
convertMatches ((Dec (HsFunBind loc ms)):ds)
= let toFunBind m = Dec (HsFunBind loc [m])
in (map toFunBind ms) ++ (convertMatches ds)
convertMatches (d:ds) = d : convertMatches ds
-- checkCalls searched for all identifiers and checks whether their
-- defining entity still occurs or not.
-- if not, the identifier is replaced with a call to error
-- (passing in its parameters via a show)
checkCalls decs t
= applyTP (stop_tdTP (failTP `adhocTP` rmInExp )) t
where
rmInExp e@(Exp (HsId (HsVar x)))
| definingDecls [pNTtoPN x] decs False True /= []
= do
let newE = (render.ppi) e
let typeName = declToName defDecl
let line = pntToLine pnt
update e (createError newE typeName line) e
rmInExp e@(Exp (HsApp e1 e2))
| concatMap (definingDecls' decs False True) (map expToPN (flatternApp e)) /= []
= do
let newE = (render.ppi) e
let typeName = declToName defDecl
let line = pntToLine pnt
update e (createError newE typeName line) e
rmInExp x = mzero
definingDecls' x y z l = definingDecls [l] x y z
flatternApp :: HsExpP -> [HsExpP]
flatternApp (Exp (HsApp e1 e2)) = flatternApp e1 ++ flatternApp e2
flatternApp (Exp (HsParen e)) = flatternApp e
flatternApp x = [x]
-- comTypeSigs :: (MonadState (([PosToken], Bool), t1) m, MonadPlus m) => [HsDeclP] -> [HsDeclP] -> m [HsDeclP]
comTypeSigs [] _ _ = return []
comTypeSigs (d@(Dec (HsTypeSig _ _ _ _)):ds) e decs
| not (any (isTypeSigOf' d) (map declToPNT' (hsDecls e)))
= do -- we must comment out this type signature
rest <- comTypeSigs ds e decs
((toks,_),others)<-get
let (startPos,(endPosR, endPosC)) = getStartEndLoc toks d
(toks', decls')
= ((commentToks (startPos, (endPosR, endPosC)) toks),(rest \\ [d]))
put ((toks',modified),others)
let res = decls'
if isExported (declToPNT d) exps
then error ("Removing constructor forces " ++ (declToName d) ++ " in module "
++ (modNameToStr modName) ++ " to be removed. Please un-export it first.")
else return res
-- | otherwise = rmTypeSig ds environ
comTypeSigs (d:ds) e decs = do
rest <- comTypeSigs ds e decs
return (d : rest)
-- | Return True if the declaration defines the type signature of the specified identifier.
isTypeSigOf' :: HsDeclP -> PNT-> Bool
isTypeSigOf' (Dec (HsTypeSig loc is c tp)) pnt = elem (rmLocs pnt) (map rmLocs is)
isTypeSigOf' _ _ =False
rmDecls :: (MonadState (([PosToken], Bool), t1) m, MonadPlus m)
=> [Decls] -> [HsDeclP] -> m [HsDeclP]
rmDecls [] e = return e
rmDecls ((PatBind decl):ds) decls
= do rest <- rmDecls ds decls
((toks,_),others)<-get
let (startPos,(endPosR, endPosC)) = getStartEndLoc toks decl
(toks', decls')
= ((commentToks (startPos, (endPosR, endPosC)) toks),(rest \\ [decl]))
put ((toks',modified),others)
let res = decls'
return res
rmDecls ((MatchBind match):ds) decls
= do rest <- rmDecls ds decls
((toks,_),others)<-get
let (startPos,(endPosR, endPosC)) = getStartEndLoc toks match
modDecls = removedMatch match rest -- decls
(toks', decls')
= ((commentToks (startPos, (endPosR, endPosC)) toks), modDecls)
put ((toks',modified),others)
let res = decls'
return res
removedMatch match decls =
concatMap (removeMatch match) decls
removeMatch match decl@(Dec (HsFunBind loc (m:ms)))
| removesMatches match (m:ms) == [] = []
| otherwise = [ (Dec (HsFunBind loc (removesMatches match (m:ms)))) ]
removeMatch m d = [d]
removesMatches match [] = []
removesMatches match (m:ms)
| sameOccurrence match m = removesMatches match ms
| otherwise = m : removesMatches match ms
isLast (HsLast e)=True
isLast _=False
--returns the expression included in the last statement.
expInLast::HsStmtP->Maybe HsExpP
expInLast (HsLast e)=Just e
expInLast _=Nothing
canBeRemoved pn t
=let decls=hsDecls t
decl=definingDecls2 pnt decls False
-- pnames=concatMap definedPNs decl
in (decl/=[] && all (not.flip findPNRHS (replaceDecls t (decls \\ decl))) [pNTtoPN pn])
whatCanBeRemoved pn t
=let decls=hsDecls t
decl=definingDecls1 pnt decls False
in decl
removeConstr pnt defDecl t
= applyTP (once_tdTP (failTP `adhocTP` rmInDat)) t
where
--1. The constructor is within a data declaration
rmInDat (dat@(Dec (HsDataDecl a b t c d))::HsDeclP)
| sameOccurrence dat defDecl = do
let newConstrs = removeConst c (pNTtoPN pnt)
update dat (Dec (HsDataDecl a b t newConstrs d)) dat
rmInDat _ = mzero
removeConst [] _ = []
removeConst (m@(HsConDecl _ _ _ (PNT pname _ _) _):ms) pn
| pname == pn = (removeConst ms pn)
| otherwise = m : (removeConst ms pn)
removeConst (m@(HsRecDecl _ _ _ (PNT pname _ _) _):ms) pn
| pname == pn = (removeConst ms pn)
| otherwise = m : (removeConst ms pn)
pntsToBeRemoved pnt t
= let decls=hsDecls t
decl=definingDecls [pNTtoPN pnt] decls False False
in (concatMap definedPNsForConstr decl, ghead "pntsToBeRemoved" decl)
--Find those declarations(function/pattern binding and type signature) which reference
-- the constructor on the LHS of the equation
-- if we are removing the last equation then we must also remove the type signature...
definingDecls1::PNT->[HsDeclP]->Bool->[Decls]
definingDecls1 pnt ds incTypeSig=concatMap (defines pnt) ds
where
defines pnt decl@(Dec (HsFunBind loc (m:ms)))
= nub (definesMatches (m:ms))
where
definesMatches [] = []
definesMatches (decl@(HsMatch loc1 (PNT pname ty loc2) pats rhs ds'):ms)
| (defineLoc pnt) `elem` (concatMap flatternPat pats)
= (MatchBind decl) : definesMatches ms
| otherwise = definesMatches ms
defines pnt decl@(Dec (HsPatBind loc p rhs ds))
| (defineLoc pnt) `elem` flatternPat p = [PatBind decl]
defines pn decl= []
--Find those declarations(function/pattern binding and type signature) which reference
-- the constructor on the LHS of the equation
definingDecls2::PNT->[HsDeclP]->Bool->[HsDeclP]
definingDecls2 pnt ds incTypeSig=concatMap (defines pnt) ds
where
defines pnt decl@(Dec (HsFunBind loc (m:ms)))
| or (definesMatches (m:ms)) = [decl]
where
definesMatches [] = [False]
definesMatches (decl@(HsMatch loc1 (PNT pname ty loc2) pats rhs ds'):ms)
| (defineLoc pnt) `elem` (concatMap flatternPat pats)
= True : definesMatches ms
| otherwise = definesMatches ms
defines pnt decl@(Dec (HsPatBind loc p rhs ds))
| (defineLoc pnt) `elem` flatternPat p = error "Refactoring cannot be performed as constructor is used in a pattern binding!" -- [decl]
defines pn decl= []
flatternPat :: HsPatP -> [SrcLoc]
flatternPat t
= inPat t
where
inPat (Pat (HsPId (HsVar pnt@(PNT _ _ _)))) = [defineLoc pnt]
inPat (Pat (HsPInfixApp p1 pnt@(PNT _ _ _) p2))
= addPat (defineLoc pnt) (concatMap flatternPat [p1,p2])
inPat (Pat (HsPApp pnt@(PNT _ _ _) pats))=addPat (defineLoc pnt) (concatMap flatternPat pats)
inPat (Pat (HsPRec pnt@(PNT _ _ _) fields))=[defineLoc pnt]
inPat (Pat (HsPTuple _ pats)) = concatMap flatternPat pats
inPat (Pat (HsPList _ pats)) = concatMap flatternPat pats
inPat (Pat (HsPParen pats) ) = flatternPat pats
inPat (Pat (HsPAsPat _ pats)) = flatternPat pats
inPat (Pat (HsPIrrPat pats)) = flatternPat pats
inPat _ = []
addPat pat mfd= ([pat] `union` mfd)
| mpickering/HaRe | old/refactorer/RefacRmCon.hs | bsd-3-clause | 21,299 | 0 | 23 | 7,574 | 6,276 | 3,150 | 3,126 | -1 | -1 |
{-# LANGUAGE CPP, ForeignFunctionInterface, DeriveDataTypeable #-}
-- We cannot actually specify all the language pragmas, see ghc ticket #
-- If we could, these are what they would be:
{-# LANGUAGE UnliftedFFITypes, MagicHash,
UnboxedTuples, DeriveDataTypeable #-}
{-# OPTIONS_HADDOCK hide #-}
{-@ LIQUID "--c-files=../../cbits/fpstring.c" @-}
{-@ LIQUID "-i../../include" @-}
-- |
-- Module : Data.ByteString.Internal
-- License : BSD-style
-- Maintainer : Don Stewart <dons@galois.com>
-- Stability : experimental
-- Portability : portable
--
-- A module containing semi-public 'ByteString' internals. This exposes the
-- 'ByteString' representation and low level construction functions. As such
-- all the functions in this module are unsafe. The API is also not stable.
--
-- Where possible application should instead use the functions from the normal
-- public interface modules, such as "Data.ByteString.Unsafe". Packages that
-- extend the ByteString system at a low level will need to use this module.
--
module Data.ByteString.Internal (
liquidCanary, -- LIQUID
ptrLen, -- LIQUID GHOST for getting a pointer's length
packWith, -- LIQUID, because we hid the Read instance... FIX.
-- * The @ByteString@ type and representation
ByteString(..), -- instances: Eq, Ord, Show, Read, Data, Typeable
-- * Low level introduction and elimination
create, -- :: Int -> (Ptr Word8 -> IO ()) -> IO ByteString
createAndTrim, -- :: Int -> (Ptr Word8 -> IO Int) -> IO ByteString
createAndTrim', -- :: Int -> (Ptr Word8 -> IO (Int, Int, a)) -> IO (ByteString, a)
createAndTrimEQ, -- :: Int -> (Ptr Word8 -> IO (Int, Int, a)) -> IO (Int, ByteString, a)
createAndTrimMEQ, -- :: Int -> (Ptr Word8 -> IO (Int, Int, Maybe a)) -> IO (Int, ByteString, Maybe a)
unsafeCreate, -- :: Int -> (Ptr Word8 -> IO ()) -> ByteString
mallocByteString, -- :: Int -> IO (ForeignPtr a)
-- * Conversion to and from ForeignPtrs
fromForeignPtr, -- :: ForeignPtr Word8 -> Int -> Int -> ByteString
toForeignPtr, -- :: ByteString -> (ForeignPtr Word8, Int, Int)
-- * Utilities
inlinePerformIO, -- :: IO a -> a
nullForeignPtr, -- :: ForeignPtr Word8
-- * Standard C Functions
c_strlen, -- :: CString -> IO CInt
c_free_finalizer, -- :: FunPtr (Ptr Word8 -> IO ())
memchr, -- :: Ptr Word8 -> Word8 -> CSize -> IO Ptr Word8
memcmp, -- :: Ptr Word8 -> Ptr Word8 -> CSize -> IO CInt
memcpy, -- :: Ptr Word8 -> Ptr Word8 -> CSize -> IO ()
memset, -- :: Ptr Word8 -> Word8 -> CSize -> IO (Ptr Word8)
-- * cbits functions
c_reverse, -- :: Ptr Word8 -> Ptr Word8 -> CInt -> IO ()
c_intersperse, -- :: Ptr Word8 -> Ptr Word8 -> CInt -> Word8 -> IO ()
c_maximum, -- :: Ptr Word8 -> CInt -> IO Word8
c_minimum, -- :: Ptr Word8 -> CInt -> IO Word8
c_count, -- :: Ptr Word8 -> CInt -> Word8 -> IO CInt
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 611
-- * Internal GHC magic
memcpy_ptr_baoff, -- :: Ptr a -> RawBuffer -> CInt -> CSize -> IO (Ptr ())
#endif
-- * Chars
w2c, c2w, isSpaceWord8, isSpaceChar8
) where
import Foreign.ForeignPtr (ForeignPtr, withForeignPtr)
import Foreign.Ptr (Ptr, FunPtr, plusPtr)
import Foreign.Storable (Storable(..))
import Foreign.C.Types (CInt(..), CSize(..), CULong(..))
import Foreign.C.String (CString)
import Foreign.Marshal.Alloc (finalizerFree) --LIQUID: added
import Language.Haskell.Liquid.Prelude (liquidAssert)
import Language.Haskell.Liquid.Foreign (intCSize)
#ifndef __NHC__
import Control.Exception (assert)
#endif
import Data.Char (ord)
import Data.Word (Word8)
#if defined(__GLASGOW_HASKELL__)
import Data.Typeable (Typeable)
#if __GLASGOW_HASKELL__ >= 610
import Data.Data (Data)
#else
import Data.Generics (Data)
#endif
import GHC.Base (realWorld#, unsafeChr)
#if __GLASGOW_HASKELL__ >= 611
import GHC.IO (IO(IO))
#else
import GHC.IOBase (IO(IO),RawBuffer)
#endif
#if __GLASGOW_HASKELL__ >= 611
import GHC.IO (unsafeDupablePerformIO)
#else
import GHC.IOBase (unsafeDupablePerformIO)
#endif
#else
import Data.Char (chr)
import System.IO.Unsafe (unsafePerformIO)
#endif
#ifdef __GLASGOW_HASKELL__
import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
#else
import Foreign.ForeignPtr (mallocForeignPtrBytes)
#endif
#ifdef __GLASGOW_HASKELL__
import GHC.ForeignPtr (ForeignPtr(ForeignPtr))
import GHC.Base (nullAddr#)
#else
import Foreign.Ptr (nullPtr)
#endif
#if __HUGS__
import Hugs.ForeignPtr (newForeignPtr_)
#elif __GLASGOW_HASKELL__<=604
import Foreign.ForeignPtr (newForeignPtr_)
#endif
-- CFILES stuff is Hugs only
{-# CFILES cbits/fpstring.c #-}
-- An alternative to Control.Exception (assert) for nhc98
#ifdef __NHC__
#define assert assertS "__FILE__ : __LINE__"
assertS :: String -> Bool -> a -> a
assertS _ True = id
assertS s False = error ("assertion failed at "++s)
#endif
-- -----------------------------------------------------------------------------
--
-- Useful macros, until we have bang patterns
--
#define STRICT1(f) f a | a `seq` False = undefined
#define STRICT2(f) f a b | a `seq` b `seq` False = undefined
#define STRICT3(f) f a b c | a `seq` b `seq` c `seq` False = undefined
#define STRICT4(f) f a b c d | a `seq` b `seq` c `seq` d `seq` False = undefined
#define STRICT5(f) f a b c d e | a `seq` b `seq` c `seq` d `seq` e `seq` False = undefined
-- -----------------------------------------------------------------------------
-- | A space-efficient representation of a Word8 vector, supporting many
-- efficient operations. A 'ByteString' contains 8-bit characters only.
--
-- Instances of Eq, Ord, Read, Show, Data, Typeable
--
data ByteString = PS {-# UNPACK #-} !(ForeignPtr Word8) -- payload
{-# UNPACK #-} !Int -- offset
{-# UNPACK #-} !Int -- length
-- LIQUID #if defined(__GLASGOW_HASKELL__)
-- LIQUID deriving (Data, Typeable)
-- LIQUID #endif
-- LIQUID WIERD CONSTANTS like
-- LIQUID (scc<CAF> Data.Typeable.Internal.mkTyCon)
-- LIQUID (scc<CAF> __word64 5047387852870479354))
-- LIQUID (scc<CAF> __word64 13413741352319211914))
-------------------------------------------------------------------------
-- LiquidHaskell Specifications -----------------------------------------
-------------------------------------------------------------------------
{-@ measure bLength :: ByteString -> Int
bLength (PS p o l) = l
@-}
{-@ measure bOffset :: ByteString -> Int
bOffset (PS p o l) = o
@-}
{-@ measure bPayload :: ByteString -> (ForeignPtr Word8)
bPayload (PS p o l) = p
@-}
{-@ predicate BSValid Payload Offset Length = (Offset + Length <= (fplen Payload)) @-}
{- predicate OkIndex B I = ((0 <= I) && (I <= (bLength B))) -}
{-@ predicate OkPLen N P = (N <= (plen P)) @-}
{-@ data ByteString [bLength]
= PS { payload :: (ForeignPtr Word8)
, offset :: {v: Nat | (v <= (fplen payload)) }
, length :: {v: Nat | (BSValid payload offset v) }
}
@-}
{-@ invariant {v:ByteString | 0 <= (bLength v)} @-}
{-@ type ByteStringSplit B = {v:[ByteString] | ((bLengths v) + (len v) - 1) = (bLength B) }
@-}
{-@ type ByteStringPair B = (ByteString, ByteString)<{\x1 x2 -> (bLength x1) + (bLength x2) = (bLength B)}>
@-}
{-@ measure bLengths :: [ByteString] -> Int
bLengths ([]) = 0
bLengths (x:xs) = (bLength x) + (bLengths xs)
@-}
{-@ type ByteStringN N = {v: ByteString | (bLength v) = N} @-}
{-@ type ByteStringNE = {v:ByteString | (bLength v) > 0} @-}
{-@ type ByteStringSZ B = {v:ByteString | (bLength v) = (bLength B)} @-}
{-@ type ByteStringLE B = {v:ByteString | (bLength v) <= (bLength B)} @-}
{-@ predicate SuffixPtr V N P = ((isNullPtr V) || ((NNLen V N P) && (NNBase V P))) @-}
{-@ predicate NNLen V N P = ((((plen P) - N) < (plen V)) && (plen V) <= (plen P)) @-}
{-@ predicate NNBase V P = ((pbase V) = (pbase P)) @-}
{-@ qualif EqFPLen(v: a, x: ForeignPtr b): v = (fplen x) @-}
{-@ qualif EqPLen(v: a, x: Ptr b): v = (plen x) @-}
{-@ qualif EqPLen(v:Ptr a, l:int): (plen v) = l @-}
{-@ qualif EqPLen(v: ForeignPtr a, x: Ptr b): (fplen v) = (plen x) @-}
{-@ qualif EqPLen(v: Ptr a, x: ForeignPtr b): (plen v) = (fplen x) @-}
{-@ qualif PValid(v: int, p: Ptr a): v <= (plen p) @-}
{-@ qualif PLLen(v:a, p:b) : (len v) <= (plen p) @-}
{-@ qualif FPLenPos(v: ForeignPtr a): 0 <= (fplen v) @-}
{-@ qualif PLenPos(v: Ptr a): 0 <= (plen v) @-}
{-@ qualif LTPLen(v: int, p:Ptr a): v < (plen p) @-}
{-@ ptrLen :: p:(PtrV a) -> {v:Nat | v = (plen p)} @-}
ptrLen :: Ptr a -> Int
ptrLen = undefined
-------------------------------------------------------------------------
instance Show ByteString where
showsPrec p ps r = showsPrec p (unpackWith w2c ps) r
-- LIQUID instance Read ByteString where
-- LIQUID readsPrec p str = [ (packWith c2w x, y) | (x, y) <- readsPrec p str ]
-- | /O(n)/ Converts a 'ByteString' to a '[a]', using a conversion function.
{-@ unpackWith :: (Word8 -> a) -> ByteString -> [a] @-}
unpackWith :: (Word8 -> a) -> ByteString -> [a]
unpackWith _ (PS _ _ 0) = []
unpackWith k (PS ps s l) = inlinePerformIO $ withForeignPtr ps $ \p ->
go (p `plusPtr` s) (l - 1) []
where
STRICT3(go)
go p 0 acc = peek p >>= \e -> return (k e : acc)
go p n acc = peekByteOff p n >>= \e -> go p (n-1) (k e : acc)
{-# INLINE unpackWith #-}
-- | /O(n)/ Convert a '[a]' into a 'ByteString' using some
-- conversion function
{-@ packWith :: (a -> Word8) -> [a] -> ByteString @-}
packWith :: (a -> Word8) -> [a] -> ByteString
packWith k str = unsafeCreate (length str) $ \p -> go p str
where
{-@ Decrease go 2 @-}
STRICT2(go)
go _ [] = return ()
go p (x:xs) = poke p (k x) >> go (p `plusPtr` 1) xs -- less space than pokeElemOff
{-# INLINE packWith #-}
------------------------------------------------------------------------
-- | The 0 pointer. Used to indicate the empty Bytestring.
{-@ assume nullForeignPtr :: {v: ForeignPtr Word8 | (fplen v) = 0} @-}
nullForeignPtr :: ForeignPtr Word8
#ifdef __GLASGOW_HASKELL__
nullForeignPtr = ForeignPtr nullAddr# undefined --TODO: should ForeignPtrContents be strict?
#else
nullForeignPtr = unsafePerformIO $ newForeignPtr_ nullPtr
{-# NOINLINE nullForeignPtr #-}
#endif
-- ---------------------------------------------------------------------
-- Low level constructors
-- | /O(1)/ Build a ByteString from a ForeignPtr.
--
-- If you do not need the offset parameter then you do should be using
-- 'Data.ByteString.Unsafe.unsafePackCStringLen' or
-- 'Data.ByteString.Unsafe.unsafePackCStringFinalizer' instead.
--
{-@ fromForeignPtr :: p:(ForeignPtr Word8)
-> o:{v:Nat | v <= (fplen p)}
-> l:{v:Nat | (BSValid p o v)}
-> ByteStringN l
@-}
fromForeignPtr :: ForeignPtr Word8
-> Int -- ^ Offset
-> Int -- ^ Length
-> ByteString
fromForeignPtr fp s l = PS fp s l
{-# INLINE fromForeignPtr #-}
-- | /O(1)/ Deconstruct a ForeignPtr from a ByteString
{-@ toForeignPtr :: b:ByteString
-> ( {v:(ForeignPtr Word8) | v = (bPayload b)}
, {v:Int | v = (bOffset b)}
, {v:Int | v = (bLength b)} )
@-}
toForeignPtr :: ByteString -> (ForeignPtr Word8, Int, Int) -- ^ (ptr, offset, length)
toForeignPtr (PS ps s l) = (ps, s, l)
{-# INLINE toForeignPtr #-}
-- | A way of creating ByteStrings outside the IO monad. The @Int@
-- argument gives the final size of the ByteString. Unlike
-- 'createAndTrim' the ByteString is not reallocated if the final size
-- is less than the estimated size.
{-@ unsafeCreate :: l:Nat -> ((PtrN Word8 l) -> IO ()) -> (ByteStringN l) @-}
unsafeCreate :: Int -> (Ptr Word8 -> IO ()) -> ByteString
unsafeCreate l f = unsafeDupablePerformIO (create l f)
{-# INLINE unsafeCreate #-}
#ifndef __GLASGOW_HASKELL__
-- for Hugs, NHC etc
unsafeDupablePerformIO :: IO a -> a
unsafeDupablePerformIO = unsafePerformIO
#endif
-- | Create ByteString of size @l@ and use action @f@ to fill it's contents.
{-@ create :: l:Nat -> ((PtrN Word8 l) -> IO ()) -> IO (ByteStringN l) @-}
create :: Int -> (Ptr Word8 -> IO ()) -> IO ByteString
create l f = do
fp <- mallocByteString l
withForeignPtr fp $ \p -> f p
return $! PS fp 0 l
{-# INLINE create #-}
-- | Given the maximum size needed and a function to make the contents
-- of a ByteString, createAndTrim makes the 'ByteString'. The generating
-- function is required to return the actual final size (<= the maximum
-- size), and the resulting byte array is realloced to this size.
--
-- createAndTrim is the main mechanism for creating custom, efficient
-- ByteString functions, using Haskell or C functions to fill the space.
{-@ createAndTrim :: l:Nat
-> ((PtrN Word8 l) -> IO {v:Nat | v <= l})
-> IO {v:ByteString | (bLength v) <= l}
@-}
createAndTrim :: Int -> (Ptr Word8 -> IO Int) -> IO ByteString
createAndTrim l f = do
fp <- mallocByteString l
withForeignPtr fp $ \p -> do
l' <- f p
if assert (l' <= l) $ l' >= l
then return $! PS fp 0 l
else create l' $ \p' -> memcpy p' p ({- LIQUID fromIntegral -} intCSize l')
{-# INLINE createAndTrim #-}
{-@ createAndTrim' :: l:Nat
-> ((PtrN Word8 l) -> IO ((Nat, Nat, a)<{\o v -> (v <= l - o)}, {\o l v -> true}>))
-> IO ({v:ByteString | (bLength v) <= l}, a)
@-}
createAndTrim' :: Int -> (Ptr Word8 -> IO (Int, Int, a)) -> IO (ByteString, a)
createAndTrim' l f = do
fp <- mallocByteString l
withForeignPtr fp $ \p -> do
(off, l', res) <- f p
if assert (l' <= l) $ l' >= l
then return $! (PS fp 0 l, res)
else do ps <- create l' $ \p' ->
memcpy p' (p `plusPtr` off) ({- LIQUID fromIntegral -} intCSize l')
return $! (ps, res)
-- LIQUID DUPLICATECODE
{-@ createAndTrimEQ :: l:Nat
-> ((PtrN Word8 l) -> IO ((Nat, {v:Nat | v=l}, a)<{\o v -> (v <= l - o)}, {\o l v -> true}>))
-> IO ({v:ByteString | (bLength v) = l}, a)
@-}
createAndTrimEQ :: Int -> (Ptr Word8 -> IO (Int, Int, a)) -> IO (ByteString, a)
createAndTrimEQ l f = do
fp <- mallocByteString l
withForeignPtr fp $ \p -> do
(off, l', res) <- f p
if assert (l' <= l) $ l' >= l
then return $! (PS fp 0 l, res)
else do ps <- create l' $ \p' ->
memcpy p' (p `plusPtr` off) ({- LIQUID fromIntegral -} intCSize l')
return $! (ps, res)
{-@ createAndTrimMEQ :: l:Nat
-> ((PtrN Word8 l)
-> IO ({v:(Nat, {v0:Nat | v0<=l}, Maybe a) |
(((tsnd v) <= (l-(tfst v)))
&& ((isJust (ttrd v)) => ((tsnd v)=l)))}))
-> IO ({v:ByteString | (bLength v) <= l}, Maybe a)<{\b m ->
((isJust m) => ((bLength b) = l))}>
@-}
createAndTrimMEQ :: Int -> (Ptr Word8 -> IO (Int, Int, Maybe a)) -> IO (ByteString, Maybe a)
createAndTrimMEQ l f = do
fp <- mallocByteString l
withForeignPtr fp $ \p -> do
(off, l', res) <- f p
if assert (l' <= l) $ l' >= l
then return $! (PS fp 0 l, res)
else do ps <- create l' $ \p' ->
memcpy p' (p `plusPtr` off) ({- LIQUID fromIntegral -} intCSize l')
return $! (ps, res)
{-@ measure tfst :: (a,b,c) -> a
tfst (a,b,c) = a
@-}
{-@ measure tsnd :: (a,b,c) -> b
tsnd (a,b,c) = b
@-}
{-@ measure ttrd :: (a,b,c) -> c
ttrd (a,b,c) = c
@-}
-- LIQUID CONSTRUCTIVE VERSION (Till we support pred-applications properly,
-- cf. tests/pos/cont2.hs
{-@ createAndTrim'' :: forall <p :: Int -> Prop>.
l:Nat<p>
-> ((PtrN Word8 l) -> IO ((Nat, Nat<p>, a)<{\o v -> (v <= l - o)}, {\o l v -> true}>))
-> IO ({v:Nat<p> | v <= l}, ByteString, a)<{\sz v -> (bLength v) = sz},{\o l v -> true}>
@-}
createAndTrim'' :: Int -> (Ptr Word8 -> IO (Int, Int, a)) -> IO (Int, ByteString, a)
createAndTrim'' l f = do
fp <- mallocByteString l
withForeignPtr fp $ \p -> do
(off, l', res) <- f p
if assert (l' <= l) $ l' >= l
then return $! (l, PS fp 0 l, res)
else do ps <- create l' $ \p' ->
memcpy p' (p `plusPtr` off) ({- LIQUID fromIntegral -} intCSize l')
return $! (l', ps, res)
-- | Wrapper of 'mallocForeignPtrBytes' with faster implementation for GHC
--
{-@ mallocByteString :: l:Nat -> IO (ForeignPtrN a l) @-}
mallocByteString :: Int -> IO (ForeignPtr a)
mallocByteString l = do
#ifdef __GLASGOW_HASKELL__
mallocPlainForeignPtrBytes l
#else
mallocForeignPtrBytes l
#endif
{-# INLINE mallocByteString #-}
------------------------------------------------------------------------
-- | Conversion between 'Word8' and 'Char'. Should compile to a no-op.
w2c :: Word8 -> Char
#if !defined(__GLASGOW_HASKELL__)
w2c = chr . fromIntegral
#else
w2c = unsafeChr . fromIntegral
#endif
{-# INLINE w2c #-}
-- | Unsafe conversion between 'Char' and 'Word8'. This is a no-op and
-- silently truncates to 8 bits Chars > '\255'. It is provided as
-- convenience for ByteString construction.
c2w :: Char -> Word8
c2w = fromIntegral . ord
{-# INLINE c2w #-}
-- | Selects words corresponding to white-space characters in the Latin-1 range
-- ordered by frequency.
isSpaceWord8 :: Word8 -> Bool
isSpaceWord8 w =
w == 0x20 ||
w == 0x0A || -- LF, \n
w == 0x09 || -- HT, \t
w == 0x0C || -- FF, \f
w == 0x0D || -- CR, \r
w == 0x0B || -- VT, \v
w == 0xA0 -- spotted by QC..
{-# INLINE isSpaceWord8 #-}
-- | Selects white-space characters in the Latin-1 range
isSpaceChar8 :: Char -> Bool
isSpaceChar8 c =
c == ' ' ||
c == '\t' ||
c == '\n' ||
c == '\r' ||
c == '\f' ||
c == '\v' ||
c == '\xa0'
{-# INLINE isSpaceChar8 #-}
------------------------------------------------------------------------
-- | Just like unsafePerformIO, but we inline it. Big performance gains as
-- it exposes lots of things to further inlining. /Very unsafe/. In
-- particular, you should do no memory allocation inside an
-- 'inlinePerformIO' block. On Hugs this is just @unsafePerformIO@.
--
{-# INLINE inlinePerformIO #-}
{-@ assume inlinePerformIO :: IO a -> a @-}
inlinePerformIO :: IO a -> a
#if defined(__GLASGOW_HASKELL__)
inlinePerformIO (IO m) = case m realWorld# of (# _, r #) -> r
#else
inlinePerformIO = unsafePerformIO
#endif
-- ---------------------------------------------------------------------
--
-- Standard C functions
--
-- LIQUID ANFTransform scope wierdness, see Internal0.hs
-- LIQUID
foreign import ccall unsafe "string.h strlen" c_strlen
:: CString -> IO CSize
{-@ assume c_strlen :: s:CString -> IO {v: CSize | ((0 <= v) && (v = (plen s)))} @-}
-- LIQUID: for some reason this foreign import causes an infinite loop...
-- foreign import ccall unsafe "static stdlib.h &free" c_free_finalizer
-- :: Ptr Word8 -> IO ()
c_free_finalizer = finalizerFree
foreign import ccall unsafe "string.h memchr" c_memchr
:: Ptr Word8 -> CInt -> CSize -> IO (Ptr Word8)
{-@ assume c_memchr :: p:(Ptr Word8) -> CInt -> n:{v:CSize| (0 <= v && v <= (plen p))} -> (IO {v:(Ptr Word8) | (SuffixPtr v n p)}) @-}
{-@ memchr :: p:(Ptr Word8) -> Word8 -> n:{v:CSize| (0 <= v && v <= (plen p))} -> (IO {v:(Ptr Word8) | (SuffixPtr v n p)}) @-}
memchr :: Ptr Word8 -> Word8 -> CSize -> IO (Ptr Word8)
memchr p w s = c_memchr p (fromIntegral w) s
foreign import ccall unsafe "string.h memcmp" memcmp
:: Ptr Word8 -> Ptr Word8 -> CSize -> IO CInt
{-@ assume memcmp :: p:(Ptr Word8) -> q:(Ptr Word8) -> {v:CSize | (v <= (plen p) && v <= (plen q)) } -> IO Foreign.C.Types.CInt @-}
foreign import ccall unsafe "string.h memcpy" c_memcpy
:: Ptr Word8 -> Ptr Word8 -> CSize -> IO (Ptr Word8)
{-@ assume
memcpy :: dst:(PtrV Word8)
-> src:(PtrV Word8)
-> size: {v:CSize| (v <= (plen src) && v <= (plen dst))}
-> IO ()
@-}
memcpy :: Ptr Word8 -> Ptr Word8 -> CSize -> IO ()
memcpy p q s = c_memcpy p q s >> return ()
{- liquidCanary :: x:Int -> {v: Int | v > x} @-}
liquidCanary :: Int -> Int
liquidCanary x = x - 1
{-
foreign import ccall unsafe "string.h memmove" c_memmove
:: Ptr Word8 -> Ptr Word8 -> CSize -> IO (Ptr Word8)
memmove :: Ptr Word8 -> Ptr Word8 -> CSize -> IO ()
memmove p q s = do c_memmove p q s
return ()
-}
foreign import ccall unsafe "string.h memset" c_memset
:: Ptr Word8 -> CInt -> CSize -> IO (Ptr Word8)
memset :: Ptr Word8 -> Word8 -> CSize -> IO (Ptr Word8)
memset p w s = c_memset p (fromIntegral w) s
-- ---------------------------------------------------------------------
--
-- Uses our C code
--
foreign import ccall unsafe "static fpstring.h fps_reverse" c_reverse
:: Ptr Word8 -> Ptr Word8 -> CULong -> IO ()
{-@ assume c_reverse :: dst:(PtrV Word8) -> src:(PtrV Word8) -> {v:CULong | ((OkPLen v src) && (OkPLen v dst)) } -> IO () @-}
foreign import ccall unsafe "static fpstring.h fps_intersperse" c_intersperse
:: Ptr Word8 -> Ptr Word8 -> CULong -> Word8 -> IO ()
{-@ assume c_intersperse :: dst:(Ptr Word8) -> src:(Ptr Word8) -> {v: CULong | ((OkPLen v src) && ((v+v-1) <= (plen dst)))} -> Word8 -> IO () @-}
foreign import ccall unsafe "static fpstring.h fps_maximum" c_maximum
:: Ptr Word8 -> CULong -> IO Word8
{-@ assume c_maximum :: p:(Ptr Word8) -> {v:CULong | (OkPLen v p)} -> IO Word8 @-}
foreign import ccall unsafe "static fpstring.h fps_minimum" c_minimum
:: Ptr Word8 -> CULong -> IO Word8
{-@ assume c_minimum :: p:(Ptr Word8) -> {v:CULong | (OkPLen v p)} -> IO Word8 @-}
foreign import ccall unsafe "static fpstring.h fps_count" c_count
:: Ptr Word8 -> CULong -> Word8 -> IO CULong
{-@ assume
c_count :: p:(Ptr Word8)
-> n:{v:CULong | (OkPLen v p)}
-> Word8
-> (IO {v:CULong | ((0 <= v) && (v <= n)) }) @-}
-- ---------------------------------------------------------------------
-- Internal GHC Haskell magic
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 611
foreign import ccall unsafe "__hscore_memcpy_src_off"
memcpy_ptr_baoff :: Ptr a -> RawBuffer -> CInt -> CSize -> IO (Ptr ())
#endif
| mightymoose/liquidhaskell | benchmarks/bytestring-0.9.2.1/Data/ByteString/Internal.hs | bsd-3-clause | 23,608 | 0 | 19 | 6,384 | 3,119 | 1,763 | 1,356 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
module SetOperations (benchmark) where
import Criterion.Main
import Data.List (partition)
benchmark :: ([Int] -> container) -> Bool -> [(String, container -> container -> container)] -> IO ()
benchmark fromList swap methods = do
defaultMain $ [ bench (method_str++"-"++input_str) $ whnf (method input1) input2 | (method_str, method) <- methods, (input_str, input1, input2) <- inputs ]
where
n, s, t :: Int
n = 100000
s {-small-} = n `div` 10
t {-tiny-} = round $ sqrt $ fromIntegral n
inputs = [ (mode_str, left, right)
| (mode_str, (left, right)) <- [ ("disj_nn", disj_nn), ("disj_ns", disj_ns), ("disj_nt", disj_nt)
, ("common_nn", common_nn), ("common_ns", common_ns), ("common_nt", common_nt)
, ("mix_nn", mix_nn), ("mix_ns", mix_ns), ("mix_nt", mix_nt)
, ("block_nn", block_nn), ("block_sn", block_ns)
]
, (mode_str, left, right) <- replicate 2 (mode_str, left, right) ++
replicate (if swap && take 4 mode_str /= "diff" && last mode_str /= last (init mode_str) then 2 else 0)
(init (init mode_str) ++ [last mode_str] ++ [last (init mode_str)], right, left)
]
all_n = fromList [1..n]
!disj_nn = seqPair $ (all_n, fromList [n+1..n+n])
!disj_ns = seqPair $ (all_n, fromList [n+1..n+s])
!disj_nt = seqPair $ (all_n, fromList [n+1..n+t])
!common_nn = seqPair $ (all_n, fromList [2,4..n])
!common_ns = seqPair $ (all_n, fromList [0,1+n`div`s..n])
!common_nt = seqPair $ (all_n, fromList [0,1+n`div`t..n])
!mix_nn = seqPair $ fromLists $ partition ((== 0) . (`mod` 2)) [1..n+n]
!mix_ns = seqPair $ fromLists $ partition ((== 0) . (`mod` (1 + n`div`s))) [1..s+n]
!mix_nt = seqPair $ fromLists $ partition ((== 0) . (`mod` (1 + n`div`t))) [1..t+n]
!block_nn = seqPair $ fromLists $ partition ((< t) . (`mod` (t * 2))) [1..n+n]
!block_ns = seqPair $ fromLists $ partition ((< t) . (`mod` (t * (1 + n`div`s)))) [1..s+n]
fromLists (xs, ys) = (fromList xs, fromList ys)
seqPair pair@(xs, ys) = xs `seq` ys `seq` pair
| DavidAlphaFox/ghc | libraries/containers/benchmarks/SetOperations/SetOperations.hs | bsd-3-clause | 2,329 | 0 | 18 | 691 | 1,019 | 579 | 440 | 33 | 2 |
{-# OPTIONS_GHC -fplugin RuleDefiningPlugin #-}
module T10420a where
| ezyang/ghc | testsuite/tests/plugins/T10420a.hs | bsd-3-clause | 69 | 0 | 2 | 8 | 5 | 4 | 1 | 2 | 0 |
-- Checks that the correct type is used checking the using clause of the group
{-# OPTIONS_GHC -XMonadComprehensions -XTransformListComp #-}
module ShouldFail where
import GHC.Exts( the )
import GHC.List
data Unorderable = Gnorf | Pinky | Brain
foo = [ GHC.List.length x
| x <- [Gnorf, Brain]
, then group using take 5
]
| sdiehl/ghc | testsuite/tests/typecheck/should_fail/mc21.hs | bsd-3-clause | 342 | 0 | 8 | 75 | 71 | 42 | 29 | 8 | 1 |
class A a where
op1 :: a
class B a where
op2 :: b -> b
class A a where
op3 :: a
| urbanslug/ghc | testsuite/tests/rename/should_fail/rnfail012.hs | bsd-3-clause | 86 | 0 | 7 | 29 | 47 | 23 | 24 | 6 | 0 |
{-# LANGUAGE TemplateHaskell, ParallelListComp #-}
module Main where
list = [ (x,y) | x <- [1..10], x `mod` 2 == 0 | y <- [2,6..50] ]
list' = $( [| [ (x,y) | x <- [1..10], x `mod` 2 == 0 | y <- [2,6..50] ] |] )
main = do putStrLn (show list)
putStrLn (show list')
putStrLn $ show (list == list') | siddhanathan/ghc | testsuite/tests/th/T8186.hs | bsd-3-clause | 319 | 1 | 11 | 86 | 122 | 66 | 56 | 7 | 1 |
-- | Internal module to `Dfterm3.Game.DwarfFortress`.
--
module Dfterm3.Game.DwarfFortress.Internal.Running
( DFPid
, DFState()
, newDFState
, allAliveInstances
, ProcureStatus(..)
, takeOldOrStartProcuring
, registerNew
, unregister )
where
import Data.Word
import Data.IORef
import Data.Maybe ( catMaybes )
import Control.Monad
import Control.Exception ( mask_ )
import Control.Concurrent.MVar
import qualified Data.ByteString as B
import qualified Data.Map as M
type DFPid = Word64
newtype DFState a = DFState (IORef (M.Map B.ByteString (DFStatus a)))
newDFState :: IO (DFState a)
newDFState = DFState `fmap` newIORef M.empty
data DFStatus a = Procuring (MVar a)
| Alive a
data ProcureStatus a = PleaseProcure (MVar a)
| AlreadyProcuring (MVar a)
allAliveInstances :: DFState a -> IO [a]
allAliveInstances (DFState vals) = do
insides <- readIORef vals
return $ catMaybes $ fmap mapping (M.elems insides)
where
mapping (Alive x) = Just x
mapping _ = Nothing
takeOldOrStartProcuring :: B.ByteString -> DFState a -> IO (ProcureStatus a)
takeOldOrStartProcuring key (DFState vals) = mask_ $ do
mvar <- newEmptyMVar
join $ atomicModifyIORef' vals $ \old ->
case M.lookup key old of
Nothing ->
( M.insert key (Procuring mvar) old
, return $ PleaseProcure mvar )
Just ( Alive x ) ->
( old, putMVar mvar x >> return (AlreadyProcuring mvar) )
Just ( Procuring mvar' ) ->
( old, return $ AlreadyProcuring mvar' )
registerNew :: B.ByteString -> DFState a -> a -> IO ()
registerNew key (DFState vals) val = mask_ $
join $ atomicModifyIORef' vals $ \old ->
case M.lookup key old of
Nothing ->
( M.insert key (Alive val) old, return () )
Just ( Alive _ ) ->
error $ "Same Dwarf Fortress ('" ++ show key ++ "') twice."
Just ( Procuring mvar ) ->
( M.insert key (Alive val) old
, putMVar mvar val )
unregister :: B.ByteString -> DFState a -> IO ()
unregister key (DFState vals) = mask_ $
atomicModifyIORef' vals $ \old ->
( M.delete key old, () )
| Noeda/dfterm3 | src/Dfterm3/Game/DwarfFortress/Internal/Running.hs | isc | 2,276 | 0 | 17 | 658 | 745 | 389 | 356 | 60 | 3 |
-- This example also depends on wai-digestive-functors
module Main (main) where
import Control.Applicative
import Data.Monoid
import Data.String (IsString, fromString)
import Data.Text (Text)
import Network.Wai (Application, Response(ResponseBuilder))
import Network.Wai.Util (stringHeaders')
import Network.Wai.Handler.Warp (run)
import Network.Wai.Digestive (bodyFormEnv_)
import Network.HTTP.Types (ok200)
import Text.Blaze.Html.Renderer.Utf8 (renderHtmlBuilder)
import Text.Blaze.XHtml5
import Text.Blaze.XHtml5.Attributes hiding (form, name)
import SimpleForm.Combined hiding (text)
import SimpleForm.Digestive.Combined
import SimpleForm.Render.XHTML5
s :: (IsString s) => String -> s
s = fromString
-- | Enumerable type for package categories
data Category = Web | Text | Math deriving (Bounded, Enum, Eq, Show, Read)
-- | The type of a Package (this is what our form will produce)
data Package = Package {
name :: Text,
category :: Category
} deriving (Show)
app :: Application
app req = do
-- Run the given form in the presence of params from the HTTP request body
-- Produces the 'Html' of the form, and also 'Maybe Package'
(html, pkg) <- postSimpleForm render (bodyFormEnv_ req) $ do
-- Add the input for name, and get the parser for the associated field
name' <- input_ (s"name") (Just . name)
-- Add the input for category, and get the parser for the associated field
-- The field will use 'SelectEnum' to generate the options automatically
-- from the enumerated type.
category' <- input_ (s"category") (Just . SelectEnum . category)
-- Build up the parser for 'Package' from the parsers for each field
return $ Package <$> name' <*> fmap unSelectEnum category'
-- Create a WAI 'Response' that shows the parse result and the form
return $ ResponseBuilder ok200 headers $ renderHtmlBuilder $ mconcat [
toHtml $ show $ pkg, -- Show parse result
form ! action (s "/") ! method (s"POST") $ html -- and form
]
where
headers = stringHeaders' [("Content-Type", "text/html; charset=utf-8")]
main :: IO ()
main = run 3000 app
| singpolyma/simple-form-haskell | examples/wai.hs | isc | 2,077 | 12 | 15 | 348 | 495 | 283 | 212 | 35 | 1 |
module Data.Core.Graph.Persistence
( PersistentGraph, persistGraph, loadGraph )
where
import Data.Core.Graph.PureCore
import Data.Core.Graph.NodeManager
import Data.Hashable
import qualified Data.IntMap.Strict as IM
import qualified Data.Vector.Unboxed as VU
data PersistentGraph k
= PersistentGraph
{ pg_nodeData :: NodeMap k
, pg_graphData :: [(Node, [Node])]
} deriving (Show, Eq)
persistGraph :: (Eq k, Hashable k) => NodeManager k -> Graph -> PersistentGraph k
persistGraph nodeManager graph =
PersistentGraph
{ pg_nodeData = getNodeMap nodeManager
, pg_graphData = map (\(k, vals) -> (k, VU.toList vals)) (IM.toList $ g_adj graph)
}
loadGraph :: (Eq k, Hashable k) => PersistentGraph k -> (NodeManager k, Graph)
loadGraph (PersistentGraph nodeData graphData) =
(initNodeManager nodeData, fromAdj graphData) | factisresearch/graph-core | src/Data/Core/Graph/Persistence.hs | mit | 851 | 0 | 12 | 142 | 271 | 157 | 114 | 20 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE UndecidableInstances #-}
module Betfair.APING.Types.MarketFilter
( MarketFilter(..)
, defaultMarketFilter
) where
import Betfair.APING.Types.MarketBettingType (MarketBettingType)
import Betfair.APING.Types.OrderStatus (OrderStatus)
import Betfair.APING.Types.TimeRange (TimeRange)
import Data.Aeson.TH (Options (omitNothingFields),
defaultOptions,
deriveJSON)
import Protolude
import Text.PrettyPrint.GenericPretty
data MarketFilter = MarketFilter
{ textQuery :: Maybe Text
, exchangeIds :: Maybe [Text]
, eventTypeIds :: Maybe [Text]
, eventIds :: Maybe [Text]
, competitionIds :: Maybe [Text]
, marketIds :: Maybe [Text]
, venues :: Maybe [Text]
, bspOnly :: Maybe Bool
, turnInPlayEnabled :: Maybe Bool
, inPlayOnly :: Maybe Bool
, marketBettingTypes :: [MarketBettingType]
, marketCountries :: Maybe [Text]
, marketTypeCodes :: Maybe [Text]
, marketStartTime :: Maybe TimeRange
, withOrders :: Maybe [OrderStatus]
} deriving (Eq, Show, Generic, Pretty)
defaultMarketFilter :: MarketFilter
defaultMarketFilter =
MarketFilter
{ textQuery = Nothing
, exchangeIds = Nothing
, eventTypeIds = Nothing
, eventIds = Nothing
, competitionIds = Nothing
, marketIds = Nothing
, venues = Nothing
, bspOnly = Nothing
, turnInPlayEnabled = Nothing
, inPlayOnly = Nothing
, marketBettingTypes = []
, marketCountries = Nothing
, marketTypeCodes = Nothing
, marketStartTime = Nothing
, withOrders = Nothing
}
-- this is what deriveDefault does anyway
-- instance Default MarketSort where def = FIRST_TO_START
-- $(deriveJSON id ''Record)
$(deriveJSON defaultOptions {omitNothingFields = True} ''MarketFilter)
| joe9/betfair-api | src/Betfair/APING/Types/MarketFilter.hs | mit | 2,176 | 0 | 10 | 566 | 413 | 257 | 156 | 55 | 1 |
--generateTwoSixSidedDiceThatValueSeven = [[dieOne, dieTwo] | dieOne <- [1..6], dieTwo <- [1..6], dieOne + dieTwo == 7]
generateTwoSixSidedDiceThatValueSeven = generateTwoDiceOfThatValue 6 7
generateTwoSixSidedDiceThatValue num = generateTwoDiceOfThatValue 6 num
--[[dieOne, dieTwo] | dieOne <- [1..6], dieTwo <- [1..6], dieOne + dieTwo == num]
generateTwoDiceOfThatValue sides num = [[dieOne, dieTwo] | dieOne <- [1..sides], dieTwo <- [1..sides], dieOne + dieTwo == num]
generateDiceOfThatValue numDice sides targetNum = [[dieOne, dieTwo] | dieOne <- [1..sides], dieTwo <- [1..sides], dieOne + dieTwo == targetNum]
--getDieValue side = die | die <- [1..sides]
--fun numDice sides targetNum = [possibleDice numDice sides | roll <- die, die <- (possibleDice numDice sides), (sum (possibleDice numDice sides)) == targetNum]
possibleDice 0 _ = []
possibleDice 1 sides = [1..sides]
possibleDice numDice sides = [1..sides] ++ (possibleDice (numDice - 1) sides)
--possibleDice (die:theDice) sides = [
--foo numDice sides targetNum = [ | roll <- die <- dice numDice sides, sum
bax = 1 : [] : 4 : [] : [] : 4 : 5 : []
--generateDiceOptions 2 6 7
--generateDiceOptions numDice numSide targetNumber = []
| pegurnee/2015-01-341 | projects/project3_mini_haskell/advanced.hs | mit | 1,200 | 0 | 12 | 183 | 250 | 135 | 115 | 8 | 1 |
{-# OPTIONS_GHC -Wall #-}
module LogAnalysis where
import Log
-- Exercise 1
parseMessage :: String -> LogMessage
parseMessage ('I':xs) = LogMessage Info (basicTimestamp xs) (message xs)
parseMessage ('W':xs) = LogMessage Warning (basicTimestamp xs) (message xs)
parseMessage ('E':xs) = LogMessage (Error (errorCode xs)) (errorTimestamp xs) (errorMessage xs)
parseMessage xs = Unknown xs
basicTimestamp :: String -> Int
basicTimestamp = read . head . words
errorTimestamp :: String -> Int
errorTimestamp = read . last . take 2 . words
errorCode :: String -> Int
errorCode = read . head . words
message :: String -> String
message = unwords . drop 1 . words
errorMessage :: String -> String
errorMessage = unwords . drop 2 . words
parse :: String -> [LogMessage]
parse xs = map parseMessage (lines xs)
-- Exercise 2
-- https://en.wikipedia.org/wiki/Tree_sort#Example used as
-- refence for pseudocode (ignoring haskell implementation
-- below it).
--
-- If `Ord` was implemented for `MessageTree`, this could
-- be neater by not needing to destructure the node to
-- grab the timestamp from it (or a separate function to
-- which to offload this).
insert :: LogMessage -> MessageTree -> MessageTree
insert mes Leaf = Node Leaf mes Leaf
insert (Unknown _) tree = tree
insert mes@(LogMessage _ time _) (Node ltree node@(LogMessage _ nodeTime _) rtree)
| time <= nodeTime = Node (insert mes ltree) node rtree
| otherwise = Node ltree node (insert mes rtree)
-- Exercise 3
build :: [LogMessage] -> MessageTree
build lst = build' lst Leaf
where
build' :: [LogMessage] -> MessageTree -> MessageTree
build' [] tree = tree
build' (x:xs) tree = build' xs (insert x tree)
-- Exercise 4
inOrder :: MessageTree -> [LogMessage]
inOrder Leaf = []
inOrder (Node ltree node rtree) =
inOrder ltree ++ [node] ++ inOrder rtree
-- Exercise 5
whatWentWrong :: [LogMessage] -> [String]
whatWentWrong [] = []
whatWentWrong xs =
map getLogMessage $ filter errorWithSeverity50OrGreater $ inOrder (build xs)
errorWithSeverity50OrGreater :: LogMessage -> Bool
errorWithSeverity50OrGreater (LogMessage (Error level) _ _)
| level >= 50 = True
| otherwise = False
errorWithSeverity50OrGreater _ = False
getLogMessage :: LogMessage -> String
getLogMessage (LogMessage _ _ mes) = mes
getLogMessage (Unknown mes) = mes
| slogsdon/haskell-exercises | cis194/LogAnalysis.hs | mit | 2,377 | 0 | 10 | 455 | 751 | 388 | 363 | 47 | 2 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.SVGScriptElement (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.SVGScriptElement
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.SVGScriptElement
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/SVGScriptElement.hs | mit | 361 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
module Lang.De.Base where
import Str
data Case = Nom | Acc | Dat | Gen deriving Eq
data Person = P1 | P2 | P3 deriving Eq
data Gender = Mas | Fem | Neu deriving Eq
data Number = Sing | Plur deriving Eq
data Formality = Formal | Informal deriving Eq
data InflType = Strong | Weak | Mixed deriving Eq
data Mood = Indicative | Imperative | Reported | Conditional deriving Eq
data Tense = Present | Past deriving Eq
-- data Voice = Active | Passive deriving Eq
-- NB: German doesn't grammatically encode any Aspect information.
data T = T -- translation term
{ tF :: Str -- foreign
, tE :: Str -- English
}
onTF :: (Str -> Str) -> T -> T
onTF f (T theTF theTE) = T (f theTF) theTE
| dancor/melang | src/Lang/De/Base.hs | mit | 702 | 0 | 8 | 165 | 210 | 128 | 82 | 15 | 1 |
{-# LANGUAGE RankNTypes, FlexibleContexts #-}
{-
Copyright (C) 2012-2017 Kacper Bak, Jimmy Liang, Michal Antkiewicz, Rafael Olaechea <http://gsd.uwaterloo.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
-- | Generates Alloy4.2 code for a Clafer model
module Language.Clafer.Generator.Alloy (genModule) where
import Control.Applicative
import Control.Monad.State
import Data.List
import Data.Maybe
import Prelude
import Language.Clafer.Common
import Language.Clafer.ClaferArgs
import Language.Clafer.Front.AbsClafer
import Language.Clafer.Front.LexClafer
import Language.Clafer.Generator.Concat
import Language.Clafer.Intermediate.Intclafer hiding (exp)
data GenEnv = GenEnv
{ claferargs :: ClaferArgs
, uidIClaferMap :: UIDIClaferMap
, forScopes :: String
} deriving (Show)
-- | Alloy code generation
genModule :: ClaferArgs -> (IModule, GEnv) -> [(UID, Integer)] -> [Token] -> (Result, [(Span, IrTrace)])
genModule claferargs' (imodule, genv) scopes otherTokens' = (flatten output, filter ((/= NoTrace) . snd) $ mapLineCol output)
where
genScopes :: [(UID, Integer)] -> String
genScopes [] = ""
genScopes scopes' = " but " ++ intercalate ", " (map (\ (uid', scope) -> show scope ++ " " ++ uid') scopes')
forScopes' = "for 1" ++ genScopes scopes
genEnv = GenEnv claferargs' (uidClaferMap genv) forScopes'
output = header genEnv otherTokens' +++ (cconcat $ map (genDeclaration genEnv) (_mDecls imodule))
header :: GenEnv -> [Token] -> Concat
header genEnv otherTokens' = CString $ unlines
[ "open util/integer"
, genAlloyEscapes otherTokens' ++ "pred show {}"
, if (validate $ claferargs genEnv)
then ""
else "run show " ++ forScopes genEnv
, ""]
genAlloyEscapes :: [Token] -> String
genAlloyEscapes otherTokens' = concat $ map printAlloyEscape otherTokens'
where
printAlloyEscape (PT _ (T_PosAlloy code)) = let
code' = fromJust $ stripPrefix "[alloy|" code
in
(take ((length code') - 2) code') ++ "\n"
printAlloyEscape _ = ""
-- 07th Mayo 2012 Rafael Olaechea
genDeclaration :: GenEnv -> IElement -> Concat
genDeclaration genEnv x = case x of
IEClafer clafer' -> (genClafer genEnv [] clafer') +++ (mkFact $ cconcat $ genSetUniquenessConstraint clafer')
IEConstraint True pexp -> mkFact $ genPExp genEnv [] pexp
IEConstraint False pexp -> mkAssert genEnv (genAssertName pexp) $ genPExp genEnv [] pexp
IEGoal _ _ -> CString ""
mkFact :: Concat -> Concat
mkFact x@(CString "") = x
mkFact xs = cconcat [CString "fact ", mkSet xs, CString "\n"]
genAssertName :: PExp -> Concat
genAssertName PExp{_inPos=(Span _ (Pos line _))} = CString $ "assertOnLine_" ++ show line
mkAssert :: GenEnv -> Concat -> Concat -> Concat
mkAssert _ _ x@(CString "") = x
mkAssert genEnv name xs = cconcat
[ CString "assert ", name, CString " "
, mkSet xs
, CString "\n"
, CString "check ", name, CString " "
, CString $ forScopes genEnv
, CString "\n\n"
]
mkSet :: Concat -> Concat
mkSet xs = cconcat [CString "{ ", xs, CString " }"]
showSet :: Concat -> [Concat] -> Concat
showSet delim xs = showSet' delim $ filterNull xs
where
showSet' _ [] = CString "{}"
showSet' delim' xs' = mkSet $ cintercalate delim' xs'
optShowSet :: [Concat] -> Concat
optShowSet [] = CString ""
optShowSet xs = CString "\n" +++ showSet (CString "\n ") xs
-- optimization: top level cardinalities
-- optimization: if only boolean parents, then set card is known
genClafer :: GenEnv -> [String] -> IClafer -> Concat
genClafer genEnv resPath clafer'
= (cunlines $ filterNull
[ cardFact
+++ claferDecl clafer' (
(showSet (CString "\n, ") $ genRelations genEnv clafer')
+++ (optShowSet $ filterNull $ genConstraints genEnv resPath clafer')
)
]
)
+++ CString "\n"
+++ children'
where
children' = cconcat $ filterNull $ map
(genClafer genEnv ((_uid clafer') : resPath)) $
getSubclafers $ _elements clafer'
cardFact
| null resPath && (null $ flatten $ genOptCard clafer') =
case genCard (_uid clafer') $ _card clafer' of
CString "set" -> CString ""
c -> mkFact c
| otherwise = CString ""
claferDecl :: IClafer -> Concat -> Concat
claferDecl c rest = cconcat
[ genOptCard c
, CString $ if _isAbstract c then "abstract " else ""
, CString "sig "
, Concat NoTrace [CString $ _uid c, genExtends $ _super c, CString "\n", rest]
]
where
genExtends Nothing = CString ""
genExtends (Just (PExp _ _ _ (IClaferId _ i _ _))) = CString " " +++ Concat NoTrace [CString $ "extends " ++ i]
-- todo: handle multiple inheritance
genExtends _ = CString ""
genOptCard :: IClafer -> Concat
genOptCard c
| glCard' `elem` ["lone", "one", "some"] = cardConcat (_uid c) False [CString glCard'] +++ (CString " ")
| otherwise = CString ""
where
glCard' = genIntervalCrude $ _glCard c
-- -----------------------------------------------------------------------------
-- overlapping inheritance is a new clafer with val (unlike only relation)
-- relations: overlapping inheritance (val rel), children
-- adds parent relation
-- 29/March/2012 Rafael Olaechea: ref is now prepended with clafer name to be able to refer to it from partial instances.
genRelations :: GenEnv -> IClafer -> [Concat]
genRelations genEnv c = maybeToList r ++ (map mkRel $ getSubclafers $ _elements c)
where
r = if isJust $ _reference c
then
Just $ Concat NoTrace [CString $ genRel (genRefName $ _uid c)
c {_card = Just (1, 1)} $
flatten $ refType genEnv c]
else
Nothing
mkRel c' = Concat NoTrace [CString $ genRel (genRelName $ _uid c') c' $ _uid c']
genRelName :: String -> String
genRelName name = "r_" ++ name
genRefName :: String -> String
genRefName name = name ++ "_ref"
genRel :: String -> IClafer -> String -> String
genRel name c rType = genAlloyRel name (genCardCrude $ _card c) rType'
where
rType' = if isPrimitive rType then "Int" else rType
genAlloyRel :: String -> String -> String -> String
genAlloyRel name card' rType = concat [name, " : ", card', " ", rType]
refType :: GenEnv -> IClafer -> Concat
refType genEnv c = fromMaybe (CString "") (((genType genEnv).getTarget) <$> (_ref <$> _reference c))
getTarget :: PExp -> PExp
getTarget x = case x of
PExp _ _ _ (IFunExp op' (_:pexp:_)) -> if op' == iJoin then pexp else x
_ -> x
genType :: GenEnv -> PExp -> Concat
genType genEnv x@(PExp _ _ _ y@(IClaferId _ _ _ _)) = genPExp genEnv []
x{_exp = y{_isTop = True}}
genType m x = genPExp m [] x
-- -----------------------------------------------------------------------------
-- constraints
-- parent + group constraints + reference + user constraints
-- a = NUMBER do all x : a | x = NUMBER (otherwise alloy sums a set)
genConstraints :: GenEnv -> [String] -> IClafer -> [Concat]
genConstraints genEnv resPath c
= genParentConst resPath c
: genGroupConst genEnv c
: genRefSubrelationConstriant (uidIClaferMap genEnv) c
{- genPathConst produces incorrect code for top-level clafers
abstract System
abstract Connection
connections -> Connection *
sig c0_connections
{ ref : one c0_Connection }
{ one @r_c0_connections.this
ref = (@r_c0_System.@r_c0_Connection) }
r_c0_System does not exist because System is top-level. The constraint is useless anyway, since all instances
of Connection are nested under all Systems anyway.
disabled code:
: genPathConst genEnv (if (noalloyruncommand $ claferargs genEnv) then (_uid c ++ "_ref") else "ref") resPath c
-}
: constraints
where
constraints = concatMap genConst $ _elements c
genConst x = case x of
IEConstraint True pexp -> [ genPExp genEnv (_uid c : resPath) pexp ]
IEConstraint False pexp -> [ CString "// Assertion " +++ (genAssertName pexp) +++ CString " ignored since nested assertions are not supported in Alloy.\n"]
IEClafer c' ->
(if genCardCrude (_card c') `elem` ["one", "lone", "some"]
then CString ""
else mkCard ({- do not use the genRelName as the constraint name -} _uid c') False (genRelName $ _uid c') $ fromJust (_card c')
)
: (genParentSubrelationConstriant (uidIClaferMap genEnv) c')
: (genSetUniquenessConstraint c')
IEGoal _ _ -> error "[bug] Alloy.getConst: should not be given a goal." -- This should never happen
genSetUniquenessConstraint :: IClafer -> [Concat]
genSetUniquenessConstraint c =
(case _reference c of
Just (IReference True _ _) ->
(case _card c of
Just (lb, ub) -> if (lb > 1 || ub > 1 || ub == -1)
then [ CString $ (
(case isTopLevel c of
False -> "all disj x, y : this.@" ++ (genRelName $ _uid c)
True -> " all disj x, y : " ++ (_uid c)))
++ " | (x.@" ++ genRefName (_uid c) ++ ") != (y.@" ++ genRefName (_uid c) ++ ") "
]
else []
_ -> [])
_ -> []
)
genParentSubrelationConstriant :: UIDIClaferMap -> IClafer -> Concat
genParentSubrelationConstriant uidIClaferMap' headClafer =
case match of
Nothing -> CString ""
Just NestedInheritanceMatch {
_superClafer = superClafer
} -> if (isProperNesting uidIClaferMap' match) && (not $ isTopLevel superClafer)
then CString $ concat
[ genRelName $ _uid headClafer
, " in "
, genRelName $ _uid superClafer
]
else CString ""
where
match = matchNestedInheritance uidIClaferMap' headClafer
-- See Common.NestedInheritanceMatch
genRefSubrelationConstriant :: UIDIClaferMap -> IClafer -> Concat
genRefSubrelationConstriant uidIClaferMap' headClafer =
if isJust $ _reference headClafer
then
case match of
Nothing -> CString ""
Just NestedInheritanceMatch
{ _superClafer = superClafer
, _superClafersTarget = superClafersTarget
} -> case (isProperRefinement uidIClaferMap' match, not $ null superClafersTarget) of
((True, True, True), True) -> CString $ concat
[ genRefName $ _uid headClafer
, " in "
, genRefName $ _uid superClafer
]
_ -> CString ""
else CString ""
where
match = matchNestedInheritance uidIClaferMap' headClafer
-- optimization: if only boolean features then the parent is unique
genParentConst :: [String] -> IClafer -> Concat
genParentConst [] _ = CString ""
genParentConst _ c = genOptParentConst c
genOptParentConst :: IClafer -> Concat
genOptParentConst c
| glCard' == "one" = CString ""
| glCard' == "lone" = Concat NoTrace [CString $ "one " ++ rel]
| otherwise = Concat NoTrace [CString $ "one @" ++ rel ++ ".this"]
-- eliminating problems with cyclic containment;
-- should be added to cases when cyclic containment occurs
-- , " && no iden & @", rel, " && no ~@", rel, " & @", rel]
where
rel = genRelName $ _uid c
glCard' = genIntervalCrude $ _glCard c
genGroupConst :: GenEnv -> IClafer -> Concat
genGroupConst genEnv clafer'
| _isAbstract clafer' || null children' || flatten card' == "" = CString ""
| otherwise = cconcat [CString "let children = ", brArg id $ CString children', CString" | ", card']
where
superHierarchy :: [IClafer]
superHierarchy = findHierarchy getSuper (uidIClaferMap genEnv) clafer'
children' = intercalate " + " $ map (genRelName._uid) $
getSubclafers $ concatMap _elements superHierarchy
card' = mkCard (_uid clafer') True "children" $ _interval $ fromJust $ _gcard $ clafer'
mkCard :: String -> Bool -> String -> (Integer, Integer) -> Concat
mkCard constraintName group' element' crd
| crd' == "set" || crd' == "" = CString ""
| crd' `elem` ["one", "lone", "some"] = CString $ crd' ++ " " ++ element'
| otherwise = interval'
where
interval' = genInterval constraintName group' element' crd
crd' = flatten $ interval'
{-
-- generates expression for references that point to expressions (not single clafers)
genPathConst :: GenEnv -> String -> [String] -> IClafer -> Concat
genPathConst genEnv name resPath c
| isRefPath (c ^. reference) = cconcat [CString name, CString " = ",
fromMaybe (error "genPathConst: impossible.") $
fmap ((brArg id).(genPExp genEnv resPath)) $
_ref <$> _reference c]
| otherwise = CString ""
isRefPath :: Maybe IReference -> Bool
isRefPath Nothing = False
isRefPath (Just IReference{_ref=s}) = not $ isSimplePath s
isSimplePath :: PExp -> Bool
isSimplePath (PExp _ _ _ (IClaferId _ _ _ _)) = True
isSimplePath (PExp _ _ _ (IFunExp op' _)) = op' == iUnion
isSimplePath _ = False
-}
-- -----------------------------------------------------------------------------
-- Not used?
-- genGCard element gcard = genInterval element $ interval $ fromJust gcard
genCard :: String -> Maybe Interval -> Concat
genCard element' crd = genInterval element' False element' $ fromJust crd
genCardCrude :: Maybe Interval -> String
genCardCrude crd = genIntervalCrude $ fromJust crd
genIntervalCrude :: Interval -> String
genIntervalCrude x = case x of
(1, 1) -> "one"
(0, 1) -> "lone"
(1, -1) -> "some"
_ -> "set"
genInterval :: String -> Bool -> String -> Interval -> Concat
genInterval constraintName group' element' x = case x of
(1, 1) -> cardConcat constraintName group' [CString "one"]
(0, 1) -> cardConcat constraintName group' [CString "lone"]
(1, -1) -> cardConcat constraintName group' [CString "some"]
(0, -1) -> CString "set" -- "set"
(n, exinteger) ->
case (s1, s2) of
(Just c1, Just c2) -> cconcat [c1, CString " and ", c2]
(Just c1, Nothing) -> c1
(Nothing, Just c2) -> c2
(Nothing, Nothing) -> undefined
where
s1 = if n == 0
then Nothing
else Just $ cardLowerConcat constraintName group' [CString $ concat [show n, " <= #", element']]
s2 =
do
result <- genExInteger element' x exinteger
return $ cardUpperConcat constraintName group' [CString result]
cardConcat :: String -> Bool -> [Concat] -> Concat
cardConcat constraintName = Concat . ExactCard constraintName
cardLowerConcat :: String -> Bool -> [Concat] -> Concat
cardLowerConcat constraintName = Concat . LowerCard constraintName
cardUpperConcat :: String -> Bool -> [Concat] -> Concat
cardUpperConcat constraintName = Concat . UpperCard constraintName
genExInteger :: String -> Interval -> Integer -> Maybe Result
genExInteger element' (y,z) x =
if (y==0 && z==0) then Just $ concat ["#", element', " = ", "0"] else
if x == -1 then Nothing else Just $ concat ["#", element', " <= ", show x]
-- -----------------------------------------------------------------------------
-- Generate code for logical expressions
genPExp :: GenEnv -> [String] -> PExp -> Concat
genPExp genEnv resPath x = genPExp' genEnv resPath $ adjustPExp resPath x
genPExp' :: GenEnv -> [String] -> PExp -> Concat
genPExp' genEnv resPath (PExp iType' pid' pos exp') = case exp' of
IDeclPExp q d pexp -> Concat (IrPExp pid') $
[ CString $ genQuant q, CString " "
, cintercalate (CString ", ") $ map (genDecl genEnv resPath) d
, CString $ optBar d, genPExp' genEnv resPath pexp]
where
optBar [] = ""
optBar _ = " | "
IClaferId _ "integer" _ _ -> CString "Int"
IClaferId _ "int" _ _ -> CString "Int"
IClaferId _ "string" _ _ -> CString "Int"
IClaferId _ "dref" _ _ -> CString $ "@" ++ getTClaferUID iType' ++ "_ref"
where
getTClaferUID (Just TMap{_so = TClafer{_hi = [u]}}) = u
getTClaferUID (Just TMap{_so = TClafer{_hi = (u:_)}}) = u
getTClaferUID t = error $ "[bug] Alloy.genPExp'.getTClaferUID: unknown type: " ++ show t
IClaferId _ sid istop _ -> CString $
if head sid == '~'
then sid
else case iType' of
Just TInteger -> vsident
Just TDouble -> vsident
Just TReal -> vsident
Just TString -> vsident
_ -> sid'
where
sid' = (if istop then "" else '@' : genRelName "") ++ sid
vsident = sid' ++ ".@" ++ genRefName (if sid == "this" then head resPath else sid)
IFunExp _ _ -> case exp'' of
IFunExp _ _ -> genIFunExp pid' genEnv resPath exp''
_ -> genPExp' genEnv resPath $ PExp iType' pid' pos exp''
where
exp'' = transformExp exp'
IInt n -> CString $ show n
IDouble _ -> error "no double numbers allowed"
IReal _ -> error "no real numbers allowed"
IStr _ -> error "no strings allowed"
-- 3-May-2012 Rafael Olaechea.
-- Removed transfromation from x = -2 to x = (0-2) as this creates problem with partial instances.
-- See http://gsd.uwaterloo.ca:8888/question/461/new-translation-of-negative-number-x-into-0-x-is.
transformExp :: IExp -> IExp
transformExp (IFunExp op' (e1:_))
| op' == iMin = IFunExp iMul [PExp (_iType e1) "" noSpan $ IInt (-1), e1]
transformExp x@(IFunExp op' exps'@(e1:e2:_))
| op' == iXor = IFunExp iNot [PExp (Just TBoolean) "" noSpan (IFunExp iIff exps')]
| op' == iJoin && isClaferName' e1 && isClaferName' e2 &&
getClaferName e1 == thisIdent && head (getClaferName e2) == '~' =
IFunExp op' [e1{_iType = Just $ TClafer []}, e2]
| otherwise = x
transformExp x = x
genIFunExp :: String -> GenEnv -> [String] -> IExp -> Concat
genIFunExp pid' genEnv resPath (IFunExp "min" [exp']) = Concat (IrPExp pid') $ (CString "min[") : (genPExp' genEnv resPath exp') : [CString "]"]
genIFunExp pid' genEnv resPath (IFunExp "max" [exp']) = Concat (IrPExp pid') $ (CString "max[") : (genPExp' genEnv resPath exp') : [CString "]"]
-- ignore navigation from the root
genIFunExp _ genEnv resPath (IFunExp "." [PExp{_exp=IClaferId{_sident="root"}}, exp2]) = genPExp' genEnv resPath exp2
genIFunExp pid' genEnv resPath (IFunExp op' exps')
| op' == iSumSet = genIFunExp pid' genEnv resPath (IFunExp iSumSet' [(removeright (head exps')), (getRight $ head exps')])
| op' == iSumSet' = Concat (IrPExp pid') $ intl exps'' (map CString $ genOp iSumSet)
| otherwise = Concat (IrPExp pid') $ intl exps'' (map CString $ genOp op')
where
iSumSet' = "sum'"
intl
| op' == iSumSet' = flip interleave
| op' `elem` arithBinOps && length exps' == 2 = interleave
| otherwise = \xs ys -> reverse $ interleave (reverse xs) (reverse ys)
exps'' = map (optBrArg genEnv resPath) exps'
genIFunExp _ _ _ x = error $ "[bug] Alloy.genIFunExp: expecting a IFunExp, instead got: " ++ show x--This should never happen
optBrArg :: GenEnv -> [String] -> PExp -> Concat
optBrArg genEnv resPath x = brFun (genPExp' genEnv resPath) x
where
brFun = case x of
PExp _ _ _ IClaferId{} -> ($)
PExp _ _ _ (IInt _) -> ($)
_ -> brArg
interleave :: [Concat] -> [Concat] -> [Concat]
interleave [] [] = []
interleave (x:xs) [] = x:xs
interleave [] (x:xs) = x:xs
interleave (x:xs) ys = x : interleave ys xs
brArg :: (a -> Concat) -> a -> Concat
brArg f arg = cconcat [CString "(", f arg, CString ")"]
genOp :: String -> [String]
genOp op'
| op' == iPlus = [".plus[", "]"]
| op' == iSub = [".minus[", "]"]
| op' == iSumSet = ["sum temp : "," | temp."]
| op' == iProdSet = ["prod temp : "," | temp."]
| op' `elem` unOps = [op']
| op' == iPlus = [".add[", "]"]
| op' == iSub = [".sub[", "]"]
| op' == iMul = [".mul[", "]"]
| op' == iDiv = [".div[", "]"]
| op' == iRem = [".rem[", "]"]
| op' `elem` logBinOps ++ relBinOps ++ arithBinOps = [" " ++ op' ++ " "]
| op' == iUnion = [" + "]
| op' == iDifference = [" - "]
| op' == iIntersection = [" & "]
| op' == iDomain = [" <: "]
| op' == iRange = [" :> "]
| op' == iJoin = ["."]
| op' == iIfThenElse = [" => ", " else "]
genOp op' = error $ "[bug] Alloy.genOp: Unmatched operator: " ++ op'
-- adjust parent
adjustPExp :: [String] -> PExp -> PExp
adjustPExp resPath (PExp t pid' pos x) = PExp t pid' pos $ adjustIExp resPath x
adjustIExp :: [String] -> IExp -> IExp
adjustIExp resPath x = case x of
IDeclPExp q d pexp -> IDeclPExp q d $ adjustPExp resPath pexp
IFunExp op' exps' -> adjNav $ IFunExp op' $ map adjExps exps'
where
(adjNav, adjExps) = if op' == iJoin then (aNav, id)
else (id, adjustPExp resPath)
IClaferId{} -> aNav x
_ -> x
where
aNav = fst.(adjustNav resPath)
adjustNav :: [String] -> IExp -> (IExp, [String])
adjustNav resPath x@(IFunExp op' (pexp0:pexp:_))
| op' == iJoin = (IFunExp iJoin
[pexp0{_exp = iexp0},
pexp{_exp = iexp}], path')
| otherwise = (x, resPath)
where
(iexp0, path) = adjustNav resPath (_exp pexp0)
(iexp, path') = adjustNav path (_exp pexp)
adjustNav resPath x@(IClaferId _ id' _ _)
| id' == parentIdent = (x{_sident = "~@" ++ (genRelName $ head resPath)}, tail resPath)
| otherwise = (x, resPath)
adjustNav _ _ = error "Function adjustNav Expect a IFunExp or IClaferID as one of it's argument but it was given a differnt IExp" --This should never happen
genQuant :: IQuant -> String
genQuant x = case x of
INo -> "no"
ILone -> "lone"
IOne -> "one"
ISome -> "some"
IAll -> "all"
genDecl :: GenEnv -> [String] -> IDecl -> Concat
genDecl genEnv resPath x = case x of
IDecl disj locids pexp -> cconcat [CString $ genDisj disj, CString " ",
CString $ intercalate ", " locids, CString " : ", genPExp genEnv resPath pexp]
genDisj :: Bool -> String
genDisj True = "disj"
genDisj False = ""
-- mapping line/columns between Clafer and Alloy code
data AlloyEnv = AlloyEnv {
lineCol :: (LineNo, ColNo),
mapping :: [(Span, IrTrace)]
} deriving (Eq,Show)
mapLineCol :: Concat -> [(Span, IrTrace)]
mapLineCol code = mapping $ execState (mapLineCol' code) (AlloyEnv (firstLine, firstCol) [])
addCode :: MonadState AlloyEnv m => String -> m ()
addCode str = modify (\s -> s {lineCol = lineno (lineCol s) str})
mapLineCol' :: MonadState AlloyEnv m => Concat -> m ()
mapLineCol' (CString str) = addCode str
mapLineCol' c@(Concat srcPos' n) = do
posStart <- gets lineCol
_ <- mapM mapLineCol' n
posEnd <- gets lineCol
{-
- Alloy only counts inner parenthesis as part of the constraint, but not outer parenthesis.
- ex1. the constraint looks like this in the file
- (constraint a) <=> (constraint b)
- But the actual constraint in the API is
- constraint a) <=> (constraint b
-
- ex2. the constraint looks like this in the file
- (((#((this.@r_c2_Finger).@r_c3_Pinky)).add[(#((this.@r_c2_Finger).@r_c4_Index))]).add[(#((this.@r_c2_Finger).@r_c5_Middle))]) = 0
- But the actual constraint in the API is
- #((this.@r_c2_Finger).@r_c3_Pinky)).add[(#((this.@r_c2_Finger).@r_c4_Index))]).add[(#((this.@r_c2_Finger).@r_c5_Middle))]) = 0
-
- Seems unintuitive since the brackets are now unbalanced but that's how they work in Alloy. The next
- few lines of code is counting the beginning and ending parenthesis's and subtracting them from the
- positions in the map file.
- Same is true for square brackets.
- This next little snippet is rather inefficient since we are retraversing the Concat's to flatten.
- But it's the simplest and correct solution I can think of right now.
-}
let flat = flatten c
raiseStart = countLeading "([" flat
deductEnd = -(countTrailing ")]" flat)
modify (\s -> s {mapping = (Span (uncurry Pos $ posStart `addColumn` raiseStart) (uncurry Pos $ posEnd `addColumn` deductEnd), srcPos') : (mapping s)})
addColumn :: Interval -> Integer -> Interval
addColumn (x, y) c = (x, y + c)
countLeading :: String -> String -> Integer
countLeading c xs = toInteger $ length $ takeWhile (`elem` c) xs
countTrailing :: String -> String -> Integer
countTrailing c xs = countLeading c (reverse xs)
lineno :: (Integer, ColNo) -> String -> (Integer, ColNo)
lineno (l, c) str = (l + newLines, (if newLines > 0 then firstCol else c) + newCol)
where
newLines = toInteger $ length $ filter (== '\n') str
newCol = toInteger $ length $ takeWhile (/= '\n') $ reverse str
firstCol :: ColNo
firstCol = 1 :: ColNo
firstLine :: LineNo
firstLine = 1 :: LineNo
removeright :: PExp -> PExp
removeright (PExp _ _ _ (IFunExp _ (x : (PExp _ _ _ IClaferId{}) : _))) = x
removeright (PExp _ _ _ (IFunExp _ (x : (PExp _ _ _ (IInt _ )) : _))) = x
removeright (PExp _ _ _ (IFunExp _ (x : (PExp _ _ _ (IStr _ )) : _))) = x
removeright (PExp _ _ _ (IFunExp _ (x : (PExp _ _ _ (IDouble _ )) : _))) = x
removeright (PExp t id' pos (IFunExp o (x1:x2:xs))) = PExp t id' pos (IFunExp o (x1:(removeright x2):xs))
removeright x@PExp{} = error $ "[bug] AlloyGenerator.removeright: expects a PExp with a IFunExp inside but was given: " ++ show x --This should never happen
getRight :: PExp -> PExp
getRight (PExp _ _ _ (IFunExp _ (_:x:_))) = getRight x
getRight p = p
| gsdlab/clafer | src/Language/Clafer/Generator/Alloy.hs | mit | 26,639 | 1 | 29 | 6,593 | 7,856 | 4,041 | 3,815 | 427 | 22 |
{-# LANGUAGE QuasiQuotes, TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Yesod.Auth.Email
( -- * Plugin
authEmail
, YesodAuthEmail (..)
, EmailCreds (..)
, saltPass
-- * Routes
, loginR
, registerR
, setpassR
, isValidPass
) where
import Network.Mail.Mime (randomString)
import Yesod.Auth
import System.Random
import Control.Monad (when)
import Control.Applicative ((<$>), (<*>))
import Data.Digest.Pure.MD5
import qualified Data.Text.Lazy as T
import qualified Data.Text as TS
import Data.Text.Lazy.Encoding (encodeUtf8)
import Data.Text (Text)
import qualified Crypto.PasswordStore as PS
import qualified Data.Text.Encoding as DTE
import Yesod.Form
import Yesod.Handler
import Yesod.Content
import Yesod.Core (PathPiece, fromPathPiece, whamlet, defaultLayout, setTitleI, toPathPiece)
import Control.Monad.IO.Class (liftIO)
import qualified Yesod.Auth.Message as Msg
loginR, registerR, setpassR :: AuthRoute
loginR = PluginR "email" ["login"]
registerR = PluginR "email" ["register"]
setpassR = PluginR "email" ["set-password"]
verify :: Text -> Text -> AuthRoute -- FIXME
verify eid verkey = PluginR "email" ["verify", eid, verkey]
type Email = Text
type VerKey = Text
type VerUrl = Text
type SaltedPass = Text
type VerStatus = Bool
-- | Data stored in a database for each e-mail address.
data EmailCreds m = EmailCreds
{ emailCredsId :: AuthEmailId m
, emailCredsAuthId :: Maybe (AuthId m)
, emailCredsStatus :: VerStatus
, emailCredsVerkey :: Maybe VerKey
}
class (YesodAuth m, PathPiece (AuthEmailId m)) => YesodAuthEmail m where
type AuthEmailId m
addUnverified :: Email -> VerKey -> GHandler Auth m (AuthEmailId m)
sendVerifyEmail :: Email -> VerKey -> VerUrl -> GHandler Auth m ()
getVerifyKey :: AuthEmailId m -> GHandler Auth m (Maybe VerKey)
setVerifyKey :: AuthEmailId m -> VerKey -> GHandler Auth m ()
verifyAccount :: AuthEmailId m -> GHandler Auth m (Maybe (AuthId m))
getPassword :: AuthId m -> GHandler Auth m (Maybe SaltedPass)
setPassword :: AuthId m -> SaltedPass -> GHandler Auth m ()
getEmailCreds :: Email -> GHandler Auth m (Maybe (EmailCreds m))
getEmail :: AuthEmailId m -> GHandler Auth m (Maybe Email)
-- | Generate a random alphanumeric string.
randomKey :: m -> IO Text
randomKey _ = do
stdgen <- newStdGen
return $ TS.pack $ fst $ randomString 10 stdgen
authEmail :: YesodAuthEmail m => AuthPlugin m
authEmail =
AuthPlugin "email" dispatch $ \tm ->
[whamlet|
$newline never
<form method="post" action="@{tm loginR}">
<table>
<tr>
<th>_{Msg.Email}
<td>
<input type="email" name="email">
<tr>
<th>_{Msg.Password}
<td>
<input type="password" name="password">
<tr>
<td colspan="2">
<input type="submit" value=_{Msg.LoginViaEmail}>
<a href="@{tm registerR}">I don't have an account
|]
where
dispatch "GET" ["register"] = getRegisterR >>= sendResponse
dispatch "POST" ["register"] = postRegisterR >>= sendResponse
dispatch "GET" ["verify", eid, verkey] =
case fromPathPiece eid of
Nothing -> notFound
Just eid' -> getVerifyR eid' verkey >>= sendResponse
dispatch "POST" ["login"] = postLoginR >>= sendResponse
dispatch "GET" ["set-password"] = getPasswordR >>= sendResponse
dispatch "POST" ["set-password"] = postPasswordR >>= sendResponse
dispatch _ _ = notFound
getRegisterR :: YesodAuthEmail master => GHandler Auth master RepHtml
getRegisterR = do
toMaster <- getRouteToMaster
defaultLayout $ do
setTitleI Msg.RegisterLong
[whamlet|
$newline never
<p>_{Msg.EnterEmail}
<form method="post" action="@{toMaster registerR}">
<label for="email">_{Msg.Email}
<input type="email" name="email" width="150">
<input type="submit" value=_{Msg.Register}>
|]
postRegisterR :: YesodAuthEmail master => GHandler Auth master RepHtml
postRegisterR = do
y <- getYesod
email <- runInputPost $ ireq emailField "email"
mecreds <- getEmailCreds email
(lid, verKey) <-
case mecreds of
Just (EmailCreds lid _ _ (Just key)) -> return (lid, key)
Just (EmailCreds lid _ _ Nothing) -> do
key <- liftIO $ randomKey y
setVerifyKey lid key
return (lid, key)
Nothing -> do
key <- liftIO $ randomKey y
lid <- addUnverified email key
return (lid, key)
render <- getUrlRender
tm <- getRouteToMaster
let verUrl = render $ tm $ verify (toPathPiece lid) verKey
sendVerifyEmail email verKey verUrl
defaultLayout $ do
setTitleI Msg.ConfirmationEmailSentTitle
[whamlet|
$newline never
<p>_{Msg.ConfirmationEmailSent email}
|]
getVerifyR :: YesodAuthEmail m
=> AuthEmailId m -> Text -> GHandler Auth m RepHtml
getVerifyR lid key = do
realKey <- getVerifyKey lid
memail <- getEmail lid
case (realKey == Just key, memail) of
(True, Just email) -> do
muid <- verifyAccount lid
case muid of
Nothing -> return ()
Just _uid -> do
setCreds False $ Creds "email" email [("verifiedEmail", email)] -- FIXME uid?
toMaster <- getRouteToMaster
setMessageI Msg.AddressVerified
redirect $ toMaster setpassR
_ -> return ()
defaultLayout $ do
setTitleI Msg.InvalidKey
[whamlet|
$newline never
<p>_{Msg.InvalidKey}
|]
postLoginR :: YesodAuthEmail master => GHandler Auth master ()
postLoginR = do
(email, pass) <- runInputPost $ (,)
<$> ireq emailField "email"
<*> ireq textField "password"
mecreds <- getEmailCreds email
maid <-
case (mecreds >>= emailCredsAuthId, fmap emailCredsStatus mecreds) of
(Just aid, Just True) -> do
mrealpass <- getPassword aid
case mrealpass of
Nothing -> return Nothing
Just realpass -> return $
if isValidPass pass realpass
then Just aid
else Nothing
_ -> return Nothing
case maid of
Just _aid ->
setCreds True $ Creds "email" email [("verifiedEmail", email)] -- FIXME aid?
Nothing -> do
setMessageI Msg.InvalidEmailPass
toMaster <- getRouteToMaster
redirect $ toMaster LoginR
getPasswordR :: YesodAuthEmail master => GHandler Auth master RepHtml
getPasswordR = do
toMaster <- getRouteToMaster
maid <- maybeAuthId
case maid of
Just _ -> return ()
Nothing -> do
setMessageI Msg.BadSetPass
redirect $ toMaster LoginR
defaultLayout $ do
setTitleI Msg.SetPassTitle
[whamlet|
$newline never
<h3>_{Msg.SetPass}
<form method="post" action="@{toMaster setpassR}">
<table>
<tr>
<th>_{Msg.NewPass}
<td>
<input type="password" name="new">
<tr>
<th>_{Msg.ConfirmPass}
<td>
<input type="password" name="confirm">
<tr>
<td colspan="2">
<input type="submit" value="_{Msg.SetPassTitle}">
|]
postPasswordR :: YesodAuthEmail master => GHandler Auth master ()
postPasswordR = do
(new, confirm) <- runInputPost $ (,)
<$> ireq textField "new"
<*> ireq textField "confirm"
toMaster <- getRouteToMaster
y <- getYesod
when (new /= confirm) $ do
setMessageI Msg.PassMismatch
redirect $ toMaster setpassR
maid <- maybeAuthId
aid <- case maid of
Nothing -> do
setMessageI Msg.BadSetPass
redirect $ toMaster LoginR
Just aid -> return aid
salted <- liftIO $ saltPass new
setPassword aid salted
setMessageI Msg.PassUpdated
redirect $ loginDest y
saltLength :: Int
saltLength = 5
-- | Salt a password with a randomly generated salt.
saltPass :: Text -> IO Text
saltPass = fmap DTE.decodeUtf8
. flip PS.makePassword 12
. DTE.encodeUtf8
saltPass' :: String -> String -> String
saltPass' salt pass =
salt ++ show (md5 $ fromString $ salt ++ pass)
where
fromString = encodeUtf8 . T.pack
isValidPass :: Text -- ^ cleartext password
-> SaltedPass -- ^ salted password
-> Bool
isValidPass ct salted =
PS.verifyPassword (DTE.encodeUtf8 ct) (DTE.encodeUtf8 salted) || isValidPass' ct salted
isValidPass' :: Text -- ^ cleartext password
-> SaltedPass -- ^ salted password
-> Bool
isValidPass' clear' salted' =
let salt = take saltLength salted
in salted == saltPass' salt clear
where
clear = TS.unpack clear'
salted = TS.unpack salted'
| piyush-kurur/yesod | yesod-auth/Yesod/Auth/Email.hs | mit | 9,063 | 0 | 20 | 2,588 | 2,244 | 1,141 | 1,103 | 203 | 8 |
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Examples.RedBlue
Description : Predefined network: redblue.
Copyright : (c) Julien Schmaltz 2015
Predefined network: redblue.
-}
module Examples.RedBlue (redblue) where
import Madl.Network
import Examples.TypesAndFunctions
import Utils.Text
-- | Network redblue. The well-known red-blue example
redblue :: Bool -> MadlNetwork
redblue dl = mkNetwork (NSpec components channels ports) where
src0 = Source "src0" req
src1 = Source "src1" rsp
fork = Fork "fork"
merge0 = Merge "merge0"
queue0 = Queue "queue0" 2
queue1 = Queue "queue1" 2
queue2 = Queue "queue2" 2
switch0 = Switch "switch0" (if dl then [isRsp, isReq] else [isReq,isRsp])
switch1 = Switch "switch1" [isReq,isRsp]
join0 = ControlJoin "join0"
join1 = ControlJoin "join1"
sink0 = Sink "sink0"
sink1 = Sink "sink1"
src0_merge0 = "src0_merge0"
src1_merge0 = "src1_merge0"
merge0_queue0 = "merge0_queue0"
queue0_fork = "queue0_fork"
fork_queue1 = "fork_queue1"
fork_queue2 = "fork_queue2"
queue2_switch0 = "queue2_switch0"
queue1_switch1 = "queue1_switch1"
switch1_join1 = "switch1_join1"
switch1_join0 = "switch1_join0"
switch0_join1 = "switch0_join1"
switch0_join0 = "switch0_join0"
join0_sink0 = "join0_sink0"
join1_sink1 = "join1_sink1"
src0_o = ("src0" , "src0_merge0")
src1_o = ("src1" , "src1_merge0")
merge0_a = ("src0_merge0" , "merge0")
merge0_b = ("src1_merge0" , "merge0")
merge0_o = ("merge0" , "merge0_queue0")
queue0_i = ("merge0_queue0" , "queue0")
queue0_o = ("queue0" , "queue0_fork")
fork_i = ("queue0_fork" , "fork")
fork_a = ("fork" , "fork_queue1")
fork_b = ("fork" , "fork_queue2")
queue1_i = ("fork_queue1" , "queue1")
queue2_i = ("fork_queue2" , "queue2")
queue1_o = ("queue1" , "queue1_switch1")
queue2_o = ("queue2" , "queue2_switch0")
switch0_i = ("queue2_switch0", "switch0")
switch0_a = ("switch0" , "switch0_join1")
switch0_b = ("switch0" , "switch0_join0")
switch1_i = ("queue1_switch1", "switch1")
switch1_a = ("switch1" , "switch1_join1")
swicth1_b = ("switch1" , "switch1_join0")
join1_a = ("switch0_join1" , "join1")
join1_b = ("switch1_join1" , "join1")
join1_o = ("join1" , "join1_sink1")
join0_a = ("switch0_join0" , "join0")
join0_b = ("switch1_join0" , "join0")
join0_o = ("join0" , "join0_sink0")
sink0_i = ("join0_sink0" , "sink0")
sink1_i = ("join1_sink1" , "sink1")
components =
map C [src0, src1, fork, merge0, queue0, queue1, queue2, switch0, switch1, join0, join1, sink0, sink1]
channels =
map Channel [src0_merge0, src1_merge0, merge0_queue0, queue0_fork, fork_queue1, fork_queue2, queue2_switch0, queue1_switch1, switch1_join1, switch1_join0, switch0_join1, switch0_join0, join0_sink0, join1_sink1]
ports :: [(Text, Text)]
ports = [ src0_o, src1_o, merge0_a, merge0_b, merge0_o, queue0_i, queue0_o, fork_i, fork_a, fork_b, queue1_i, queue2_i, queue1_o, queue2_o, switch0_i, switch0_a, switch0_b, switch1_i, switch1_a, swicth1_b, join1_a, join1_b, join1_o, join0_a, join0_b, join0_o, sink0_i, sink1_i] | julienschmaltz/madl | examples/Examples/RedBlue.hs | mit | 3,515 | 0 | 10 | 930 | 790 | 483 | 307 | 68 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Y2021.M04.D01.Exercise where
import Network.HTTP.Req
{--
Hi. Good morning, all.
Today's Haskell problem. We're going to get some data from a web endpoint.
The GET examples for Network.HTTP.Req have you got to httpbin.org and get
some random bytes.
Now, I'm not SAYING you have to use the Req library. In fact, what I'm SAYING
is this: use whatever library you like to do the task. That task?
Go to httpbin.org/bytes/5?seed=100 and get five random byte and display
their values here.
--}
fiveRandomBytes :: IO ()
fiveRandomBytes = undefined
{--
NOW, if you DO want to use the Req example in the documentation to do this,
I'm not going to stop you (trans.: please do use the documentation).
--}
-- The 'fun' part -------------------------------------------------------
{--
Okay, here's where the fun begins.
If you go to a bad URL, the Req library defaults to throwing an error, but
today's Haskell exercise doesn't want you to do that. Instead, what I'd like
you to do is this: go to a wrong URL, and if that fails (or, if it doesn't
succeed, to put it another way), then, instead, display some helpful message
to your client, like: "Website not found. Would you like to play a game of
chess?"
For, we all know that the WHOPR beat the Big Mac.
And global thermonuclear war is less fun that chess.
*ahem* So, instead of going to the above URL, go, instead to
https://httpbin.org/sed/4?sedes=mustard
to get that big, ol' 404 both you and I are cravin'
... and NOT throw an exception, but instead prints out a User Friendly Message.
--}
whopr :: IO ()
whopr = undefined -- "beat the big mac."
| geophf/1HaskellADay | exercises/HAD/Y2021/M04/D01/Exercise.hs | mit | 1,650 | 0 | 6 | 300 | 50 | 32 | 18 | 7 | 1 |
{-# LANGUAGE TupleSections #-}
module Y2016.M11.D15.Solution where
import Control.Applicative
import Control.Monad
import Data.Monoid
-- below import available from 1HaskellADay repository
import Control.Logic.Frege
import Y2016.M11.D14.Exercise
{--
It's a question of unification.
Yesterday, we had a 'simple' logic puzzle. A conundrum arose, however, when
the value AMY also happened to be the same person as (Person DaughterInLaw).
How can we show these two things are equal?
Well, structurally, they are not, so to equate them would be a major twist
on the Eq-instance and then have possibly major consequences.
So, ick!
But SCIENCE to the rescue.
There is a thing in logical programming called unification. That does not
solve our problem at all, but if we look through the problem through a logic
lens we can see that we can use unification with a different structure
If we redeclare Person to be
Person (Maybe Name) Role
then we take a definition of unification to be 'Nothing unifies with a Just-
value and is promoted to that Just-value,' then we no longer strain at
redefining equality.
So, let's look at some simple rules for a simply unifier.
1. Just x unifies with Just y if x == y
2. Nothing unifies with Just x IN THE UNIFICATION MONAD (monad? applicative?)
3. Nothing unifies with Nothing
1. and 3. are simple enough. What about that 2.?
Today's Haskell problem: define simple (not occurs-checking) unification for
the Maybe-type.
--}
data Unity x = U x | Fail
deriving (Eq, Show)
instance Functor Unity where
fmap f Fail = Fail
fmap f (U x) = U (f x)
instance Applicative Unity where
pure = U
U f <*> U x = U (f x)
_ <*> _ = Fail
instance Monad Unity where
return = U
Fail >>= f = Fail
(U x) >>= f = f x
instance {-- Monoid x => --} Monoid (Unity x) where
mempty = Fail
Fail `mappend` u2 = Fail
_ `mappend` Fail = Fail
U x `mappend` U y = U x -- (x `mappend` y)
-- does requiring x to be monoidal simplify the monoidal definition?
-- does requiring x to be monoidal complicate the monoidal Unity-use?
-- ... yeah, I'm relaxing the monoidal constraint on the funked-value
-- which complicates the monoid definition of Unity with a conceit that
-- first is preferable
instance Alternative Unity where
empty = Fail
Fail <|> u2 = u2
u1 <|> _ = u1
instance MonadPlus Unity where
mzero = Fail
Fail `mplus` u2 = u2
u1 `mplus` _ = u1
unify :: (Eq a, MonadPlus m, Monoid (m (Maybe a))) =>
Maybe a -> Maybe a -> m (Maybe a)
unify ans@(Just x) (Just y) = x == y -| return ans
unify Nothing x = return x
unify x _ = return x
-- hint: does it 'work' when unification fails because Just 3 /= Just 4?
{-- let's see:
*Y2016.M11.D15.Solution> unify (Just 3) (Just 4) :: Unity (Maybe Int)
Fail
*Y2016.M11.D15.Solution> unify (Just "Amy") Nothing :: Unity (Maybe String)
U (Just "Amy")
*Y2016.M11.D15.Solution> unify (Just 3) (Just 3) :: Unity (Maybe Int)
U (Just 3)
*Y2016.M11.D15.Solution> unify Nothing (Just 3) :: Unity (Maybe Int)
U (Just 3)
Yup. Looks good.
--}
-- Exercises: unify (or don't unify) the following. How would you go about it?
type Name = String
data Human = Pers (Maybe Name) (Maybe Role)
deriving (Eq, Show)
roles :: [Role]
roles = [Husband, Mother, DaughterInLaw, Sister]
toUnify :: [(Human, Human)]
-- actually, the argument runs thus:
toUnify = map (Pers (Just "Amy") (Just DaughterInLaw),)
(map (Pers Nothing . Just) roles)
-- and the we can match anybody else with anybody else:
-- ++ [(Pers Nothing (Just x), Pers Nothing (Just y)) | x <- roles, y <- roles]
{-- not this:
toUnify = [(Pers x y, Pers a b) | x <- [Nothing, Just "Amy"],
a <- [Nothing, Just "Amy"],
y <- [Husband, Mother, DaughterInLaw, Sister],
b <- [Husband, Mother, DaughterInLaw, Sister]]
--}
{--
The problem of Amy: Amy's role changes, based on her relationship to the person
compared. To her mother-in-law, she is a daughter-in-law. To her husband, she
is a wife. To her daughter, she is a mother. Hm.
PEOPLE ARE COMPLICATED AND HARD THINGS!
(I just learned this, today ... yes.)
--}
unifyPeeps :: Human -> Human -> Unity Human
unifyPeeps (Pers n1 r1) (Pers n2 r2) =
liftA2 Pers (unify n1 n2) (unify r1 r2)
-- *Y2016.M11.D15.Solution> map (uncurry unifyPeeps) toUnify ~>
-- [Fail,Fail,U (Pers (Just "Amy") (Just DaughterInLaw)),Fail]
| geophf/1HaskellADay | exercises/HAD/Y2016/M11/D15/Solution.hs | mit | 4,481 | 0 | 10 | 1,000 | 674 | 359 | 315 | 49 | 1 |
-- PrettyJSON.hs
-- Prettify module provides the text, double, string functions.
import SimpleJSON
import Prettify
import Numeric (showHex)
renderJValue :: JValue -> Doc
renderJValue (JBool True) = text "true"
renderJValue (JBool False) = text "false"
renderJValue JNull = text "null"
renderJValue (JNumber num) = double num
renderJValue (JString str) = string str
string :: String -> Doc
string = enclose '"' '"' . hcat . map oneChar
enclose :: Char -> Char -> Doc -> Doc
enclose left right x = char left <> x <> char right
-- lookup looks for keys in list of tuples
oneChar :: Char -> Doc
oneChar c = case lookup c simpleEscapes of
Just r -> text r
otherwise -> char c
-- Nothing | mustEscape c -> hexEscape c
-- | otherwise -> char c
-- where mustEscape c = c < ' ' || c == '\x7f' || c > '\xff'
-- zipWith f (a:as) (b:bs) = f a b : zipWith as bs
simpleEscapes :: [(Char, [Char])]
simpleEscapes = zipWith ch "\b\n\f\r\t\\\"/" "bnfrt\\\"/"
where ch a b = (a, ['\\', b])
hcat = undefined
-- hexEscape = undefined
-- smallHex :: Int -> Doc
-- smallHex x = text "\\u"
-- <> text (replicate (4 - length h) '0')
-- <> text h
-- where h = showHex x ""
| gitrookie/functionalcode | code/Haskell/jsonparser/PrettyJSON.hs | mit | 1,194 | 0 | 8 | 267 | 294 | 156 | 138 | 21 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-streamspecification.html
module Stratosphere.ResourceProperties.DynamoDBTableStreamSpecification where
import Stratosphere.ResourceImports
import Stratosphere.Types
-- | Full data type definition for DynamoDBTableStreamSpecification. See
-- 'dynamoDBTableStreamSpecification' for a more convenient constructor.
data DynamoDBTableStreamSpecification =
DynamoDBTableStreamSpecification
{ _dynamoDBTableStreamSpecificationStreamViewType :: Val StreamViewType
} deriving (Show, Eq)
instance ToJSON DynamoDBTableStreamSpecification where
toJSON DynamoDBTableStreamSpecification{..} =
object $
catMaybes
[ (Just . ("StreamViewType",) . toJSON) _dynamoDBTableStreamSpecificationStreamViewType
]
-- | Constructor for 'DynamoDBTableStreamSpecification' containing required
-- fields as arguments.
dynamoDBTableStreamSpecification
:: Val StreamViewType -- ^ 'ddbtssStreamViewType'
-> DynamoDBTableStreamSpecification
dynamoDBTableStreamSpecification streamViewTypearg =
DynamoDBTableStreamSpecification
{ _dynamoDBTableStreamSpecificationStreamViewType = streamViewTypearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-streamspecification.html#cfn-dynamodb-streamspecification-streamviewtype
ddbtssStreamViewType :: Lens' DynamoDBTableStreamSpecification (Val StreamViewType)
ddbtssStreamViewType = lens _dynamoDBTableStreamSpecificationStreamViewType (\s a -> s { _dynamoDBTableStreamSpecificationStreamViewType = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/DynamoDBTableStreamSpecification.hs | mit | 1,716 | 0 | 13 | 165 | 179 | 103 | 76 | 24 | 1 |
{-# LANGUAGE QuasiQuotes #-}
module ALangUtilsSpec where
import Ohua.Prelude
import Test.Hspec
import Ohua.ALang.Lang
import Ohua.ALang.Util (lambdaLifting)
import Ohua.Test (embedALang)
-- substitute' :: Binding -> Expression -> Expression -> Expression
-- substitute' var val = lrPostwalkExpr f
-- where
-- f (Var (Local v)) | var == v = val
-- f e = e
simpleLift = [embedALang| \a -> some/sfn a c |]
expectedSimpleLift = ([embedALang| \a c_0 -> some/sfn a c_0 |], ["c"])
simpleLiftWithLet = [embedALang| \a -> let b = some/sfn a c in b |]
expectedSimpleLiftWithLet =
([embedALang| \a c_0 -> let b = some/sfn a c_0 in b |], ["c"])
moreComplexExpr =
[embedALang| \a b ->
let c = some/computation a d
in if c
then something.on.true/branch b e
else something.on.false/branch f
|]
expectedMoreComplexExpr =
( [embedALang| \a b d_0 e_0 f_0 ->
let c = some/computation a d_0
in if c
then something.on.true/branch b e_0
else something.on.false/branch f_0
|]
, ["d", "e", "f"])
liftLambda expr expected =
(runSilentLoggingT $ runFromExpr def lambdaLifting expr) >>=
((`shouldBe` expected) .
(fromRight ([embedALang| some.failure/happened |], [])))
utilsSpec :: Spec
utilsSpec
-- describe "substitute with postwalk" $ do
-- it "substitutes a single var" $
-- substitute' "v" "testval" "v" `shouldBe` "testval"
-- it "substitutes a complicated expression" $
-- let toSubBinding = "h"
-- toSub = Var $ Local toSubBinding
-- subVal = "result" `Apply` "e"
-- e =
-- Let "x" toSub $
-- Let "v" (toSub `Apply` "c") $
-- Let "q" (Lambda "g" ("some/func" `Apply` toSub))
-- "q"
--
-- e1 =
-- Let "x" subVal $
-- Let "v" (subVal `Apply` "c") $
-- Let "q" (Lambda "g" ("some/func" `Apply` subVal))
-- "q"
-- in substitute' toSubBinding subVal e `shouldBe` e1
--
-- it "does not recurse indefinitely" $
-- substitute' "h" "h" "h" `shouldBe` "h"
= do
describe "lambda lifting" $ do
it "lambda lift single free var in function application" $
liftLambda simpleLift expectedSimpleLift
it
"lambda lift single free var in function application (with let binding)" $
liftLambda simpleLiftWithLet expectedSimpleLiftWithLet
it "a more complex expression with conditionals" $
liftLambda moreComplexExpr expectedMoreComplexExpr
spec :: Spec
spec = utilsSpec
| ohua-dev/ohua-core | tests/src/ALangUtilsSpec.hs | epl-1.0 | 3,030 | 0 | 11 | 1,156 | 290 | 187 | 103 | 34 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Number.Wert where
class Num b => Wert a b where
wert :: a -> b
class Num b => Wert_at a b where
wert_at :: Int -> a -> b
| Erdwolf/autotool-bonn | src/Number/Wert.hs | gpl-2.0 | 181 | 0 | 8 | 49 | 65 | 33 | 32 | 6 | 0 |
-- This file is part of economy.
--
-- economy is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- economy is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with economy. If not, see <http://www.gnu.org/licenses/>.
module Main where
import Month
import Economy
import System.FilePath
import System.Directory
import Options.Applicative
import qualified Data.ByteString.Lazy as B
import Data.Monoid
data Config = Config { dataFilename :: FilePath
, withTags :: [Tag]
, withoutTags :: [Tag]
, subcommand :: SubCommand}
data SubCommand = ShowMonth ShowMonthOptions | ShowYear
data ShowMonthOptions = ShowMonthOptions { showMonthCmdMonth :: Month }
configParser :: FilePath -> Month -> Parser Config
configParser defaultFilePath currentMonth = Config
<$> strOption ( long "file"
<> short 'f'
<> metavar "FILE"
<> value defaultFilePath
<> help ("the file to load data from")
<> showDefault)
<*> many (strOption ( long "with"
<> metavar "TAG"
<> help "Only consider entries with tag TAG"))
<*> many (strOption ( long "without"
<> metavar "TAG"
<> help "Only consider entries without tag TAG"))
<*> subcommandParser
where
subcommandParser :: Parser SubCommand
subcommandParser = subparser ( command "month" (info (helper <*> showMonthParser) (progDesc "Show details for a month"))
<> command "year" (info (helper <*> showYearParser) (progDesc "Show the whole year"))
)
showMonthParser :: Parser SubCommand
showMonthParser = ShowMonth <$> showMonthOptionsParser
showMonthOptionsParser :: Parser ShowMonthOptions
showMonthOptionsParser = ShowMonthOptions <$> argument auto (metavar "MONTH" <> value currentMonth)
showYearParser :: Parser SubCommand
showYearParser = pure ShowYear
fromFile :: Config -> IO Economy
fromFile config = do
datafileContent <- B.readFile $ dataFilename config
let myIncomeFilters = (map incomeWithTag (withTags config)) ++ (map incomeWithoutTag (withoutTags config))
let myExpenseFilters = (map expenseWithTag (withTags config)) ++ (map expenseWithoutTag (withoutTags config))
let decodeOptions = defaultDecodeOptions { expenseFilters = myExpenseFilters, incomeFilters = myIncomeFilters}
case decodeEconomy decodeOptions datafileContent of
Left err -> fail err
Right economy -> return economy
run :: Economy -> SubCommand -> IO ()
run economy (ShowMonth options) = detailsOfMonth economy (showMonthCmdMonth options)
run economy ShowYear = detailsOfYear economy
getDefaultFilePath :: IO FilePath
getDefaultFilePath = do
home <- getHomeDirectory
return $ home </> ".config" </> "economy.json"
main :: IO ()
main = do
defaultFilePath <- getDefaultFilePath
currentMonth <- getCurrentMonth
config <- execParser $ info (helper <*> configParser defaultFilePath currentMonth) fullDesc
economy <- fromFile config
run economy (subcommand config)
| rootmos/economy | src/Main.hs | gpl-3.0 | 3,734 | 0 | 16 | 981 | 759 | 388 | 371 | 61 | 2 |
-- |
-- Module : HSParedit.Types
-- Copyright : (c) Mateusz Kowalczyk 2013
-- License : GPL-3
--
-- Maintainer : fuuzetsu@fuuzetsu.co.uk
-- Stability : experimental
-- Portability : portable
module HSParedit.Types where
data Code = CodeSymbol | RoundNode | SquareNode | StringNode
| SymbolChar Char | TopLevel deriving Eq
instance Show Code where
show CodeSymbol = "CodeSymbol"
show RoundNode = "RoundNode"
show SquareNode = "SquareNode"
show (SymbolChar c) = [c]
show StringNode = "StringNode"
show TopLevel = "TopLevel"
| Fuuzetsu/hs-paredit | src/HSParedit/Types.hs | gpl-3.0 | 573 | 0 | 8 | 130 | 106 | 62 | 44 | 10 | 0 |
module Problem028 (answer) where
answer :: Int
answer = 1 + sum (take ((s-1)*2) $ pick [2..])
where s = 1001
-- pick number on diagonals means taking 1 number every 2n
-- n ranging from 0 to (s-1)/2 with s the side of the square
pick :: [Int] -> [Int]
pick = go 1 1 4
where
go _ _ _ [] = undefined
go n nRemain totalRemain (x:xs)
| totalRemain == 0 = go (n+1) (2*n) 4 xs
| nRemain == 0 = x : go n (2*n-1) (totalRemain-1) xs
| otherwise = go n (nRemain-1) totalRemain xs
| geekingfrog/project-euler | Problem028.hs | gpl-3.0 | 502 | 0 | 13 | 132 | 233 | 122 | 111 | 11 | 2 |
x // y = do
a <- x
b <- y
if b == 0
then Nothing
else Just (a/b)
soma x y = do
a <- x
b <- y
return (a+b)
total x y = let
one = return 1
r1 = return x
r2 = return y
in one // (soma (one // r1) (one // r2))
| zambonin/UFSC-INE5416 | docs/monads/ine5416_r10.hs | gpl-3.0 | 264 | 0 | 11 | 118 | 154 | 74 | 80 | -1 | -1 |
{-| Module : PatternMatch
License : GPL
Maintainer : helium@cs.uu.nl
Stability : experimental
Portability : portable
-}
module Helium.CodeGeneration.PatternMatch(patternToCore, patternsToCore, nextClauseId, freshIds) where
import qualified Lvm.Core.Expr as Core
import Helium.Syntax.UHA_Syntax
import Helium.Syntax.UHA_Utils
import Helium.Syntax.UHA_Range
import Lvm.Common.Id
import Data.Char
import Helium.Utils.Utils
import Helium.CodeGeneration.CoreUtils
patternsToCore :: [(Id, Pattern)] -> Core.Expr -> Core.Expr
patternsToCore nps continue = fst (patternsToCore' nps continue 0)
patternsToCore' :: [(Id, Pattern)] -> Core.Expr -> Int -> (Core.Expr, Int)
patternsToCore' [] continue nr = (continue, nr)
patternsToCore' (np:nps) continue nr =
let (expr, nr') = patternsToCore' nps continue nr
in patternToCore' np expr nr'
patternToCore :: (Id, Pattern) -> Core.Expr -> Core.Expr
patternToCore np continue = fst (patternToCore' np continue 0)
withNr :: a -> b -> (b, a)
withNr nr e = (e, nr)
patternToCore' :: (Id, Pattern) -> Core.Expr -> Int -> (Core.Expr, Int)
patternToCore' (name, pat) continue nr =
case pat of
-- let x = _u1 in ...
Pattern_Variable _ n -> withNr nr $
if name == wildcardId || name == idFromName n then
continue
else
let_ (idFromName n) (Core.Var name) continue
-- case _u1 of C _l1 _l2 -> ...
-- _ -> _next
Pattern_Constructor _ n ps ->
let
(ids, nr') =
if all isSimple ps then
(map getIdOfSimplePattern ps, nr)
else
freshIds' "l$" nr (length ps)
(expr, nr'') =
patternsToCore' (zip ids ps) continue nr'
in withNr nr'' $
case_ name
[ Core.Alt
(Core.PatCon (Core.ConId (idFromName n)) ids)
expr
]
-- case _u1 of _l1 : _l2 -> ...
-- _ -> _next
Pattern_InfixConstructor _ p1 n p2 ->
let ie = internalError "PatternMatch" "patternToCore'" "shouldn't look at range"
in patternToCore' (name, Pattern_Constructor ie n [p1, p2]) continue nr
Pattern_Parenthesized _ p ->
patternToCore' (name, p) continue nr
-- let n = _u1 in ...
Pattern_As _ n p ->
let (expr, nr') = patternToCore' (name, p) continue nr
in withNr nr' $
let_
(idFromName n) (Core.Var name)
expr
Pattern_Wildcard _ -> withNr nr continue
-- case _u1 of 42 -> ...
-- _ -> _next
Pattern_Literal _ l ->
case l of
Literal_Int _ i -> withNr nr $
case_ name [ Core.Alt (Core.PatLit (Core.LitInt (read i))) continue ]
Literal_Char _ c -> withNr nr $
case_ name
[ Core.Alt
(Core.PatLit
(Core.LitInt (ord (read ("'" ++ c ++ "'"))))
)
continue
]
Literal_Float _ f -> withNr nr $
if_ (var "$primEqFloat" `app_` float f `app_` Core.Var name)
continue
(Core.Var nextClauseId)
-- !!! if we would have MATCHFLOAT instruction it could be:
-- case_ name [ Core.Alt (Core.PatLit (Core.LitDouble (read f))) continue ]
Literal_String _ s ->
patternToCore'
( name
, Pattern_List noRange
(map (Pattern_Literal noRange . Literal_Int noRange . show . ord) characters)
)
continue
nr
where
characters = read ("\"" ++ s ++ "\"") :: String
Pattern_List _ ps ->
patternToCore' (name, expandPatList ps) continue nr
Pattern_Tuple _ ps ->
let
(ids, nr') =
if all isSimple ps then
(map getIdOfSimplePattern ps, nr)
else
freshIds' "l$" nr (length ps)
(expr, nr'') =
patternsToCore' (zip ids ps) continue nr'
in withNr nr'' $
case_ name
[ Core.Alt
(Core.PatCon (Core.ConTag 0 (length ps)) ids)
expr
]
Pattern_Negate _ (Literal_Int r v) ->
patternToCore'
(name, Pattern_Literal r (Literal_Int r neg))
continue
nr
where
neg = show (-(read v :: Int))
Pattern_Negate _ (Literal_Float r v) ->
patternToCore'
(name, Pattern_Literal r (Literal_Float r neg))
continue
nr
where
neg = show (-(read v :: Float))
Pattern_NegateFloat _ (Literal_Float r v) ->
patternToCore'
(name, Pattern_Literal r (Literal_Float r neg))
continue
nr
where
neg = show (-(read v :: Float))
-- ~p ====>
-- let x = case _u1 of p -> x
-- y = case _u1 of p -> y (for each var in p)
-- in continue
Pattern_Irrefutable _ p ->
let vars = map idFromName (patternVars p)
in withNr nr $ foldr
(\v r -> let_ v (patternToCore (name, p) (Core.Var v)) r)
continue
vars
_ -> internalError "PatternMatch" "patternToCore'" "unknown pattern kind"
-- [1, 2, 3] ==> 1 : (2 : (3 : [] ) )
expandPatList :: [Pattern] -> Pattern
expandPatList [] =
Pattern_Constructor noRange (Name_Special noRange [] [] "[]") [] -- !!!Name
expandPatList (p:ps) =
Pattern_InfixConstructor
noRange
p
(Name_Identifier noRange [] [] ":") -- !!!Name
(expandPatList ps)
isSimple :: Pattern -> Bool
isSimple p =
case p of
Pattern_Variable _ _ -> True
Pattern_Wildcard _ -> True
_ -> False
getIdOfSimplePattern :: Pattern -> Id
getIdOfSimplePattern p =
case p of
Pattern_Variable _ n -> idFromName n
Pattern_Wildcard _ -> wildcardId
_ -> internalError "PatternMatch" "getIdOfSimplePattern" "not a simple pattern"
freshIds :: String -> Int -> [Id]
freshIds prefix number = fst (freshIds' prefix 0 number)
freshIds' :: String -> Int -> Int -> ([Id], Int)
freshIds' prefix start number =
( take number [ idFromString (prefix ++ show i) | i <- [start..] ]
, number + start
)
nextClauseAlternative :: Core.Alt
nextClauseAlternative =
Core.Alt Core.PatDefault (Core.Var nextClauseId)
wildcardId, nextClauseId :: Id
( wildcardId : nextClauseId : [] ) = map idFromString ["_", "nextClause$"]
case_ :: Id -> [Core.Alt] -> Core.Expr
case_ ident alts =
Core.Let
(Core.Strict (Core.Bind ident (Core.Var ident))) -- let! id = id in
(Core.Match ident (alts++[nextClauseAlternative])) -- match id { alt; ...; alt; _ -> _nextClause }
| Helium4Haskell/helium | src/Helium/CodeGeneration/PatternMatch.hs | gpl-3.0 | 7,609 | 0 | 25 | 3,084 | 1,977 | 1,021 | 956 | 151 | 20 |
{-# LANGUAGE DeriveFunctor #-}
module FractalComonad where
import Control.Comonad
import Control.Applicative
data Layer a = Layer a
deriving (Show, Read, Eq, Functor)
instance Comonad Layer where
-- duplicate :: w a -> w (w a)
duplicate (Layer l) = Layer (Layer l)
-- extract :: w a -> a
extract (Layer l) = l
checkComLaws1 = (extract . duplicate $ cantorLayer) == cantorLayer
checkComLaws2 = (fmap extract . duplicate $ cantorLayer) == cantorLayer
checkComLaws3 = (duplicate . duplicate $ cantorLayer) == (fmap duplicate . duplicate $ cantorLayer)
cLaws = [checkComLaws1, checkComLaws2, checkComLaws3]
comonadCantorRule :: Layer Segments -> Segments
comonadCantorRule layer = concatMap cantorRule . extract
let segments = extract layer
in concatMap cantorRule segments
type Segment = (Float, Float)
type Segments = [(Float, Float)]
cantorRule :: Segment -> Segments
cantorRule (x1, x2) = let
len = x2 - x1
oneThird = len / 3.0
in [(x1, x1 + oneThird), (x2 - oneThird, x2)]
cantorCustomGen :: Segments -> Segments
cantorCustomGen segs = concatMap cantorRule segs
fractal' :: [Segments]
fractal' = iterate cantorCustomGen [(0.0, 0.9)]
cantorStartSegment x1 x2 = [(x1, x2)]
cantorLayer = mkCantor 0.0 9.0
mkCantor :: Float -> Float -> Layer Segments
mkCantor x1 x2 = Layer $ cantorStartSegment x1 x2
comonadCantorGen :: Layer Segments -> Layer Segments
comonadCantorGen = (=>> comonadCantorRule)
fractal = iterate comonadCantorGen cantorLayer
{- LYAH -}
{-
data Tree a = Empty | Node a (Tree a) (Tree a)
deriving (Show)
data TreeZ a = L a (Tree a)
| R a (Tree a)
deriving (Show)
type TreeZS a = [TreeZ a]
type TreeZipper a = (Tree a, TreeZS a)
left, right :: TreeZipper a -> TreeZipper a
left (Node x l r, bs) = (l, L x r:bs)
right (Node x l r, bs) = (r, R x l:bs)
type CantorTree = Tree Segment
genLSegment x = Node (head $ cantorGen x) Empty Empty
genRSegment x = Node (head $ tail $ cantorGen x) Empty Empty
cantorLeft (Node x Empty r, bs) = (genLSegment x, L x r : bs)
cantorLeft (Node x l r, bs) = (l, L x r : bs)
cantorRight (Node x l Empty, bs) = (genRSegment x, R x l : bs)
-}
| graninas/Haskell-Algorithms | Tests/Fractal/FractalWithData.hs | gpl-3.0 | 2,176 | 0 | 11 | 456 | 480 | 261 | 219 | -1 | -1 |
-- | This module contains instances of Tree for various data structures. These are used
-- for converting between ATerm and the given data structure. These functions aren't very
-- complicated, they just allow 'flattening' a datastructure into a portable format, and
-- converting it back again.
--
module Common.TreeInstances where
import CCO.Tree (ATerm (App,List,String), Tree (fromTree, toTree))
import CCO.Tree.Parser
import CCO.Feedback
import Common.BibTypes
import Common.HtmlTypes
import Control.Applicative
instance Tree BibTex where
fromTree = bibfromTree
toTree = bibtoTree
-- | Converts from BibTex to ATerm
bibfromTree :: BibTex -> ATerm
bibfromTree (BibTex p l) = App "BibTex" [List (map fromTree p), List (map fromTree l)]
-- | Converts an ATerm back into a BibTex tree
bibtoTree :: ATerm -> Feedback BibTex
bibtoTree = parseTree [app "BibTex" (BibTex <$> arg <*> arg)]
instance Tree Entry where
fromTree = entryfromTree
toTree = entrytoTree
-- | Converts from bibtex Entry to ATerm
entryfromTree :: Entry -> ATerm
entryfromTree e = App "Entry" [ fromTree $ entryType e -- type
, fromTree $ reference e -- ref
, List $ map fromTree (fields e) -- fields
]
-- | Converts an ATerm back into a BibTex entry
entrytoTree :: ATerm -> Feedback Entry
entrytoTree = parseTree [app "Entry" (Entry <$> arg <*> arg <*> arg)]
instance Tree Field where
fromTree = fieldfromTree
toTree = fieldtoTree
-- | Converts from Field (key/value pair) to ATerm
fieldfromTree :: Field -> ATerm
fieldfromTree (Field k v) = App "Field" [ String k -- key
, String v -- value
]
-- | Converts an ATerm back into a key/value pair
fieldtoTree :: ATerm -> Feedback Field
fieldtoTree = parseTree [app "Field" (Field <$> arg <*> arg)]
instance Tree Html where
fromTree = htmlfromTree
toTree = htmltoTree
-- | Converts from HTML document to ATerm
htmlfromTree :: Html -> ATerm
htmlfromTree (Html head body) = App "html" [fromTree head, List $ map fromTree body]
-- | Converts an ATerm back into an HTML document
htmltoTree :: ATerm -> Feedback Html
htmltoTree = parseTree [app "html" (Html <$> arg <*> arg)]
instance Tree Head where
fromTree = headfromTree
toTree = headtoTree
-- | Converts from HTML head element to ATerm
headfromTree :: Head -> ATerm
headfromTree (Head title) = App "head" [fromTree title]
-- | Converts an ATerm back into an html head element
headtoTree :: ATerm -> Feedback Head
headtoTree = parseTree [app "head" (Head <$> arg)]
instance Tree BlockElem where
fromTree = blockitemfromTree
toTree = blockitemtoTree
-- | Converts from HTML entity to ATerm
blockitemfromTree :: BlockElem -> ATerm
blockitemfromTree (A attr ref) = App "a" [List $ map fromTree attr, fromTree ref]
blockitemfromTree Hr = App "hr" []
blockitemfromTree (Table attr tr) = App "table" [List $ map fromTree attr, List $ map fromTree tr]
blockitemfromTree (P attr str) = App "p" [List $ map fromTree attr, fromTree str]
-- | Converts an ATerm back into an html element
blockitemtoTree :: ATerm -> Feedback BlockElem
blockitemtoTree = parseTree [ app "a" (A <$> arg <*> arg)
, app "hr" (pure Hr)
, app "table" (Table <$> arg <*> arg)
, app "p" (P <$> arg <*> arg)
]
instance Tree Tr where
fromTree = trfromTree
toTree = trtoTree
-- | Converts from HTML horizontal rule to ATerm
trfromTree :: Tr -> ATerm
trfromTree (Tr attr td) = App "tr" [List $ map fromTree attr, List $ map fromTree td]
-- | Converts an ATerm back into a horizontal rule (html element)
trtoTree :: ATerm -> Feedback Tr
trtoTree = parseTree [app "tr" (Tr <$> arg <*> arg)]
| toothbrush/cco-bibtex2html | Common/TreeInstances.hs | gpl-3.0 | 4,353 | 0 | 11 | 1,432 | 977 | 521 | 456 | 65 | 1 |
module MaybeConcat where
import Data.Maybe
concatMaybe :: Maybe String -> Maybe String -> Maybe String
concatMaybe a b = Just (fromJust a ++ " " ++ fromJust b)
| ice1000/OI-codes | codewars/101-200/maybe-concat-2-maybes.hs | agpl-3.0 | 162 | 0 | 9 | 30 | 61 | 30 | 31 | 4 | 1 |
{-# OPTIONS -cpp #-}
#include "../../../../config.h"
import System.Plugins
import API
-- an example where we just want to load an object and run it
main = do
let includes = [TOP ++ "/testsuite/load/null/api"]
m_v <- load "../Null.o" includes [] "resource"
v <- case m_v of
LoadSuccess _ v -> return v
LoadFailure es -> mapM_ putStrLn es >> error "load failed"
print $ a v
| Changaco/haskell-plugins | testsuite/load/null/prog/Main.hs | lgpl-2.1 | 410 | 0 | 12 | 103 | 107 | 51 | 56 | 10 | 2 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
module Language.SSVM.Binary
(dumpCode, loadCode)
where
import Control.Applicative
import Control.Monad (forM_)
import qualified Control.Monad.State as S
import Data.BinaryState
import qualified Data.Map as M
import Data.Char
import Data.Word
import Language.SSVM.Types
data BState = BState {
bMarks :: Marks,
bWords :: M.Map String Int,
bLastWord :: Int,
bAfterColon :: Bool }
deriving (Eq, Show)
emptyBState :: BState
emptyBState = BState {
bMarks = M.empty,
bWords = M.empty,
bLastWord = 0,
bAfterColon = False }
type Put a = PutState BState a
type Get a = GetState BState a
allocWord :: String -> Put Int
allocWord w = do
st <- S.get
let next = 1 + bLastWord st
ws = M.insert w next (bWords st)
S.put $ st {bWords = ws, bLastWord = next}
return next
getWordN :: String -> Put Int
getWordN w = do
ws <- S.gets bWords
case M.lookup w ws of
Nothing -> fail $ "Undefined word: " ++ w
Just i -> return i
byte :: Word8 -> Put ()
byte x = putZ x
char :: Char -> Put ()
char c = putZ (fromIntegral (ord c) :: Word8)
getChar8 :: Get Char
getChar8 = (chr . fromIntegral) <$> (getZ :: Get Word8)
getMark :: String -> Put Int
getMark name = do
ms <- S.gets bMarks
case M.lookup name ms of
Nothing -> fail $ "Undefined mark: @" ++ name
Just n -> return n
wordName :: Int -> Get String
wordName n = return $ "WORD_" ++ show n
markName :: Int -> Get String
markName n = do
let name = "mark_at_" ++ show n
st <- S.get
let ms = M.insert name n (bMarks st)
S.put $ st {bMarks = ms}
return name
instance BinaryState BState Instruction where
put NOP = byte 0
put (PUSH x) = byte 1 >> put x
put DROP = byte 2
put DUP = byte 3
put SWAP = byte 4
put OVER = byte 5
put PRINT = byte 6
put PRINTALL = byte 7
put ADD = byte 8
put MUL = byte 9
put DIV = byte 10
put REM = byte 11
put SUB = byte 12
put NEG = byte 13
put ABS = byte 14
put CMP = byte 15
put DEFINE = byte 16
put COLON = do
st <- S.get
S.put $ st {bAfterColon = True}
byte 17
put (CALL s) = do
n <- getWordN s
byte 18
putZ n
put VARIABLE = byte 19
put ASSIGN = byte 20
put READ = byte 21
put INPUT = byte 22
put MARK = byte 23
put (GETMARK x) = do
n <- getMark x
byte 24
putZ n
put GOTO = byte 25
put JZ = byte 26
put JNZ = byte 27
put JGT = byte 28
put JLT = byte 29
put JGE = byte 30
put JLE = byte 31
put ARRAY = byte 32
put READ_ARRAY = byte 33
put ASSIGN_ARRAY = byte 34
get = do
c <- getZ :: Get Word8
case c of
0 -> return NOP
1 -> PUSH <$> get
2 -> return DROP
3 -> return DUP
4 -> return SWAP
5 -> return OVER
6 -> return PRINT
7 -> return PRINTALL
8 -> return ADD
9 -> return MUL
10 -> return DIV
11 -> return REM
12 -> return SUB
13 -> return NEG
14 -> return ABS
15 -> return CMP
16 -> return DEFINE
17 -> return COLON
18 -> CALL <$> (wordName =<< getZ)
19 -> return VARIABLE
20 -> return ASSIGN
21 -> return READ
22 -> return INPUT
23 -> return MARK
24 -> GETMARK <$> (markName =<< getZ)
25 -> return GOTO
26 -> return JZ
27 -> return JNZ
28 -> return JGT
29 -> return JLT
30 -> return JGE
31 -> return JLE
32 -> return ARRAY
33 -> return READ_ARRAY
34 -> return ASSIGN_ARRAY
_ -> fail $ "Unknown opcode: " ++ show c
instance BinaryState BState StackItem where
put (SInteger x) = putZ 'I' >> putZ x
put (SString x) = do
a <- S.gets bAfterColon
if a
then do
st <- S.get
S.put $ st {bAfterColon = False}
putZ 'W'
w <- allocWord x
putZ w
else putZ 'S' >> putZ x
put (SInstruction x) = putZ 'O' >> put x
put (SArray _) = fail "Array literals are not supported"
put (Quote x) = putZ 'Q' >> put x
get = do
c <- getChar8
case c of
'I' -> SInteger <$> getZ
'S' -> SString <$> getZ
'O' -> SInstruction <$> get
'Q' -> Quote <$> get
'W' -> SString <$> (wordName =<< getZ)
_ -> fail $ "Unknown stack item type: " ++ [c]
instance BinaryState BState [StackItem] where
put list = forM_ list put
get = getUntilEOF
where
getUntilEOF = do
b <- isEmpty
if b
then return []
else do
x <- get
next <- getUntilEOF
return (x:next)
-- | Dump bytecode to file
dumpCode :: FilePath -> Code -> IO ()
dumpCode path (Code marks code) = encodeFile path (emptyBState {bMarks = head marks}) code
-- | Load bytecode from file
loadCode :: FilePath -> IO Code
loadCode path = do
(code, st) <- decodeFile' path emptyBState
return $ Code [bMarks st] code
| portnov/simple-stacked-vm | Language/SSVM/Binary.hs | lgpl-3.0 | 5,345 | 0 | 15 | 1,999 | 1,994 | 963 | 1,031 | 184 | 2 |
import qualified Data.Foldable as F
data BinaryTree a = Leaf
| Node (BinaryTree a) a (BinaryTree a)
deriving (Eq, Ord, Show)
insert' :: Ord a => a -> BinaryTree a -> BinaryTree a
insert' b Leaf = Node Leaf b Leaf
insert' b (Node left a right)
| b == a = Node left a right
| b < a = Node (insert' b left) a right
| b > a = Node left a (insert' b right)
mapTree :: (a -> b) -> BinaryTree a -> BinaryTree b
mapTree _ Leaf = Leaf
mapTree f (Node left a right) = Node (mapTree f left) (f a) (mapTree f right)
--
preorder :: BinaryTree a -> [a]
preorder x = go x []
where go tree acc =
case tree of
Node Leaf a Leaf -> a:acc
Node left a right ->
a : (go left acc) ++ (go right acc)
inorder :: BinaryTree a -> [a]
inorder x = go x []
where go tree acc =
case tree of
Node Leaf a Leaf -> a:acc
Node left a right ->
(go left acc) ++ [a] ++ (go right acc)
postorder :: Ord a => BinaryTree a -> [a]
postorder x = go x []
where go tree acc =
case tree of
Node Leaf a Leaf -> a:acc
Node left a right ->
(go left acc) ++ (go right acc) ++ [a]
testTree :: BinaryTree Integer
testTree = Node (Node Leaf 1 Leaf) 2 (Node Leaf 3 Leaf)
testPreorder :: IO ()
testPreorder =
if preorder testTree == [2,1,3]
then putStrLn "Preorder fine!"
else putStrLn "Bad news bears."
testInorder :: IO ()
testInorder =
if inorder testTree == [1,2,3]
then putStrLn "Inorder fine!"
else putStrLn "Bad news bears."
testPostorder :: IO ()
testPostorder =
if postorder testTree == [1,3,2]
then putStrLn "Postorder fine!"
else putStrLn "Postorder failed check"
main :: IO ()
main = do
testPreorder
testInorder
testPostorder
foldTree :: (a -> b -> b -> b) -> b -> BinaryTree a -> b
foldTree f b node =
case node of
Node Leaf a Leaf -> f a b b
Node Leaf a right -> f a b (foldTree f b right)
Node left a Leaf -> f a b (foldTree f b left)
Node left a right -> f a (foldTree f b right) (foldTree f b left)
mapTree' :: (a -> b) -> BinaryTree a -> BinaryTree b
mapTree' f = foldTree (\a b c -> Node b (f a) c) Leaf
| dmvianna/haskellbook | src/Ch11-BinaryTree.hs | unlicense | 2,298 | 0 | 13 | 748 | 1,022 | 507 | 515 | 65 | 4 |
import Data.Char
import Data.Maybe
import Data.List
import System.Environment
import System.IO
import System.Exit
-- Exercise 1
parseBNF :: Descr f => f BNF
parseBNF = pure []
-- Example: Simple expressions:
data Expr = Plus Expr Expr | Mult Expr Expr | Const Integer
deriving Show
mkPlus :: Expr -> [Expr] -> Expr
mkPlus = foldl Plus
mkMult :: Expr -> [Expr] -> Expr
mkMult = foldl Mult
parseExpr :: Descr f => f Expr
parseExpr = recNonTerminal "expr" $ \ exp ->
ePlus exp
ePlus :: Descr f => f Expr -> f Expr
ePlus exp = nonTerminal "plus" $
mkPlus <$> eMult exp
<*> many (spaces *> char '+' *> spaces *> eMult exp)
<* spaces
eMult :: Descr f => f Expr -> f Expr
eMult exp = nonTerminal "mult" $
mkPlus <$> eAtom exp
<*> many (spaces *> char '*' *> spaces *> eAtom exp)
<* spaces
eAtom :: Descr f => f Expr -> f Expr
eAtom exp = nonTerminal "atom" $
aConst `orElse` eParens exp
aConst :: Descr f => f Expr
aConst = nonTerminal "const" $ Const . read <$> many1 digit
eParens :: Descr f => f a -> f a
eParens inner =
id <$ char '('
<* spaces
<*> inner
<* spaces
<* char ')'
<* spaces
-- EBNF in Haskell
data RHS
= Terminal String
| NonTerminal String
| Choice RHS RHS
| Sequence RHS RHS
| Optional RHS
| Repetition RHS
deriving (Show, Eq)
mkChoices :: RHS -> [RHS] -> RHS
mkChoices = foldl Choice
mkSequences :: RHS -> [RHS] -> RHS
mkSequences = foldl Sequence
ppRHS :: RHS -> String
ppRHS = go 0
where
go _ (Terminal s) = surround "'" "'" $ concatMap quote s
go _ (NonTerminal s) = s
go a (Choice x1 x2) = p a 1 $ go 1 x1 ++ " | " ++ go 1 x2
go a (Sequence x1 x2) = p a 2 $ go 2 x1 ++ ", " ++ go 2 x2
go _ (Optional x) = surround "[" "]" $ go 0 x
go _ (Repetition x) = surround "{" "}" $ go 0 x
surround c1 c2 x = c1 ++ x ++ c2
p a n | a > n = surround "(" ")"
| otherwise = id
quote '\'' = "\\'"
quote '\\' = "\\\\"
quote c = [c]
type Production = (String, RHS)
type BNF = [Production]
ppBNF :: BNF -> String
ppBNF = unlines . map (\(i,rhs) -> i ++ " = " ++ ppRHS rhs ++ ";")
-- The parser
newtype Parser a = P (String -> Maybe (a, String))
runParser :: Parser t -> String -> Maybe (t, String)
runParser (P p) = p
parse :: Parser a -> String -> Maybe a
parse p input = case runParser p input of
Just (result, "") -> Just result
_ -> Nothing -- handles both no result and leftover input
noParserP :: Parser a
noParserP = P (\_ -> Nothing)
pureParserP :: a -> Parser a
pureParserP x = P (\input -> Just (x,input))
instance Functor Parser where
fmap f p = P p'
where
p' input = case runParser p input of
Just (result, rest) -> Just (f result, rest)
Nothing -> Nothing
instance Applicative Parser where
pure = pureParserP
p1 <*> p2 = P $ \input -> do
(f, rest1) <- runParser p1 input
(x, rest2) <- runParser p2 rest1
return (f x, rest2)
instance Monad Parser where
return = pure
p1 >>= k = P $ \input -> do
(x, rest1) <- runParser p1 input
runParser (k x) rest1
anyCharP :: Parser Char
anyCharP = P $ \input -> case input of
(c:rest) -> Just (c, rest)
[] -> Nothing
charP :: Char -> Parser ()
charP c = do
c' <- anyCharP
if c == c' then return ()
else noParserP
anyCharButP :: Char -> Parser Char
anyCharButP c = do
c' <- anyCharP
if c /= c' then return c'
else noParserP
letterOrDigitP :: Parser Char
letterOrDigitP = do
c <- anyCharP
if isAlphaNum c then return c else noParserP
orElseP :: Parser a -> Parser a -> Parser a
orElseP p1 p2 = P $ \input -> case runParser p1 input of
Just r -> Just r
Nothing -> runParser p2 input
manyP :: Parser a -> Parser [a]
manyP p = ((:) <$> p <*> manyP p) `orElseP` return []
many1P :: Parser a -> Parser [a]
many1P p = pure (:) <*> p <*> manyP p
sepByP :: Parser a -> Parser () -> Parser [a]
sepByP p1 p2 = ((:) <$> p1 <*> (manyP (p2 >> p1))) `orElseP` return []
-- A grammar-producing type constructor
newtype Grammar a = G (BNF, RHS)
runGrammer :: String -> Grammar a -> BNF
runGrammer main (G (prods, NonTerminal nt)) | main == nt = prods
runGrammer main (G (prods, rhs)) = prods ++ [(main, rhs)]
ppGrammar :: String -> Grammar a -> String
ppGrammar main g = ppBNF $ runGrammer main g
charG :: Char -> Grammar ()
charG c = G (([], Terminal [c]))
anyCharG :: Grammar Char
anyCharG = G ([], NonTerminal "char")
manyG :: Grammar a -> Grammar [a]
manyG (G (prods, rhs)) = G (prods, Repetition rhs)
mergeProds :: [Production] -> [Production] -> [Production]
mergeProds prods1 prods2 = nub $ prods1 ++ prods2
orElseG :: Grammar a -> Grammar a -> Grammar a
orElseG (G (prods1, rhs1)) (G (prods2, rhs2))
= G (mergeProds prods1 prods2, Choice rhs1 rhs2)
instance Functor Grammar where
fmap _ (G bnf) = G bnf
instance Applicative Grammar where
pure x = G ([], Terminal "")
G (prods1, Terminal "") <*> G (prods2, rhs2) = G (mergeProds prods1 prods2, rhs2)
G (prods1, rhs1) <*> G (prods2, Terminal "") = G (mergeProds prods1 prods2, rhs1)
G (prods1, rhs1) <*> G (prods2, rhs2) = G (mergeProds prods1 prods2, Sequence rhs1 rhs2)
many1G :: Grammar a -> Grammar [a]
many1G p = pure (:) <*> p <*> manyG p
sepByG :: Grammar a -> Grammar () -> Grammar [a]
sepByG p1 p2 = ((:) <$> p1 <*> (manyG (p2 *> p1))) `orElseG` pure []
primitiveG :: String -> Grammar a
primitiveG s = G ([], NonTerminal s)
newlineG :: Grammar ()
newlineG = primitiveG "newline"
recNonTerminalG :: String -> (Grammar a -> Grammar a) -> Grammar a
recNonTerminalG name f =
let G (prods, rhs) = f (G ([], NonTerminal name))
in G (prods ++ [(name, rhs)], NonTerminal name)
-- The generic approach
class Applicative f => Descr f where
char :: Char -> f ()
many :: f a -> f [a]
orElse :: f a -> f a -> f a
primitive :: String -> Parser a -> f a
recNonTerminal :: String -> (f a -> f a) -> f a
instance Descr Parser where
char = charP
many = manyP
orElse = orElseP
primitive _ p = p
recNonTerminal _ p = let r = p r in r
instance Descr Grammar where
char = charG
many = manyG
orElse = orElseG
primitive s _ = primitiveG s
recNonTerminal = recNonTerminalG
many1 :: Descr f => f a -> f [a]
many1 p = pure (:) <*> p <*> many p
sepBy :: Descr f => f a -> f () -> f [a]
sepBy p1 p2 = ((:) <$> p1 <*> (many (p2 *> p1))) `orElse` pure []
newline :: Descr f => f ()
newline = primitive "newline" (charP '\n')
nonTerminal :: Descr f => String -> f a -> f a
nonTerminal name p = recNonTerminal name (const p)
anyChar :: Descr f => f Char
anyChar = primitive "char" anyCharP
letter :: Descr f => f Char
letter = primitive "letter" $ do
c <- anyCharP
if isLetter c then return c else noParserP
digit :: Descr f => f Char
digit = primitive "digit" $ do
c <- anyCharP
if isDigit c then return c else noParserP
notQuoteOrBackslash :: Descr f => f Char
notQuoteOrBackslash = primitive "non-quote-or-backslash" $ do
c <- anyCharP
if c `notElem` "\\'" then return c else noParserP
spaces :: Descr f => f ()
spaces = nonTerminal "spaces" $
() <$ many (char ' ' `orElse` newline)
-- The main function
main :: IO ()
main = do
args <- getArgs
case args of
[] -> do
putStr $ ppGrammar "bnf" parseBNF
[fileName] -> do
input <- readFile fileName
case parse parseBNF input of
Just i -> putStr $ ppBNF i
Nothing -> do
hPutStrLn stderr "Failed to parse INI file."
exitFailure
_ -> hPutStrLn stderr "Too many arguments given" >> exitFailure
| nyirog/cis194 | 09-more-applicative.hs | unlicense | 7,837 | 0 | 17 | 2,175 | 3,399 | 1,707 | 1,692 | 218 | 8 |
module Spark.Core.Internal.RowStructures where
import Data.Aeson
import Data.Vector(Vector)
import qualified Data.Text as T
-- | The basic representation of one row of data. This is a standard type that comes out of the
-- SQL engine in Spark.
-- | An element in a Row object.
-- All objects manipulated by the Spark framework are assumed to
-- be convertible to cells.
--
-- This is usually handled by generic transforms.
data Cell =
Empty -- To represent maybe
| IntElement !Int
| DoubleElement !Double
| StringElement !T.Text
| BoolElement !Bool
| RowArray !(Vector Cell) deriving (Show, Eq)
-- | A Row of data: the basic data structure to transport information
-- TODO rename to rowCells
data Row = Row {
cells :: !(Vector Cell)
} deriving (Show, Eq)
-- AESON INSTANCES
-- TODO(kps) add some workaround to account for the restriction of
-- JSON types:
-- int32 -> int32
-- double -> double
-- weird double -> string?
-- long/bigint -> string?
-- | Cell
instance ToJSON Cell where
toJSON Empty = Null
toJSON (DoubleElement d) = toJSON d
toJSON (IntElement i) = toJSON i
toJSON (BoolElement b) = toJSON b
toJSON (StringElement s) = toJSON s
toJSON (RowArray arr) = toJSON arr
-- | Row
instance ToJSON Row where
toJSON (Row x) = toJSON x
| krapsh/kraps-haskell | src/Spark/Core/Internal/RowStructures.hs | apache-2.0 | 1,292 | 0 | 11 | 269 | 265 | 147 | 118 | 35 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Openshift.V1.ImageImportSpec where
import GHC.Generics
import Openshift.V1.LocalObjectReference
import Openshift.V1.ObjectReference
import Openshift.V1.TagImportPolicy
import qualified Data.Aeson
-- |
data ImageImportSpec = ImageImportSpec
{ from :: ObjectReference -- ^ the source of an image to import; only kind DockerImage is allowed
, to :: Maybe LocalObjectReference -- ^ a tag in the current image stream to assign the imported image to, if name is not specified the default tag from from.name will be used
, importPolicy :: Maybe TagImportPolicy -- ^ policy controlling how the image is imported
, includeManifest :: Maybe Bool -- ^ if true, return the manifest for this image in the response
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON ImageImportSpec
instance Data.Aeson.ToJSON ImageImportSpec
| minhdoboi/deprecated-openshift-haskell-api | openshift/lib/Openshift/V1/ImageImportSpec.hs | apache-2.0 | 1,024 | 0 | 9 | 163 | 123 | 76 | 47 | 19 | 0 |
module ChessBoard.Pieces (
Player (White,Black)
, Piece (King,Queen,Bishop,Knight,Rook,Pawn)
, PlayerPiece (PlayerPiece)
) where
-- | The types of player on the chess board.
data Player = White | Black deriving (Eq)
-- | All of the pieces that are on the board
data Piece = King | Queen | Bishop | Knight | Rook | Pawn deriving (Eq)
-- | Pieces on the chess board have both a player and a type
data PlayerPiece = PlayerPiece Player Piece deriving (Eq)
-- | Prints either "w" or "b"
instance Show Player where
show White = "w"
show Black = "b"
-- | Prints "k" , "q" , "b" , "n" , "r" or "p"
instance Show Piece where
show King = "k"
show Queen = "q"
show Bishop = "b"
show Knight = "n"
show Rook = "r"
show Pawn = "p"
-- | Combines piece ++ player. (e.g. "pb" for pawn black)
instance Show PlayerPiece where
show (PlayerPiece player piece) = (show piece) ++ (show player)
| benkolera/haskell-chess | src/ChessBoard/Pieces.hs | bsd-2-clause | 910 | 0 | 8 | 205 | 231 | 136 | 95 | 25 | 0 |
{-# LANGUAGE ImplicitParams, ScopedTypeVariables #-}
{-|
Module: HaskHOL.Lib.Canon
Copyright: (c) Evan Austin 2015
LICENSE: BSD3
Maintainer: e.c.austin@gmail.com
Stability: unstable
Portability: unknown
-}
module HaskHOL.Lib.Canon
( convPRESIMP
, ruleCONJ_ACI
, convSKOLEM
, convPRENEX
, convCONDS_ELIM
, convCONDS_CELIM
, convWEAK_DNF
, convWEAK_CNF
, convASSOC
, tacASM_FOL
, convLAMBDA_ELIM
, tacSELECT_ELIM
, convGEN_NNF
, convNNF
, convNNFC
, convPROP_ATOM
) where
import HaskHOL.Core
import qualified HaskHOL.Core.Kernel as K (typeOf)
import HaskHOL.Lib.Bool
import HaskHOL.Lib.Classic
import HaskHOL.Lib.Equal
import HaskHOL.Lib.IndDefs
import HaskHOL.Lib.Theorems
import HaskHOL.Lib.Simp
import HaskHOL.Lib.DRule
import HaskHOL.Lib.Tactics
import HaskHOL.Lib.Trivia
tmA, tmB, tmC, tmP, tmQ :: TriviaCtxt thry => HOL cls thry HOLTerm
tmA = serve [trivia| a:bool |]
tmB = serve [trivia| b:bool |]
tmC = serve [trivia| c:bool |]
tmP = serve [trivia| p:bool |]
tmQ = serve [trivia| q:bool |]
tmAnd, tmOr, tmNot, tmFalse, tmTrue :: TriviaCtxt thry => HOL cls thry HOLTerm
tmAnd = serve [trivia| (/\) |]
tmOr = serve [trivia| (\/) |]
tmNot = serve [trivia| (~) |]
tmFalse = serve [trivia| F |]
tmTrue = serve [trivia| T |]
pthNotNot :: TriviaCtxt thry => HOL cls thry HOLThm
pthNotNot = cacheProof "pthNotNot" ctxtTrivia $
ruleTAUT [txt| ~ ~ p = p |]
pthNotAnd :: TriviaCtxt thry => HOL cls thry HOLThm
pthNotAnd = cacheProof "pthNotAnd" ctxtTrivia $
ruleTAUT [txt| ~(p /\ q) <=> ~p \/ ~q |]
pthNotOr :: TriviaCtxt thry => HOL cls thry HOLThm
pthNotOr = cacheProof "pthNotOr" ctxtTrivia $
ruleTAUT [txt| ~(p \/ q) <=> ~p /\ ~q |]
pthImp :: TriviaCtxt thry => HOL cls thry HOLThm
pthImp = cacheProof "pthImp" ctxtTrivia $
ruleTAUT [txt| p ==> q <=> ~p \/ q |]
pthNotImp :: TriviaCtxt thry => HOL cls thry HOLThm
pthNotImp = cacheProof "pthNotImp" ctxtTrivia $
ruleTAUT [txt| ~(p ==> q) <=> p /\ ~q |]
pthEq :: TriviaCtxt thry => HOL cls thry HOLThm
pthEq = cacheProof "pthEq" ctxtTrivia $
ruleTAUT [txt| (p <=> q) <=> p /\ q \/ ~p /\ ~q |]
pthNotEq :: TriviaCtxt thry => HOL cls thry HOLThm
pthNotEq = cacheProof "pthNotEq" ctxtTrivia $
ruleTAUT [txt| ~(p <=> q) <=> p /\ ~q \/ ~p /\ q |]
pthEq' :: TriviaCtxt thry => HOL cls thry HOLThm
pthEq' = cacheProof "pthEq'" ctxtTrivia $
ruleTAUT [txt| (p <=> q) <=> (p \/ ~q) /\ (~p \/ q) |]
pthNotEq' :: TriviaCtxt thry => HOL cls thry HOLThm
pthNotEq' = cacheProof "pthNotEq'" ctxtTrivia $
ruleTAUT [txt| ~(p <=> q) <=> (p \/ q) /\ (~p \/ ~q) |]
pthNots :: TriviaCtxt thry => [HOL cls thry HOLThm]
pthNots =
cacheProofs ["pthNotForall", "pthNotExists", "pthNotExu"] ctxtTrivia .
ruleCONJUNCTS .
prove [txt| (~((!) P) <=> ?x:A. ~(P x)) /\
(~((?) P) <=> !x:A. ~(P x)) /\
(~((?!) P) <=> (!x:A. ~(P x)) \/
?x y. P x /\ P y /\ ~(y = x)) |] $
_REPEAT tacCONJ `_THEN`
tacGEN_REWRITE (convLAND . funpow 2 convRAND) [ruleGSYM axETA] `_THEN`
tacREWRITE [ thmNOT_EXISTS, thmNOT_FORALL, defEXISTS_UNIQUE
, thmDE_MORGAN, thmNOT_IMP ] `_THEN`
tacREWRITE [thmCONJ_ASSOC, thmEQ_SYM_EQ]
pthNotForall :: TriviaCtxt thry => HOL cls thry HOLThm
pthNotForall = getProof "pthNotForall" <|> head pthNots
pthNotExists :: TriviaCtxt thry => HOL cls thry HOLThm
pthNotExists = getProof "pthNotExists" <|> pthNots !! 1
pthNotExu :: TriviaCtxt thry => HOL cls thry HOLThm
pthNotExu = getProof "pthNotExu" <|> pthNots !! 2
pthExu :: TriviaCtxt thry => HOL cls thry HOLThm
pthExu = cacheProof "pthExu" ctxtTrivia .
prove [txt| ((?!) P) <=> (?x:A. P x) /\
!x y. ~(P x) \/ ~(P y) \/ (y = x) |] $
tacGEN_REWRITE (convLAND . convRAND) [ruleGSYM axETA] `_THEN`
tacREWRITE [ defEXISTS_UNIQUE
, ruleTAUT [txt| a /\ b ==> c <=> ~a \/ ~b \/ c |] ] `_THEN`
tacREWRITE [thmEQ_SYM_EQ]
convPRESIMP :: ClassicCtxt thry => Conversion cls thry
convPRESIMP = Conv $ \ tm ->
let ths = [ thmNOT_CLAUSES, thmAND_CLAUSES, thmOR_CLAUSES
, thmIMP_CLAUSES, thmEQ_CLAUSES, thmFORALL_SIMP
, thmEXISTS_SIMP, thmEXISTS_OR, thmFORALL_AND
, thmLEFT_EXISTS_AND, thmRIGHT_EXISTS_AND
, thmLEFT_FORALL_OR, thmRIGHT_FORALL_OR
] in
runConv (convGEN_REWRITE convTOP_DEPTH ths) tm
ruleCONJ_ACI :: (BoolCtxt thry, HOLTermRep tm cls thry)
=> tm -> HOL cls thry HOLThm
ruleCONJ_ACI ptm =
do tm <- toHTm ptm
case tm of
(p := p')
| p == p' -> primREFL p
| otherwise ->
do th <- useFun p' =<< mkFun funcEmpty =<< primASSUME p
th' <- useFun p =<< mkFun funcEmpty =<< primASSUME p'
ruleIMP_ANTISYM (ruleDISCH_ALL th) $ ruleDISCH_ALL th'
_ -> fail "ruleCONJ_ACI: not an equational term."
where useFun :: BoolCtxt thry => HOLTerm -> Func HOLTerm HOLThm
-> HOL cls thry HOLThm
useFun (l :/\ r) fn =
do l' <- useFun l fn
ruleCONJ l' $ useFun r fn
useFun tm fn = apply fn tm
mkFun :: BoolCtxt thry => Func HOLTerm HOLThm -> HOLThm
-> HOL cls thry (Func HOLTerm HOLThm)
mkFun fn th@(Thm _ (_ :/\ _)) =
do (th1, th2) <- ruleCONJ_PAIR th
flip mkFun th1 =<< mkFun fn th2
mkFun fn th = return $! (concl th |-> th) fn
convSKOLEM :: ClassicCtxt thry => Conversion cls thry
convSKOLEM = Conv $ \ tm ->
let ths1 = [ thmEXISTS_OR, thmLEFT_EXISTS_AND
, thmRIGHT_EXISTS_AND, thmFORALL_AND
, thmLEFT_FORALL_OR, thmRIGHT_FORALL_OR
, thmFORALL_SIMP, thmEXISTS_SIMP
]
ths2 = [ thmRIGHT_AND_EXISTS, thmLEFT_AND_EXISTS
, thmOR_EXISTS, thmRIGHT_OR_EXISTS
, thmLEFT_OR_EXISTS, thmSKOLEM
] in
runConv (convGEN_REWRITE convTOP_DEPTH ths1 `_THEN`
convGEN_REWRITE convREDEPTH ths2) tm
convPRENEX :: ClassicCtxt thry => Conversion cls thry
convPRENEX = Conv $ \ tm ->
let ths = [ thmAND_FORALL, thmLEFT_AND_FORALL
, thmRIGHT_AND_FORALL, thmLEFT_OR_FORALL
, thmRIGHT_OR_FORALL, thmOR_EXISTS
, thmLEFT_OR_EXISTS, thmRIGHT_OR_EXISTS
, thmLEFT_AND_EXISTS, thmRIGHT_AND_EXISTS
] in
runConv (convGEN_REWRITE convREDEPTH ths) tm
-- eliminate all lambda-terms exception those part of quantifiers
convHALF_MK_ABS :: TriviaCtxt thry => [HOLTerm] -> Conversion cls thry
convHALF_MK_ABS = conv
where conv :: TriviaCtxt thry => [HOLTerm] -> Conversion cls thry
conv [] = _ALL
conv (_:vs) = convGEN_REWRITE id [convHALF_MK_ABS_pth] `_THEN`
convBINDER (conv vs)
convHALF_MK_ABS_pth :: TriviaCtxt thry => HOL cls thry HOLThm
convHALF_MK_ABS_pth = cacheProof "convHALF_MK_ABS_pth" ctxtTrivia $
prove [txt| (s = \x. t x) <=> (!x. s x = t x) |] $
tacREWRITE [thmFUN_EQ]
findLambda :: HOLTerm -> HOL cls thry HOLTerm
findLambda tm@Abs{} = return tm
findLambda Var{} = fail "findLambda: var case"
findLambda Const{} = fail "findLambda: const case"
findLambda tm =
if isForall tm || isExists tm || isUExists tm
then findLambda =<< body (rand tm)
else case tm of
(Comb l r) ->
findLambda l <|> findLambda r
_ -> fail "findLambda: quantified case"
elimLambda :: Conversion cls thry -> Conversion cls thry
elimLambda conv = Conv $ \ tm ->
runConv conv tm <|>
(if isAbs tm then runConv (convABS $ elimLambda conv) tm
else if isVar tm || isConst tm then primREFL tm
else if isForall tm || isExists tm || isUExists tm
then runConv (convBINDER $ elimLambda conv) tm
else runConv (convCOMB $ elimLambda conv) tm)
applyPTH :: TriviaCtxt thry => HOLThm -> HOL cls thry HOLThm
applyPTH = ruleMATCH_MP applyPTH_pth
where applyPTH_pth :: TriviaCtxt thry => HOL cls thry HOLThm
applyPTH_pth = cacheProof "applyPTH_pth" ctxtTrivia .
prove [txt| (!a. (a = c) ==> (P = Q a)) ==>
(P <=> !a. (a = c) ==> Q a) |] $
tacSIMP [thmLEFT_FORALL_IMP, thmEXISTS_REFL]
convLAMB1 :: TriviaCtxt thry => Conversion cls thry
convLAMB1 = Conv $ \ tm -> note "convLAMB1" $
do atm <- findLambda tm
(v, _) <- destAbs atm
let vs = frees atm
vs' = vs ++ [v]
aatm <- listMkAbs vs atm
f <- genVar $ typeOf aatm
eq <- mkEq f aatm
th1 <- ruleSYM . ruleRIGHT_BETAS vs $ primASSUME eq
th2 <- runConv (elimLambda $ convGEN_REWRITE id [th1]) tm
th3 <- applyPTH =<< ruleGEN f (ruleDISCH_ALL th2)
ruleCONV (convRAND . convBINDER .convLAND $ convHALF_MK_ABS vs') th3
convLAMBDA_ELIM :: TriviaCtxt thry => Conversion cls thry
convLAMBDA_ELIM = Conv $ \ tm ->
runConv (convLAMB1 `_THEN` convLAMBDA_ELIM) tm
<|> primREFL tm
-- eliminate select terms from a goal
selectElimThm :: TriviaCtxt thry => HOLTerm
-> HOL cls thry HOLThm
selectElimThm (Comb (Const "@" _) atm@(Abs bv _)) =
ruleCONV (convLAND convBETA) $
rulePINST [(tyA, typeOf bv)]
[(serve [trivia| P:A->bool |], atm)] selectElimThm_pth
where selectElimThm_pth :: TriviaCtxt thry => HOL cls thry HOLThm
selectElimThm_pth = cacheProof "selectElimThm_pth" ctxtTrivia .
prove [txt| (P:A->bool)((@) P) <=> (?) P |] $
tacREWRITE [thmEXISTS] `_THEN`
tacBETA `_THEN`
tacREFL
selectElimThm _ = fail "selectElimThm: not a select term"
convSELECT_ELIM :: TriviaCtxt thry => Conversion cls thry
convSELECT_ELIM = Conv $ \ tm ->
do ths <- mapM selectElimThm $ findTerms isSelect tm
runConv (convPURE_REWRITE ths) tm
selectAxThm :: TriviaCtxt thry => HOLTerm -> HOL cls thry HOLThm
selectAxThm (Comb (Const "@" _) atm@(Abs bv _)) =
let fvs = frees atm in
do th1 <- rulePINST [(tyA, typeOf bv)]
[(serve [trivia| P:A->bool |], atm)] selectAxThm_pth
th2 <- ruleCONV (convBINDER $ convBINOP convBETA) th1
ruleGENL fvs th2
where selectAxThm_pth :: TriviaCtxt thry => HOL cls thry HOLThm
selectAxThm_pth = cacheProof "selectAxThm_pth" ctxtTrivia $
ruleISPEC [txt| P:A->bool |] axSELECT
selectAxThm _ = fail "selectAxThm: not a select term"
iconvSELECT_ELIM :: TriviaCtxt thry => Conversion cls thry
iconvSELECT_ELIM = Conv $ \ tm ->
(do t <- findTerm isSelect tm
th1 <- selectAxThm t
itm <- mkImp (concl th1) tm
ith <- primASSUME itm
th2 <- ruleDISCH_ALL $ ruleMP ith th1
let fvs = frees t
fty <- foldrM (mkFunTy . typeOf) (K.typeOf t) fvs
fn <- genVar fty
atm <- listMkAbs fvs t
rawdef <- mkEq fn atm
def <- ruleGENL fvs . ruleSYM . ruleRIGHT_BETAS fvs $ primASSUME rawdef
l <- lHand $ concl th2
th3 <- runConv (convPURE_REWRITE [def]) l
r <- rand $ concl th3
gtm <- mkForall fn r
th4 <- ruleSYM th3
th5 <- ruleSPEC fn $ primASSUME gtm
th6 <- primEQ_MP th4 th5
th7 <- ruleDISCH gtm th6
th8 <- ruleIMP_TRANS th7 th2
th9 <- ruleDISCH rawdef th8
ruleMP (primINST [(fn, atm)] th9) $ primREFL atm)
<?> "iconvSELECT_ELIM"
iconvSELECT_ELIMS :: TriviaCtxt thry => Conversion cls thry
iconvSELECT_ELIMS = Conv $ \ tm ->
(do th <- runConv iconvSELECT_ELIM tm
tm' <- lHand $ concl th
th2 <- runConv iconvSELECT_ELIM tm'
ruleIMP_TRANS th2 th)
<|> (ruleDISCH tm $ primASSUME tm)
tacSELECT_ELIM :: TriviaCtxt thry => Tactic cls thry
tacSELECT_ELIM =
tacCONV convSELECT_ELIM `_THEN`
(\ g@(Goal _ w) -> do th <- runConv iconvSELECT_ELIMS w
tacMATCH_MP th g)
-- eliminate conditionals
condsElimConv :: TriviaCtxt thry => Bool -> Conversion cls thry
condsElimConv dfl = Conv $ \ tm ->
(do t <- findConditional [] tm
p <- lHand $ rator t
prosimps <- basicNet
let conv = convDEPTH (gconvREWRITES prosimps)
thNew <- case p of
F -> runConv conv tm
T -> runConv conv tm
_ ->
do asm0 <- mkEq p $ tmFalse
ath0 <- primASSUME asm0
asm1 <- mkEq p $ tmTrue
ath1 <- primASSUME asm1
simp0 <- netOfThm False ath0 prosimps
simp1 <- netOfThm False ath1 prosimps
th0 <- ruleDISCH asm0 $
runConv (convDEPTH $ gconvREWRITES simp0) tm
th1 <- ruleDISCH asm1 $
runConv (convDEPTH $ gconvREWRITES simp1) tm
th2 <- ruleCONJ th0 th1
let convTh = if dfl then convCONDS_ELIM_thCond
else convCONDS_ELIM_thCond'
th3 <- ruleMATCH_MP convTh th2
let cnv = _TRY (gconvREWRITES prosimps)
proptsimpConv = convBINOP cnv `_THEN` cnv
rth <- runConv proptsimpConv $ rand (concl th3)
primTRANS th3 rth
ruleCONV (convRAND $ condsElimConv dfl) thNew) <|>
(if isNeg tm
then runConv (convRAND . condsElimConv $ not dfl) tm
else if isConj tm || isDisj tm
then runConv (convBINOP $ condsElimConv dfl) tm
else if isImp tm || isIff tm
then runConv (convCOMB2 (convRAND . condsElimConv $ not dfl)
(condsElimConv dfl)) tm
else if isForall tm
then runConv (convBINDER $ condsElimConv False) tm
else if isExists tm || isUExists tm
then runConv (convBINDER $ condsElimConv True) tm
else primREFL tm)
<?> "condsElimConv"
where convCONDS_ELIM_thCond :: TriviaCtxt thry => HOL cls thry HOLThm
convCONDS_ELIM_thCond = cacheProof "convCONDS_ELIM_thCond" ctxtTrivia .
prove [txt| ((b <=> F) ==> x = x0) /\
((b <=> T) ==> x = x1) ==>
x = (b /\ x1 \/ ~b /\ x0) |] $
tacBOOL_CASES [txt| b:bool |] `_THEN` tacASM_REWRITE_NIL
convCONDS_ELIM_thCond' :: TriviaCtxt thry => HOL cls thry HOLThm
convCONDS_ELIM_thCond' =
cacheProof "convCONDS_ELIM_thCond'" ctxtTrivia .
prove [txt| ((b <=> F) ==> x = x0) /\
((b <=> T) ==> x = x1) ==>
x = ((~b \/ x1) /\ (b \/ x0)) |] $
tacBOOL_CASES [txt| b:bool |] `_THEN` tacASM_REWRITE_NIL
findConditional :: [HOLTerm] -> HOLTerm -> HOL cls thry HOLTerm
findConditional fvs tm@(Comb s t)
| isCond tm =
do freesL <- frees `fmap` lHand s
if null (freesL `intersect` fvs)
then return tm
else findConditional fvs s <|> findConditional fvs t
| otherwise = findConditional fvs s <|> findConditional fvs t
findConditional fvs (Abs x t) = findConditional (x:fvs) t
findConditional _ _ = fail "findConditional"
convCONDS_ELIM :: TriviaCtxt thry => Conversion cls thry
convCONDS_ELIM = condsElimConv True
convCONDS_CELIM :: TriviaCtxt thry => Conversion cls thry
convCONDS_CELIM = condsElimConv False
-- Weak DNF
distributeDNF :: TriviaCtxt thry => Conversion cls thry
distributeDNF = Conv $ \ tm -> note "distributeDNF" $
case tm of
(a :/\ (b :\/ c)) ->
do th <- primINST [(tmA, a), (tmB, b), (tmC, c)] convWEAK_DNF_pth1
th' <- runConv (convBINOP distributeDNF) $ rand (concl th)
primTRANS th th'
((a :\/ b) :/\ c) ->
do th <- primINST [(tmA, a), (tmB, b), (tmC, c)] convWEAK_DNF_pth2
th' <- runConv (convBINOP distributeDNF) $ rand (concl th)
primTRANS th th'
_ -> primREFL tm
where convWEAK_DNF_pth1 :: TriviaCtxt thry => HOL cls thry HOLThm
convWEAK_DNF_pth1 = cacheProof "convWEAK_DNF_pth1" ctxtTrivia $
ruleTAUT [txt| a /\ (b \/ c) <=> a /\ b \/ a /\ c |]
convWEAK_DNF_pth2 :: TriviaCtxt thry => HOL cls thry HOLThm
convWEAK_DNF_pth2 = cacheProof "convWEAK_DNF_pth2" ctxtTrivia $
ruleTAUT [txt| (a \/ b) /\ c <=> a /\ c \/ b /\ c |]
convWEAK_DNF :: TriviaCtxt thry => Conversion cls thry
convWEAK_DNF = Conv $ \ tm -> note "convWEAK_DNF" $
case tm of
Forall{} -> runConv (convBINDER convWEAK_DNF) tm
Exists{} -> runConv (convBINDER convWEAK_DNF) tm
(_ :\/ _) -> runConv (convBINOP convWEAK_DNF) tm
(l :/\ r) ->
do l' <- runConv convWEAK_DNF l
r' <- runConv convWEAK_DNF r
th <- primMK_COMB (ruleAP_TERM tmAnd l') r'
th' <- runConv distributeDNF $ rand (concl th)
primTRANS th th'
_ -> primREFL tm
-- Weak CNF
distribute :: TriviaCtxt thry => Conversion cls thry
distribute = Conv $ \ tm -> note "distribute" $
case tm of
(a :\/ (b :/\ c)) ->
do th <- primINST [(tmA, a), (tmB, b), (tmC, c)] distribute_pth1
rth <- runConv (convBINOP distribute) $ rand (concl th)
primTRANS th rth
((a :/\ b) :\/ c) ->
do th <- primINST [(tmA, a), (tmB, b), (tmC, c)] distribute_pth2
rth <- runConv (convBINOP distribute) $ rand (concl th)
primTRANS th rth
_ -> primREFL tm
where distribute_pth1 :: TriviaCtxt thry => HOL cls thry HOLThm
distribute_pth1 = cacheProof "distribute_pth1" ctxtTrivia $
ruleTAUT [txt| a \/ (b /\ c) <=> (a \/ b) /\ (a \/ c) |]
distribute_pth2 :: TriviaCtxt thry => HOL cls thry HOLThm
distribute_pth2 = cacheProof "distribute_pth2" ctxtTrivia $
ruleTAUT [txt| (a /\ b) \/ c <=> (a \/ c) /\ (b \/ c) |]
convWEAK_CNF :: TriviaCtxt thry => Conversion cls thry
convWEAK_CNF = Conv $ \ tm -> note "convWEAK_CNF" $
case tm of
Forall{} -> runConv (convBINDER convWEAK_CNF) tm
Exists{} -> runConv (convBINDER convWEAK_CNF) tm
(_ :/\ _) -> runConv (convBINOP convWEAK_CNF) tm
(l :\/ r) ->
do lth <- runConv convWEAK_CNF l
rth <- runConv convWEAK_CNF r
th <- primMK_COMB (ruleAP_TERM tmOr lth) rth
rtm <- rand $ concl th
th2 <- runConv distribute rtm
primTRANS th th2
_ -> primREFL tm
distrib :: HOLTerm -> HOLTerm -> HOLTerm -> HOLTerm -> HOLThm -> HOLTerm
-> HOL cls thry HOLThm
distrib op x y z th' tm@(Comb (Comb op' (Comb (Comb op'' p) q)) r)
| op' == op && op'' == op = note "distrib" $
do th1 <- primINST [(x, p), (y, q), (z, r)] th'
case concl th1 of
(Comb _ (Comb l r')) ->
do th2 <- ruleAP_TERM l $ distrib op x y z th' r'
rtm <- rand $ concl th2
th3 <- distrib op x y z th' rtm
primTRANS th1 $ primTRANS th2 th3
_ -> fail "not a combination."
| otherwise = primREFL tm
distrib _ _ _ _ _ t = primREFL t
convASSOC :: (BoolCtxt thry, HOLThmRep thm cls thry) => thm
-> Conversion cls thry
convASSOC thm = Conv $ \ tm -> note "convASSOC" $
do thm' <- ruleSYM $ ruleSPEC_ALL thm
case concl thm' of
(_ := (Binop op x (Binop _ y z))) ->
canonAssoc op x y z thm' tm
_ -> fail "bad term structure."
where canonAssoc :: HOLTerm -> HOLTerm -> HOLTerm -> HOLTerm -> HOLThm
-> HOLTerm -> HOL cls thry HOLThm
canonAssoc op x y z th' tm@(Comb l@(Comb op' _) q)
| op' == op =
(do th <- ruleAP_TERM l $ canonAssoc op x y z th' q
r <- rand $ concl th
primTRANS th $ distrib op x y z th' r)
<?> "canonAssoc"
| otherwise = primREFL tm
canonAssoc _ _ _ _ _ tm = primREFL tm
getHeads :: [HOLTerm] -> HOLTerm -> ([(HOLTerm, Int)], [(HOLTerm, Int)])
-> ([(HOLTerm, Int)], [(HOLTerm, Int)])
getHeads lconsts (Forall v bod) sofar =
getHeads (lconsts \\ [v]) bod sofar
getHeads lconsts (l :/\ r) sofar =
getHeads lconsts l (getHeads lconsts r sofar)
getHeads lconsts (l :\/ r) sofar =
getHeads lconsts l (getHeads lconsts r sofar)
getHeads lconsts (Neg tm') sofar =
getHeads lconsts tm' sofar
getHeads lconsts tm sofar@(cheads, vheads) =
let (hop, args) = stripComb tm
len = length args
newHeads
| isConst hop || hop `elem` lconsts =
(insert (hop, len) cheads, vheads)
| len > 0 =
(cheads, insert (hop, len) vheads)
| otherwise = sofar in
foldr (getHeads lconsts) newHeads args
getThmHeads :: HOLThm -> ([(HOLTerm, Int)], [(HOLTerm, Int)])
-> ([(HOLTerm, Int)], [(HOLTerm, Int)])
getThmHeads th = getHeads (catFrees $ hyp th) (concl th)
convAPP :: TriviaCtxt thry => Conversion cls thry
convAPP = convREWR convAPP_pth
where convAPP_pth :: TriviaCtxt thry => HOL cls thry HOLThm
convAPP_pth = cacheProof "convAPP_pth" ctxtTrivia .
prove [txt| !(f:A->B) x. f x = I f x |] $
tacREWRITE [thmI]
convAPP_N :: TriviaCtxt thry => Int -> Conversion cls thry
convAPP_N 1 = convAPP
convAPP_N n = convRATOR (convAPP_N $ n - 1) `_THEN` convAPP
convFOL :: TriviaCtxt thry => [(HOLTerm, Int)]
-> Conversion cls thry
convFOL hddata = Conv $ \ tm ->
case tm of
Forall{} -> runConv (convBINDER $ convFOL hddata) tm
(_ :/\ _) -> runConv (convBINOP $ convFOL hddata) tm
(_ :\/ _) -> runConv (convBINOP $ convFOL hddata) tm
_ ->
let (op, args) = stripComb tm in
do th1 <- primREFL op
th2 <- mapM (runConv (convFOL hddata)) args
th <- foldlM primMK_COMB th1 th2
tm' <- rand $ concl th
let n = case lookup op hddata of
Just x -> length args - x
Nothing -> 0
if n == 0
then return th
else primTRANS th $ runConv (convAPP_N n) tm'
convGEN_FOL :: TriviaCtxt thry => ([(HOLTerm, Int)], [(HOLTerm, Int)])
-> Conversion cls thry
convGEN_FOL (cheads, []) =
let hops = setify $ map fst cheads
getMin h = let ns = mapFilter (\ (k, n) ->
if k == h then return n
else fail' "getMin") cheads in
if length ns < 2 then fail' "getMin"
else return (h, minimum ns)
hddata = mapFilter getMin hops in
convFOL hddata
convGEN_FOL (cheads, vheads) =
let hddata = map (\ t -> case t of
(Const "=" _) -> (t, 2)
_ -> (t, 0))
(setify . map fst $ vheads ++ cheads) in
convFOL hddata
tacASM_FOL :: TriviaCtxt thry => Tactic cls thry
tacASM_FOL gl@(Goal asl _) =
let headsp = foldr (getThmHeads . snd) ([], []) asl in
tacRULE_ASSUM (ruleCONV $ convGEN_FOL headsp) gl
-- conv NFF
nnfDConv :: TriviaCtxt thry => Bool
-> (HOLTerm -> HOL cls thry (HOLThm, HOLThm)) -> HOLTerm
-> HOL cls thry (HOLThm, HOLThm)
nnfDConv cf baseconvs (l :/\ r) =
(do (thLp, thLn) <- nnfDConv cf baseconvs l
(thRp, thRn) <- nnfDConv cf baseconvs r
rth1 <- primINST [(tmP, l), (tmQ, r)] pthNotAnd
lth <- ruleAP_TERM tmAnd thLp
th1 <- primMK_COMB lth thRp
rth2 <- ruleAP_TERM tmOr thLn
th2 <- primTRANS rth1 $ primMK_COMB rth2 thRn
return (th1, th2))
<?> "nnfDConv: conjunction case"
nnfDConv cf baseconvs (l :\/ r) =
(do (thLp, thLn) <- nnfDConv cf baseconvs l
(thRp, thRn) <- nnfDConv cf baseconvs r
rth1 <- primINST [(tmP, l), (tmQ, r)] pthNotOr
lth <- ruleAP_TERM tmOr thLp
th1 <- primMK_COMB lth thRp
rth2 <- ruleAP_TERM tmAnd thLn
th2 <- primTRANS rth1 $ primMK_COMB rth2 thRn
return (th1, th2))
<?> "nnfDConv: disjunction case"
nnfDConv cf baseconvs (l :==> r) =
(do (thLp, thLn) <- nnfDConv cf baseconvs l
(thRp, thRn) <- nnfDConv cf baseconvs r
lth1 <- primINST [(tmP, l), (tmQ, r)] pthImp
rth1 <- primINST [(tmP, l), (tmQ, r)] pthNotImp
lth2 <- ruleAP_TERM tmOr thLn
th1 <- primTRANS lth1 $ primMK_COMB lth2 thRp
rth2 <- ruleAP_TERM tmAnd thLp
th2 <- primTRANS rth1 $ primMK_COMB rth2 thRn
return (th1, th2))
<?> "nnfDConv: implication case"
nnfDConv True baseconvs (l :<=> r) =
(do (thLp, thLn) <- nnfDConv True baseconvs l
(thRp, thRn) <- nnfDConv True baseconvs r
lth1 <- primINST [(tmP, l), (tmQ, r)] pthEq'
rth1 <- primINST [(tmP, l), (tmQ, r)] pthNotEq'
lth2 <- ruleAP_TERM tmOr thLp
lth3 <- ruleAP_TERM tmAnd $ primMK_COMB lth2 thRn
lth4 <- ruleAP_TERM tmOr thLn
th1 <- primTRANS lth1 . primMK_COMB lth3 $ primMK_COMB lth4 thRp
rth2 <- ruleAP_TERM tmOr thLp
rth3 <- ruleAP_TERM tmAnd $ primMK_COMB rth2 thRp
rth4 <- ruleAP_TERM tmOr thLn
th2 <- primTRANS rth1 . primMK_COMB rth3 $ primMK_COMB rth4 thRn
return (th1, th2))
<?> "nnfDConv: true equality case"
nnfDConv False baseconvs (l :<=> r) =
(do (thLp, thLn) <- nnfDConv False baseconvs l
(thRp, thRn) <- nnfDConv False baseconvs r
lth1 <- primINST [(tmP, l), (tmQ, r)] pthEq
rth1 <- primINST [(tmP, l), (tmQ, r)] pthNotEq
lth2 <- ruleAP_TERM tmAnd thLp
lth3 <- ruleAP_TERM tmOr $ primMK_COMB lth2 thRp
lth4 <- ruleAP_TERM tmAnd thLn
th1 <- primTRANS lth1 . primMK_COMB lth3 $ primMK_COMB lth4 thRn
rth2 <- ruleAP_TERM tmAnd thLp
rth3 <- ruleAP_TERM tmOr $ primMK_COMB rth2 thRn
rth4 <- ruleAP_TERM tmAnd thLn
th2 <- primTRANS rth1 . primMK_COMB rth3 $ primMK_COMB rth4 thRp
return (th1, th2))
<?> "nnfDConv: equality case"
nnfDConv _ baseconvs (Comb q@(Const "!" ((ty :-> _) :-> _)) bod@(Abs x t)) =
(do (thP, thN) <- nnfDConv True baseconvs t
th1 <- ruleAP_TERM q $ primABS x thP
p <- liftM (mkVar "P") $ mkFunTy ty tyBool
rth1 <- primINST [(p, bod)] $ primINST_TYPE [(tyA, ty)] pthNotForall
rth2 <- ruleAP_TERM tmNot . primBETA $ mkComb bod x
rth3 <- primTRANS rth2 thN
rth4 <- ruleMK_EXISTS x rth3
th2 <- primTRANS rth1 rth4
return (th1, th2))
<?> "nnfDConv: forall case"
nnfDConv cf baseconvs (Comb q@(Const "?" ((ty :-> _) :-> _)) bod@(Abs x t)) =
(do (thP, thN) <- nnfDConv cf baseconvs t
th1 <- ruleAP_TERM q $ primABS x thP
p <- liftM (mkVar "P") $ mkFunTy ty tyBool
rth1 <- primINST [(p, bod)] $ primINST_TYPE [(tyA, ty)] pthNotExists
rth2 <- ruleAP_TERM tmNot . primBETA $ mkComb bod x
rth3 <- primTRANS rth2 thN
rth4 <- ruleMK_FORALL x rth3
th2 <- primTRANS rth1 rth4
return (th1, th2))
<?> "nnfDConv: exists case"
nnfDConv cf baseconvs (Comb (Const "?!" ((ty :-> _) :-> _)) bod@(Abs x t)) =
(do (thP, thN) <- nnfDConv cf baseconvs t
let y = variant (x : frees t) x
eq <- mkEq y x
(ethP, ethN) <- baseconvs eq
bth <- primBETA $ mkComb bod x
bth' <- runConv convBETA $ mkComb bod y
thP' <- primINST [(x, y)] thP
thN' <- primINST [(x, y)] thN
p <- liftM (mkVar "P") $ mkFunTy ty tyBool
lth1 <- primINST [(p, bod)] $ primINST_TYPE [(tyA, ty)] pthExu
rth1 <- primINST [(p, bod)] $ primINST_TYPE [(tyA, ty)] pthNotExu
lth2 <- ruleMK_EXISTS x $ primTRANS bth thP
lth3 <- ruleAP_TERM tmAnd lth2
lth4 <- ruleAP_TERM tmNot bth
lth5 <- ruleAP_TERM tmOr $ primTRANS lth4 thN
lth6 <- ruleAP_TERM tmNot bth'
lth7 <- ruleAP_TERM tmOr $ primTRANS lth6 thN'
lth8 <- primMK_COMB lth5 $ primMK_COMB lth7 ethP
lth9 <- ruleMK_FORALL x $ ruleMK_FORALL y lth8
lth10 <- primMK_COMB lth3 lth9
rth2 <- primTRANS (ruleAP_TERM tmNot bth) thN
rth3 <- ruleMK_FORALL x rth2
rth4 <- ruleAP_TERM tmOr rth3
rth5 <- ruleAP_TERM tmAnd $ primTRANS bth thP
rth6 <- ruleAP_TERM tmAnd $ primTRANS bth' thP'
rth7 <- primMK_COMB rth5 $ primMK_COMB rth6 ethN
rth8 <- ruleMK_EXISTS x $ ruleMK_EXISTS y rth7
rth9 <- primMK_COMB rth4 rth8
th1 <- primTRANS lth1 lth10
th2 <- primTRANS rth1 rth9
return (th1, th2))
<?> "nnfDConv: unique exists case"
nnfDConv cf baseconvs (Neg t) =
(do (th1, th2) <- nnfDConv cf baseconvs t
rth1 <- primINST [(tmP, t)] pthNotNot
rth2 <- primTRANS rth1 th1
return (th2, rth2))
<?> "nnfDConv: not case"
nnfDConv _ baseconvs tm = nnfDConvBase baseconvs tm
nnfDConvBase :: (HOLTerm -> HOL cls thry (HOLThm, HOLThm)) -> HOLTerm
-> HOL cls thry (HOLThm, HOLThm)
nnfDConvBase baseconvs tm =
(baseconvs tm <|>
(do th1 <- primREFL tm
th2 <- primREFL $ mkNeg tm
return (th1, th2)))
<?> "nnfDConv: base case"
type NNFConv cls thry =
Bool -> (Conversion cls thry, HOLTerm -> HOL cls thry (HOLThm, HOLThm)) ->
Conversion cls thry
nnfConv' :: forall cls thry. TriviaCtxt thry => NNFConv cls thry
nnfConv' cf baseconvs@(base1, base2) = Conv $ \ tm ->
case tm of
(l :/\ r) ->
let ?pth = pthNotAnd
?lconv = nnfConv'
?rconv = nnfConv'
?btm = tmOr in
boolCase "conjunction" l r
(l :\/ r) ->
let ?pth = pthNotOr
?lconv = nnfConv'
?rconv = nnfConv'
?btm = tmAnd in
boolCase "disjunction" l r
(l :==> r) ->
let ?pth = pthNotImp
?lconv = nnfConv
?rconv = nnfConv'
?btm = tmAnd in
boolCase "implication" l r
(l :<=> r) ->
(do (thLp, thLn) <- nnfDConv cf base2 l
(thRp, thRn) <- nnfDConv cf base2 r
pth <- if cf then pthNotEq' else pthNotEq
let (ltm, rtm) = if cf then (tmOr, tmAnd) else (tmAnd, tmOr)
(rth1, rth2) = if cf then (thRp, thRn) else (thRn, thRp)
lth1 <- primINST [(tmP, l), (tmQ, r)] pth
lth2 <- ruleAP_TERM ltm thLp
lth3 <- ruleAP_TERM rtm $ primMK_COMB lth2 rth1
lth4 <- ruleAP_TERM ltm thLn
primTRANS lth1 . primMK_COMB lth3 $ primMK_COMB lth4 rth2)
<?> "nnfConv': equality case"
(BindWhole "!" bod@(Abs x@(Var _ ty) t)) ->
let ?pth = pthNotForall
?cf = cf
?rule = ruleMK_EXISTS in
quantCase "forall" bod x t ty
(BindWhole "?" bod@(Abs x@(Var _ ty) t)) ->
let ?pth = pthNotExists
?cf = True
?rule = ruleMK_FORALL in
quantCase "exists" bod x t ty
(BindWhole "?!" bod@(Abs x@(Var _ ty) t)) ->
(do (thP, thN) <- nnfDConv cf base2 t
let y = variant (x:frees t) x
eq <- mkEq y x
(_, ethN) <- base2 eq
bth <- primBETA $ mkComb bod x
bth' <- runConv convBETA $ mkComb bod y
th1' <- instPth pthNotExu bod ty
lth1 <- primTRANS (ruleAP_TERM tmNot bth) thN
lth2 <- ruleMK_FORALL x lth1
lth3 <- ruleAP_TERM tmOr lth2
lth4 <- ruleAP_TERM tmAnd $ primTRANS bth thP
lth5 <- ruleAP_TERM tmAnd . primTRANS bth' $ primINST [(x, y)] thP
lth6 <- primMK_COMB lth4 $ primMK_COMB lth5 ethN
lth7 <- ruleMK_EXISTS x $ ruleMK_EXISTS y lth6
primTRANS th1' $ primMK_COMB lth3 lth7)
<?> "nnfConv': unique exists case"
(Neg t) ->
(do th1 <- runConv (nnfConv cf baseconvs) t
primTRANS (primINST [(tmP, t)] pthNotNot) th1)
<?> "nnfConv': not case"
_ -> baseCase tm
where boolCase :: (TriviaCtxt thry, ?pth :: HOL cls thry HOLThm,
?lconv :: NNFConv cls thry,
?rconv :: NNFConv cls thry, ?btm :: HOL cls thry HOLTerm)
=> String -> HOLTerm -> HOLTerm -> HOL cls thry HOLThm
boolCase err l r =
(do pth <- ?pth
lth <- runConv (?lconv cf baseconvs) l
rth <- runConv (?rconv cf baseconvs) r
lth1 <- primINST [(tmP, l), (tmQ, r)] pth
lth2 <- ruleAP_TERM ?btm lth
primTRANS lth1 $ primMK_COMB lth2 rth)
<?> ("nnfConv': " ++ err ++ " case")
quantCase :: (TriviaCtxt thry, ?pth :: HOL cls thry HOLThm, ?cf :: Bool,
?rule :: HOLTerm -> HOLThm -> HOL cls thry HOLThm)
=> String -> HOLTerm -> HOLTerm -> HOLTerm -> HOLType
-> HOL cls thry HOLThm
quantCase err bod x t ty =
(do pth <- ?pth
thN <- runConv (nnfConv' ?cf baseconvs) t
th1 <- instPth pth bod ty
lth <- ruleAP_TERM tmNot . primBETA $ mkComb bod x
th2 <- ?rule x =<< primTRANS lth thN
primTRANS th1 th2)
<?> ("nnfConv': " ++ err ++ " case")
baseCase :: TriviaCtxt thry => HOLTerm -> HOL cls thry HOLThm
baseCase tm =
(do tm' <- mkNeg tm
runConv base1 tm' <|> (primREFL tm'))
<?>" nnfConv': base case"
instPth :: HOLThmRep thm cls thry
=> thm -> HOLTerm -> HOLType -> HOL cls thry HOLThm
instPth pth bod ty =
do p <- liftM (mkVar "P") $ mkFunTy ty tyBool
primINST [(p, bod)] $ primINST_TYPE [(tyA, ty)] pth
nnfConv :: TriviaCtxt thry => NNFConv cls thry
nnfConv cf baseconvs@(base1, base2) = Conv $ \ tm ->
case tm of
(l :/\ r) ->
(do thLp <- runConv (nnfConv cf baseconvs) l
thRp <- runConv (nnfConv cf baseconvs) r
lth <- ruleAP_TERM tmAnd thLp
primMK_COMB lth thRp)
<?> "nnfConv: conjunction case"
(l :\/ r) ->
(do thLp <- runConv (nnfConv cf baseconvs) l
thRp <- runConv (nnfConv cf baseconvs) r
lth <- ruleAP_TERM tmOr thLp
primMK_COMB lth thRp)
<?> "nnfConv: disjunction case"
(l :==> r) ->
(do thLn <- runConv (nnfConv' cf baseconvs) l
thRp <- runConv (nnfConv cf baseconvs) r
lth1 <- primINST [(tmP, l), (tmQ, r)] pthImp
lth2 <- ruleAP_TERM tmOr thLn
primTRANS lth1 $ primMK_COMB lth2 thRp)
<?> "nnfConv: implication case"
(l :<=> r) ->
(do (thLp, thLn) <- nnfDConv cf base2 l
(thRp, thRn) <- nnfDConv cf base2 r
if cf
then do lth1 <- primINST [(tmP, l), (tmQ, r)] pthEq'
lth2 <- ruleAP_TERM tmOr thLp
lth3 <- ruleAP_TERM tmOr thLn
lth4 <- ruleAP_TERM tmAnd $ primMK_COMB lth2 thRn
primTRANS lth1 . primMK_COMB lth4 $
primMK_COMB lth3 thRp
else do lth1 <- primINST [(tmP, l), (tmQ, r)] pthEq
lth2 <- ruleAP_TERM tmAnd thLp
lth3 <- ruleAP_TERM tmAnd thLn
lth4 <- ruleAP_TERM tmOr $ primMK_COMB lth2 thRp
primTRANS lth1 . primMK_COMB lth4 $
primMK_COMB lth3 thRn)
<?> "nnfConv: equation case"
(Comb q@(Const "!" _) (Abs x t)) ->
(do thP <- runConv (nnfConv True baseconvs) t
ruleAP_TERM q $ primABS x thP)
<?> "nnfConv: forall case"
(Comb q@(Const "?" _) (Abs x t)) ->
(do thP <- runConv (nnfConv cf baseconvs) t
ruleAP_TERM q $ primABS x thP)
<?> "nnfConv: exists case"
(BindWhole "?!" bod@(Abs x@(Var _ ty) t)) ->
(do (thP, thN) <- nnfDConv cf base2 t
let y = variant (x:frees t) x
eq <- mkEq y x
(ethP, _) <- base2 eq
bth <- primBETA $ mkComb bod x
bth' <- runConv convBETA $ mkComb bod y
thN' <- primINST [(x, y)] thN
p <- liftM (mkVar "P") $ mkFunTy ty tyBool
th1 <- primINST [(p, bod)] $ primINST_TYPE [(tyA, ty)] pthExu
th2 <- ruleMK_EXISTS x $ primTRANS bth thP
lth1 <- ruleAP_TERM tmAnd th2
lth2 <- ruleAP_TERM tmNot bth
lth3 <- ruleAP_TERM tmOr $ primTRANS lth2 thN
lth4 <- ruleAP_TERM tmNot bth'
lth5 <- ruleAP_TERM tmOr $ primTRANS lth4 thN'
lth6 <- primMK_COMB lth3 $ primMK_COMB lth5 ethP
th3 <- ruleMK_FORALL x $ ruleMK_FORALL y lth6
primTRANS th1 $ primMK_COMB lth1 th3)
<?> "nnfConv: unique exists case"
(Neg t) ->
runConv (nnfConv' cf baseconvs) t
_ -> nnfConvBase base1 tm
nnfConvBase :: Conversion cls thry -> HOLTerm -> HOL cls thry HOLThm
nnfConvBase base1 tm =
(runConv base1 tm <|> (primREFL tm))
<?> "nnfConv: base case"
convGEN_NNF :: TriviaCtxt thry => Bool
-> (Conversion cls thry, HOLTerm -> HOL cls thry (HOLThm, HOLThm))
-> Conversion cls thry
convGEN_NNF = nnfConv
convNNF :: TriviaCtxt thry => Conversion cls thry
convNNF = convGEN_NNF False (_ALL, \ t -> do th1 <- primREFL t
th2 <- primREFL $ mkNeg t
return (th1, th2))
convNNFC :: TriviaCtxt thry => Conversion cls thry
convNNFC = convGEN_NNF True (_ALL, \ t -> do th1 <- primREFL t
th2 <- primREFL $ mkNeg t
return (th1, th2))
convPROP_ATOM :: Conversion cls thry -> Conversion cls thry
convPROP_ATOM conv = Conv $ \ tm ->
case tm of
(Comb (Const op _) Abs{})
| op == "!" || op == "?" || op == "?!" ->
runConv (convBINDER (convPROP_ATOM conv)) tm
| otherwise -> runConv (_TRY conv) tm
(Comb (Comb (Const op (TyFun TyBool _)) _) _)
| op == "/\\" || op == "\\/" || op == "==>" || op == "=" ->
runConv (convBINOP (convPROP_ATOM conv)) tm
| otherwise -> runConv (_TRY conv) tm
(Comb (Const "~" _) _) -> runConv (convRAND (convPROP_ATOM conv)) tm
_ -> runConv (_TRY conv) tm
| ecaustin/haskhol-deductive | src/HaskHOL/Lib/Canon.hs | bsd-2-clause | 39,170 | 1 | 23 | 13,252 | 13,067 | 6,484 | 6,583 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QDragEnterEvent.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:22
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QDragEnterEvent (
QqqDragEnterEvent(..), QqDragEnterEvent(..)
,QqqDragEnterEvent_nf(..), QqDragEnterEvent_nf(..)
,qDragEnterEvent_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqqDragEnterEvent x1 where
qqDragEnterEvent :: x1 -> IO (QDragEnterEvent ())
class QqDragEnterEvent x1 where
qDragEnterEvent :: x1 -> IO (QDragEnterEvent ())
instance QqDragEnterEvent ((QDragEnterEvent t1)) where
qDragEnterEvent (x1)
= withQDragEnterEventResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragEnterEvent cobj_x1
foreign import ccall "qtc_QDragEnterEvent" qtc_QDragEnterEvent :: Ptr (TQDragEnterEvent t1) -> IO (Ptr (TQDragEnterEvent ()))
instance QqqDragEnterEvent ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qqDragEnterEvent (x1, x2, x3, x4, x5)
= withQDragEnterEventResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragEnterEvent1 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
foreign import ccall "qtc_QDragEnterEvent1" qtc_QDragEnterEvent1 :: Ptr (TQPoint t1) -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> IO (Ptr (TQDragEnterEvent ()))
instance QqDragEnterEvent ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qDragEnterEvent (x1, x2, x3, x4, x5)
= withQDragEnterEventResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragEnterEvent2 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
foreign import ccall "qtc_QDragEnterEvent2" qtc_QDragEnterEvent2 :: CInt -> CInt -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> IO (Ptr (TQDragEnterEvent ()))
class QqqDragEnterEvent_nf x1 where
qqDragEnterEvent_nf :: x1 -> IO (QDragEnterEvent ())
class QqDragEnterEvent_nf x1 where
qDragEnterEvent_nf :: x1 -> IO (QDragEnterEvent ())
instance QqDragEnterEvent_nf ((QDragEnterEvent t1)) where
qDragEnterEvent_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragEnterEvent cobj_x1
instance QqqDragEnterEvent_nf ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qqDragEnterEvent_nf (x1, x2, x3, x4, x5)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragEnterEvent1 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
instance QqDragEnterEvent_nf ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qDragEnterEvent_nf (x1, x2, x3, x4, x5)
= withObjectRefResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragEnterEvent2 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
qDragEnterEvent_delete :: QDragEnterEvent a -> IO ()
qDragEnterEvent_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragEnterEvent_delete cobj_x0
foreign import ccall "qtc_QDragEnterEvent_delete" qtc_QDragEnterEvent_delete :: Ptr (TQDragEnterEvent a) -> IO ()
| uduki/hsQt | Qtc/Gui/QDragEnterEvent.hs | bsd-2-clause | 3,824 | 0 | 17 | 579 | 1,054 | 562 | 492 | 65 | 1 |
{-# LANGUAGE GADTs, StandaloneDeriving #-}
module GL.Geometry where
import GL.Array
import GL.Scalar
data Mode = Points | Lines | LineLoop | LineStrip | Triangles | TriangleStrip
data Geometry a where
Geometry :: (Foldable v, GLScalar n) => Mode -> [v n] -> Geometry (v n)
data ArrayRange = ArrayRange { mode :: Mode, firstVertexIndex :: Int, vertexCount :: Int }
data GeometryArray n = GeometryArray { geometryRanges :: [ArrayRange], geometryArray :: GLArray n }
-- Instances
deriving instance Foldable Geometry
| robrix/ui-effects | src/GL/Geometry.hs | bsd-3-clause | 523 | 0 | 10 | 90 | 151 | 90 | 61 | 10 | 0 |
-- |
-- Module: Data.Chimera
-- Copyright: (c) 2018-2019 Andrew Lelechenko
-- Licence: MIT
-- Maintainer: Andrew Lelechenko <andrew.lelechenko@gmail.com>
--
-- Lazy infinite streams with O(1) indexing.
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
module Data.Chimera
( -- * Memoization
memoize
, memoizeFix
-- * Chimera
, Chimera
, VChimera
, UChimera
-- * Construction
, tabulate
, tabulateFix
, tabulateFix'
, iterate
, cycle
-- * Elimination
, index
, toList
-- * Monadic construction
-- $monadic
, tabulateM
, tabulateFixM
, iterateM
-- * Subvectors
-- $subvectors
, mapSubvectors
, zipSubvectors
) where
import Prelude hiding ((^), (*), div, fromIntegral, not, and, or, cycle, iterate, drop)
import Control.Applicative
import Control.Monad.Fix
import Control.Monad.Zip
import Data.Bits
import Data.Functor.Identity
import qualified Data.Vector as V
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as U
#ifdef MIN_VERSION_mtl
import Control.Monad.Reader (MonadReader, ask, local)
#endif
#ifdef MIN_VERSION_distributive
import Data.Distributive
#ifdef MIN_VERSION_adjunctions
import qualified Data.Functor.Rep as Rep
#endif
#endif
import Data.Chimera.Compat
import Data.Chimera.FromIntegral
-- $monadic
-- Be careful: the stream is infinite, so
-- monadic effects must be lazy
-- in order to be executed in a finite time.
--
-- For instance, lazy state monad works fine:
--
-- >>> import Control.Monad.State.Lazy
-- >>> ch = evalState (tabulateM (\i -> do modify (+ i); get)) 0 :: UChimera Word
-- >>> take 10 (toList ch)
-- [0,1,3,6,10,15,21,28,36,45]
--
-- But the same computation in the strict state
-- monad "Control.Monad.State.Strict" diverges.
-- $subvectors
-- Internally 'Chimera' consists of a number of subvectors.
-- Following functions provide a low-level access to them.
-- This ability is especially important for streams of booleans.
--
-- Let us use 'Chimera' to memoize predicates @f1@, @f2@ @::@ 'Word' @->@ 'Bool'.
-- Imagine them both already
-- caught in amber as @ch1@, @ch2@ @::@ 'UChimera' 'Bool',
-- and now we want to memoize @f3 x = f1 x && f2 x@ as @ch3@.
-- One can do it in as follows:
--
-- > ch3 = tabulate (\i -> index ch1 i && index ch2 i)
--
-- There are two unsatisfactory things here. Firstly,
-- even unboxed vectors store only one boolean per byte.
-- We would rather reach out for 'Data.Bit.Bit' wrapper,
-- which provides an instance of unboxed vector
-- with one boolean per bit. Secondly, combining
-- existing predicates by indexing them and tabulating again
-- becomes relatively expensive, given how small and simple
-- our data is. Fortunately, there is an ultra-fast 'Data.Bit.zipBits'
-- to zip bit vectors. We can combine it altogether like this:
--
-- > import Data.Bit
-- > import Data.Bits
-- > ch1 = tabulate (Bit . f1)
-- > ch2 = tabulate (Bit . f2)
-- > ch3 = zipSubvectors (zipBits (.&.)) ch1 ch2
-- | Lazy infinite streams with elements from @a@,
-- backed by a 'G.Vector' @v@ (boxed, unboxed, storable, etc.).
-- Use 'tabulate', 'tabulateFix', etc. to create a stream
-- and 'index' to access its arbitrary elements
-- in constant time.
newtype Chimera v a = Chimera { _unChimera :: V.Vector (v a) }
deriving (Functor, Foldable, Traversable)
-- | Streams backed by boxed vectors.
type VChimera = Chimera V.Vector
-- | Streams backed by unboxed vectors.
type UChimera = Chimera U.Vector
-- | 'pure' creates a constant stream.
instance Applicative (Chimera V.Vector) where
pure = tabulate . const
(<*>) = zipSubvectors (<*>)
#if __GLASGOW_HASKELL__ > 801
liftA2 f = zipSubvectors (liftA2 f)
#endif
instance Monad (Chimera V.Vector) where
m >>= f = tabulate $ \w -> index (f (index m w)) w
instance MonadFix (Chimera V.Vector) where
mfix = tabulate . mfix . fmap index
instance MonadZip (Chimera V.Vector) where
mzip as bs = tabulate (\w -> (index as w, index bs w))
mzipWith f as bs = tabulate $ \w -> f (index as w) (index bs w)
#ifdef MIN_VERSION_mtl
instance MonadReader Word (Chimera V.Vector) where
ask = tabulate id
local = flip $ (tabulate .) . (.) . index
#endif
#ifdef MIN_VERSION_distributive
instance Distributive (Chimera V.Vector) where
distribute = tabulate . flip (fmap . flip index)
collect f = tabulate . flip ((<$>) . (. f) . flip index)
#ifdef MIN_VERSION_adjunctions
instance Rep.Representable (Chimera V.Vector) where
type Rep (Chimera V.Vector) = Word
tabulate = tabulate
index = index
#endif
#endif
bits :: Int
bits = fbs (0 :: Word)
-- | Create a stream of values of a given function.
-- Once created it can be accessed via 'index' or 'toList'.
--
-- >>> ch = tabulate (^ 2) :: UChimera Word
-- >>> index ch 9
-- 81
-- >>> take 10 (toList ch)
-- [0,1,4,9,16,25,36,49,64,81]
tabulate :: G.Vector v a => (Word -> a) -> Chimera v a
tabulate f = runIdentity $ tabulateM (pure . f)
-- | Monadic version of 'tabulate'.
tabulateM
:: forall m v a.
(Monad m, G.Vector v a)
=> (Word -> m a)
-> m (Chimera v a)
tabulateM f = Chimera <$> V.generateM (bits + 1) tabulateSubVector
where
tabulateSubVector :: Int -> m (v a)
tabulateSubVector 0 = G.singleton <$> f 0
tabulateSubVector i = G.generateM ii (\j -> f (int2word (ii + j)))
where
ii = 1 `unsafeShiftL` (i - 1)
{-# SPECIALIZE tabulateM :: G.Vector v a => (Word -> Identity a) -> Identity (Chimera v a) #-}
-- | For a given @f@ create a stream of values of a recursive function 'fix' @f@.
-- Once created it can be accessed via 'index' or 'toList'.
--
-- For example, imagine that we want to tabulate
-- <https://en.wikipedia.org/wiki/Catalan_number Catalan numbers>:
--
-- >>> catalan n = if n == 0 then 1 else sum [ catalan i * catalan (n - 1 - i) | i <- [0 .. n - 1] ]
--
-- Can we find @catalanF@ such that @catalan@ = 'fix' @catalanF@?
-- Just replace all recursive calls to @catalan@ with @f@:
--
-- >>> catalanF f n = if n == 0 then 1 else sum [ f i * f (n - 1 - i) | i <- [0 .. n - 1] ]
--
-- Now we are ready to use 'tabulateFix':
--
-- >>> ch = tabulateFix catalanF :: VChimera Integer
-- >>> index ch 9
-- 4862
-- >>> take 10 (toList ch)
-- [1,1,2,5,14,42,132,429,1430,4862]
--
-- __Note__: Only recursive function calls with decreasing arguments are memoized.
-- If full memoization is desired, use 'tabulateFix'' instead.
tabulateFix :: G.Vector v a => ((Word -> a) -> Word -> a) -> Chimera v a
tabulateFix uf = runIdentity $ tabulateFixM ((pure .) . uf . (runIdentity .))
-- | Fully memoizing version of 'tabulateFix'.
-- This function will tabulate every recursive call,
-- but might allocate a lot of memory in doing so.
-- For example, the following piece of code calculates the
-- highest number reached by the
-- <https://en.wikipedia.org/wiki/Collatz_conjecture#Statement_of_the_problem Collatz sequence>
-- of a given number, but also allocates tens of gigabytes of memory,
-- because the Collatz sequence will spike to very high numbers.
--
-- >>> collatzF :: (Word -> Word) -> (Word -> Word)
-- >>> collatzF _ 0 = 0
-- >>> collatzF f n = if n <= 2 then 4 else n `max` f (if even n then n `quot` 2 else 3 * n + 1)
-- >>>
-- >>> maximumBy (comparing $ index $ tabulateFix' collatzF) [0..1000000]
-- ...
--
-- Using 'memoizeFix' instead fixes the problem:
--
-- >>> maximumBy (comparing $ memoizeFix collatzF) [0..1000000]
-- 56991483520
tabulateFix' :: G.Vector v a => ((Word -> a) -> Word -> a) -> Chimera v a
tabulateFix' uf = runIdentity $ tabulateFixM' ((pure .) . uf . (runIdentity .))
-- | Monadic version of 'tabulateFix'.
-- There are no particular guarantees about the order of recursive calls:
-- they may be executed more than once or executed in different order.
-- That said, monadic effects must be idempotent and commutative.
tabulateFixM
:: forall m v a.
(Monad m, G.Vector v a)
=> ((Word -> m a) -> Word -> m a)
-> m (Chimera v a)
tabulateFixM = tabulateFixM_ Downwards
{-# SPECIALIZE tabulateFixM :: G.Vector v a => ((Word -> Identity a) -> Word -> Identity a) -> Identity (Chimera v a) #-}
-- | Monadic version of 'tabulateFix''.
tabulateFixM'
:: forall m v a.
(Monad m, G.Vector v a)
=> ((Word -> m a) -> Word -> m a)
-> m (Chimera v a)
tabulateFixM' = tabulateFixM_ Full
-- | Memoization strategy, only used by 'tabulateFixM_'.
data Strategy = Full | Downwards
-- | Internal implementation for 'tabulateFixM' and 'tabulateFixM''.
tabulateFixM_
:: forall m v a.
(Monad m, G.Vector v a)
=> Strategy
-> ((Word -> m a) -> Word -> m a)
-> m (Chimera v a)
tabulateFixM_ strat f = result
where
result :: m (Chimera v a)
result = Chimera <$> V.generateM (bits + 1) tabulateSubVector
tabulateSubVector :: Int -> m (v a)
tabulateSubVector 0 = G.singleton <$> case strat of
Downwards -> fix f 0
Full -> f (\k -> flip index k <$> result) 0
tabulateSubVector i = subResult
where
subResult = G.generateM ii (\j -> f fixF (int2word (ii + j)))
subResultBoxed = V.generateM ii (\j -> f fixF (int2word (ii + j)))
ii = 1 `unsafeShiftL` (i - 1)
fixF :: Word -> m a
fixF k
| k < int2word ii
= flip index k <$> result
| k <= int2word ii `shiftL` 1 - 1
= (`V.unsafeIndex` (word2int k - ii)) <$> subResultBoxed
| otherwise
= case strat of
Downwards -> f fixF k
Full -> flip index k <$> result
-- | 'iterate' @f@ @x@ returns an infinite stream
-- of repeated applications of @f@ to @x@.
--
-- >>> ch = iterate (+ 1) 0 :: UChimera Int
-- >>> take 10 (toList ch)
-- [0,1,2,3,4,5,6,7,8,9]
iterate :: G.Vector v a => (a -> a) -> a -> Chimera v a
iterate f = runIdentity . iterateM (pure . f)
-- | Monadic version of 'iterate'.
iterateM :: forall m v a. (Monad m, G.Vector v a) => (a -> m a) -> a -> m (Chimera v a)
iterateM f seed = do
nextSeed <- f seed
let z = G.singleton seed
zs <- V.iterateNM bits go (G.singleton nextSeed)
pure $ Chimera $ z `V.cons` zs
where
go :: v a -> m (v a)
go vec = do
nextSeed <- f (G.unsafeLast vec)
G.iterateNM (G.length vec `shiftL` 1) f nextSeed
{-# SPECIALIZE iterateM :: G.Vector v a => (a -> Identity a) -> a -> Identity (Chimera v a) #-}
-- | Index a stream in a constant time.
--
-- >>> ch = tabulate (^ 2) :: UChimera Word
-- >>> index ch 9
-- 81
index :: G.Vector v a => Chimera v a -> Word -> a
index (Chimera vs) i =
(vs `V.unsafeIndex` (fbs i - lz))
`G.unsafeIndex`
word2int (i .&. complement ((1 `shiftL` (fbs i - 1)) `unsafeShiftR` lz))
where
lz :: Int
!lz = word2int (clz i)
{-# INLINE index #-}
-- | Convert a stream to an infinite list.
--
-- >>> ch = tabulate (^ 2) :: UChimera Word
-- >>> take 10 (toList ch)
-- [0,1,4,9,16,25,36,49,64,81]
toList :: G.Vector v a => Chimera v a -> [a]
toList (Chimera vs) = foldMap G.toList vs
-- | Return an infinite repetion of a given vector.
-- Throw an error on an empty vector.
--
-- >>> ch = cycle (Data.Vector.fromList [4, 2]) :: VChimera Int
-- >>> take 10 (toList ch)
-- [4,2,4,2,4,2,4,2,4,2]
cycle :: G.Vector v a => v a -> Chimera v a
cycle vec = case l of
0 -> error "Data.Chimera.cycle: empty list"
_ -> tabulate (G.unsafeIndex vec . word2int . (`rem` l))
where
l = int2word $ G.length vec
-- | Memoize a function:
-- repeating calls to 'memoize' @f@ @n@
-- would compute @f@ @n@ only once
-- and cache the result in 'VChimera'.
-- This is just a shortcut for 'index' '.' 'tabulate'.
-- When @a@ is 'U.Unbox', it is faster to use
-- 'index' ('tabulate' @f@ :: 'UChimera' @a@).
--
-- prop> memoize f n = f n
memoize :: (Word -> a) -> (Word -> a)
memoize = index @V.Vector . tabulate
-- | For a given @f@ memoize a recursive function 'fix' @f@,
-- caching results in 'VChimera'.
-- This is just a shortcut for 'index' '.' 'tabulateFix'.
-- When @a@ is 'U.Unbox', it is faster to use
-- 'index' ('tabulateFix' @f@ :: 'UChimera' @a@).
--
-- prop> memoizeFix f n = fix f n
--
-- For example, imagine that we want to memoize
-- <https://en.wikipedia.org/wiki/Fibonacci_number Fibonacci numbers>:
--
-- >>> fibo n = if n < 2 then toInteger n else fibo (n - 1) + fibo (n - 2)
--
-- Can we find @fiboF@ such that @fibo@ = 'fix' @fiboF@?
-- Just replace all recursive calls to @fibo@ with @f@:
--
-- >>> fiboF f n = if n < 2 then toInteger n else f (n - 1) + f (n - 2)
--
-- Now we are ready to use 'memoizeFix':
--
-- >>> memoizeFix fiboF 10
-- 55
-- >>> memoizeFix fiboF 100
-- 354224848179261915075
--
-- This function can be used even when arguments
-- of recursive calls are not strictly decreasing,
-- but they might not get memoized. If this is not desired
-- use 'tabulateFix'' instead.
-- For example, here is a routine to measure the length of
-- <https://oeis.org/A006577 Collatz sequence>:
--
-- >>> collatzF f n = if n <= 1 then 0 else 1 + f (if even n then n `quot` 2 else 3 * n + 1)
-- >>> memoizeFix collatzF 27
-- 111
memoizeFix :: ((Word -> a) -> Word -> a) -> (Word -> a)
memoizeFix = index @V.Vector . tabulateFix
-- | Map subvectors of a stream, using a given length-preserving function.
mapSubvectors
:: (G.Vector u a, G.Vector v b)
=> (u a -> v b)
-> Chimera u a
-> Chimera v b
mapSubvectors f (Chimera bs) = Chimera (fmap f bs)
-- | Zip subvectors from two streams, using a given length-preserving function.
zipSubvectors
:: (G.Vector u a, G.Vector v b, G.Vector w c)
=> (u a -> v b -> w c)
-> Chimera u a
-> Chimera v b
-> Chimera w c
zipSubvectors f (Chimera bs1) (Chimera bs2) = Chimera (mzipWith f bs1 bs2)
| Bodigrim/bit-stream | Data/Chimera.hs | bsd-3-clause | 13,879 | 2 | 16 | 2,965 | 2,736 | 1,548 | 1,188 | 158 | 4 |
-- #!/usr/bin/env runghc
-- (,st') in parse
-- {-# LANGUAGE TupleSections #-}
-- {-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
-- {-# OPTIONS_GHC -cpp -DPiForallInstalled #-}
--------------------------------------------------------------------
-- |
-- Copyright : (c) Andreas Reuleaux 2015
-- License : BSD2
-- Maintainer: Andreas Reuleaux <rx@a-rx.info>
-- Stability : experimental
-- Portability: non-portable
--
-- This module tests Pire's parser, declartions in particular
--------------------------------------------------------------------
module ParserTests.Decls where
import Test.Tasty
import Test.Tasty.HUnit
import Pire.Syntax.Nm
import Pire.Syntax.Ws
import Pire.Syntax.Token
import Pire.Syntax.Telescope
import Pire.Syntax.Eps
import Pire.Syntax.Decl
import Pire.Syntax.Constructor
import Pire.Syntax
import Pire.NoPos
import Pire.Forget
import Pire.Untie
import Pire.Parser.ParseUtils
import Pire.Parser.PiParseUtils
import Pire.Parser.Decl
-- import Pire.Parser.DataType
#ifdef PiForallInstalled
import qualified PiForall.Parser as P
#endif
-- main' "decls"
parsingDeclsU = testGroup "parsing decls - unit tests" $ tail [
undefined
-- sigs
, let s = "foo : bar"
in
testGroup ("sig '"++s++"'") $ tail [
undefined
, testCase ("parsing sigDef '"++s++"'")
$ (nopos $ parse sigDef s) @?= (Sig "foo" $ V "bar")
, testCase ("parse & forget sigDef_ '"++s++"'")
$ (forget $ parseP sigDef_ s) @?= (parseP sigDef s)
]
#ifdef PiForallInstalled
++ tail [
undefined
, testCase ("parse & untie sigDef '"++s++"'")
$ (untie $ parse sigDef s) @?= (piParse P.sigDef s)
, testCase ("parse & untie sigDef_ '"++s++"'")
$ (untie $ parseP sigDef_ s) @?= (piParseP P.sigDef s)
, testCase ("parse & untie decl_ '"++s++"'")
$ (untie $ parseP decl_ s) @?= (piParseP P.decl s)
]
#endif
, let s = "foo{-f-}:{-c-}bar{-b-}"
in
testGroup ("sig '"++s++"'") $ tail [
undefined
, testCase ("parsing sigDef '"++s++"'")
$ (nopos $ parse sigDef s) @?= (Sig "foo" $ V "bar")
, testCase ("parsing sigDef_ '"++s++"'")
$ (nopos $ parse sigDef_ s)
-- @?= (Sig_ (Nm_ "foo" $ Ws "{-f-}") (Colon ":" $ Ws "{-c-}") $ V_ "bar" $ Ws "{-b-}")
@?= (Sig_ (Nm1_ "foo" $ Ws "{-f-}") (Colon ":" $ Ws "{-c-}") $ Ws_ (V "bar") $ Ws "{-b-}")
, testCase ("parse & forget sigDef_ '"++s++"'")
$ (forget $ parseP sigDef_ s) @?= (parseP sigDef s)
]
#ifdef PiForallInstalled
++ tail [
undefined
, testCase ("parse & untie sigDef_ '"++s++"'")
$ (untie $ parseP sigDef_ s) @?= (piParseP P.sigDef s)
, testCase ("parse & untie decl_ '"++s++"'")
$ (untie $ parseP decl_ s) @?= (piParseP P.decl s)
]
#endif
-- vals
-- , let s = " foo = bar"
-- in
-- testCase ("parsing valDef '"++s++"'")
-- $ (nopos $ parse valDef s)
-- @?= (Def "foo" $ V "bar")
, let s = "foo = bar"
in
testGroup ("valDef '"++s++"'") $ tail [
undefined
, testCase ("parsing valDef '"++s++"'")
$ (nopos $ parse valDef s) @?= (Def "foo" $ V "bar")
, testCase ("parse & forget valDef_ '"++s++"'")
$ (forget $ parseP valDef_ s) @?= (parseP valDef s)
]
#ifdef PiForallInstalled
++ tail [
undefined
, testCase ("parse & untie valDef '"++s++"'")
$ (untie $ parse valDef s) @?= (piParse P.valDef s)
, testCase ("parse & untie valDef_ '"++s++"'")
$ (untie $ parseP valDef_ s) @?= (piParseP P.valDef s)
, testCase ("parse & untie decl_ '"++s++"'")
$ (untie $ parseP decl_ s) @?= (piParseP P.decl s)
]
#endif
, let s = "foo{-f-}={-c-}bar{-b-}"
in
testGroup ("val '"++s++"'") $ tail [
undefined
, testCase ("parsing valDef '"++s++"'")
$ (nopos $ parse valDef s)
@?= (Def "foo" $ V "bar")
, testCase ("parsing valDef_ '"++s++"'")
$ (nopos $ parse valDef_ s)
-- @?= (Def_ (Nm_ "foo" $ Ws "{-f-}") (Equal $ Ws "{-c-}") $ V_ "bar" $ Ws "{-b-}")
@?= (Def_ (Nm1_ "foo" $ Ws "{-f-}") (Equal "=" $ Ws "{-c-}") $ Ws_ (V "bar") $ Ws "{-b-}")
, testCase ("parse & forget valDef_ '"++s++"'")
$ (forget $ parseP valDef_ s) @?= (parseP valDef s)
]
#ifdef PiForallInstalled
++ tail [
undefined
, testCase ("parse & untie valDef_ '"++s++"'")
$ (untie $ parseP valDef_ s) @?= (piParseP P.valDef s)
, testCase ("parse & untie decl_ '"++s++"'")
$ (untie $ parseP decl_ s) @?= (piParseP P.decl s)
]
#endif
-- dataDef
{-
for cut & paste in ghci / cabal repl
let s = unlines ["data Nat : Type where"," Zero" ," Succ of (Nat)"]
-}
, let s = unlines $ tail [
undefined
, "data Nat : Type where"
, " Zero"
, " Succ of (Nat)"
]
in
testGroup ("dataDef '"++s++"'") $ tail [
undefined
, testCase ("parsing dataDef '"++s++"'")
$ (nopos $ parse dataDef s)
@?= (Data "Nat" EmptyTele [ConstructorDef' "Zero" EmptyTele,ConstructorDef' "Succ" (Cons RuntimeP "_" (TCon "Nat" []) EmptyTele)])
-- , testCase ("parsing dataDef_ '"++s++"'")
-- $ (nopos $ parse dataDef_ s)
-- @?= (Data_ (DataTok "data" $ Ws " ") (Nm_ "Nat" $ Ws " ") EmptyTele (Colon ":" (Ws " ")) (Type_ "Type" (Ws " ")) (Where "where" (Ws "\n ")) Nothing [(ConstructorDef'_ (Nm_ "Zero" $ Ws "\n ") Nothing EmptyTele,Nothing),(ConstructorDef'_ (Nm_ "Succ" $ Ws " ") (Just (Of "of" (Ws " "))) (ConsWildInParens_ RuntimeP (ParenOpen "(" (Ws "")) "_" (TCon_ (Nm_ "Nat" $ Ws "") []) (ParenClose ")" (Ws "\n")) EmptyTele),Nothing)] Nothing)
-- , testCase ("parsing dataDef_ '"++s++"'")
-- $ (nopos $ parse dataDef_ s)
-- @?= (Data_ (DataTok "data" $ Ws " ") (Nm_ "Nat" $ Ws " ") EmptyTele (Colon ":" (Ws " ")) (Type_ "Type" (Ws " ")) (Where "where" (Ws "\n ")) Nothing [(ConstructorDef'_ (Nm_ "Zero" $ Ws "\n ") Nothing EmptyTele,Nothing),(ConstructorDef'_ (Nm_ "Succ" $ Ws " ") (Just (Of "of" (Ws " "))) (ConsWildInParens_ RuntimeP (ParenOpen "(" (Ws "")) (InvisibleBinder 0) (TCon_ (Nm_ "Nat" $ Ws "") []) (ParenClose ")" (Ws "\n")) EmptyTele),Nothing)] Nothing)
, testCase ("parsing dataDef_ '"++s++"'")
$ (nopos $ parse dataDef_ s)
@?= (Data_ (DataTok "data" $ Ws " ") (Nm1_ "Nat" $ Ws " ") EmptyTele (Colon ":" (Ws " ")) (Type_ "Type" (Ws " ")) (Where "where" (Ws "\n ")) Nothing [(ConstructorDef'_ (Nm1_ "Zero" $ Ws "\n ") Nothing EmptyTele,Nothing),(ConstructorDef'_ (Nm1_ "Succ" $ Ws " ") (Just (Of "of" (Ws " "))) (ConsWildInParens_ RuntimeP (ParenOpen "(" (Ws "")) (InvisibleBinder 0) (TCon_ (Nm_ "Nat" $ Ws "") []) (ParenClose ")" (Ws "\n")) EmptyTele),Nothing)] Nothing)
, testCase ("parse & forget dataDef_ '"++s++"'")
$ (forget $ parseP dataDef_ s) @?= (parseP dataDef s)
]
#ifdef PiForallInstalled
++ tail [
undefined
, testCase ("parse & untie dataDef_ '"++s++"'")
$ (untie $ parseP dataDef_ s) @?= (piParseP P.dataDef s)
, testCase ("parse & untie decl_ '"++s++"'")
$ (untie $ parseP decl_ s) @?= (piParseP P.decl s)
-- need telescopes+constructor defs first...
, testCase ("parse & untie dataDef w/ nopos '"++s++"'")
$ (nopos $ untie $ parse dataDef s) @?= (nopos $ piParse P.dataDef s)
, testCase ("parse & untie dataDef '"++s++"'")
$ (untie $ parse dataDef s) @?= (piParse P.dataDef s)
]
#endif
]
| reuleaux/pire | tests/ParserTests/Decls.hs | bsd-3-clause | 8,018 | 0 | 26 | 2,342 | 2,067 | 1,083 | 984 | 71 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.AmountOfMoney.EN.BZ.Corpus
( allExamples
, negativeExamples
) where
import Data.String
import Data.Text (Text)
import Prelude
import Duckling.AmountOfMoney.Types
import Duckling.Testing.Types
allExamples :: [Example]
allExamples = concat
[ examples (simple Dollar 1000)
[ "a grand"
, "1 grand"
]
, examples (simple Dollar 10000)
[ "10 grand"
, "two hundred thousand nickels"
]
, examples (simple Dollar 1)
[ "four quarters"
, "ten dimes"
, "twenty nickels"
]
, examples (simple Dollar 0.1)
[ "dime"
, "a dime"
, "two nickels"
]
, examples (simple Dollar 0.25)
[ "quarter"
, "a quarter"
, "five nickels"
]
, examples (simple Dollar 0.05)
[ "nickel"
, "a nickel"
]
]
negativeExamples :: [Text]
negativeExamples =
[ "grand"
]
| facebookincubator/duckling | Duckling/AmountOfMoney/EN/BZ/Corpus.hs | bsd-3-clause | 1,282 | 0 | 9 | 456 | 226 | 134 | 92 | 35 | 1 |
module Yawn.Util.Maybe where
liftIOMaybe :: b -> (a -> IO (b)) -> IO (Maybe a) -> IO (b)
liftIOMaybe d f m = m >>= \m' -> case m' of
Nothing -> return d
Just y -> f y
liftIOMaybe_ :: (a -> IO ()) -> IO (Maybe a) -> IO ()
liftIOMaybe_ = liftIOMaybe ()
fromIOMaybe :: IO (Maybe b) -> IO (Maybe a) -> (a -> IO (Maybe b)) -> IO (Maybe b)
fromIOMaybe d m f = m >>= \m' -> case m' of
Nothing -> d
Just y -> f y
fromIOMaybe_ :: IO (Maybe a) -> (a -> IO (Maybe b)) -> IO (Maybe b)
fromIOMaybe_ = fromIOMaybe (return Nothing)
| ameingast/yawn | src/Yawn/Util/Maybe.hs | bsd-3-clause | 531 | 0 | 12 | 129 | 311 | 154 | 157 | 13 | 2 |
module Simplify where
import qualified Data.Set as DataSet
import Grammar
simplify :: (Show a, Ord a) => Refs a -> Expr a -> Expr a
simplify refs expr =
let simp = simplify' refs
in case expr of
Empty -> Empty
EmptySet -> EmptySet
(Internal v) -> Internal v
(Call v e) -> Call v e
(Return v) -> Return v
(Concat e1 e2) -> simplifyConcat (simp e1) (simp e2)
(Or e1 e2) -> simplifyOr refs (simp e1) (simp e2)
(And e1 e2) -> simplifyAnd refs (simp e1) (simp e2)
(ZeroOrMore e) -> simplifyZeroOrMore (simp e)
(Not e) -> simplifyNot (simp e)
(Optional e) -> simplifyOptional (simp e)
(Interleave e1 e2) -> simplifyInterleave (simp e1) (simp e2)
(Contains e) -> simplifyContains (simp e)
e@(Reference _) -> e
wtf -> error $ "unexpected expression: " ++ show wtf
simplify' :: (Show a, Ord a) => Refs a -> Expr a -> Expr a
simplify' refs e = checkRef refs $ simplify refs e
simplifyConcat :: Expr a -> Expr a -> Expr a
simplifyConcat EmptySet _ = EmptySet
simplifyConcat _ EmptySet = EmptySet
simplifyConcat (Concat e1 e2) e3 =
simplifyConcat e1 (Concat e2 e3)
simplifyConcat Empty e = e
simplifyConcat e Empty = e
simplifyConcat (Not EmptySet) (Concat e (Not EmptySet)) = Contains e
simplifyConcat e1 e2 = Concat e1 e2
simplifyOr :: (Ord a) => Refs a -> Expr a -> Expr a -> Expr a
simplifyOr _ EmptySet e = e
simplifyOr _ e EmptySet = e
simplifyOr _ (Not EmptySet) _ = (Not EmptySet)
simplifyOr _ _ (Not EmptySet) = (Not EmptySet)
simplifyOr refs Empty e = if nullable refs e then e else Or Empty e
simplifyOr refs e Empty = if nullable refs e then e else Or Empty e
simplifyOr _ e1 e2 = bin Or $ DataSet.toAscList $ setOfOrs e1 `DataSet.union` setOfOrs e2
bin :: (Expr a -> Expr a -> Expr a) -> [Expr a] -> Expr a
bin op [e] = e
bin op [e1,e2] = op e1 e2
bin op (e:es) = op e (bin op es)
setOfOrs :: (Ord a) => Expr a -> DataSet.Set (Expr a)
setOfOrs (Or e1 e2) = setOfOrs e1 `DataSet.union` setOfOrs e2
setOfOrs e = DataSet.singleton e
simplifyAnd :: (Ord a) => Refs a -> Expr a -> Expr a -> Expr a
simplifyAnd _ EmptySet _ = EmptySet
simplifyAnd _ _ EmptySet = EmptySet
simplifyAnd _ (Not EmptySet) e = e
simplifyAnd _ e (Not EmptySet) = e
simplifyAnd refs Empty e = if nullable refs e then Empty else EmptySet
simplifyAnd refs e Empty = if nullable refs e then Empty else EmptySet
simplifyAnd _ e1 e2 = bin And $ DataSet.toAscList $ setOfAnds e1 `DataSet.union` setOfAnds e2
setOfAnds :: (Ord a) => Expr a -> DataSet.Set (Expr a)
setOfAnds (And e1 e2) = setOfAnds e1 `DataSet.union` setOfAnds e2
setOfAnds e = DataSet.singleton e
simplifyZeroOrMore :: Expr a -> Expr a
simplifyZeroOrMore (ZeroOrMore e) = ZeroOrMore e
simplifyZeroOrMore e = ZeroOrMore e
simplifyNot :: Expr a -> Expr a
simplifyNot (Not e) = e
simplifyNot e = Not e
simplifyOptional :: Expr a -> Expr a
simplifyOptional Empty = Empty
simplifyOptional e = Optional e
simplifyInterleave :: (Ord a) => Expr a -> Expr a -> Expr a
simplifyInterleave EmptySet _ = EmptySet
simplifyInterleave _ EmptySet = EmptySet
simplifyInterleave Empty e = e
simplifyInterleave e Empty = e
simplifyInterleave (Not EmptySet) (Not EmptySet) = (Not EmptySet)
simplifyInterleave e1 e2 = bin Interleave $ DataSet.toAscList $ setOfInterleaves e1 `DataSet.union` setOfInterleaves e2
setOfInterleaves :: (Ord a) => Expr a -> DataSet.Set (Expr a)
setOfInterleaves (Interleave e1 e2) = setOfInterleaves e1 `DataSet.union` setOfInterleaves e2
setOfInterleaves e = DataSet.singleton e
simplifyContains :: Expr a -> Expr a
simplifyContains Empty = (Not EmptySet)
simplifyContains (Not EmptySet) = (Not EmptySet)
simplifyContains EmptySet = EmptySet
simplifyContains e = Contains e
checkRef :: (Eq a) => Refs a -> Expr a -> Expr a
checkRef refs e = case reverseLookupRef e refs of
Nothing -> e
(Just k) -> Reference k
| katydid/nwe | src/Simplify.hs | bsd-3-clause | 3,805 | 36 | 15 | 728 | 1,723 | 847 | 876 | 87 | 15 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
#if __GLASGOW_HASKELL__ == 704
{-# LANGUAGE ConstraintKinds #-}
#endif
module Database.InfluxDB.TH
( Options(..), defaultOptions
, deriveSeriesData
, deriveToSeriesData
, deriveFromSeriesData
, stripPrefixLower
, stripPrefixSnake
) where
import Control.Applicative
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (VarStrictType)
import Prelude
import qualified Data.Vector as V
import Database.InfluxDB.Decode
import Database.InfluxDB.Encode
import Database.InfluxDB.Types.Internal
data Options = Options
{ fieldLabelModifier :: String -> String
}
defaultOptions :: Options
defaultOptions = Options
{ fieldLabelModifier = id
}
deriveSeriesData :: Options -> Name -> Q [Dec]
deriveSeriesData opts name = (++)
<$> deriveToSeriesData opts name
<*> deriveFromSeriesData opts name
deriveToSeriesData :: Options -> Name -> Q [Dec]
deriveToSeriesData opts name = do
info <- reify name
case info of
TyConI dec -> pure <$> deriveWith toSeriesDataBody opts dec
_ -> fail $ "Expected a type constructor, but got " ++ show info
deriveFromSeriesData :: Options -> Name -> Q [Dec]
deriveFromSeriesData opts name = do
info <- reify name
case info of
TyConI dec -> pure <$> deriveWith fromSeriesDataBody opts dec
_ -> fail $ "Expected a type constructor, but got " ++ show info
deriveWith
:: (Options -> Name -> [TyVarBndr] -> Con -> Q Dec)
-> Options -> Dec -> Q Dec
deriveWith f opts dec = case dec of
DataD _ tyName tyVars [con] _ -> f opts tyName tyVars con
NewtypeD _ tyName tyVars con _ -> f opts tyName tyVars con
_ -> fail $ "Expected a data or newtype declaration, but got " ++ show dec
toSeriesDataBody :: Options -> Name -> [TyVarBndr] -> Con -> Q Dec
toSeriesDataBody opts tyName tyVars con = do
case con of
RecC conName vars -> InstanceD
<$> mapM tyVarToPred tyVars
<*> [t| ToSeriesData $(conT tyName) |]
<*> deriveDecs conName vars
_ -> fail $ "Expected a record, but got " ++ show con
where
tyVarToPred tv = case tv of
#if MIN_VERSION_template_haskell(2, 10, 0)
PlainTV name -> conT ''FromValue `appT` varT name
KindedTV name _ -> conT ''FromValue `appT` varT name
#else
PlainTV name -> classP ''FromValue [varT name]
KindedTV name _ -> classP ''FromValue [varT name]
#endif
deriveDecs _conName vars = do
a <- newName "a"
sequence
[ funD 'toSeriesColumns
[ clause [wildP]
(normalB [| V.fromList $(listE columns) |]) []
]
, funD 'toSeriesPoints
[ clause [varP a]
(normalB [| V.fromList $(listE $ map (applyToValue a) vars) |]) []
]
]
where
applyToValue a (name, _, _) = [| toValue ($(varE name) $(varE a)) |]
columns = map (varStrictTypeToColumn opts) vars
fromSeriesDataBody :: Options -> Name -> [TyVarBndr] -> Con -> Q Dec
fromSeriesDataBody opts tyName tyVars con = do
case con of
RecC conName vars -> instanceD
(mapM tyVarToPred tyVars)
[t| FromSeriesData $(conT tyName) |]
[deriveDec conName vars]
_ -> fail $ "Expected a record, but got " ++ show con
where
tyVarToPred tv = case tv of
#if MIN_VERSION_template_haskell(2, 10, 0)
PlainTV name -> conT ''FromValue `appT` varT name
KindedTV name _ -> conT ''FromValue `appT` varT name
#else
PlainTV name -> classP ''FromValue [varT name]
KindedTV name _ -> classP ''FromValue [varT name]
#endif
deriveDec conName vars = funD 'parseSeriesData
[ clause [] (normalB deriveBody) []
]
where
deriveBody = do
values <- newName "values"
appE (varE 'withValues) $ lamE [varP values] $
foldl (go values) [| pure $(conE conName) |] columns
where
go :: Name -> Q Exp -> Q Exp -> Q Exp
go values expQ col = [| $expQ <*> $(varE values) .: $col |]
columns = map (varStrictTypeToColumn opts) vars
varStrictTypeToColumn :: Options -> VarStrictType -> Q Exp
varStrictTypeToColumn opts = column opts . f
where
f (var, _, _) = var
column :: Options -> Name -> Q Exp
column opts = litE . stringL . fieldLabelModifier opts . nameBase
| alphaHeavy/influxdb-haskell | src/Database/InfluxDB/TH.hs | bsd-3-clause | 4,263 | 0 | 15 | 1,053 | 1,194 | 620 | 574 | 92 | 3 |
module Life.Type
(Lifegame(..))
where
data Lifegame = Lifegame { size :: Int
, board :: [(Int, Int)]
} deriving (Eq, Show)
| nichiyoubi/lifegame | src/Life/Type.hs | bsd-3-clause | 133 | 2 | 10 | 31 | 58 | 36 | 22 | 5 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
module Mismi.Cloudwatch.Amazonka (
module AWS
) where
import Network.AWS.CloudWatch as AWS
| ambiata/mismi | mismi-cloudwatch/src/Mismi/Cloudwatch/Amazonka.hs | bsd-3-clause | 144 | 0 | 4 | 33 | 22 | 16 | 6 | 4 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Main where
import Control.Lens hiding ((...))
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Writer hiding (Alt)
import qualified Data.Map.Strict as M
import qualified Data.Sequence as Sequence
import Numeric.Interval
import Data.Text.Prettyprint.Doc (pretty)
import Data.Text.Prettyprint.Doc.Util (putDocW)
import Mtg.Data
import qualified Mtg.Decks as Decks
import Mtg.Effects
import Mtg.Statistics
-- | Turn a deck into a library
shuffle :: MonadRandom m => Deck -> m Library
shuffle (Deck cards) = fmap Library $ go theSeq []
where
theSeq =
M.foldlWithKey'
(\s cd (Sum count) -> s <> Sequence.replicate count cd)
mempty
cards
go theDeck lib =
case Sequence.length theDeck of
0 -> return lib
n -> do
idx <- chooseFromInterval (0 ... n)
let topCard = Sequence.index theDeck idx
let deck' = Sequence.deleteAt idx theDeck
go deck' (topCard : lib)
-- | Draw a number of cards from the library
draw ::
(Monad m, HasLibrary a, HasHand a, MonadState a m, MonadReader a m)
=> Int
-> m ()
draw i = do
(hd, rst) <- view $ library . unLibrary . to (splitAt i)
library .= (Library rst)
hand <>= (Hand hd)
hasLand :: (Monad m, HasHand a, MonadReader a m) => m Bool
hasLand = view $ hand . unHand . to (any isLand)
playLand ::
( Monad m
, HasHand a
, HasBattlefield a
, MonadReader a m
, MonadPlus m
, MonadState a m
)
=> m ()
playLand = do
ld <- selectFromHand isLand
battlefield <>= (Battlefield [ld])
playLand' ::
( Monad m
, HasHand a
, HasBattlefield a
, MonadReader a m
, MonadPlus m
, MonadState a m
) => m ()
playLand' = do
l <- hasLand
if l
then playLand
else return ()
emptyHand ::
( Monad m
, HasHand a
, MonadState a m)
=> m ()
emptyHand = hand .= mempty
-- | Start the game by shuffling a deck.
startGame ::
( Monad m
, HasGameState a
, HasLibrary a
, HasTurn a
, MonadState a m
, MonadRandom m
, MonadReader a m
, HasHand a
, HasBattlefield a
, MonadWriter DeckStatistics m
, MonadPlus m
)
=> Deck
-> m ()
startGame theDeck = do
gameState .= initialState
library <~ shuffle theDeck
draw 7
maybeMulligan theDeck
playTurn
playTurn
playTurn
playTurn
playTurn
maybeMulligan :: ( Monad m
, HasHand a
, HasLibrary a
, MonadState a m
, MonadRandom m
, MonadReader a m
, MonadWriter DeckStatistics m
, MonadPlus m)
=> Deck
-> m ()
maybeMulligan d = do
Hand hnd <- view hand
let numLands = length $ filter isLand hnd
case length hnd of
7 -> do
if numLands < 3 then (library <~ shuffle d) >> emptyHand >> (draw 6) else return ()
6 -> do
if numLands < 3 then (library <~ shuffle d) >> emptyHand >> (draw 5) else return ()
_ -> return ()
playTurn :: ( Monad m
, HasGameState a
, HasLibrary a
, HasTurn a
, MonadState a m
, MonadRandom m
, MonadReader a m
, HasHand a
, HasBattlefield a
, MonadWriter DeckStatistics m
, MonadPlus m
)
=> m ()
playTurn = do
turn %= succ
draw 1
logLandsInHand
logConvertedManaCost
logCardsInHand
playLand'
logAvgManaCurve
-- | Play a number of times and aggregate the results
-- | TODO: Return type should not be IO
simulate :: Int -> Deck -> IO DeckStatistics
simulate n d =
fmap (foldMap snd) $ mapM (const $ evalGame (startGame d)) [1 .. n]
main :: IO ()
main = (simulate 1000 Decks.myDeck) >>= putDocW 80 . pretty
| j-mueller/mtg-builder | src/Main.hs | bsd-3-clause | 3,938 | 0 | 17 | 1,250 | 1,284 | 651 | 633 | 140 | 5 |
module Main where
import Data.Decimal
import Data.Ratio
import Data.Word
import Test.HUnit
import Control.Applicative
import Test.QuickCheck
import Test.Framework as TF (defaultMain, testGroup, Test)
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2 (testProperty)
instance (Integral i, Arbitrary i) => Arbitrary (DecimalRaw i) where
arbitrary = Decimal <$> arbitrary <*> arbitrary
-- arbitrary = do
-- e <- sized (\n -> resize (n `div` 10) arbitrary) :: Gen Int
-- m <- sized (\n -> resize (n * 10) arbitrary)
-- return $ Decimal (fromIntegral $ abs e) m
instance (Integral i, Arbitrary i) => CoArbitrary (DecimalRaw i) where
coarbitrary (Decimal e m) = variant (v:: Integer)
where v = fromIntegral e + fromIntegral m
-- | "read" is the inverse of "show".
--
-- > read (show n) == n
prop_readShow :: Decimal -> Bool
prop_readShow d = read (show d) == d
-- | Read and show preserve decimal places.
--
-- > decimalPlaces (read (show n)) == decimalPlaces n
prop_readShowPrecision :: Decimal -> Bool
prop_readShowPrecision d = decimalPlaces (read (show d) :: Decimal)
== decimalPlaces d
-- | "fromInteger" definition.
--
-- > decimalPlaces (fromInteger n) == 0 &&
-- > decimalMantissa (fromInteger n) == n
prop_fromIntegerZero :: Integer -> Bool
prop_fromIntegerZero n = decimalPlaces (fromInteger n :: Decimal) == 0 &&
decimalMantissa (fromInteger n :: Decimal) == n
-- | Increased precision does not affect equality.
--
-- > decimalPlaces d < maxBound ==> roundTo (decimalPlaces d + 1) d == d
prop_increaseDecimals :: Decimal -> Property
prop_increaseDecimals d =
decimalPlaces d < maxBound ==> roundTo (decimalPlaces d + 1) d == d
-- | Decreased precision can make two decimals equal, but it can never change
-- their order.
--
-- > forAll d1, d2 :: Decimal -> legal beforeRound afterRound
-- > where
-- > beforeRound = compare d1 d2
-- > afterRound = compare (roundTo 0 d1) (roundTo 0 d2)
-- > legal GT x = x `elem` [GT, EQ]
-- > legal EQ x = x `elem` [EQ]
-- > legal LT x = x `elem` [LT, EQ]
prop_decreaseDecimals :: Decimal -> Decimal -> Bool
prop_decreaseDecimals d1 d2 = legal beforeRound afterRound
where
beforeRound = compare d1 d2
afterRound = compare (roundTo 0 d1) (roundTo 0 d2)
legal GT x = x `elem` [GT, EQ]
legal EQ x = x `elem` [EQ]
legal LT x = x `elem` [LT, EQ]
-- | Greedy rounding always produces a larger or equal value when we drop precision
prop_roundingGreedy :: Decimal -> Property
prop_roundingGreedy d =
let afterRound = compare d rounded
rounded = roundTo' (decimalPlaces d - 1) d
legal LT = True
legal EQ = True
legal GT = False
in decimalPlaces d < maxBound ==> legal afterRound
-- | > (x + y) - y == x
prop_inverseAdd :: Decimal -> Decimal -> Bool
prop_inverseAdd x y = (x + y) - y == x
-- | Multiplication is repeated addition.
--
-- > forall d, NonNegative i : (sum $ replicate i d) == d * fromIntegral (max i 0)
prop_repeatedAdd :: Decimal -> Word8 -> Bool
prop_repeatedAdd d i = (sum $ replicate (fromIntegral i) d) == d * fromIntegral (max i 0)
-- | Division produces the right number of parts.
--
-- > forall d, Positive i : (sum $ map fst $ divide d i) == i
prop_divisionParts :: Decimal -> Positive Int -> Property
prop_divisionParts d (Positive i) = i > 0 ==> (sum $ map fst $ divide d i) == i
-- | Division doesn't drop any units.
--
-- > forall d, Positive i : (sum $ map (\(n,d1) -> fromIntegral n * d1) $ divide d i) == d
prop_divisionUnits :: Decimal -> Positive Int -> Bool
prop_divisionUnits d (Positive i) =
(sum $ map (\(n,d1) -> fromIntegral n * d1) $ divide d i) == d
-- | Allocate produces the right number of parts.
--
-- > sum ps /= 0 ==> length ps == length (allocate d ps)
prop_allocateParts :: Decimal -> [Integer] -> Property
prop_allocateParts d ps =
sum ps /= 0 ==> length ps == length (allocate d ps)
-- | Allocate doesn't drop any units.
--
-- > sum ps /= 0 ==> sum (allocate d ps) == d
prop_allocateUnits :: Decimal -> [Integer] -> Property
prop_allocateUnits d ps =
sum ps /= 0 ==> sum (allocate d ps) == d
-- | Absolute value definition
--
-- > decimalPlaces a == decimalPlaces d &&
-- > decimalMantissa a == abs (decimalMantissa d)
-- > where a = abs d
prop_abs :: Decimal -> Bool
prop_abs d = decimalPlaces a == decimalPlaces d &&
decimalMantissa a == abs (decimalMantissa d)
where a = abs d
-- | Sign number defintion
--
-- > signum d == (fromInteger $ signum $ decimalMantissa d)
prop_signum :: Decimal -> Bool
prop_signum d = signum d == (fromInteger $ signum $ decimalMantissa d)
-- | The addition is valid
prop_sumValid :: Decimal -> Decimal -> Property
prop_sumValid a b = (decimalPlaces a < maxBound && decimalPlaces b < maxBound) ==>
(toRational (a + b) == (toRational a) + (toRational b))
prop_mulValid :: Decimal -> Decimal -> Property
prop_mulValid a b = ((ad + bd) < fromIntegral (maxBound :: Word8)) ==>
(toRational (a * b) == (toRational a) * (toRational b))
where
ad, bd :: Integer
ad = fromIntegral $ decimalPlaces a
bd = fromIntegral $ decimalPlaces b
prop_eitherFromRational :: Decimal -> Bool
prop_eitherFromRational d = (Right d) == (eitherFromRational $ toRational d)
prop_normalizeDecimal :: Decimal -> Bool
prop_normalizeDecimal d = d == (normalizeDecimal d)
-- | Division is the inverted multiplication
prop_divisionMultiplication :: Decimal -> Decimal -> Property
prop_divisionMultiplication a b = ((ad + bd) < fromIntegral (maxBound :: Word8) && a /= 0 && b /= 0) ==>
(c / a == b) .&&. (c / b == a)
where
ad :: Integer
ad = fromIntegral $ decimalPlaces a
bd = fromIntegral $ decimalPlaces b
c = a * b
prop_fromRational :: Decimal -> Bool
prop_fromRational a = a == (fromRational $ toRational a)
prop_properFraction :: Decimal -> Bool
prop_properFraction a = a == (fromIntegral b + d)
where
b :: Integer
(b, d) = properFraction a
main :: IO ()
main = defaultMain tests
-- Monomorphic variations on polymorphic themes to avoid type default warnings.
dec :: Word8 -> Integer -> Decimal
dec = Decimal
dec1 :: Word8 -> Int -> DecimalRaw Int
dec1 = Decimal
piD :: Double
piD = pi
tests :: [TF.Test]
tests = [
testGroup "QuickCheck Data.Decimal" [
testProperty "readShow" prop_readShow,
testProperty "readShowPrecision" prop_readShowPrecision,
testProperty "fromIntegerZero" prop_fromIntegerZero,
testProperty "roundingGreedy" prop_roundingGreedy,
testProperty "increaseDecimals" prop_increaseDecimals,
testProperty "decreaseDecimals" prop_decreaseDecimals,
testProperty "inverseAdd" prop_inverseAdd,
testProperty "repeatedAdd" prop_repeatedAdd,
testProperty "divisionParts" prop_divisionParts,
testProperty "divisionUnits" prop_divisionUnits,
testProperty "allocateParts" prop_allocateParts,
testProperty "allocateUnits" prop_allocateUnits,
testProperty "abs" prop_abs,
testProperty "signum" prop_signum,
testProperty "sumvalid" prop_sumValid,
testProperty "mulValid" prop_mulValid,
testProperty "eitherFromRational" prop_eitherFromRational,
testProperty "normalizeDecimal" prop_normalizeDecimal,
testProperty "divisionMultiplication" prop_divisionMultiplication,
testProperty "fromRational" prop_fromRational,
testProperty "properFraction" prop_properFraction
],
testGroup "Point tests Data.Decimal" [
testCase "pi to 3dp" (dec 3 3142 @=? realFracToDecimal 3 piD),
testCase "pi to 2dp" (dec 2 314 @=? realFracToDecimal 2 piD),
testCase "100*pi to 2dp" (dec 2 31416 @=? realFracToDecimal 2 (100 * piD)),
testCase "1.0 * pi" (dec 1 31 @=? dec 1 10 *. piD),
testCase "1.23 * pi" (dec 2 386 @=? dec 2 123 *. piD),
testCase "Decimal to DecimalRaw Int"
(decimalConvert (dec 2 123) @=? Just (dec1 2 123)),
testCase "decimalConvert overflow prevention"
(decimalConvert (1/3) @=? (Nothing :: Maybe (DecimalRaw Int))),
testCase "1.234 to rational" (1234 % 1000 @=? toRational (dec 3 1234)),
testCase "fromRational (1%10) for DecimalRaw Int" -- Fixed bug #3
(let v :: DecimalRaw Int
v = fromRational (1%10)
in toRational v @=? 1%10)
]
]
| superduper/Haskell-Decimal | tests/Main.hs | bsd-3-clause | 9,193 | 0 | 16 | 2,629 | 2,112 | 1,113 | 999 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.