code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
module LogicCode ( HuffmanNode, truthTable, grayCode, huffmanCode ) where data HuffmanNode a = Empty | Leaf (a, Int) | Branch Int (HuffmanNode a) (HuffmanNode a) --Problem 46 - 49: Problem 48: Truth tables for logical expressions. --Eg: truthTable 3 (\[a, b, c] -> Logical expr involving a, b, and c) truthTable :: Int -> ([Bool] -> Bool) -> IO () truthTable n fn = printTable $ map (\x -> x ++ [fn x]) (cart n [True, False]) where printTable :: [[Bool]] -> IO () printTable = mapM_ (putStrLn . concatMap showSpace) where showSpace :: Bool -> String showSpace True = show True ++ " " showSpace False = show False ++ " " cart :: Int -> [a] -> [[a]] cart 1 xs = foldr (\x acc -> [x] : acc) [] xs cart l xs = [ x ++ y | x <- cart 1 xs, y <- cart (l - 1) xs] --Problem 49: Gray codes. --An n-bit Gray code is a sequence of n-bit strings constructed according to certain rules; for example, --n = 1: C(1) = ['0','1']. --n = 2: C(2) = ['00','01','11','10']. --n = 3: C(3) = ['000','001','011','010',´110´,´111´,´101´,´100´]. grayCode :: Int -> [String] grayCode 1 = ["0", "1"] grayCode n = map ('0':) (grayCode $ n - 1) ++ (map ('1':) $ reverse $ grayCode (n - 1)) --Problem 50: Huffman Codes. --Generate a Huffman code list from a given list of alphabets and their frequencies. huffmanCode :: (Ord a) => [(a, Int)] -> [(a, String)] huffmanCode ls = sort' $ process "" $ makeTree $ sort $ turnLeaf ls where sort :: [HuffmanNode a] -> [HuffmanNode a] sort [] = [] sort (x : xs) = let smallerSorted = sort [a | a <- xs, snd' a <= snd' x] biggerSorted = sort [a | a <- xs, snd' a > snd' x] in smallerSorted ++ [x] ++ biggerSorted turnLeaf :: [(a, Int)] -> [HuffmanNode a] turnLeaf = map Leaf makeTree :: [HuffmanNode a] -> HuffmanNode a makeTree [tr] = tr makeTree (m : n : ys) = makeTree $ sort $ Branch (snd' m + snd' n) m n : ys process :: String -> HuffmanNode a -> [(a, String)] process _ Empty = [] process str (Leaf (e, _)) = [(e, str)] process str (Branch _ ltr rtr) = process (str ++ "0") ltr ++ process (str ++ "1") rtr snd' :: HuffmanNode a -> Int snd' (Leaf (_, n)) = n snd' (Branch n _ _) = n sort' :: (Ord a) => [(a, String)] -> [(a, String)] sort' [] = [] sort' (x : xs) = let smallerSorted = sort' [a | a <- xs, fst a <= fst x] biggerSorted = sort' [a | a <- xs, fst x < fst a] in smallerSorted ++ [x] ++ biggerSorted
5hubh4m/99-haskell-problems
LogicCode.hs
Haskell
mit
2,437
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE CPP #-} module Data.Bson.Types ( RegexOption(..) , RegexOptions , Value(..) , Binary(..) , ObjectId(..) , Document , Array , Label , Field ) where import Data.Int (Int32, Int64) import Data.Time.Clock (UTCTime) import Data.Time.Format () import Data.Typeable (Typeable) import Data.Word (Word32, Word16) import qualified Data.ByteString as S import Data.BitSet.Word (BitSet) import Data.Vector (Vector) import Data.Word.Word24 (Word24) import Data.Text (Text) import Data.UUID (UUID) import {-# SOURCE #-} Data.Bson.Document (Document) -- | Options for 'ValueRegex', constructors order is important because -- it's binary representation should be encoded in alphabetical order. data RegexOption = RegexOptionCaseInsensitive -- i | RegexOptionLocaleDependent -- l | RegexOptionMultiline -- m | RegexOptionDotall -- s | RegexOptionUnicode -- u | RegexOptionVerbose -- x deriving (Eq, Show, Typeable, Enum) type RegexOptions = BitSet RegexOption -- | A value is one of the following types of values data Value = ValueDouble {-# UNPACK #-} !Double | ValueString {-# UNPACK #-} !Text | ValueDocument !Document | ValueArray {-# UNPACK #-} !Array | ValueBinary !Binary | ValueObjectId {-# UNPACK #-} !ObjectId | ValueBool !Bool | ValueUtcTime {-# UNPACK #-} !UTCTime | ValueNull | ValueRegex {-# UNPACK #-} !Text !RegexOptions | ValueJavascript {-# UNPACK #-} !Text | ValueJavascriptWithScope {-# UNPACK #-} !Text !Document | ValueInt32 {-# UNPACK #-} !Int32 | ValueInt64 {-# UNPACK #-} !Int64 | ValueTimestamp {-# UNPACK #-} !Int64 | ValueMin | ValueMax deriving (Eq, Show, Typeable) type Label = Text type Array = Vector Value type Field = (Label, Value) data ObjectId = ObjectId { objectIdTime :: {-# UNPACK #-} !Word32 , objectIdMachine :: {-# UNPACK #-} !Word24 , objectIdPid :: {-# UNPACK #-} !Word16 , objectIdInc :: {-# UNPACK #-} !Word24 } deriving (Eq, Show, Typeable) data Binary = BinaryGeneric {-# UNPACK #-} !S.ByteString | BinaryFunction {-# UNPACK #-} !S.ByteString | BinaryUuid {-# UNPACK #-} !UUID | BinaryMd5 {-# UNPACK #-} !S.ByteString | BinaryUserDefined {-# UNPACK #-} !S.ByteString deriving (Eq, Show, Typeable)
lambda-llama/bresson
src/Data/Bson/Types.hs
Haskell
mit
2,635
module Graphics.Urho3D.UI.Internal.Sprite( Sprite , spriteCntx , sharedSpritePtrCntx , SharedSprite ) where import qualified Language.C.Inline as C import qualified Language.C.Inline.Context as C import qualified Language.C.Types as C import Graphics.Urho3D.Container.Ptr import qualified Data.Map as Map data Sprite spriteCntx :: C.Context spriteCntx = mempty { C.ctxTypesTable = Map.fromList [ (C.TypeName "Sprite", [t| Sprite |]) ] } sharedPtrImpl "Sprite"
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/UI/Internal/Sprite.hs
Haskell
mit
494
-- Examples from chapter 8 -- http://learnyouahaskell.com/making-our-own-types-and-typeclasses import qualified Data.Map as Map data Point = Point Float Float deriving (Show) data Shape = Circle Point Float | Rectangle Point Point deriving (Show) surface :: Shape -> Float surface (Circle _ r) = pi * r ^ 2 surface (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1) nudge :: Shape -> Float -> Float -> Shape nudge (Circle (Point x y) r) a b = Circle (Point (x+a) (y+b)) r nudge (Rectangle (Point x1 y1) (Point x2 y2)) a b = Rectangle (Point (x1+a) (y1+b)) (Point (x2+a) (y2+b)) baseCircle :: Float -> Shape baseCircle = Circle (Point 0 0) baseRect :: Float -> Float -> Shape baseRect width height = Rectangle (Point 0 0) (Point width height) data Person = Person { firstName :: String , lastName :: String , age :: Int , height :: Float , phoneNumber :: String , flavor :: String } deriving (Show) data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Eq, Ord, Show, Read, Bounded, Enum) type PhoneNumber = String type Name = String type PhoneBook = [(Name,PhoneNumber)] type IntMap = Map.Map Int data LockerState = Taken | Free deriving (Show, Eq) type Code = String type LockerMap = Map.Map Int (LockerState, Code) lockerLookup :: Int -> LockerMap -> Either String Code lockerLookup lockerNumber map = case Map.lookup lockerNumber map of Nothing -> Left $ "Locker number " ++ show lockerNumber ++ " doesn't exist!" Just (state, code) -> if state /= Taken then Right code else Left $ "Locker " ++ show lockerNumber ++ " is already taken!" lockers :: LockerMap lockers = Map.fromList [(100,(Taken,"ZD39I")) ,(101,(Free,"JAH3I")) ,(103,(Free,"IQSA9")) ,(105,(Free,"QOTSA")) ,(109,(Taken,"893JJ")) ,(110,(Taken,"99292")) ] data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq) singleton :: a -> Tree a singleton x = Node x EmptyTree EmptyTree treeInsert :: (Ord a) => a -> Tree a -> Tree a treeInsert x EmptyTree = singleton x treeInsert x (Node a left right) | x == a = Node x left right | x < a = Node a (treeInsert x left) right | x > a = Node a left (treeInsert x right) treeElem :: (Ord a) => a -> Tree a -> Bool treeElem x EmptyTree = False treeElem x (Node a left right) | x == a = True | x < a = treeElem x left | x > a = treeElem x right data TrafficLight = Red | Yellow | Green instance Eq TrafficLight where Red == Red = True Green == Green = True Yellow == Yellow = True _ == _ = False class YesNo a where yesno :: a -> Bool instance YesNo Int where yesno 0 = False yesno _ = True instance YesNo [a] where yesno [] = False yesno _ = True instance YesNo Bool where yesno = id instance YesNo (Maybe a) where yesno (Just _) = True yesno Nothing = False
Sgoettschkes/learning
haskell/LearnYouAHaskell/08.hs
Haskell
mit
3,046
{-| Module: Flaw.UI.ScrollBox Description: Scroll box. License: MIT -} module Flaw.UI.ScrollBox ( ScrollBox(..) , newScrollBox , ScrollBar(..) , newScrollBar , newVerticalScrollBar , newHorizontalScrollBar , processScrollBarEvent , ensureVisibleScrollBoxArea ) where import Control.Concurrent.STM import Control.Monad import Data.Maybe import Flaw.Graphics import Flaw.Graphics.Canvas import Flaw.Input.Mouse import Flaw.Math import Flaw.UI import Flaw.UI.Drawer data ScrollBox = ScrollBox { scrollBoxElement :: !SomeScrollable -- | Position of left-top corner of child element -- relative to scroll box' left-top corner, i.e. <= 0. , scrollBoxScrollVar :: {-# UNPACK #-} !(TVar Position) , scrollBoxSizeVar :: {-# UNPACK #-} !(TVar Size) } newScrollBox :: Scrollable e => e -> STM ScrollBox newScrollBox element = do scrollVar <- newTVar $ Vec2 0 0 sizeVar <- newTVar $ Vec2 0 0 return ScrollBox { scrollBoxElement = SomeScrollable element , scrollBoxScrollVar = scrollVar , scrollBoxSizeVar = sizeVar } instance Element ScrollBox where layoutElement ScrollBox { scrollBoxElement = SomeScrollable element , scrollBoxSizeVar = sizeVar } size = do writeTVar sizeVar size layoutElement element size dabElement ScrollBox { scrollBoxElement = SomeScrollable element , scrollBoxScrollVar = scrollVar , scrollBoxSizeVar = sizeVar } (Vec2 x y) = if x < 0 || y < 0 then return False else do size <- readTVar sizeVar let Vec2 sx sy = size if x < sx && y < sy then do scroll <- readTVar scrollVar let Vec2 ox oy = scroll dabElement element $ Vec2 (x - ox) (y - oy) else return False elementMouseCursor ScrollBox { scrollBoxElement = SomeScrollable element } = elementMouseCursor element renderElement ScrollBox { scrollBoxElement = SomeScrollable element , scrollBoxScrollVar = scrollVar , scrollBoxSizeVar = sizeVar } drawer position@(Vec2 px py) = do scroll <- readTVar scrollVar size <- readTVar sizeVar ssize <- scrollableElementSize element -- correct scroll if needed let Vec2 ox oy = scroll Vec2 sx sy = size Vec2 ssx ssy = ssize newScroll@(Vec2 nox noy) = Vec2 (min 0 $ max ox $ sx - ssx) (min 0 $ max oy $ sy - ssy) when (scroll /= newScroll) $ writeTVar scrollVar newScroll r <- renderScrollableElement element drawer (position + newScroll) (Vec4 (-nox) (-noy) (sx - nox) (sy - noy)) return $ do renderIntersectScissor $ Vec4 px py (px + sx) (py + sy) r processInputEvent ScrollBox { scrollBoxElement = SomeScrollable element , scrollBoxScrollVar = scrollVar } inputEvent inputState = case inputEvent of MouseInputEvent mouseEvent -> case mouseEvent of CursorMoveEvent x y -> do scroll <- readTVar scrollVar let Vec2 ox oy = scroll processInputEvent element (MouseInputEvent (CursorMoveEvent (x - ox) (y - oy))) inputState _ -> processInputEvent element inputEvent inputState _ -> processInputEvent element inputEvent inputState focusElement ScrollBox { scrollBoxElement = SomeScrollable element } = focusElement element unfocusElement ScrollBox { scrollBoxElement = SomeScrollable element } = unfocusElement element data ScrollBar = ScrollBar { scrollBarScrollBox :: !ScrollBox , scrollBarDirection :: {-# UNPACK #-} !(Vec2 Metric) , scrollBarSizeVar :: {-# UNPACK #-} !(TVar Size) , scrollBarLastMousePositionVar :: {-# UNPACK #-} !(TVar (Maybe Position)) , scrollBarPressedVar :: {-# UNPACK #-} !(TVar Bool) } newScrollBar :: Vec2 Metric -> ScrollBox -> STM ScrollBar newScrollBar direction scrollBox = do sizeVar <- newTVar $ Vec2 0 0 lastMousePositionVar <- newTVar Nothing pressedVar <- newTVar False return ScrollBar { scrollBarScrollBox = scrollBox , scrollBarDirection = direction , scrollBarSizeVar = sizeVar , scrollBarLastMousePositionVar = lastMousePositionVar , scrollBarPressedVar = pressedVar } newVerticalScrollBar :: ScrollBox -> STM ScrollBar newVerticalScrollBar = newScrollBar $ Vec2 0 1 newHorizontalScrollBar :: ScrollBox -> STM ScrollBar newHorizontalScrollBar = newScrollBar $ Vec2 1 0 instance Element ScrollBar where layoutElement ScrollBar { scrollBarSizeVar = sizeVar } = writeTVar sizeVar dabElement ScrollBar { scrollBarSizeVar = sizeVar } (Vec2 x y) = if x < 0 || y < 0 then return False else do size <- readTVar sizeVar let Vec2 sx sy = size return $ x < sx && y < sy renderElement scrollBar@ScrollBar { scrollBarSizeVar = barSizeVar , scrollBarLastMousePositionVar = lastMousePositionVar , scrollBarPressedVar = pressedVar } Drawer { drawerCanvas = canvas , drawerStyles = DrawerStyles { drawerFlatStyleVariant = StyleVariant { styleVariantNormalStyle = flatNormalStyle } , drawerRaisedStyleVariant = StyleVariant { styleVariantNormalStyle = raisedNormalStyle , styleVariantMousedStyle = raisedMousedStyle , styleVariantPressedStyle = raisedPressedStyle } } } (Vec2 px py) = do barSize <- readTVar barSizeVar let Vec2 sx sy = barSize piece <- scrollBarPiece scrollBar moused <- isJust <$> readTVar lastMousePositionVar pressed <- readTVar pressedVar let pieceStyle | pressed = raisedPressedStyle | moused = raisedMousedStyle | otherwise = raisedNormalStyle return $ do -- render border drawBorderedRectangle canvas (Vec4 px (px + 1) (px + sx - 1) (px + sx)) (Vec4 py (py + 1) (py + sy - 1) (py + sy)) (styleFillColor flatNormalStyle) (styleBorderColor flatNormalStyle) case piece of Just ScrollBarPiece { scrollBarPieceRect = pieceRect } -> let Vec4 ppx ppy pqx pqy = pieceRect + Vec4 px py px py in -- render piece drawBorderedRectangle canvas (Vec4 ppx (ppx + 1) (pqx - 1) pqx) (Vec4 ppy (ppy + 1) (pqy - 1) pqy) (styleFillColor pieceStyle) (styleBorderColor pieceStyle) Nothing -> return () processInputEvent scrollBar@ScrollBar { scrollBarScrollBox = ScrollBox { scrollBoxScrollVar = scrollVar } , scrollBarLastMousePositionVar = lastMousePositionVar , scrollBarPressedVar = pressedVar } inputEvent _inputState = case inputEvent of MouseInputEvent mouseEvent -> case mouseEvent of MouseDownEvent LeftMouseButton -> do writeTVar pressedVar True return True MouseUpEvent LeftMouseButton -> do writeTVar pressedVar False return True RawMouseMoveEvent _x _y z -> do piece <- scrollBarPiece scrollBar case piece of Just ScrollBarPiece { scrollBarPieceOffsetMultiplier = offsetMultiplier } -> do modifyTVar' scrollVar (+ signum offsetMultiplier * vecFromScalar (floor (z * (-15)))) return True Nothing -> return False CursorMoveEvent x y -> do pressed <- readTVar pressedVar when pressed $ do maybeLastMousePosition <- readTVar lastMousePositionVar case maybeLastMousePosition of Just lastMousePosition -> do piece <- scrollBarPiece scrollBar case piece of Just ScrollBarPiece { scrollBarPieceOffsetMultiplier = offsetMultiplier } -> modifyTVar' scrollVar (+ (Vec2 x y - lastMousePosition) * offsetMultiplier) Nothing -> return () Nothing -> return () writeTVar lastMousePositionVar $ Just $ Vec2 x y return True _ -> return False MouseLeaveEvent -> do writeTVar lastMousePositionVar Nothing writeTVar pressedVar False return True _ -> return False -- | Internal information about piece. data ScrollBarPiece = ScrollBarPiece { scrollBarPieceRect :: {-# UNPACK #-} !Rect , scrollBarPieceOffsetMultiplier :: {-# UNPACK #-} !(Vec2 Metric) } -- | Get scroll bar piece rect and piece offset multiplier. scrollBarPiece :: ScrollBar -> STM (Maybe ScrollBarPiece) scrollBarPiece ScrollBar { scrollBarScrollBox = ScrollBox { scrollBoxElement = SomeScrollable element , scrollBoxScrollVar = scrollVar , scrollBoxSizeVar = boxSizeVar } , scrollBarDirection = direction , scrollBarSizeVar = barSizeVar } = do barSize <- readTVar barSizeVar let Vec2 sx sy = barSize boxSize <- readTVar boxSizeVar scrollableSize <- scrollableElementSize element scroll <- readTVar scrollVar let padding = 2 contentOffset = dot scroll direction boxLength = dot boxSize direction contentLength = dot scrollableSize direction barLength = dot barSize direction - padding * 2 minPieceLength = min sx sy - padding * 2 pieceLength = max minPieceLength $ (barLength * boxLength) `quot` max 1 contentLength pieceOffset = (negate contentOffset * (barLength - pieceLength)) `quot` max 1 (contentLength - boxLength) Vec2 ppx ppy = vecFromScalar padding + direction * vecFromScalar pieceOffset Vec2 psx psy = vecfmap (max minPieceLength) $ direction * vecFromScalar pieceLength piece = if contentLength > boxLength then Just ScrollBarPiece { scrollBarPieceRect = Vec4 ppx ppy (ppx + psx) (ppy + psy) , scrollBarPieceOffsetMultiplier = direction * vecFromScalar (negate $ (contentLength - boxLength) `quot` max 1 (barLength - pieceLength)) } else Nothing return piece -- | Process possibly scroll bar event. -- Could be used for passing scrolling events from other elements. processScrollBarEvent :: ScrollBar -> InputEvent -> InputState -> STM Bool processScrollBarEvent scrollBar inputEvent inputState = case inputEvent of MouseInputEvent RawMouseMoveEvent {} -> processInputEvent scrollBar inputEvent inputState _ -> return False -- | Adjust scrolling so the specified area (in content coords) is visible. ensureVisibleScrollBoxArea :: ScrollBox -> Rect -> STM () ensureVisibleScrollBoxArea ScrollBox { scrollBoxScrollVar = scrollVar , scrollBoxSizeVar = sizeVar } (Vec4 left top right bottom) = do scroll <- readTVar scrollVar let Vec2 ox oy = scroll size <- readTVar sizeVar let Vec2 sx sy = size -- dimensions are to be adjusted independently -- function to adjust one dimension let adjust o s a b = if a + o >= 0 then if b + o <= s then o else s - b else -a newScroll = Vec2 (adjust ox sx left right) (adjust oy sy top bottom) unless (scroll == newScroll) $ writeTVar scrollVar newScroll
quyse/flaw
flaw-ui/Flaw/UI/ScrollBox.hs
Haskell
mit
10,754
module Diamond (diamond) where diamond :: Char -> Maybe [String] diamond = error "You need to implement this function"
exercism/xhaskell
exercises/practice/diamond/src/Diamond.hs
Haskell
mit
120
import Control.Monad main = print . msum $ do x <- [ 1 .. 1000 ] y <- [x + 1 .. div (1000 - x) 2 ] let z = 1000 - x - y return $ if x^2 + y^2 == z^2 && x + y + z == 1000 then Just $ x * y * z else Nothing
nickspinale/euler
complete/009.hs
Haskell
mit
253
module BFLib.BrainfuchFollow where import Control.Monad.State import Control.Monad.Writer import System.IO import BFLib.Brainfuch (Code , Stack , bfTail , emptyStack , incPtr , decPtr , incCell , decCell , bfGetLoop , bfDropLoop) {- - Syntax > Increment pointer < Decrement pointer + Increment contents - Decrement contents . Put cell content , Read cell content [ ] Loop ([ - Skip following part if content == 0; ] go to last [ if content != 0) -} type StackCode = (Stack,Char) -- As function: Stack -> IO ((a,[StackCode]),Stack) type BFFState = WriterT [StackCode] (StateT Stack IO) -- monadic ops bffTell :: StackCode -> BFFState () bffTell sc = tell [sc] mIncPtr :: BFFState () mIncPtr = WriterT . StateT $ \s -> let s' = incPtr s in return (((),[(s','>')]),s') mDecPtr :: BFFState () mDecPtr = WriterT . StateT $ \s -> let s' = decPtr s in return (((),[(s','<')]),s') mIncCell :: BFFState () mIncCell = WriterT . StateT $ \s -> let s' = incCell s in return (((),[(s','+')]),s') mDecCell :: BFFState () mDecCell = WriterT . StateT $ \s -> let s' = decCell s in return (((),[(s','-')]),s') mPrintContent :: BFFState () mPrintContent = WriterT . StateT $ \s@(_,e,_) -> (putStrLn . show) e >> hFlush stdout >> return (((),[(s,'.')]),s) mReadContent :: BFFState () mReadContent = WriterT . StateT $ \(xs,_,ys) -> readLn >>= \e -> let s' = (xs,e,ys) in return (((),[(s',',')]),s') mIsZero :: BFFState Bool mIsZero = WriterT . StateT $ \s@(_,e,_) -> return ((e == 0,[]),s) -- Interpreter bfInt :: Code -> BFFState () bfInt [] = return () bfInt allc@(c:cs) = case c of '>' -> mIncPtr >> bfInt cs '<' -> mDecPtr >> bfInt cs '+' -> mIncCell >> bfInt cs '-' -> mDecCell >> bfInt cs '.' -> mPrintContent >> bfInt cs ',' -> mReadContent >> bfInt cs '[' -> do p <- mIsZero if p then bfInt . bfDropLoop $ allc else let loopcode = bfGetLoop allc in do bfInt loopcode bfInt (c:cs) _ -> bfInt cs
dermesser/Brainfuch
BFLib/BrainfuchFollow.hs
Haskell
mit
2,592
module PartialRecordSel where -- Partial record selectors use 'error' in the output (which is undefined) -- Would be better to use 'panic' (or be able to skip them entirely). data R = R1 { a :: Bool } | R2 { b :: Bool }
antalsz/hs-to-coq
examples/base-tests/PartialRecordSel.hs
Haskell
mit
222
module Examples.EX3 where import Control.Lens import Control.Lens.Setter import Control.Monad (void) import Control.Monad.Trans.Class (lift) import Data.List (intersperse, isPrefixOf) import Data.Time.LocalTime import Data.Maybe (catMaybes) import Twilio.Key import Twilio.IVR data User = User { lastname :: String, firstname :: String, extension :: Maybe String } deriving (Show) users = [ User "Smith" "Joe" $ Just "7734", User "Doe" "Jane" $ Just "1556", User "Doe" "Linda" Nothing, User "Samson" "Tina" $ Just "3443", User "O'Donald" "Jack" $ Just "5432", User "Sam-son" "Tony" $ Nothing ] -- | match last name by removing non-keypad characters matchingUsers :: [User] -> [Key] -> [User] matchingUsers ux kx = filter (\u -> let lnky = catMaybes $ map letterToKey (lastname u) in isPrefixOf kx lnky) ux describeUser :: User -> TwilioIVRCoroutine () describeUser u = do say (firstname u) say (lastname u) case extension u of (Just x) -> say $ "Phone extension " ++ (intersperse ' ' x) Nothing -> return () search :: Call -> TwilioIVRCoroutine () search _ = do say "Welcome." name <- gather "Please enter the last name of the person you wish to find. You do not have to enter the entire name. Finish with the pound key." ((finishOnKey .~ Just KPound).(timeout .~ 30)) case matchingUsers users name of [] -> say "Sorry, no matching results found." [x] -> describeUser x xs -> do say $ "We found "++(show $ length xs)++" matching users." mapM_ describeUser xs say "Have a nice day."
steven777400/TwilioIVR
src/Examples/EX3.hs
Haskell
mit
1,669
{-# OPTIONS_GHC -Wall #-} module LogAnalysis where import Log import Data.Char (isDigit) parseMessage :: String -> LogMessage parseMessage (x:' ':xs) | x == 'I' = LogMessage Info first body | x == 'W' = LogMessage Warning first body | x == 'E' = LogMessage (Error first) second (trim body) where body = tail . dropWhile isDigit $ xs first = read . takeWhile isDigit $ xs second = read . takeWhile isDigit . dropWhileHeader $ xs where dropWhileHeader = tail . snd . span isDigit trim = tail . dropWhile isDigit parseMessage x = Unknown x parse :: String -> [LogMessage] parse = map parseMessage . lines insert :: LogMessage -> MessageTree -> MessageTree insert (Unknown _) tree = tree insert _ tree@(Node _ (Unknown _) _) = tree insert m (Leaf) = Node Leaf m Leaf insert m@(LogMessage _ ts _) (Node l c@(LogMessage _ other _) r) | other > ts = Node (insert m l) c r | otherwise = Node l c (insert m r) build :: [LogMessage] -> MessageTree build [] = Leaf build (xs) = foldl buildTree Leaf xs where buildTree acc x = insert x acc inOrder :: MessageTree -> [LogMessage] inOrder (Leaf) = [] inOrder (Node l m r) = (inOrder l) ++ [m] ++ (inOrder r) whatWentWrong :: [LogMessage] -> [String] whatWentWrong [] = [] whatWentWrong (ms) = map printMsg $ filter bigs $ filter errors logs where logs = inOrder $ build ms bigs (LogMessage (Error n) _ _) | n >= 50 = True | otherwise = False bigs _ = False printMsg (LogMessage _ _ s) = s printMsg (Unknown s) = s errors (LogMessage (Error _) _ _) = True errors _ = False
tylerjl/cis194
old/hw02/LogAnalysis.hs
Haskell
mit
1,674
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QNetworkInterface.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:36 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Network.QNetworkInterface ( InterfaceFlag, InterfaceFlags, eIsUp, fIsUp, eIsRunning, fIsRunning, eCanBroadcast, fCanBroadcast, eIsLoopBack, fIsLoopBack, eIsPointToPoint, fIsPointToPoint, eCanMulticast, fCanMulticast ) where import Foreign.C.Types import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CInterfaceFlag a = CInterfaceFlag a type InterfaceFlag = QEnum(CInterfaceFlag Int) ieInterfaceFlag :: Int -> InterfaceFlag ieInterfaceFlag x = QEnum (CInterfaceFlag x) instance QEnumC (CInterfaceFlag Int) where qEnum_toInt (QEnum (CInterfaceFlag x)) = x qEnum_fromInt x = QEnum (CInterfaceFlag x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> InterfaceFlag -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () data CInterfaceFlags a = CInterfaceFlags a type InterfaceFlags = QFlags(CInterfaceFlags Int) ifInterfaceFlags :: Int -> InterfaceFlags ifInterfaceFlags x = QFlags (CInterfaceFlags x) instance QFlagsC (CInterfaceFlags Int) where qFlags_toInt (QFlags (CInterfaceFlags x)) = x qFlags_fromInt x = QFlags (CInterfaceFlags x) withQFlagsResult x = do ti <- x return $ qFlags_fromInt $ fromIntegral ti withQFlagsListResult x = do til <- x return $ map qFlags_fromInt til instance Qcs (QObject c -> InterfaceFlags -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qFlags_fromInt hint) return () eIsUp :: InterfaceFlag eIsUp = ieInterfaceFlag $ 1 eIsRunning :: InterfaceFlag eIsRunning = ieInterfaceFlag $ 2 eCanBroadcast :: InterfaceFlag eCanBroadcast = ieInterfaceFlag $ 4 eIsLoopBack :: InterfaceFlag eIsLoopBack = ieInterfaceFlag $ 8 eIsPointToPoint :: InterfaceFlag eIsPointToPoint = ieInterfaceFlag $ 16 eCanMulticast :: InterfaceFlag eCanMulticast = ieInterfaceFlag $ 32 fIsUp :: InterfaceFlags fIsUp = ifInterfaceFlags $ 1 fIsRunning :: InterfaceFlags fIsRunning = ifInterfaceFlags $ 2 fCanBroadcast :: InterfaceFlags fCanBroadcast = ifInterfaceFlags $ 4 fIsLoopBack :: InterfaceFlags fIsLoopBack = ifInterfaceFlags $ 8 fIsPointToPoint :: InterfaceFlags fIsPointToPoint = ifInterfaceFlags $ 16 fCanMulticast :: InterfaceFlags fCanMulticast = ifInterfaceFlags $ 32
keera-studios/hsQt
Qtc/Enums/Network/QNetworkInterface.hs
Haskell
bsd-2-clause
4,834
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Acid (loadSet, addExperiment) where import Control.Monad.Reader import Control.Monad.State import Data.Acid import Data.SafeCopy import Data.Time.LocalTime (ZonedTime(..)) import Data.Typeable import qualified Data.Map as Map import Network.ImageTrove.Main import Network.MyTardis.RestTypes import qualified Data.Set as Set import Data.Set (Set) data ExperimentSet = ExperimentSet !(Set RestExperiment) deriving (Typeable) $(deriveSafeCopy 0 'base ''RestParameter) $(deriveSafeCopy 0 'base ''RestSchema) $(deriveSafeCopy 0 'base ''RestExperimentParameterSet) $(deriveSafeCopy 0 'base ''RestPermission) $(deriveSafeCopy 0 'base ''RestGroup) $(deriveSafeCopy 0 'base ''RestObjectACL) $(deriveSafeCopy 0 'base ''RestExperiment) $(deriveSafeCopy 0 'base ''ExperimentSet) insertExperiment :: RestExperiment -> Update ExperimentSet () insertExperiment e = do ExperimentSet s <- get put $ ExperimentSet $ Set.insert e s {- isMember :: RestExperiment -> Query ExperimentSet Bool isMember e = do ExperimentSet s <- get return True -- $ Set.member e s Doesn't compile: Acid.hs:41:24: No instance for (MonadState ExperimentSet (Query ExperimentSet)) arising from a use of `get' Possible fix: add an instance declaration for (MonadState ExperimentSet (Query ExperimentSet)) In a stmt of a 'do' block: ExperimentSet s <- get In the expression: do { ExperimentSet s <- get; return True } In an equation for `isMember': isMember e = do { ExperimentSet s <- get; return True } -} getSetInternal :: Query ExperimentSet (Set RestExperiment) getSetInternal = do ExperimentSet s <- ask return s $(makeAcidic ''ExperimentSet ['insertExperiment, 'getSetInternal]) loadSet :: FilePath -> IO (Set RestExperiment) loadSet fp = do acid <- openLocalStateFrom fp (ExperimentSet Set.empty) m <- query acid GetSetInternal closeAcidState acid return m addExperiment :: FilePath -> RestExperiment -> IO () addExperiment fp e = do acid <- openLocalStateFrom fp (ExperimentSet Set.empty) _ <- update acid (InsertExperiment e) closeAcidState acid
carlohamalainen/imagetrove-cai-projects-db
Acid.hs
Haskell
bsd-2-clause
2,332
{-# LANGUAGE CPP, FlexibleContexts, GeneralizedNewtypeDeriving, InstanceSigs, RankNTypes, ScopedTypeVariables, TypeFamilies, UndecidableInstances #-} module Text.Grampa.ContextFree.Memoizing {-# DEPRECATED "Use Text.Grampa.ContextFree.SortedMemoizing instead" #-} (ResultList(..), Parser(..), BinTree(..), reparseTails, longest, peg, terminalPEG) where import Control.Applicative import Control.Monad (Monad(..), MonadPlus(..)) #if MIN_VERSION_base(4,13,0) import Control.Monad (MonadFail(fail)) #endif import Data.Function (on) import Data.Foldable (toList) import Data.Functor.Classes (Show1(..)) import Data.Functor.Compose (Compose(..)) import Data.List (maximumBy) import Data.Monoid (Monoid(mappend, mempty)) import Data.Monoid.Null (MonoidNull(null)) import Data.Monoid.Factorial (FactorialMonoid, length, splitPrimePrefix) import Data.Monoid.Textual (TextualMonoid) import qualified Data.Monoid.Factorial as Factorial import qualified Data.Monoid.Textual as Textual import Data.Ord (Down(Down)) import Data.Semigroup (Semigroup((<>))) import Data.Semigroup.Cancellative (LeftReductive(isPrefixOf)) import Data.String (fromString) import Debug.Trace (trace) import Witherable (Filterable(mapMaybe)) import qualified Text.Parser.Char import Text.Parser.Char (CharParsing) import Text.Parser.Combinators (Parsing(..)) import Text.Parser.LookAhead (LookAheadParsing(..)) import qualified Rank2 import Text.Grampa.Class (GrammarParsing(..), MultiParsing(..), DeterministicParsing(..), InputParsing(..), InputCharParsing(..), TailsParsing(parseTails), ParseResults, ParseFailure(..), FailureDescription(..), Pos) import Text.Grampa.Internal (BinTree(..), TraceableParsing(..), expected, erroneous) import qualified Text.Grampa.PEG.Backtrack.Measured as Backtrack import Prelude hiding (iterate, length, null, showList, span, takeWhile) -- | Parser for a context-free grammar with packrat-like sharing of parse results. It does not support left-recursive -- grammars. newtype Parser g s r = Parser{applyParser :: [(s, g (ResultList g s))] -> ResultList g s r} data ResultList g s r = ResultList !(BinTree (ResultInfo g s r)) {-# UNPACK #-} !(ParseFailure Pos s) data ResultInfo g s r = ResultInfo !Int ![(s, g (ResultList g s))] !r instance (Show s, Show r) => Show (ResultList g s r) where show (ResultList l f) = "ResultList (" ++ shows l (") (" ++ shows f ")") instance Show s => Show1 (ResultList g s) where liftShowsPrec _sp showList _prec (ResultList l f) rest = "ResultList " ++ showList (simplify <$> toList l) (shows f rest) where simplify (ResultInfo _ _ r) = r instance (Show s, Show r) => Show (ResultInfo g s r) where show (ResultInfo l _ r) = "(ResultInfo @" ++ show l ++ " " ++ shows r ")" instance Functor (ResultInfo g s) where fmap f (ResultInfo l t r) = ResultInfo l t (f r) instance Foldable (ResultInfo g s) where foldMap f (ResultInfo _ _ r) = f r instance Traversable (ResultInfo g s) where traverse f (ResultInfo l t r) = ResultInfo l t <$> f r instance Functor (ResultList g s) where fmap f (ResultList l failure) = ResultList ((f <$>) <$> l) failure instance Filterable (ResultList g s) where mapMaybe f (ResultList l failure) = ResultList (mapMaybe (traverse f) l) failure instance Ord s => Semigroup (ResultList g s r) where ResultList rl1 f1 <> ResultList rl2 f2 = ResultList (rl1 <> rl2) (f1 <> f2) instance Ord s => Monoid (ResultList g s r) where mempty = ResultList mempty mempty mappend = (<>) instance Functor (Parser g i) where fmap f (Parser p) = Parser (fmap f . p) {-# INLINABLE fmap #-} instance Ord s => Applicative (Parser g s) where pure a = Parser (\rest-> ResultList (Leaf $ ResultInfo 0 rest a) mempty) Parser p <*> Parser q = Parser r where r rest = case p rest of ResultList results failure -> ResultList mempty failure <> foldMap continue results continue (ResultInfo l rest' f) = continue' l f (q rest') continue' l f (ResultList rs failure) = ResultList (adjust l f <$> rs) failure adjust l f (ResultInfo l' rest' a) = ResultInfo (l+l') rest' (f a) {-# INLINABLE pure #-} {-# INLINABLE (<*>) #-} instance Ord s => Alternative (Parser g s) where empty = Parser (\rest-> ResultList mempty $ ParseFailure (Down $ length rest) [] []) Parser p <|> Parser q = Parser r where r rest = p rest <> q rest {-# INLINABLE (<|>) #-} instance Filterable (Parser g i) where mapMaybe f (Parser p) = Parser (mapMaybe f . p) {-# INLINABLE mapMaybe #-} instance Ord s => Monad (Parser g s) where return = pure Parser p >>= f = Parser q where q rest = case p rest of ResultList results failure -> ResultList mempty failure <> foldMap continue results continue (ResultInfo l rest' a) = continue' l (applyParser (f a) rest') continue' l (ResultList rs failure) = ResultList (adjust l <$> rs) failure adjust l (ResultInfo l' rest' a) = ResultInfo (l+l') rest' a #if MIN_VERSION_base(4,13,0) instance Ord s => MonadFail (Parser g s) where #endif fail msg = Parser p where p rest = ResultList mempty (erroneous (Down $ length rest) msg) instance Ord s => MonadPlus (Parser g s) where mzero = empty mplus = (<|>) instance (Semigroup x, Ord s) => Semigroup (Parser g s x) where (<>) = liftA2 (<>) instance (Monoid x, Ord s) => Monoid (Parser g s x) where mempty = pure mempty mappend = liftA2 mappend instance (Ord s, LeftReductive s, FactorialMonoid s) => GrammarParsing (Parser g s) where type ParserGrammar (Parser g s) = g type GrammarFunctor (Parser g s) = ResultList g s parsingResult _ = Compose . fromResultList nonTerminal f = Parser p where p ((_, d) : _) = f d p _ = ResultList mempty (expected 0 "NonTerminal at endOfInput") {-# INLINE nonTerminal #-} instance (Ord s, LeftReductive s, FactorialMonoid s) => TailsParsing (Parser g s) where parseTails = applyParser -- | Memoizing parser guarantees O(n²) performance for grammars with unambiguous productions, but provides no left -- recursion support. -- -- @ -- 'parseComplete' :: ("Rank2".'Rank2.Functor' g, 'FactorialMonoid' s) => -- g (Memoizing.'Parser' g s) -> s -> g ('Compose' ('ParseResults' s) []) -- @ instance (LeftReductive s, FactorialMonoid s, Ord s) => MultiParsing (Parser g s) where type GrammarConstraint (Parser g s) g' = (g ~ g', Rank2.Functor g) type ResultFunctor (Parser g s) = Compose (ParseResults s) [] -- | Returns the list of all possible input prefix parses paired with the remaining input suffix. parsePrefix g input = Rank2.fmap (Compose . Compose . fromResultList) (snd $ head $ parseGrammarTails g input) -- parseComplete :: (Rank2.Functor g, Eq s, FactorialMonoid s) => -- g (Parser g s) -> s -> g (Compose (ParseResults s) []) parseComplete g input = Rank2.fmap ((snd <$>) . Compose . fromResultList) (snd $ head $ reparseTails close $ parseGrammarTails g input) where close = Rank2.fmap (<* eof) g parseGrammarTails :: (Rank2.Functor g, FactorialMonoid s) => g (Parser g s) -> s -> [(s, g (ResultList g s))] parseGrammarTails g input = foldr parseTail [] (Factorial.tails input) where parseTail s parsedTail = parsed where parsed = (s,d):parsedTail d = Rank2.fmap (($ parsed) . applyParser) g reparseTails :: Rank2.Functor g => g (Parser g s) -> [(s, g (ResultList g s))] -> [(s, g (ResultList g s))] reparseTails _ [] = [] reparseTails final parsed@((s, _):_) = (s, gd):parsed where gd = Rank2.fmap (`applyParser` parsed) final instance (LeftReductive s, FactorialMonoid s, Ord s) => InputParsing (Parser g s) where type ParserInput (Parser g s) = s getInput = Parser p where p rest@((s, _):_) = ResultList (Leaf $ ResultInfo 0 rest s) mempty p [] = ResultList (Leaf $ ResultInfo 0 [] mempty) mempty anyToken = Parser p where p rest@((s, _):t) = case splitPrimePrefix s of Just (first, _) -> ResultList (Leaf $ ResultInfo 1 t first) mempty _ -> ResultList mempty (expected (Down $ length rest) "anyToken") p [] = ResultList mempty (expected 0 "anyToken") satisfy predicate = Parser p where p rest@((s, _):t) = case splitPrimePrefix s of Just (first, _) | predicate first -> ResultList (Leaf $ ResultInfo 1 t first) mempty _ -> ResultList mempty (expected (Down $ length rest) "satisfy") p [] = ResultList mempty (expected 0 "satisfy") scan s0 f = Parser (p s0) where p s rest@((i, _) : _) = ResultList (Leaf $ ResultInfo l (drop l rest) prefix) mempty where (prefix, _, _) = Factorial.spanMaybe' s f i l = Factorial.length prefix p _ [] = ResultList (Leaf $ ResultInfo 0 [] mempty) mempty take 0 = mempty take n = Parser p where p rest@((s, _) : _) | x <- Factorial.take n s, l <- Factorial.length x, l == n = ResultList (Leaf $ ResultInfo l (drop l rest) x) mempty p rest = ResultList mempty (expected (Down $ length rest) $ "take " ++ show n) takeWhile predicate = Parser p where p rest@((s, _) : _) | x <- Factorial.takeWhile predicate s, l <- Factorial.length x = ResultList (Leaf $ ResultInfo l (drop l rest) x) mempty p [] = ResultList (Leaf $ ResultInfo 0 [] mempty) mempty takeWhile1 predicate = Parser p where p rest@((s, _) : _) | x <- Factorial.takeWhile predicate s, l <- Factorial.length x, l > 0 = ResultList (Leaf $ ResultInfo l (drop l rest) x) mempty p rest = ResultList mempty (expected (Down $ length rest) "takeWhile1") string s = Parser p where p rest@((s', _) : _) | s `isPrefixOf` s' = ResultList (Leaf $ ResultInfo l (Factorial.drop l rest) s) mempty p rest = ResultList mempty (ParseFailure (Down $ length rest) [LiteralDescription s] []) l = Factorial.length s notSatisfy predicate = Parser p where p rest@((s, _):_) | Just (first, _) <- splitPrimePrefix s, predicate first = ResultList mempty (expected (Down $ length rest) "notSatisfy") p rest = ResultList (Leaf $ ResultInfo 0 rest ()) mempty {-# INLINABLE string #-} instance InputParsing (Parser g s) => TraceableParsing (Parser g s) where traceInput description (Parser p) = Parser q where q rest@((s, _):_) = case traceWith "Parsing " (p rest) of rl@(ResultList EmptyTree _) -> traceWith "Failed " rl rl -> traceWith "Parsed " rl where traceWith prefix = trace (prefix <> description s) q [] = p [] instance (Ord s, Show s, TextualMonoid s) => InputCharParsing (Parser g s) where satisfyCharInput predicate = Parser p where p rest@((s, _):t) = case Textual.characterPrefix s of Just first | predicate first -> ResultList (Leaf $ ResultInfo 1 t $ Factorial.primePrefix s) mempty _ -> ResultList mempty (expected (Down $ length rest) "satisfyCharInput") p [] = ResultList mempty (expected 0 "satisfyCharInput") scanChars s0 f = Parser (p s0) where p s rest@((i, _) : _) = ResultList (Leaf $ ResultInfo l (drop l rest) prefix) mempty where (prefix, _, _) = Textual.spanMaybe_' s f i l = Factorial.length prefix p _ [] = ResultList (Leaf $ ResultInfo 0 [] mempty) mempty takeCharsWhile predicate = Parser p where p rest@((s, _) : _) | x <- Textual.takeWhile_ False predicate s, l <- Factorial.length x = ResultList (Leaf $ ResultInfo l (drop l rest) x) mempty p [] = ResultList (Leaf $ ResultInfo 0 [] mempty) mempty takeCharsWhile1 predicate = Parser p where p rest@((s, _) : _) | x <- Textual.takeWhile_ False predicate s, l <- Factorial.length x, l > 0 = ResultList (Leaf $ ResultInfo l (drop l rest) x) mempty p rest = ResultList mempty (expected (Down $ length rest) "takeCharsWhile1") notSatisfyChar predicate = Parser p where p rest@((s, _):_) | Just first <- Textual.characterPrefix s, predicate first = ResultList mempty (expected (Down $ length rest) "notSatisfyChar") p rest = ResultList (Leaf $ ResultInfo 0 rest ()) mempty instance (MonoidNull s, Ord s) => Parsing (Parser g s) where try (Parser p) = Parser q where q rest = rewindFailure (p rest) where rewindFailure (ResultList rl _) = ResultList rl (ParseFailure (Down $ length rest) [] []) Parser p <?> msg = Parser q where q rest = replaceFailure (p rest) where replaceFailure (ResultList EmptyTree (ParseFailure pos msgs erroneous')) = ResultList EmptyTree (ParseFailure pos (if pos == Down (length rest) then [StaticDescription msg] else msgs) erroneous') replaceFailure rl = rl notFollowedBy (Parser p) = Parser (\input-> rewind input (p input)) where rewind t (ResultList EmptyTree _) = ResultList (Leaf $ ResultInfo 0 t ()) mempty rewind t ResultList{} = ResultList mempty (expected (Down $ length t) "notFollowedBy") skipMany p = go where go = pure () <|> p *> go unexpected msg = Parser (\t-> ResultList mempty $ expected (Down $ length t) msg) eof = Parser f where f rest@((s, _):_) | null s = ResultList (Leaf $ ResultInfo 0 rest ()) mempty | otherwise = ResultList mempty (expected (Down $ length rest) "endOfInput") f [] = ResultList (Leaf $ ResultInfo 0 [] ()) mempty instance (MonoidNull s, Ord s) => DeterministicParsing (Parser g s) where Parser p <<|> Parser q = Parser r where r rest = case p rest of rl@(ResultList EmptyTree _failure) -> rl <> q rest rl -> rl takeSome p = (:) <$> p <*> takeMany p takeMany (Parser p) = Parser (q 0 id) where q len acc rest = case p rest of ResultList EmptyTree _failure -> ResultList (Leaf $ ResultInfo len rest (acc [])) mempty ResultList rl _ -> foldMap continue rl where continue (ResultInfo len' rest' result) = q (len + len') (acc . (result:)) rest' skipAll (Parser p) = Parser (q 0) where q len rest = case p rest of ResultList EmptyTree _failure -> ResultList (Leaf $ ResultInfo len rest ()) mempty ResultList rl _failure -> foldMap continue rl where continue (ResultInfo len' rest' _) = q (len + len') rest' instance (MonoidNull s, Ord s) => LookAheadParsing (Parser g s) where lookAhead (Parser p) = Parser (\input-> rewind input (p input)) where rewind t (ResultList rl failure) = ResultList (rewindInput t <$> rl) failure rewindInput t (ResultInfo _ _ r) = ResultInfo 0 t r instance (Ord s, Show s, TextualMonoid s) => CharParsing (Parser g s) where satisfy predicate = Parser p where p rest@((s, _):t) = case Textual.characterPrefix s of Just first | predicate first -> ResultList (Leaf $ ResultInfo 1 t first) mempty _ -> ResultList mempty (expected (Down $ length rest) "Char.satisfy") p [] = ResultList mempty (expected 0 "Char.satisfy") string s = Textual.toString (error "unexpected non-character") <$> string (fromString s) text t = (fromString . Textual.toString (error "unexpected non-character")) <$> string (Textual.fromText t) fromResultList :: FactorialMonoid s => ResultList g s r -> ParseResults s [(s, r)] fromResultList (ResultList EmptyTree (ParseFailure pos positive negative)) = Left (ParseFailure (pos - 1) positive negative) fromResultList (ResultList rl _failure) = Right (f <$> toList rl) where f (ResultInfo _ ((s, _):_) r) = (s, r) f (ResultInfo _ [] r) = (mempty, r) -- | Turns a context-free parser into a backtracking PEG parser that consumes the longest possible prefix of the list -- of input tails, opposite of 'peg' longest :: Parser g s a -> Backtrack.Parser g [(s, g (ResultList g s))] a longest p = Backtrack.Parser q where q rest = case applyParser p rest of ResultList EmptyTree (ParseFailure pos positive negative) -> Backtrack.NoParse (ParseFailure pos (map message positive) (map message negative)) ResultList rs _ -> parsed (maximumBy (compare `on` resultLength) rs) resultLength (ResultInfo l _ _) = l parsed (ResultInfo l s r) = Backtrack.Parsed l r s message (StaticDescription msg) = StaticDescription msg message (LiteralDescription s) = LiteralDescription [(s, error "longest")] -- | Turns a backtracking PEG parser of the list of input tails into a context-free parser, opposite of 'longest' peg :: Ord s => Backtrack.Parser g [(s, g (ResultList g s))] a -> Parser g s a peg p = Parser q where q rest = case Backtrack.applyParser p rest of Backtrack.Parsed l result suffix -> ResultList (Leaf $ ResultInfo l suffix result) mempty Backtrack.NoParse (ParseFailure pos positive negative) -> ResultList mempty (ParseFailure pos (original <$> positive) (original <$> negative)) where original = (fst . head <$>) -- | Turns a backtracking PEG parser into a context-free parser terminalPEG :: (Monoid s, Ord s) => Backtrack.Parser g s a -> Parser g s a terminalPEG p = Parser q where q [] = case Backtrack.applyParser p mempty of Backtrack.Parsed l result _ -> ResultList (Leaf $ ResultInfo l [] result) mempty Backtrack.NoParse failure -> ResultList mempty failure q rest@((s, _):_) = case Backtrack.applyParser p s of Backtrack.Parsed l result _ -> ResultList (Leaf $ ResultInfo l (drop l rest) result) mempty Backtrack.NoParse failure -> ResultList mempty failure
blamario/grampa
grammatical-parsers/src/Text/Grampa/ContextFree/Memoizing.hs
Haskell
bsd-2-clause
18,417
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module ApiTypes where import Control.Applicative (Applicative) import Control.Concurrent.STM (TVar) import Control.Monad.Reader (MonadReader, ReaderT (..)) import Control.Monad.Trans (MonadIO) import Data.HashMap.Strict (HashMap) import Data.Set (Set) import Type.Comment (Comment) import Type.Invoice (Invoice) import Type.Customer (Customer) import qualified Type.Invoice as Invoice data ServerData = ServerData { customers :: TVar (Set Customer) , invoices :: TVar (Set Invoice) , comments :: TVar (HashMap Invoice.Id (Set Comment)) } newtype BlogApi a = BlogApi { unBlogApi :: ReaderT ServerData IO a } deriving ( Applicative , Functor , Monad , MonadIO , MonadReader ServerData ) runBlogApi :: ServerData -> BlogApi a -> IO a runBlogApi serverdata = flip runReaderT serverdata . unBlogApi
tinkerthaler/basic-invoice-rest
example-api/ApiTypes.hs
Haskell
bsd-3-clause
914
{-| Module : MixedTypesNumPrelude Description : Bottom-up typed numeric expressions Copyright : (c) Michal Konecny, Pieter Collins License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable @MixedTypesNumPrelude@ provides a version of @Prelude@ where unary and binary operations such as @not@, @+@, @==@ have their result type derived from the parameter type(s). This module facilitates a single-line import for the package mixed-types-num. See the re-exported modules for further details. -} module MixedTypesNumPrelude ( -- * Re-exporting Prelude, hiding the operators we are changing module Numeric.MixedTypes.PreludeHiding, -- * Error-collecting wrapper type CN, cn, unCN, clearPotentialErrors, -- * A part of package ``convertible'' module Data.Convertible.Base, -- * Modules with Prelude alternatives module Numeric.MixedTypes.Literals, module Numeric.MixedTypes.Bool, module Numeric.MixedTypes.Eq, module Numeric.MixedTypes.Ord, module Numeric.MixedTypes.MinMaxAbs, module Numeric.MixedTypes.AddSub, module Numeric.MixedTypes.Round, module Numeric.MixedTypes.Reduce, module Numeric.MixedTypes.Mul, module Numeric.MixedTypes.Ring, module Numeric.MixedTypes.Div, module Numeric.MixedTypes.Power, module Numeric.MixedTypes.Field, module Numeric.MixedTypes.Elementary, module Numeric.MixedTypes.Complex, -- module Numeric.CollectErrors, module Utils.TH.DeclForTypes, module Utils.Test.EnforceRange, -- * Re-export for convenient Rational literals (%) ) where import Data.Ratio ((%)) import Numeric.CollectErrors (CN, cn, unCN, clearPotentialErrors) import Data.Convertible.Instances.Num() import Data.Convertible.Base import Utils.TH.DeclForTypes import Utils.Test.EnforceRange import Numeric.MixedTypes.PreludeHiding import Numeric.MixedTypes.Literals import Numeric.MixedTypes.Bool import Numeric.MixedTypes.Eq import Numeric.MixedTypes.Ord import Numeric.MixedTypes.MinMaxAbs import Numeric.MixedTypes.AddSub import Numeric.MixedTypes.Round import Numeric.MixedTypes.Reduce import Numeric.MixedTypes.Mul import Numeric.MixedTypes.Ring import Numeric.MixedTypes.Div import Numeric.MixedTypes.Power import Numeric.MixedTypes.Field import Numeric.MixedTypes.Elementary import Numeric.MixedTypes.Complex
michalkonecny/mixed-types-num
src/MixedTypesNumPrelude.hs
Haskell
bsd-3-clause
2,375
module Signal.Wavelet.Eval2Bench where import Signal.Wavelet.Eval2 {-# INLINE benchDwt #-} benchDwt :: ([Double], [Double]) -> [Double] benchDwt (ls, sig) = dwt ls sig {-# INLINE benchIdwt #-} benchIdwt :: ([Double], [Double]) -> [Double] benchIdwt (ls, sig) = idwt ls sig
jstolarek/lattice-structure-hs
bench/Signal/Wavelet/Eval2Bench.hs
Haskell
bsd-3-clause
278
{-# LANGUAGE MultiParamTypeClasses, NoImplicitPrelude, RebindableSyntax #-} {-# LANGUAGE ScopedTypeVariables, ViewPatterns #-} module Numeric.Field.Fraction ( Fraction , numerator , denominator , Ratio , (%) , lcm ) where import Data.Proxy import Numeric.Additive.Class import Numeric.Additive.Group import Numeric.Algebra.Class import Numeric.Algebra.Commutative import Numeric.Algebra.Division import Numeric.Algebra.Unital import Numeric.Decidable.Units import Numeric.Decidable.Zero import Numeric.Domain.Euclidean import Numeric.Natural import Numeric.Rig.Characteristic import Numeric.Rig.Class import Numeric.Ring.Class import Numeric.Semiring.Integral import Prelude hiding (Integral (..), Num (..), gcd, lcm) -- | Fraction field @k(D)@ of 'Euclidean' domain @D@. data Fraction d = Fraction !d !d -- Invariants: r == Fraction p q -- ==> leadingUnit q == one && q /= 0 -- && isUnit (gcd p q) -- | Convenient synonym for 'Fraction'. type Ratio = Fraction lcm :: Euclidean r => r -> r -> r lcm p q = p * q `quot` gcd p q instance (Eq d, Show d, Unital d) => Show (Fraction d) where showsPrec d (Fraction p q) | q == one = showsPrec d p | otherwise = showParen (d > 5) $ showsPrec 6 p . showString " / " . showsPrec 6 q infixl 7 % (%) :: Euclidean d => d -> d -> Fraction d a % b = let (ua, a') = splitUnit a (ub, b') = splitUnit b Just ub' = recipUnit ub r = gcd a' b' in Fraction (ua * ub' * a' `quot` r) (b' `quot` r) numerator :: Fraction t -> t numerator (Fraction q _) = q {-# INLINE numerator #-} denominator :: Fraction t -> t denominator (Fraction _ p) = p {-# INLINE denominator #-} instance Euclidean d => IntegralSemiring (Fraction d) instance (Eq d, Multiplicative d) => Eq (Fraction d) where Fraction p q == Fraction s t = p*t == q*s {-# INLINE (==) #-} instance (Ord d, Multiplicative d) => Ord (Fraction d) where compare (Fraction p q) (Fraction p' q') = compare (p*q') (p'*q) {-# INLINE compare #-} instance Euclidean d => Division (Fraction d) where recip (Fraction p q) | isZero p = error "Ratio has zero denominator!" | otherwise = let (recipUnit -> Just u, p') = splitUnit p in Fraction (q * u) p' Fraction p q / Fraction s t = (p*t) % (q*s) {-# INLINE recip #-} {-# INLINE (/) #-} instance (Commutative d, Euclidean d) => Commutative (Fraction d) instance Euclidean d => DecidableZero (Fraction d) where isZero (Fraction p _) = isZero p {-# INLINE isZero #-} instance Euclidean d => DecidableUnits (Fraction d) where isUnit (Fraction p _) = not $ isZero p {-# INLINE isUnit #-} recipUnit (Fraction p q) | isZero p = Nothing | otherwise = Just (Fraction q p) {-# INLINE recipUnit #-} instance Euclidean d => Ring (Fraction d) instance Euclidean d => Abelian (Fraction d) instance Euclidean d => Semiring (Fraction d) instance Euclidean d => Group (Fraction d) where negate (Fraction p q) = Fraction (negate p) q Fraction p q - Fraction p' q' = (p*q'-p'*q) % (q*q') instance Euclidean d => Monoidal (Fraction d) where zero = Fraction zero one {-# INLINE zero #-} instance Euclidean d => LeftModule Integer (Fraction d) where n .* Fraction p r = (n .* p) % r {-# INLINE (.*) #-} instance Euclidean d => RightModule Integer (Fraction d) where Fraction p r *. n = (p *. n) % r {-# INLINE (*.) #-} instance Euclidean d => LeftModule Natural (Fraction d) where n .* Fraction p r = (n .* p) % r {-# INLINE (.*) #-} instance Euclidean d => RightModule Natural (Fraction d) where Fraction p r *. n = (p *. n) % r {-# INLINE (*.) #-} instance Euclidean d => Additive (Fraction d) where Fraction p q + Fraction s t = let u = gcd q t in Fraction (p * t `quot` u + s*q`quot`u) (q*t`quot`u) {-# INLINE (+) #-} instance Euclidean d => Unital (Fraction d) where one = Fraction one one {-# INLINE one #-} instance Euclidean d => Multiplicative (Fraction d) where Fraction p q * Fraction s t = (p*s) % (q*t) instance Euclidean d => Rig (Fraction d) instance (Characteristic d, Euclidean d) => Characteristic (Fraction d) where char _ = char (Proxy :: Proxy d)
athanclark/algebra
src/Numeric/Field/Fraction.hs
Haskell
bsd-3-clause
4,275
{-# LANGUAGE FlexibleContexts #-} module Language.Typo.Token ( typoDef -- :: LanguageDef s , typo -- :: GenTokenParser String u Identity , lexeme -- :: Parsec String u a -> Parsec String u a , parens -- :: Parsec String u a -> Parsec String u a , identifier -- :: Parsec String u String , operator -- :: Parsec String u String , natural -- :: Parsec String u Integer , whiteSpace -- :: Parsec String u () ) where import Control.Monad.Identity import Text.Parsec ( oneOf ) import Text.Parsec.Prim import Text.Parsec.Language ( emptyDef ) import Text.Parsec.Token ( GenTokenParser, LanguageDef, makeTokenParser ) import qualified Text.Parsec.Token as P typoDef :: LanguageDef s typoDef = emptyDef { P.commentLine = ";", P.opStart = P.opLetter typoDef, P.opLetter = oneOf ":!$%&*+./<=>?@\\^|-~", P.reservedNames = [ "define", "let", "if" -- language keywords , "and", "or", "imp", "cond" -- (prelude) boolean operators , "add", "sub", "mul", "div", "rem" -- (prelude) arithmetic operators , "eq", "lt" -- (prelude) comparison operators , "result", "res", "undefined" -- program keywords ] } typo :: GenTokenParser String u Identity typo = makeTokenParser typoDef lexeme, parens :: Parsec String u a -> Parsec String u a lexeme = P.lexeme typo parens = P.parens typo identifier, operator :: Parsec String u String identifier = P.identifier typo operator = P.operator typo natural :: Parsec String u Integer natural = P.natural typo whiteSpace :: Parsec String u () whiteSpace = P.whiteSpace typo
seliopou/typo
Language/Typo/Token.hs
Haskell
bsd-3-clause
1,630
{-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} -- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- module Feldspar.Core.Constructs.MutableToPure ( MutableToPure (..) ) where import qualified Control.Exception as C import Data.Array.IArray import Data.Array.MArray (freeze) import Data.Array.Unsafe (unsafeFreeze) import System.IO.Unsafe import Language.Syntactic import Language.Syntactic.Constructs.Binding import Language.Syntactic.Constructs.Binding.HigherOrder (CLambda) import Feldspar.Lattice import Feldspar.Core.Types import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.Binding data MutableToPure a where RunMutableArray :: Type a => MutableToPure (Mut (MArr a) :-> Full [a]) WithArray :: Type b => MutableToPure (MArr a :-> ([a] -> Mut b) :-> Full (Mut b)) instance Semantic MutableToPure where semantics RunMutableArray = Sem "runMutableArray" runMutableArrayEval semantics WithArray = Sem "withArray" withArrayEval runMutableArrayEval :: forall a . Mut (MArr a) -> [a] runMutableArrayEval m = unsafePerformIO $ do marr <- m iarr <- unsafeFreeze marr return (elems (iarr :: Array Integer a)) withArrayEval :: forall a b. MArr a -> ([a] -> Mut b) -> Mut b withArrayEval ma f = do a <- f (elems (unsafePerformIO $ freeze ma :: Array Integer a)) C.evaluate a instance Typed MutableToPure where typeDictSym RunMutableArray = Just Dict typeDictSym _ = Nothing semanticInstances ''MutableToPure instance EvalBind MutableToPure where evalBindSym = evalBindSymDefault instance AlphaEq dom dom dom env => AlphaEq MutableToPure MutableToPure dom env where alphaEqSym = alphaEqSymDefault instance Sharable MutableToPure instance Cumulative MutableToPure instance SizeProp MutableToPure where sizeProp RunMutableArray (WrapFull arr :* Nil) = infoSize arr sizeProp WithArray (_ :* WrapFull fun :* Nil) = snd $ infoSize fun instance ( MutableToPure :<: dom , Let :<: dom , (Variable :|| Type) :<: dom , CLambda Type :<: dom , OptimizeSuper dom ) => Optimize MutableToPure dom where optimizeFeat opts sym@WithArray (arr :* fun@(lam :$ body) :* Nil) | Dict <- exprDict fun , Dict <- exprDict body , Just (SubConstr2 (Lambda _)) <- prjLambda lam = do arr' <- optimizeM opts arr let (szl :> sze) = infoSize (getInfo arr') fun' <- optimizeFunction opts (optimizeM opts) (mkInfo (szl :> sze)) fun constructFeat opts sym (arr' :* fun' :* Nil) optimizeFeat opts sym args = optimizeFeatDefault opts sym args constructFeatUnOpt opts RunMutableArray args = constructFeatUnOptDefaultTyp opts typeRep RunMutableArray args constructFeatUnOpt opts WithArray args = constructFeatUnOptDefaultTyp opts (MutType typeRep) WithArray args
emwap/feldspar-language
src/Feldspar/Core/Constructs/MutableToPure.hs
Haskell
bsd-3-clause
4,777
{- Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.0 Kubernetes API version: v1.9.12 Generated by Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) -} {-| Module : Kubernetes.OpenAPI.API.Certificates -} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MonoLocalBinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-name-shadowing -fno-warn-unused-binds -fno-warn-unused-imports #-} module Kubernetes.OpenAPI.API.Certificates where import Kubernetes.OpenAPI.Core import Kubernetes.OpenAPI.MimeTypes import Kubernetes.OpenAPI.Model as M import qualified Data.Aeson as A import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.Data as P (Typeable, TypeRep, typeOf, typeRep) import qualified Data.Foldable as P import qualified Data.Map as Map import qualified Data.Maybe as P import qualified Data.Proxy as P (Proxy(..)) import qualified Data.Set as Set import qualified Data.String as P import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import qualified Data.Time as TI import qualified Network.HTTP.Client.MultipartFormData as NH import qualified Network.HTTP.Media as ME import qualified Network.HTTP.Types as NH import qualified Web.FormUrlEncoded as WH import qualified Web.HttpApiData as WH import Data.Text (Text) import GHC.Base ((<|>)) import Prelude ((==),(/=),($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor) import qualified Prelude as P -- * Operations -- ** Certificates -- *** getAPIGroup -- | @GET \/apis\/certificates.k8s.io\/@ -- -- get information of a group -- -- AuthMethod: 'AuthApiKeyBearerToken' -- getAPIGroup :: Accept accept -- ^ request accept ('MimeType') -> KubernetesRequest GetAPIGroup MimeNoContent V1APIGroup accept getAPIGroup _ = _mkRequest "GET" ["/apis/certificates.k8s.io/"] `_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyBearerToken) data GetAPIGroup -- | @application/json@ instance Consumes GetAPIGroup MimeJSON -- | @application/yaml@ instance Consumes GetAPIGroup MimeYaml -- | @application/vnd.kubernetes.protobuf@ instance Consumes GetAPIGroup MimeVndKubernetesProtobuf -- | @application/json@ instance Produces GetAPIGroup MimeJSON -- | @application/yaml@ instance Produces GetAPIGroup MimeYaml -- | @application/vnd.kubernetes.protobuf@ instance Produces GetAPIGroup MimeVndKubernetesProtobuf
denibertovic/haskell
kubernetes/lib/Kubernetes/OpenAPI/API/Certificates.hs
Haskell
bsd-3-clause
2,742
module Network.PushbulletSpec (main, spec) where import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "someFunction" $ do it "should work fine" $ do True `shouldBe` False
KevinCotrone/pushbullet
test/Network/PushbulletSpec.hs
Haskell
bsd-3-clause
215
import System.Environment (getArgs) import Data.List.Split (splitOn) maxran :: Int -> Int -> [Int] -> [Int] -> Int maxran x _ _ [] = x maxran x c (y:ys) (z:zs) = maxran (max x d) d (ys ++ [z]) zs where d = c - y + z maxrange :: [String] -> Int maxrange [ns, xs] = maxran (max 0 z) z zs (drop n ys) where n = read ns ys = map read (words xs) zs = take n ys z = sum zs main :: IO () main = do [inpFile] <- getArgs input <- readFile inpFile putStr . unlines . map (show . maxrange . splitOn ";") $ lines input
nikai3d/ce-challenges
easy/max_range_sum.hs
Haskell
bsd-3-clause
673
import System.Environment (getArgs) r1 :: [Int] r1 = [1, 0, 0, 0, 1, 1] r2 :: [Int] r2 = [1, 0, 1, 0, 1, 1] bnot :: Int -> Int bnot 0 = 1 bnot _ = 0 pmod6 :: Int -> Int pmod6 x | mod x 6 == 0 = 6 | otherwise = mod x 6 locks :: [Int] -> Int locks [0, _] = 0 locks [x, 0] = x locks [x, 1] = x-1 locks [x, y] | x > 6 && mod y 2 == 0 = div x 6 * 3 + locks [pmod6 x, y] | x > 6 = div x 6 * 4 + locks [pmod6 x, y] | mod y 2 == 0 = sum (init xs) + bnot (last xs) | otherwise = sum (init ys) + bnot (last ys) where xs = take x r1 ys = take x r2 main :: IO () main = do [inpFile] <- getArgs input <- readFile inpFile putStr . unlines . map (show . locks . map read . words) $ lines input
nikai3d/ce-challenges
moderate/locks.hs
Haskell
bsd-3-clause
816
module Main where import Graphics.Gnuplot.Simple -- import qualified Graphics.Gnuplot.Terminal.WXT as WXT -- import qualified Graphics.Gnuplot.Terminal.PostScript as PS ops :: [Attribute] -- ops = [(Custom "term" ["postscript", "eps", "enhanced", "color", "solid"]) -- ,(Custom "output" ["temp.eps"]) -- ] -- ops = [(terminal $ WXT.persist WXT.cons)] -- ops = [(EPS "temp.eps")] ops = [(PNG "temp.png")] main :: IO () main = do let xs = (linearScale 1000 (0,2*pi)) :: [Double] ys = fmap sin xs points = zip xs ys plotPath ops points
chupaaaaaaan/nn-with-haskell
app/Main_ex.hs
Haskell
bsd-3-clause
569
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad.Trans (lift) import qualified Data.Text as T import Data.Either import Reflex.Dom import Frontend.Function import Frontend.ImageWidget import Frontend.WebcamWidget main :: IO () main = mainWidget $ do d <- lift askDocument -- imageInputWidget d def functionPage d -- imageInputWidget d def -- webcamWidget d (constDyn mempty) -- loader <- fileImageLoader -- displayImg =<< holdDyn (T.pack "") (fmap snd loader) blank hush :: Either e a -> Maybe a hush (Right a) = Just a hush _ = Nothing
CBMM/CBaaS
cbaas-frontend/exec/Frontend.hs
Haskell
bsd-3-clause
591
module Horbits.Body (bodyUiColor, getBody, fromBodyId, module X) where import Control.Lens hiding ((*~), _2, _3, _4) import Horbits.Body.Atmosphere as X import Horbits.Body.Body as X import Horbits.Body.Color as X import Horbits.Body.Data as X import Horbits.Body.Id as X bodyUiColor :: Fold BodyId (RgbaColor Float) bodyUiColor = to getColor . traverse -- Data getBody :: BodyId -> Body getBody bId = Body bId (_bodyName bId) mu r t soi atm where soi = getSphereOfInfluence bId (r, t, mu) = getPhysicalAttrs bId atm = getAtmosphere bId _bodyName :: BodyId -> String _bodyName Sun = "Kerbol" _bodyName b = show b fromBodyId :: Getter BodyId Body fromBodyId = to getBody
chwthewke/horbits
src/horbits/Horbits/Body.hs
Haskell
bsd-3-clause
790
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | All types. module HIndent.Types (Printer(..) ,PrintState(..) ,Extender(..) ,Style(..) ,Config(..) ,defaultConfig ,NodeInfo(..) ,ComInfo(..) ,ComInfoLocation(..) ) where import Control.Applicative import Control.Monad import Control.Monad.State.Strict (MonadState(..),StateT) import Control.Monad.Trans.Maybe import Data.Data import Data.Default import Data.Functor.Identity import Data.Int (Int64) import Data.Text (Text) import Data.Text.Lazy.Builder (Builder) import Language.Haskell.Exts.Comments import Language.Haskell.Exts.Parser import Language.Haskell.Exts.SrcLoc -- | A pretty printing monad. newtype Printer s a = Printer {runPrinter :: StateT (PrintState s) (MaybeT Identity) a} deriving (Applicative,Monad,Functor,MonadState (PrintState s),MonadPlus,Alternative) -- | The state of the pretty printer. data PrintState s = PrintState {psIndentLevel :: !Int64 -- ^ Current indentation level. ,psOutput :: !Builder -- ^ The current output. ,psNewline :: !Bool -- ^ Just outputted a newline? ,psColumn :: !Int64 -- ^ Current column. ,psLine :: !Int64 -- ^ Current line number. ,psUserState :: !s -- ^ User state. ,psExtenders :: ![Extender s] -- ^ Extenders. ,psConfig :: !Config -- ^ Config which styles may or may not pay attention to. ,psEolComment :: !Bool -- ^ An end of line comment has just been outputted. ,psInsideCase :: !Bool -- ^ Whether we're in a case statement, used for Rhs printing. ,psParseMode :: !ParseMode -- ^ Mode used to parse the original AST. } instance Eq (PrintState s) where PrintState ilevel out newline col line _ _ _ eolc inc pm == PrintState ilevel' out' newline' col' line' _ _ _ eolc' inc' pm' = (ilevel,out,newline,col,line,eolc, inc) == (ilevel',out',newline',col',line',eolc', inc') -- | A printer extender. Takes as argument the user state that the -- printer was run with, and the current node to print. Use -- 'prettyNoExt' to fallback to the built-in printer. data Extender s where Extender :: forall s a. (Typeable a) => (a -> Printer s ()) -> Extender s CatchAll :: forall s. (forall a. Typeable a => s -> a -> Maybe (Printer s ())) -> Extender s -- | A printer style. data Style = forall s. Style {styleName :: !Text -- ^ Name of the style, used in the commandline interface. ,styleAuthor :: !Text -- ^ Author of the printer (as opposed to the author of the style). ,styleDescription :: !Text -- ^ Description of the style. ,styleInitialState :: !s -- ^ User state, if needed. ,styleExtenders :: ![Extender s] -- ^ Extenders to the printer. ,styleDefConfig :: !Config -- ^ Default config to use for this style. } -- | Configurations shared among the different styles. Styles may pay -- attention to or completely disregard this configuration. data Config = Config {configMaxColumns :: !Int64 -- ^ Maximum columns to fit code into ideally. ,configIndentSpaces :: !Int64 -- ^ How many spaces to indent? ,configClearEmptyLines :: !Bool -- ^ Remove spaces on lines that are otherwise empty? } instance Default Config where def = Config {configMaxColumns = 80 ,configIndentSpaces = 2 ,configClearEmptyLines = False} -- | Default style configuration. defaultConfig :: Config defaultConfig = def -- | Information for each node in the AST. data NodeInfo = NodeInfo {nodeInfoSpan :: !SrcSpanInfo -- ^ Location info from the parser. ,nodeInfoComments :: ![ComInfo] -- ^ Comments which are attached to this node. } deriving (Typeable,Show,Data) -- | Comment relative locations. data ComInfoLocation = Before | After deriving (Show,Typeable,Data,Eq) -- | Comment with some more info. data ComInfo = ComInfo {comInfoComment :: !Comment -- ^ The normal comment type. ,comInfoLocation :: !(Maybe ComInfoLocation) -- ^ Where the comment lies relative to the node. } deriving (Show,Typeable,Data)
adamse/hindent
src/HIndent/Types.hs
Haskell
bsd-3-clause
4,328
module Graphics.Vty.Widgets.Builder.SrcHelpers ( defAttr , toAST , call , bind , tBind , noLoc , act , expr , mkTyp , parseType , mkList , parens , mkName , mkString , mkInt , mkChar , mkTup , opApp , mkLet , mkImportDecl , nameStr , attrsToExpr ) where import qualified Language.Haskell.Exts as Hs defAttr :: Hs.Exp defAttr = expr $ mkName "def_attr" toAST :: (Show a) => a -> Hs.Exp toAST thing = parsed where Hs.ParseOk parsed = Hs.parse $ show thing call :: String -> [Hs.Exp] -> Hs.Exp call func [] = Hs.Var $ Hs.UnQual $ mkName func call func args = mkApp (Hs.Var $ Hs.UnQual $ mkName func) args where mkApp app [] = app mkApp app (arg:rest) = mkApp (Hs.App app arg) rest bind :: Hs.Name -> String -> [Hs.Exp] -> Hs.Stmt bind lval func args = Hs.Generator noLoc (Hs.PVar lval) $ call func args tBind :: [Hs.Name] -> String -> [Hs.Exp] -> Hs.Stmt tBind lvals func args = Hs.Generator noLoc (Hs.PTuple (map Hs.PVar lvals)) $ call func args act :: Hs.Exp -> Hs.Stmt act = Hs.Qualifier expr :: Hs.Name -> Hs.Exp expr = Hs.Var . Hs.UnQual parens :: Hs.Exp -> Hs.Exp parens = Hs.Paren mkString :: String -> Hs.Exp mkString = Hs.Lit . Hs.String mkInt :: Int -> Hs.Exp mkInt = Hs.Lit . Hs.Int . toEnum mkChar :: Char -> Hs.Exp mkChar = Hs.Lit . Hs.Char mkTup :: [Hs.Exp] -> Hs.Exp mkTup = Hs.Tuple mkList :: [Hs.Exp] -> Hs.Exp mkList = Hs.List opApp :: Hs.Exp -> Hs.Name -> Hs.Exp -> Hs.Exp opApp a op b = Hs.InfixApp a (Hs.QVarOp $ Hs.UnQual op) b mkLet :: [(Hs.Name, Hs.Exp)] -> Hs.Stmt mkLet pairs = Hs.LetStmt $ Hs.BDecls $ map mkDecl pairs where mkDecl (nam, e) = Hs.PatBind noLoc (Hs.PVar nam) Nothing (Hs.UnGuardedRhs e) (Hs.BDecls []) mkName :: String -> Hs.Name mkName = Hs.Ident mkImportDecl :: String -> [String] -> Hs.ImportDecl mkImportDecl name hidden = Hs.ImportDecl { Hs.importLoc = noLoc , Hs.importModule = Hs.ModuleName name , Hs.importQualified = False , Hs.importSrc = False , Hs.importPkg = Nothing , Hs.importAs = Nothing , Hs.importSpecs = case hidden of [] -> Nothing is -> Just (True, map (Hs.IVar . mkName) is) } parseType :: String -> Hs.Type parseType s = case Hs.parse s of Hs.ParseOk val -> val Hs.ParseFailed _ msg -> error $ "Error parsing type string '" ++ s ++ "': " ++ msg attrsToExpr :: (Maybe String, Maybe String) -> Maybe Hs.Exp attrsToExpr (Nothing, Nothing) = Nothing attrsToExpr (Just fg, Nothing) = Just $ call "fgColor" [expr $ mkName fg] attrsToExpr (Nothing, Just bg) = Just $ call "bgColor" [expr $ mkName bg] attrsToExpr (Just fg, Just bg) = Just $ opApp (expr $ mkName fg) (mkName "on") (expr $ mkName bg) nameStr :: Hs.Name -> String nameStr (Hs.Ident s) = s nameStr n = error $ "Unsupported name: " ++ (show n) noLoc :: Hs.SrcLoc noLoc = Hs.SrcLoc { Hs.srcFilename = "-" , Hs.srcLine = 0 , Hs.srcColumn = 0 } mkTyp :: String -> [Hs.Type] -> Hs.Type mkTyp tyCon [] = Hs.TyCon $ Hs.UnQual $ mkName tyCon mkTyp tyCon args = mkApp (Hs.TyCon (Hs.UnQual (mkName tyCon))) args where mkApp ty [] = ty mkApp ty (ty':tys) = mkApp (Hs.TyApp ty ty') tys
jtdaugherty/vty-ui-builder
src/Graphics/Vty/Widgets/Builder/SrcHelpers.hs
Haskell
bsd-3-clause
3,680
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE CPP #-} module Control.Distributed.Process.Serializable ( Serializable , encodeFingerprint , decodeFingerprint , fingerprint , sizeOfFingerprint , Fingerprint , showFingerprint , SerializableDict(SerializableDict) , TypeableDict(TypeableDict) ) where import Data.Binary (Binary) #if MIN_VERSION_base(4,7,0) import Data.Typeable (Typeable) import Data.Typeable.Internal (TypeRep(TypeRep), typeOf) #else import Data.Typeable (Typeable(..)) import Data.Typeable.Internal (TypeRep(TypeRep)) #endif import Numeric (showHex) import Control.Exception (throw) import GHC.Fingerprint.Type (Fingerprint(..)) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Internal as BSI ( unsafeCreate , inlinePerformIO , toForeignPtr ) import Foreign.Storable (pokeByteOff, peekByteOff, sizeOf) import Foreign.ForeignPtr (withForeignPtr) -- | Reification of 'Serializable' (see "Control.Distributed.Process.Closure") data SerializableDict a where SerializableDict :: Serializable a => SerializableDict a deriving (Typeable) -- | Reification of 'Typeable'. data TypeableDict a where TypeableDict :: Typeable a => TypeableDict a deriving (Typeable) -- | Objects that can be sent across the network class (Binary a, Typeable a) => Serializable a instance (Binary a, Typeable a) => Serializable a -- | Encode type representation as a bytestring encodeFingerprint :: Fingerprint -> ByteString encodeFingerprint fp = -- Since all CH nodes will run precisely the same binary, we don't have to -- worry about cross-arch issues here (like endianness) BSI.unsafeCreate sizeOfFingerprint $ \p -> pokeByteOff p 0 fp -- | Decode a bytestring into a fingerprint. Throws an IO exception on failure decodeFingerprint :: ByteString -> Fingerprint decodeFingerprint bs | BS.length bs /= sizeOfFingerprint = throw $ userError "decodeFingerprint: Invalid length" | otherwise = BSI.inlinePerformIO $ do let (fp, offset, _) = BSI.toForeignPtr bs withForeignPtr fp $ \p -> peekByteOff p offset -- | Size of a fingerprint sizeOfFingerprint :: Int sizeOfFingerprint = sizeOf (undefined :: Fingerprint) -- | The fingerprint of the typeRep of the argument fingerprint :: Typeable a => a -> Fingerprint fingerprint a = let TypeRep fp _ _ = typeOf a in fp -- | Show fingerprint (for debugging purposes) showFingerprint :: Fingerprint -> ShowS showFingerprint (Fingerprint hi lo) = showString "(" . showHex hi . showString "," . showHex lo . showString ")"
mboes/distributed-process
src/Control/Distributed/Process/Serializable.hs
Haskell
bsd-3-clause
2,835
module Utils ( wordCount, makeBatch, accuracy ) where import Control.Arrow ( (&&&) ) import Data.List ( sort, group, reverse, nub ) import Control.Monad ( join ) wordCount :: (Eq a, Ord a) => [a] -> [(a, Int)] wordCount = map (head &&& length) . group . sort makeBatch :: Int -> [a] -> [[a]] makeBatch _ [] = [] makeBatch size xs = let (x, xs') = splitAt size xs in x:makeBatch size xs' accuracy :: Eq a => [[a]] -> [[a]] -> Float accuracy pred gold = realToFrac correct / realToFrac (length pred') where correct = length $ filter (\(p, g) -> p == g) $ zip pred' gold' pred' = join pred gold' = join gold
masashi-y/dynet.hs
examples/utils/Utils.hs
Haskell
bsd-3-clause
653
module Data.Aeson.TH.Extra where import Data.Aeson.TH ( defaultOptions , Options(..) ) import Data.String.Extra (dropL1) prefixRemovedOpts :: Int -> Options prefixRemovedOpts i = defaultOptions {fieldLabelModifier = dropL1 i}
onurzdg/clicklac
src/Data/Aeson/TH/Extra.hs
Haskell
bsd-3-clause
260
{-#LANGUAGE FlexibleInstances #-} {-#LANGUAGE FlexibleContexts #-} {-#LANGUAGE LambdaCase #-} {-#LANGUAGE MultiParamTypeClasses #-} {-#LANGUAGE OverloadedStrings #-} {-#LANGUAGE Rank2Types #-} {-#LANGUAGE ScopedTypeVariables #-} module Twilio.Types ( APIVersion(..) , module X -- * Misc , makeTwilioRequest , makeTwilioRequest' , makeTwilioPOSTRequest , makeTwilioPOSTRequest' ) where import Control.Monad import Control.Monad.Reader.Class import Data.Aeson import qualified Data.ByteString.Char8 as C import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Network.HTTP.Client import Control.Monad.Twilio import Twilio.Types.AddressRequirement as X import Twilio.Types.AuthToken as X import Twilio.Types.Capability as X import Twilio.Types.ISOCountryCode as X import Twilio.Types.List as X import Twilio.Types.PriceUnit as X import Twilio.Types.SID as X import Twilio.Internal.Parser import Twilio.Internal.Request data APIVersion = API_2010_04_01 | API_2008_08_01 deriving Eq instance Read APIVersion where readsPrec _ = \case "2010-04-01" -> return (API_2010_04_01, "") "2008-08-01" -> return (API_2008_08_01, "") _ -> mzero instance Show APIVersion where show API_2010_04_01 = "2010-04-01" show API_2008_08_01 = "2008-08-01" instance FromJSON APIVersion where parseJSON (String "2010-04-01") = return API_2010_04_01 parseJSON (String "2008-08-01") = return API_2008_08_01 parseJSON _ = mzero makeTwilioRequest' :: Monad m => Text -> TwilioT m Request makeTwilioRequest' suffix = do ((accountSID, authToken), _) <- ask let Just request = parseUrl . T.unpack $ baseURL <> suffix return $ applyBasicAuth (C.pack . T.unpack $ getSID accountSID) (C.pack . T.unpack $ getAuthToken authToken) request makeTwilioRequest :: Monad m => Text -> TwilioT m Request makeTwilioRequest suffix = do ((_, _), accountSID) <- ask makeTwilioRequest' $ "/Accounts/" <> getSID accountSID <> suffix makeTwilioPOSTRequest' :: Monad m => Text -> [(C.ByteString, C.ByteString)] -> TwilioT m Request makeTwilioPOSTRequest' resourceURL params = makeTwilioRequest' resourceURL <&> urlEncodedBody params makeTwilioPOSTRequest :: Monad m => Text -> [(C.ByteString, C.ByteString)] -> TwilioT m Request makeTwilioPOSTRequest resourceURL params = makeTwilioRequest resourceURL <&> urlEncodedBody params
seagreen/twilio-haskell
src/Twilio/Types.hs
Haskell
bsd-3-clause
2,543
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} ------------------------------------------------------------------------------- -- | -- Module : Database.Bloodhound.Types.Internal -- Copyright : (C) 2014 Chris Allen -- License : BSD-style (see the file LICENSE) -- Maintainer : Chris Allen <cma@bitemyapp.com> -- Stability : provisional -- Portability : DeriveGeneric, RecordWildCards -- -- Internal data types for Bloodhound. These types may change without -- notice so import at your own risk. ------------------------------------------------------------------------------- module Database.V5.Bloodhound.Types.Internal ( BHEnv(..) , Server(..) , MonadBH(..) ) where import Control.Applicative as A import Control.Monad.Reader import Data.Aeson import Data.Text (Text) import Data.Typeable (Typeable) import GHC.Generics (Generic) import Network.HTTP.Client {-| Common environment for Elasticsearch calls. Connections will be pipelined according to the provided HTTP connection manager. -} data BHEnv = BHEnv { bhServer :: Server , bhManager :: Manager , bhRequestHook :: Request -> IO Request -- ^ Low-level hook that is run before every request is sent. Used to implement custom authentication strategies. Defaults to 'return' with 'mkBHEnv'. } instance (Functor m, Applicative m, MonadIO m) => MonadBH (ReaderT BHEnv m) where getBHEnv = ask {-| 'Server' is used with the client functions to point at the ES instance -} newtype Server = Server Text deriving (Eq, Show, Generic, Typeable, FromJSON) {-| All API calls to Elasticsearch operate within MonadBH . The idea is that it can be easily embedded in your own monad transformer stack. A default instance for a ReaderT and alias 'BH' is provided for the simple case. -} class (Functor m, A.Applicative m, MonadIO m) => MonadBH m where getBHEnv :: m BHEnv
bermanjosh/bloodhound
src/Database/V5/Bloodhound/Types/Internal.hs
Haskell
bsd-3-clause
2,168
{- Problem 30 Numbers that can be written as powers of their digits Result 443839 6.28 s Comment The upper boundary can be estimated since 999... = 10^k - 1 has to be equal to 9^5 + 9^5 + ... = k 9^5, which yields the maximum condition k 9^5 = 10^k - 1. A numeric solution for this is 5.51257, which yields a maximum of 10^5.51257 = 325514.24. -} module Problem30 (solution) where import CommonFunctions solution = fromIntegral . sum' $ filter is5thPowerSum [2..325515] -- Can x be written as the sum of fifth power of its digits? is5thPowerSum x = x == (sum' . map toTheFifth $ show x) -- Memoize powers toTheFifth '0' = 0^5 toTheFifth '1' = 1^5 toTheFifth '2' = 2^5 toTheFifth '3' = 3^5 toTheFifth '4' = 4^5 toTheFifth '5' = 5^5 toTheFifth '6' = 6^5 toTheFifth '7' = 7^5 toTheFifth '8' = 8^5 toTheFifth '9' = 9^5 toTheFifth _ = error "Not a digit 'to the fifth' in problem 30"
quchen/HaskellEuler
src/Problem30.hs
Haskell
bsd-3-clause
990
{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} #ifdef DEFAULT_SIGNATURES {-# LANGUAGE DefaultSignatures #-} #endif #ifdef TRUSTWORTHY {-# LANGUAGE Trustworthy #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Lens.At -- Copyright : (C) 2012 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : non-portable -- ---------------------------------------------------------------------------- module Control.Lens.At ( -- * Indexed Lens At(at) , ixAt , ixEach -- * Indexed Traversal , Ixed(ix) -- * Deprecated , _at , contains , resultAt ) where import Control.Applicative import Control.Lens.Combinators import Control.Lens.Each import Control.Lens.Indexed import Control.Lens.IndexedLens import Control.Lens.IndexedTraversal import Control.Lens.Traversal import Data.Array.IArray as Array import Data.Array.Unboxed import Data.Hashable import Data.HashMap.Lazy as HashMap import Data.HashSet as HashSet import Data.IntMap as IntMap import Data.IntSet as IntSet import Data.Map as Map import Data.Set as Set import Data.Sequence as Seq import Data.Vector as Vector hiding (indexed) import Data.Vector.Primitive as Prim import Data.Vector.Storable as Storable -- $setup -- >>> import Control.Lens -- >>> 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 deprecated alias for 'ix' contains, _at, resultAt :: (Indexable (IxKey m) p, Ixed f m) => IxKey m -> IndexedLensLike' p f m (IxValue m) contains = ix _at = ix resultAt = ix {-# DEPRECATED _at, contains, resultAt "use 'ix'. This function will be removed in version 3.9" #-} type family IxKey (m :: *) :: * type family IxValue (m :: *) :: * -- | This simple indexed traversal lets you 'traverse' the value at a given key in a map or element at an ordinal -- position in a list or sequence. class Ixed f m where -- | What is the index type? -- | This simple indexed traversal lets you 'traverse' the value at a given key in a map. -- -- *NB:* _setting_ the value of this 'Traversal' will only set the value in the lens -- if it is already present. -- -- If you want to be able to insert /missing/ values, you want 'at'. -- -- >>> Seq.fromList [a,b,c,d] & ix 2 %~ f -- fromList [a,b,f c,d] -- -- >>> Seq.fromList [a,b,c,d] & ix 2 .~ e -- fromList [a,b,e,d] -- -- >>> Seq.fromList [a,b,c,d] ^? ix 2 -- Just c -- -- >>> Seq.fromList [] ^? ix 2 -- Nothing -- -- >>> IntSet.fromList [1,2,3,4] & ix 3 .~ False -- fromList [1,2,4] -- -- >>> IntSet.fromList [1,2,3,4] ^. ix 3 -- True -- >>> IntSet.fromList [1,2,3,4] ^. ix 5 -- False ix :: Indexable (IxKey m) p => IxKey m -> IndexedLensLike' p f m (IxValue m) #ifdef DEFAULT_SIGNATURES default ix :: (Indexable (IxKey m) p, Applicative f, At m) => IxKey m -> IndexedLensLike' p f m (IxValue m) ix = ixAt #endif -- | A definition of 'ix' for types with an 'At' instance. This is the default -- if you don't specify a definition for 'ix'. ixAt :: (Indexable (IxKey m) p, Applicative f, At m) => IxKey m -> IndexedLensLike' p f m (IxValue m) ixAt i = at i <. traverse {-# INLINE ixAt #-} -- | A definition of 'ix' for types with an 'Each' instance. ixEach :: (Indexable (IxKey m) p, Applicative f, Eq (IxKey m), Each (IxKey m) f m m (IxValue m) (IxValue m)) => IxKey m -> IndexedLensLike' p f m (IxValue m) ixEach i = iwhereOf each (i ==) {-# INLINE ixEach #-} type instance IxKey [a] = Int type instance IxValue [a] = a instance Applicative f => Ixed f [a] where ix k f xs0 = go xs0 k where go [] _ = pure [] go (a:as) 0 = indexed f k a <&> (:as) go (a:as) i = (a:) <$> (go as $! i - 1) {-# INLINE ix #-} type instance IxKey (Seq a) = Int type instance IxValue (Seq a) = a instance Applicative f => Ixed f (Seq a) where ix i f m | 0 <= i && i < Seq.length m = indexed f i (Seq.index m i) <&> \a -> Seq.update i a m | otherwise = pure m {-# INLINE ix #-} type instance IxKey (IntMap a) = Int type instance IxValue (IntMap a) = a instance Applicative f => Ixed f (IntMap a) where ix k f m = case IntMap.lookup k m of Just v -> indexed f k v <&> \v' -> IntMap.insert k v' m Nothing -> pure m {-# INLINE ix #-} type instance IxKey (Map k a) = k type instance IxValue (Map k a) = a instance (Applicative f, Ord k) => Ixed f (Map k a) where ix k f m = case Map.lookup k m of Just v -> indexed f k v <&> \v' -> Map.insert k v' m Nothing -> pure m {-# INLINE ix #-} type instance IxKey (HashMap k a) = k type instance IxValue (HashMap k a) = a instance (Applicative f, Eq k, Hashable k) => Ixed f (HashMap k a) where ix k f m = case HashMap.lookup k m of Just v -> indexed f k v <&> \v' -> HashMap.insert k v' m Nothing -> pure m {-# INLINE ix #-} type instance IxKey (Array i e) = i type instance IxValue (Array i e) = e -- | -- @ -- arr '!' i ≡ arr '^.' 'ix' i -- arr '//' [(i,e)] ≡ 'ix' i '.~' e '$' arr -- @ instance (Applicative f, Ix i) => Ixed f (Array i e) where ix i f arr | inRange (bounds arr) i = indexed f i (arr Array.! i) <&> \e -> arr Array.// [(i,e)] | otherwise = pure arr {-# INLINE ix #-} type instance IxKey (UArray i e) = i type instance IxValue (UArray i e) = e -- | -- @ -- arr '!' i ≡ arr '^.' 'ix' i -- arr '//' [(i,e)] ≡ 'ix' i '.~' e '$' arr -- @ instance (Applicative f, IArray UArray e, Ix i) => Ixed f (UArray i e) where ix i f arr | inRange (bounds arr) i = indexed f i (arr Array.! i) <&> \e -> arr Array.// [(i,e)] | otherwise = pure arr {-# INLINE ix #-} type instance IxKey (Vector.Vector a) = Int type instance IxValue (Vector.Vector a) = a instance Applicative f => Ixed f (Vector.Vector a) where ix i f v | 0 <= i && i < Vector.length v = indexed f i (v Vector.! i) <&> \a -> v Vector.// [(i, a)] | otherwise = pure v {-# INLINE ix #-} type instance IxKey (Prim.Vector a) = Int type instance IxValue (Prim.Vector a) = a instance (Applicative f, Prim a) => Ixed f (Prim.Vector a) where ix i f v | 0 <= i && i < Prim.length v = indexed f i (v Prim.! i) <&> \a -> v Prim.// [(i, a)] | otherwise = pure v {-# INLINE ix #-} type instance IxKey (Storable.Vector a) = Int type instance IxValue (Storable.Vector a) = a instance (Applicative f, Storable a) => Ixed f (Storable.Vector a) where ix i f v | 0 <= i && i < Storable.length v = indexed f i (v Storable.! i) <&> \a -> v Storable.// [(i, a)] | otherwise = pure v {-# INLINE ix #-} type instance IxKey IntSet = Int type instance IxValue IntSet = Bool instance Functor f => Ixed f IntSet where ix k f s = indexed f k (IntSet.member k s) <&> \b -> if b then IntSet.insert k s else IntSet.delete k s {-# INLINE ix #-} type instance IxKey (Set a) = a type instance IxValue (Set a) = Bool instance (Functor f, Ord a) => Ixed f (Set a) where ix k f s = indexed f k (Set.member k s) <&> \b -> if b then Set.insert k s else Set.delete k s {-# INLINE ix #-} type instance IxKey (HashSet a) = a type instance IxValue (HashSet a) = Bool instance (Functor f, Eq a, Hashable a) => Ixed f (HashSet a) where ix k f s = indexed f k (HashSet.member k s) <&> \b -> if b then HashSet.insert k s else HashSet.delete k s {-# INLINE ix #-} type instance IxKey (k -> a) = k type instance IxValue (k -> a) = a instance (Functor f, Eq k) => Ixed f (k -> a) where ix e g f = indexed g e (f e) <&> \a' e' -> if e == e' then a' else f e' {-# INLINE ix #-} type instance IxKey (a,a) = Int type instance IxValue (a,a) = a instance (Applicative f, a ~ b) => Ixed f (a,b) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a) = Int type instance IxValue (a,a,a) = a instance (Applicative f, a ~ b, b ~ c) => Ixed f (a,b,c) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a) = Int type instance IxValue (a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d) => Ixed f (a,b,c,d) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a,a) = Int type instance IxValue (a,a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d, d ~ e) => Ixed f (a,b,c,d,e) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a,a,a) = Int type instance IxValue (a,a,a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d, d ~ e, e ~ f') => Ixed f (a,b,c,d,e,f') where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a,a,a,a) = Int type instance IxValue (a,a,a,a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d, d ~ e, e ~ f', f' ~ g) => Ixed f (a,b,c,d,e,f',g) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a,a,a,a,a) = Int type instance IxValue (a,a,a,a,a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d, d ~ e, e ~ f', f' ~ g, g ~ h) => Ixed f (a,b,c,d,e,f',g,h) where ix = ixEach {-# INLINE ix #-} type instance IxKey (a,a,a,a,a,a,a,a,a) = Int type instance IxValue (a,a,a,a,a,a,a,a,a) = a instance (Applicative f, a ~ b, b ~ c, c ~ d, d ~ e, e ~ f', f' ~ g, g ~ h, h ~ i) => Ixed f (a,b,c,d,e,f',g,h,i) where ix = ixEach {-# INLINE ix #-} -- | 'At' provides a lens that can be used to read, -- write or delete the value associated with a key in a map-like -- container on an ad hoc basis. -- -- An instance of @At@ should satisfy: -- -- @'el' k ≡ 'at' k '<.' 'traverse'@ class At m where -- | -- >>> Map.fromList [(1,"world")] ^.at 1 -- Just "world" -- -- >>> at 1 ?~ "hello" $ Map.empty -- fromList [(1,"hello")] -- -- /Note:/ 'Map'-like containers form a reasonable instance, but not 'Array'-like ones, where -- you cannot satisfy the 'Lens' laws. at :: IxKey m -> IndexedLens' (IxKey m) m (Maybe (IxValue m)) instance At (IntMap a) where at k f m = indexed f k mv <&> \r -> case r of Nothing -> maybe m (const (IntMap.delete k m)) mv Just v' -> IntMap.insert k v' m where mv = IntMap.lookup k m {-# INLINE at #-} instance Ord k => At (Map k a) where at k f m = indexed f k mv <&> \r -> case r of Nothing -> maybe m (const (Map.delete k m)) mv Just v' -> Map.insert k v' m where mv = Map.lookup k m {-# INLINE at #-} instance (Eq k, Hashable k) => At (HashMap k a) where at k f m = indexed f k mv <&> \r -> case r of Nothing -> maybe m (const (HashMap.delete k m)) mv Just v' -> HashMap.insert k v' m where mv = HashMap.lookup k m {-# INLINE at #-}
np/lens
src/Control/Lens/At.hs
Haskell
bsd-3-clause
10,918
module Parser ()where import Text.XML.HXT.Core import Data.String.UTF8 import Control.Monad odd :: (->) Int Bool odd a = True css tag = multi (hasName tag) testDoc = do html <- readFile "test.html" let doc = readString [withParseHTML yes, withWarnings no] html texts <- runX $ doc //> getText mapM_ putStrLn texts main = do html <- readFile "test.html" let doc = readString [withParseHTML yes, withWarnings no] html links <- runX $ doc //> hasName "a" >>> getAttrValue "href" mapM_ putStrLn links
Numberartificial/workflow
snipets/src/Demo/Parser.hs
Haskell
mit
525
{-# LANGUAGE CPP #-} module Graphics.ImageMagick.MagickWand.PixelWand ( pixelWand -- , clearPixelWand -- , cloneWand -- , cloneWands , isPixelWandSimilar -- , isPixelWand , setColorCount, getColorCount -- ** Literal names , setColor , getColorAsString, getColorAsNormalizedString -- HSL , getHSL, setHSL , getMagickColor, setMagickColor , setColorFromWand , getQuantumColor, setQuantumColor -- ** Color parts -- Index , getIndex, setIndex -- Fuzz , getFuzz, setFuzz -- Alpha , getOpacity, getOpacityQuantum, setOpacity, setOpacityQuantum , getAlpha, getAlphaQuantum, setAlpha, setAlphaQuantum -- RGB , getRed, getRedQuantum, setRed, setRedQuantum , getBlue, getBlueQuantum, setBlue, setBlueQuantum , getGreen, getGreenQuantum, setGreen, setGreenQuantum -- CMYK , getCyan, getCyanQuantum, setCyan, setCyanQuantum , getMagenta, getMagentaQuantum, setMagenta, setMagentaQuantum , getYellow, getYellowQuantum, setYellow, setYellowQuantum , getBlack, getBlackQuantum, setBlack, setBlackQuantum ) where import Control.Monad (void) import Control.Monad.IO.Class import Control.Monad.Trans.Resource import Data.ByteString (ByteString, packCString, useAsCString) import Foreign hiding (void) import Foreign.C.Types (CDouble) import qualified Graphics.ImageMagick.MagickWand.FFI.PixelWand as F import Graphics.ImageMagick.MagickWand.Types import Graphics.ImageMagick.MagickWand.Utils pixelWand :: (MonadResource m) => m PPixelWand pixelWand = fmap snd (allocate F.newPixelWand destroy) where destroy = void . F.destroyPixelWand setColor :: (MonadResource m) => PPixelWand -> ByteString -> m () setColor p s = withException_ p $ useAsCString s (F.pixelSetColor p) getMagickColor :: (MonadResource m) => PPixelWand -> m PMagickPixelPacket getMagickColor w = liftIO $ do p <- mallocForeignPtr withForeignPtr p (F.pixelGetMagickColor w) return p setMagickColor :: (MonadResource m) => PPixelWand -> PMagickPixelPacket -> m () setMagickColor w p = liftIO $ withForeignPtr p (F.pixelSetMagickColor w) setColorCount :: (MonadResource m) => PPixelWand -> Int -> m () setColorCount w i = liftIO $ F.pixelSetColorCount w (fromIntegral i) getColorCount :: (MonadResource m) => PPixelWand -> m Int getColorCount w = liftIO (F.pixelGetColorCount w) >>= return . fromIntegral getColorAsString :: (MonadResource m) => PPixelWand -> m ByteString getColorAsString w = liftIO $ F.pixelGetColorAsString w >>= packCString getColorAsNormalizedString :: (MonadResource m) => PPixelWand -> m ByteString getColorAsNormalizedString w = liftIO $ F.pixelGetColorAsNormalizedString w >>= packCString getHSL :: (MonadResource m) => PPixelWand -> m (Double, Double, Double) getHSL w = liftIO $ fmap (map3 realToFrac) (with3 (F.pixelGetHSL w)) setHSL :: (MonadResource m) => PPixelWand -> Double -> Double -> Double -> m () setHSL w h s l = liftIO $ F.pixelSetHSL w (realToFrac h) (realToFrac s) (realToFrac l) setColorFromWand :: (MonadResource m) => PPixelWand -> PPixelWand -> m () setColorFromWand = (liftIO .). F.pixelSetColorFromWand getIndex :: (MonadResource m) => PPixelWand -> m IndexPacket getIndex = liftIO . F.pixelGetIndex setIndex :: (MonadResource m) => PPixelWand -> IndexPacket -> m () setIndex w i = liftIO $ F.pixelSetIndex w i getQuantumColor :: (MonadResource m) => PPixelWand -> m PPixelPacket getQuantumColor w = liftIO $ do p <- mallocForeignPtr withForeignPtr p (F.pixelGetQuantumColor w) return p setQuantumColor :: (MonadResource m) => PPixelWand -> PPixelPacket -> m () setQuantumColor w p = liftIO $ withForeignPtr p (F.pixelSetQuantumColor w) getFuzz :: (MonadResource m) => PPixelWand -> m Double getFuzz = liftIO . ((fmap realToFrac) . F.pixelGetFuzz) setFuzz :: (MonadResource m) => PPixelWand -> Double -> m () setFuzz w i = liftIO $ F.pixelSetFuzz w (realToFrac i) isPixelWandSimilar :: (MonadResource m) => PPixelWand -> PPixelWand -> Double -> m Bool isPixelWandSimilar pw1 pw2 fuzz = fromMBool $ F.isPixelWandSimilar pw1 pw2 (realToFrac fuzz) setRedQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setRedQuantum = (liftIO .) . F.pixelSetRedQuantum getRed :: (MonadResource m) => PPixelWand -> m Double getRed = (fmap realToFrac) . liftIO . F.pixelGetRed setRed :: (MonadResource m) => PPixelWand -> Double -> m () setRed = (liftIO .) . (. realToFrac) . F.pixelSetRed getRedQuantum :: (MonadResource m) => PPixelWand -> m Quantum getRedQuantum = liftIO . F.pixelGetRedQuantum setGreenQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setGreenQuantum = (liftIO .) . F.pixelSetGreenQuantum getGreen :: (MonadResource m) => PPixelWand -> m Double getGreen = (fmap realToFrac) . liftIO . F.pixelGetGreen setGreen :: (MonadResource m) => PPixelWand -> Double -> m () setGreen = (liftIO .) . (. realToFrac) . F.pixelSetGreen getGreenQuantum :: (MonadResource m) => PPixelWand -> m Quantum getGreenQuantum = liftIO . F.pixelGetGreenQuantum setBlueQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setBlueQuantum = (liftIO .) . F.pixelSetBlueQuantum getBlue :: (MonadResource m) => PPixelWand -> m Double getBlue = (fmap realToFrac) . liftIO . F.pixelGetBlue setBlue :: (MonadResource m) => PPixelWand -> Double -> m () setBlue = (liftIO .) . (. realToFrac) . F.pixelSetBlue getBlueQuantum :: (MonadResource m) => PPixelWand -> m Quantum getBlueQuantum = liftIO . F.pixelGetBlueQuantum setAlphaQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setAlphaQuantum = (liftIO .) . F.pixelSetAlphaQuantum getAlphaQuantum :: (MonadResource m) => PPixelWand -> m Quantum getAlphaQuantum = liftIO . F.pixelGetAlphaQuantum setAlpha :: (MonadResource m) => PPixelWand -> Double -> m () setAlpha = (liftIO .) . (. realToFrac) . F.pixelSetAlpha getAlpha :: (MonadResource m) => PPixelWand -> m Double getAlpha = (fmap realToFrac) . liftIO . F.pixelGetAlpha setOpacityQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setOpacityQuantum = (liftIO .) . F.pixelSetOpacityQuantum getOpacityQuantum :: (MonadResource m) => PPixelWand -> m Quantum getOpacityQuantum = liftIO . F.pixelGetOpacityQuantum setOpacity :: (MonadResource m) => PPixelWand -> Double -> m () setOpacity = (liftIO .) . (. realToFrac) . F.pixelSetOpacity getOpacity :: (MonadResource m) => PPixelWand -> m Double getOpacity = (fmap realToFrac) . liftIO . F.pixelGetOpacity setBlackQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setBlackQuantum = (liftIO .) . F.pixelSetBlackQuantum getBlackQuantum :: (MonadResource m) => PPixelWand -> m Quantum getBlackQuantum = liftIO . F.pixelGetBlackQuantum setBlack :: (MonadResource m) => PPixelWand -> Double -> m () setBlack = (liftIO .) . (. realToFrac) . F.pixelSetBlack getBlack :: (MonadResource m) => PPixelWand -> m Double getBlack = (fmap realToFrac) . liftIO . F.pixelGetBlack setCyanQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setCyanQuantum = (liftIO .) . F.pixelSetCyanQuantum getCyanQuantum :: (MonadResource m) => PPixelWand -> m Quantum getCyanQuantum = liftIO . F.pixelGetCyanQuantum setCyan :: (MonadResource m) => PPixelWand -> Double -> m () setCyan = (liftIO .) . (. realToFrac) . F.pixelSetCyan getCyan :: (MonadResource m) => PPixelWand -> m Double getCyan = (fmap realToFrac) . liftIO . F.pixelGetCyan setMagentaQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setMagentaQuantum = (liftIO .) . F.pixelSetMagentaQuantum getMagentaQuantum :: (MonadResource m) => PPixelWand -> m Quantum getMagentaQuantum = liftIO . F.pixelGetMagentaQuantum setMagenta :: (MonadResource m) => PPixelWand -> Double -> m () setMagenta = (liftIO .) . (. realToFrac) . F.pixelSetMagenta getMagenta :: (MonadResource m) => PPixelWand -> m Double getMagenta = (fmap realToFrac) . liftIO . F.pixelGetMagenta setYellowQuantum :: (MonadResource m) => PPixelWand -> Quantum -> m () setYellowQuantum = (liftIO .) . F.pixelSetYellowQuantum getYellowQuantum :: (MonadResource m) => PPixelWand -> m Quantum getYellowQuantum = liftIO . F.pixelGetYellowQuantum setYellow :: (MonadResource m) => PPixelWand -> Double -> m () setYellow = (liftIO .) . (. realToFrac) . F.pixelSetYellow getYellow :: (MonadResource m) => PPixelWand -> m Double getYellow = (fmap realToFrac) . liftIO . F.pixelGetYellow --- with3 :: (Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()) -> IO (CDouble, CDouble, CDouble) with3 f = alloca (\x -> alloca (\y -> alloca (\z -> do _ <- f x y z x' <- peek x y' <- peek y z' <- peek z return (x',y',z') ))) map3 :: (a -> b) -> (a, a, a) -> (b, b, b) map3 f (a,b,c) = (f a, f b, f c)
flowbox-public/imagemagick
Graphics/ImageMagick/MagickWand/PixelWand.hs
Haskell
apache-2.0
9,048
module Main where import CLI.Main (runCLI) import Data.Version (showVersion) import Paths_gtfsschedule (version) programHeader :: String programHeader = "gtfsschedule - Be on time for your next public transport service (v. " ++ showVersion version ++ ")" main :: IO () main = runCLI programHeader "Shows schedule of departing vehicles based on static GTFS data."
romanofski/gtfsbrisbane
app/Main.hs
Haskell
bsd-3-clause
371
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE OverloadedStrings #-} module Test.Foundation.String ( testStringRefs ) where -- import Control.Monad (replicateM) import Foundation import Foundation.Check import Foundation.String import Foundation.Primitive (AsciiString) import Test.Data.List import Test.Checks.Property.Collection --import Test.Foundation.Encoding testStringRefs :: Test testStringRefs = Group "String" [ Group "UTF8" $ [ collectionProperties "String" (Proxy :: Proxy String) arbitrary ] <> testStringCases {- <> [ testGroup "Encoding Sample0" (testEncodings sample0) , testGroup "Encoding Sample1" (testEncodings sample1) , testGroup "Encoding Sample2" (testEncodings sample2) ] -} , Group "ASCII" $ [ collectionProperties "AsciiString" (Proxy :: Proxy AsciiString) arbitrary ] -- <> testAsciiStringCases ] testStringCases :: [Test] testStringCases = [ Group "Validation" [ Property "fromBytes . toBytes == valid" $ \l -> let s = fromList l in (fromBytes UTF8 $ toBytes UTF8 s) === (s, Nothing, mempty) , Property "Streaming" $ \(l, randomInts) -> let wholeS = fromList l wholeBA = toBytes UTF8 wholeS reconstruct (prevBa, errs, acc) ba = let ba' = prevBa `mappend` ba (s, merr, nextBa) = fromBytes UTF8 ba' in (nextBa, merr : errs, s : acc) (remainingBa, allErrs, chunkS) = foldl' reconstruct (mempty, [], []) $ chunks randomInts wholeBA in (catMaybes allErrs === []) `propertyAnd` (remainingBa === mempty) `propertyAnd` (mconcat (reverse chunkS) === wholeS) ] , Group "ModifiedUTF8" [ propertyModifiedUTF8 "The foundation Serie" "基地系列" "基地系列" , propertyModifiedUTF8 "has null bytes" "let's\0 do \0 it" "let's\0 do \0 it" , propertyModifiedUTF8 "Vincent's special" "abc\0안, 蠀\0, ☃" "abc\0안, 蠀\0, ☃" , propertyModifiedUTF8 "Long string" "this is only a simple string but quite longer than the 64 bytes used in the modified UTF8 parser" "this is only a simple string but quite longer than the 64 bytes used in the modified UTF8 parser" ] , Group "CaseMapping" [ Property "upper . upper == upper" $ \l -> let s = fromList l in upper (upper s) === upper s , CheckPlan "a should capitalize to A" $ validate "a" $ upper "a" == "A" , CheckPlan "b should capitalize to B" $ validate "b" $ upper "b" == "B" , CheckPlan "B should not capitalize" $ validate "B" $ upper "B" == "B" , CheckPlan "é should capitalize to É" $ validate "é" $ upper "é" == "É" , CheckPlan "ß should capitalize to SS" $ validate "ß" $ upper "ß" == "SS" , CheckPlan "ffl should capitalize to FFL" $ validate "ffl" $ upper "fflfflfflfflfflfflfflfflfflffl" == "FFLFFLFFLFFLFFLFFLFFLFFLFFLFFL" , CheckPlan "0a should capitalize to 0A" $ validate "0a" $ upper "\0a" == "\0A" , CheckPlan "0a should capitalize to 0A" $ validate "0a" $ upper "a\0a" == "A\0A" , CheckPlan "0a should capitalize to 0A" $ validate "0a" $ upper "\0\0" == "\0\0" , CheckPlan "00 should not capitalize" $ validate "00" $ upper "00" == "00" ] {- , testGroup "replace" [ testCase "indices '' 'bb' should raise an error" $ do res <- try (evaluate $ indices "" "bb") case res of (Left (_ :: SomeException)) -> return () Right _ -> fail "Expecting an error to be thrown, but it did not." , testCase "indices 'aa' 'bb' == []" $ do indices "aa" "bb" @?= [] , testCase "indices 'aa' 'aabbccabbccEEaaaaabb' is correct" $ do indices "aa" "aabbccabbccEEaaaaabb" @?= [Offset 0,Offset 13,Offset 15] , testCase "indices 'aa' 'aaccaadd' is correct" $ do indices "aa" "aaccaadd" @?= [Offset 0,Offset 4] , testCase "replace '' 'bb' 'foo' raises an error" $ do (res :: Either SomeException String) <- try (evaluate $ replace "" "bb" "foo") assertBool "Expecting an error to be thrown, but it did not." (isLeft res) , testCase "replace 'aa' 'bb' '' == ''" $ do replace "aa" "bb" "" @?= "" , testCase "replace 'aa' '' 'aabbcc' == 'aabbcc'" $ do replace "aa" "" "aabbcc" @?= "bbcc" , testCase "replace 'aa' 'bb' 'aa' == 'bb'" $ do replace "aa" "bb" "aa" @?= "bb" , testCase "replace 'aa' 'bb' 'aabb' == 'bbbb'" $ do replace "aa" "bb" "aabb" @?= "bbbb" , testCase "replace 'aa' 'bb' 'aaccaadd' == 'bbccbbdd'" $ do replace "aa" "bb" "aaccaadd" @?= "bbccbbdd" , testCase "replace 'aa' 'LongLong' 'aaccaadd' == 'LongLongccLongLongdd'" $ do replace "aa" "LongLong" "aaccaadd" @?= "LongLongccLongLongdd" , testCase "replace 'aa' 'bb' 'aabbccabbccEEaaaaabb' == 'bbbbccabbccEEbbbbabb'" $ do replace "aa" "bb" "aabbccabbccEEaaaaabb" @?= "bbbbccabbccEEbbbbabb" , testCase "replace 'å' 'ä' 'ååññ' == 'ääññ'" $ do replace "å" "ä" "ååññ" @?= "ääññ" ] , testGroup "Cases" [ testGroup "Invalid-UTF8" [ testCase "ff" $ expectFromBytesErr UTF8 ("", Just InvalidHeader, 0) (fromList [0xff]) , testCase "80" $ expectFromBytesErr UTF8 ("", Just InvalidHeader, 0) (fromList [0x80]) , testCase "E2 82 0C" $ expectFromBytesErr UTF8 ("", Just InvalidContinuation, 0) (fromList [0xE2,0x82,0x0c]) , testCase "30 31 E2 82 0C" $ expectFromBytesErr UTF8 ("01", Just InvalidContinuation, 2) (fromList [0x30,0x31,0xE2,0x82,0x0c]) ] ] , testGroup "Lines" [ testCase "Hello<LF>Foundation" $ (breakLine "Hello\nFoundation" @?= Right ("Hello", "Foundation")) , testCase "Hello<CRLF>Foundation" $ (breakLine "Hello\r\nFoundation" @?= Right ("Hello", "Foundation")) , testCase "Hello<LF>Foundation" $ (breakLine (drop 5 "Hello\nFoundation\nSomething") @?= Right ("", "Foundation\nSomething")) , testCase "Hello<CR>" $ (breakLine "Hello\r" @?= Left True) , testCase "CR" $ (breakLine "\r" @?= Left True) , testCase "LF" $ (breakLine "\n" @?= Right ("", "")) , testCase "empty" $ (breakLine "" @?= Left False) ] -} ] {- testAsciiStringCases :: [Test] testAsciiStringCases = [ Group "Validation-ASCII7" [ Property "fromBytes . toBytes == valid" $ \l -> let s = fromList . fromLStringASCII $ l in (fromBytes ASCII7 $ toBytes ASCII7 s) === (s, Nothing, mempty) , Property "Streaming" $ \(l, randomInts) -> let wholeS = fromList . fromLStringASCII $ l wholeBA = toBytes ASCII7 wholeS reconstruct (prevBa, errs, acc) ba = let ba' = prevBa `mappend` ba (s, merr, nextBa) = fromBytes ASCII7 ba' in (nextBa, merr : errs, s : acc) (remainingBa, allErrs, chunkS) = foldl' reconstruct (mempty, [], []) $ chunks randomInts wholeBA in (catMaybes allErrs === []) .&&. (remainingBa === mempty) .&&. (mconcat (reverse chunkS) === wholeS) ] , Group "Cases" [ Group "Invalid-ASCII7" [ testCase "ff" $ expectFromBytesErr ASCII7 ("", Just BuildingFailure, 0) (fromList [0xff]) ] ] ] expectFromBytesErr :: Encoding -> ([Char], Maybe ValidationFailure, CountOf Word8) -> UArray Word8 -> IO () expectFromBytesErr enc (expectedString,expectedErr,positionErr) ba = do let x = fromBytes enc ba (s', merr, ba') = x assertEqual "error" expectedErr merr assertEqual "remaining" (drop positionErr ba) ba' assertEqual "string" expectedString (toList s') -} propertyModifiedUTF8 :: String -> [Char] -> String -> Test propertyModifiedUTF8 name chars str = Property name $ chars === toList str chunks :: Sequential c => RandomList -> c -> [c] chunks (RandomList randomInts) = loop (randomInts <> [1..]) where loop rx c | null c = [] | otherwise = case rx of r:rs -> let (c1,c2) = splitAt (CountOf r) c in c1 : loop rs c2 [] -> loop randomInts c
vincenthz/hs-foundation
foundation/tests/Test/Foundation/String.hs
Haskell
bsd-3-clause
8,790
{-# LANGUAGE OverloadedStrings #-} module Web.Server ( runServer , formalizerApp -- Exposed for testing. ) where import Network.Wai.Middleware.RequestLogger import Network.Wai.Middleware.Static import Web.Actions as Action import Web.Spock.Safe import Web.Types -- Run the spock app. runServer :: AppConfig -> IO () runServer conf = let port = cPort conf state = AppState (cPath conf) (cSMTP conf) spockCfg = defaultSpockCfg Nothing PCNoDatabase state in runSpock port $ spock spockCfg formalizerApp -- Path for static files like .js and .css. staticPath :: String staticPath = "web/static" -- Middlewares for application. appMiddleware :: FormalizeApp () appMiddleware = do middleware logStdout middleware . staticPolicy $ noDots >-> addBase staticPath -- Routes for application. appRoutes :: FormalizeApp () appRoutes = do get root Action.home post "/submit" Action.submit hookAny GET Action.notFound -- Join middlewares and routes to spock app. formalizerApp :: FormalizeApp () formalizerApp = appMiddleware >> appRoutes
Lepovirta/Crystallize
app/Web/Server.hs
Haskell
bsd-3-clause
1,172
{- (c) The University of Glasgow 2006 (c) The AQUA Project, Glasgow University, 1998 This module contains definitions for the IdInfo for things that have a standard form, namely: - data constructors - record selectors - method and superclass selectors - primitive operations -} {-# LANGUAGE CPP #-} module MkId ( mkDictFunId, mkDictFunTy, mkDictSelId, mkDictSelRhs, mkPrimOpId, mkFCallId, wrapNewTypeBody, unwrapNewTypeBody, wrapFamInstBody, unwrapFamInstScrut, wrapTypeUnbranchedFamInstBody, unwrapTypeUnbranchedFamInstScrut, DataConBoxer(..), mkDataConRep, mkDataConWorkId, -- And some particular Ids; see below for why they are wired in wiredInIds, ghcPrimIds, unsafeCoerceName, unsafeCoerceId, realWorldPrimId, voidPrimId, voidArgId, nullAddrId, seqId, lazyId, lazyIdKey, runRWId, coercionTokenId, magicDictId, coerceId, proxyHashId, -- Re-export error Ids module PrelRules ) where #include "HsVersions.h" import Rules import TysPrim import TysWiredIn import PrelRules import Type import FamInstEnv import Coercion import TcType import MkCore import CoreUtils ( exprType, mkCast ) import CoreUnfold import Literal import TyCon import CoAxiom import Class import NameSet import VarSet import Name import PrimOp import ForeignCall import DataCon import Id import IdInfo import Demand import CoreSyn import Unique import UniqSupply import PrelNames import BasicTypes hiding ( SuccessFlag(..) ) import Util import Pair import DynFlags import Outputable import FastString import ListSetOps import qualified GHC.LanguageExtensions as LangExt import Data.Maybe ( maybeToList ) {- ************************************************************************ * * \subsection{Wired in Ids} * * ************************************************************************ Note [Wired-in Ids] ~~~~~~~~~~~~~~~~~~~ There are several reasons why an Id might appear in the wiredInIds: (1) The ghcPrimIds are wired in because they can't be defined in Haskell at all, although the can be defined in Core. They have compulsory unfoldings, so they are always inlined and they have no definition site. Their home module is GHC.Prim, so they also have a description in primops.txt.pp, where they are called 'pseudoops'. (2) The 'error' function, eRROR_ID, is wired in because we don't yet have a way to express in an interface file that the result type variable is 'open'; that is can be unified with an unboxed type [The interface file format now carry such information, but there's no way yet of expressing at the definition site for these error-reporting functions that they have an 'open' result type. -- sof 1/99] (3) Other error functions (rUNTIME_ERROR_ID) are wired in (a) because the desugarer generates code that mentions them directly, and (b) for the same reason as eRROR_ID (4) lazyId is wired in because the wired-in version overrides the strictness of the version defined in GHC.Base In cases (2-4), the function has a definition in a library module, and can be called; but the wired-in version means that the details are never read from that module's interface file; instead, the full definition is right here. -} wiredInIds :: [Id] wiredInIds = [lazyId, dollarId, oneShotId, runRWId] ++ errorIds -- Defined in MkCore ++ ghcPrimIds -- These Ids are exported from GHC.Prim ghcPrimIds :: [Id] ghcPrimIds = [ -- These can't be defined in Haskell, but they have -- perfectly reasonable unfoldings in Core realWorldPrimId, voidPrimId, unsafeCoerceId, nullAddrId, seqId, magicDictId, coerceId, proxyHashId ] {- ************************************************************************ * * \subsection{Data constructors} * * ************************************************************************ The wrapper for a constructor is an ordinary top-level binding that evaluates any strict args, unboxes any args that are going to be flattened, and calls the worker. We're going to build a constructor that looks like: data (Data a, C b) => T a b = T1 !a !Int b T1 = /\ a b -> \d1::Data a, d2::C b -> \p q r -> case p of { p -> case q of { q -> Con T1 [a,b] [p,q,r]}} Notice that * d2 is thrown away --- a context in a data decl is used to make sure one *could* construct dictionaries at the site the constructor is used, but the dictionary isn't actually used. * We have to check that we can construct Data dictionaries for the types a and Int. Once we've done that we can throw d1 away too. * We use (case p of q -> ...) to evaluate p, rather than "seq" because all that matters is that the arguments are evaluated. "seq" is very careful to preserve evaluation order, which we don't need to be here. You might think that we could simply give constructors some strictness info, like PrimOps, and let CoreToStg do the let-to-case transformation. But we don't do that because in the case of primops and functions strictness is a *property* not a *requirement*. In the case of constructors we need to do something active to evaluate the argument. Making an explicit case expression allows the simplifier to eliminate it in the (common) case where the constructor arg is already evaluated. Note [Wrappers for data instance tycons] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the case of data instances, the wrapper also applies the coercion turning the representation type into the family instance type to cast the result of the wrapper. For example, consider the declarations data family Map k :: * -> * data instance Map (a, b) v = MapPair (Map a (Pair b v)) The tycon to which the datacon MapPair belongs gets a unique internal name of the form :R123Map, and we call it the representation tycon. In contrast, Map is the family tycon (accessible via tyConFamInst_maybe). A coercion allows you to move between representation and family type. It is accessible from :R123Map via tyConFamilyCoercion_maybe and has kind Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v} The wrapper and worker of MapPair get the types -- Wrapper $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v) -- Worker MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v This coercion is conditionally applied by wrapFamInstBody. It's a bit more complicated if the data instance is a GADT as well! data instance T [a] where T1 :: forall b. b -> T [Maybe b] Hence we translate to -- Wrapper $WT1 :: forall b. b -> T [Maybe b] $WT1 b v = T1 (Maybe b) b (Maybe b) v `cast` sym (Co7T (Maybe b)) -- Worker T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c -- Coercion from family type to representation type Co7T a :: T [a] ~ :R7T a Note [Newtype datacons] ~~~~~~~~~~~~~~~~~~~~~~~ The "data constructor" for a newtype should always be vanilla. At one point this wasn't true, because the newtype arising from class C a => D a looked like newtype T:D a = D:D (C a) so the data constructor for T:C had a single argument, namely the predicate (C a). But now we treat that as an ordinary argument, not part of the theta-type, so all is well. ************************************************************************ * * \subsection{Dictionary selectors} * * ************************************************************************ Selecting a field for a dictionary. If there is just one field, then there's nothing to do. Dictionary selectors may get nested forall-types. Thus: class Foo a where op :: forall b. Ord b => a -> b -> b Then the top-level type for op is op :: forall a. Foo a => forall b. Ord b => a -> b -> b -} mkDictSelId :: Name -- Name of one of the *value* selectors -- (dictionary superclass or method) -> Class -> Id mkDictSelId name clas = mkGlobalId (ClassOpId clas) name sel_ty info where tycon = classTyCon clas sel_names = map idName (classAllSelIds clas) new_tycon = isNewTyCon tycon [data_con] = tyConDataCons tycon tyvars = dataConUnivTyVarBinders data_con n_ty_args = length tyvars arg_tys = dataConRepArgTys data_con -- Includes the dictionary superclasses val_index = assoc "MkId.mkDictSelId" (sel_names `zip` [0..]) name sel_ty = mkForAllTys tyvars $ mkFunTy (mkClassPred clas (mkTyVarTys (binderVars tyvars))) $ getNth arg_tys val_index base_info = noCafIdInfo `setArityInfo` 1 `setStrictnessInfo` strict_sig info | new_tycon = base_info `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkInlineUnfolding (Just 1) (mkDictSelRhs clas val_index) -- See Note [Single-method classes] in TcInstDcls -- for why alwaysInlinePragma | otherwise = base_info `setRuleInfo` mkRuleInfo [rule] -- Add a magic BuiltinRule, but no unfolding -- so that the rule is always available to fire. -- See Note [ClassOp/DFun selection] in TcInstDcls -- This is the built-in rule that goes -- op (dfT d1 d2) ---> opT d1 d2 rule = BuiltinRule { ru_name = fsLit "Class op " `appendFS` occNameFS (getOccName name) , ru_fn = name , ru_nargs = n_ty_args + 1 , ru_try = dictSelRule val_index n_ty_args } -- The strictness signature is of the form U(AAAVAAAA) -> T -- where the V depends on which item we are selecting -- It's worth giving one, so that absence info etc is generated -- even if the selector isn't inlined strict_sig = mkClosedStrictSig [arg_dmd] topRes arg_dmd | new_tycon = evalDmd | otherwise = mkManyUsedDmd $ mkProdDmd [ if name == sel_name then evalDmd else absDmd | sel_name <- sel_names ] mkDictSelRhs :: Class -> Int -- 0-indexed selector among (superclasses ++ methods) -> CoreExpr mkDictSelRhs clas val_index = mkLams tyvars (Lam dict_id rhs_body) where tycon = classTyCon clas new_tycon = isNewTyCon tycon [data_con] = tyConDataCons tycon tyvars = dataConUnivTyVars data_con arg_tys = dataConRepArgTys data_con -- Includes the dictionary superclasses the_arg_id = getNth arg_ids val_index pred = mkClassPred clas (mkTyVarTys tyvars) dict_id = mkTemplateLocal 1 pred arg_ids = mkTemplateLocalsNum 2 arg_tys rhs_body | new_tycon = unwrapNewTypeBody tycon (mkTyVarTys tyvars) (Var dict_id) | otherwise = Case (Var dict_id) dict_id (idType the_arg_id) [(DataAlt data_con, arg_ids, varToCoreExpr the_arg_id)] -- varToCoreExpr needed for equality superclass selectors -- sel a b d = case x of { MkC _ (g:a~b) _ -> CO g } dictSelRule :: Int -> Arity -> RuleFun -- Tries to persuade the argument to look like a constructor -- application, using exprIsConApp_maybe, and then selects -- from it -- sel_i t1..tk (D t1..tk op1 ... opm) = opi -- dictSelRule val_index n_ty_args _ id_unf _ args | (dict_arg : _) <- drop n_ty_args args , Just (_, _, con_args) <- exprIsConApp_maybe id_unf dict_arg = Just (getNth con_args val_index) | otherwise = Nothing {- ************************************************************************ * * Data constructors * * ************************************************************************ -} mkDataConWorkId :: Name -> DataCon -> Id mkDataConWorkId wkr_name data_con | isNewTyCon tycon = mkGlobalId (DataConWrapId data_con) wkr_name nt_wrap_ty nt_work_info | otherwise = mkGlobalId (DataConWorkId data_con) wkr_name alg_wkr_ty wkr_info where tycon = dataConTyCon data_con ----------- Workers for data types -------------- alg_wkr_ty = dataConRepType data_con wkr_arity = dataConRepArity data_con wkr_info = noCafIdInfo `setArityInfo` wkr_arity `setStrictnessInfo` wkr_sig `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated, -- even if arity = 0 wkr_sig = mkClosedStrictSig (replicate wkr_arity topDmd) (dataConCPR data_con) -- Note [Data-con worker strictness] -- Notice that we do *not* say the worker is strict -- even if the data constructor is declared strict -- e.g. data T = MkT !(Int,Int) -- Why? Because the *wrapper* is strict (and its unfolding has case -- expressions that do the evals) but the *worker* itself is not. -- If we pretend it is strict then when we see -- case x of y -> $wMkT y -- the simplifier thinks that y is "sure to be evaluated" (because -- $wMkT is strict) and drops the case. No, $wMkT is not strict. -- -- When the simplifier sees a pattern -- case e of MkT x -> ... -- it uses the dataConRepStrictness of MkT to mark x as evaluated; -- but that's fine... dataConRepStrictness comes from the data con -- not from the worker Id. ----------- Workers for newtypes -------------- (nt_tvs, _, nt_arg_tys, _) = dataConSig data_con res_ty_args = mkTyVarTys nt_tvs nt_wrap_ty = dataConUserType data_con nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo `setArityInfo` 1 -- Arity 1 `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` newtype_unf id_arg1 = mkTemplateLocal 1 (head nt_arg_tys) newtype_unf = ASSERT2( isVanillaDataCon data_con && isSingleton nt_arg_tys, ppr data_con ) -- Note [Newtype datacons] mkCompulsoryUnfolding $ mkLams nt_tvs $ Lam id_arg1 $ wrapNewTypeBody tycon res_ty_args (Var id_arg1) dataConCPR :: DataCon -> DmdResult dataConCPR con | isDataTyCon tycon -- Real data types only; that is, -- not unboxed tuples or newtypes , null (dataConExTyVars con) -- No existentials , wkr_arity > 0 , wkr_arity <= mAX_CPR_SIZE = if is_prod then vanillaCprProdRes (dataConRepArity con) else cprSumRes (dataConTag con) | otherwise = topRes where is_prod = isProductTyCon tycon tycon = dataConTyCon con wkr_arity = dataConRepArity con mAX_CPR_SIZE :: Arity mAX_CPR_SIZE = 10 -- We do not treat very big tuples as CPR-ish: -- a) for a start we get into trouble because there aren't -- "enough" unboxed tuple types (a tiresome restriction, -- but hard to fix), -- b) more importantly, big unboxed tuples get returned mainly -- on the stack, and are often then allocated in the heap -- by the caller. So doing CPR for them may in fact make -- things worse. {- ------------------------------------------------- -- Data constructor representation -- -- This is where we decide how to wrap/unwrap the -- constructor fields -- -------------------------------------------------- -} type Unboxer = Var -> UniqSM ([Var], CoreExpr -> CoreExpr) -- Unbox: bind rep vars by decomposing src var data Boxer = UnitBox | Boxer (TCvSubst -> UniqSM ([Var], CoreExpr)) -- Box: build src arg using these rep vars newtype DataConBoxer = DCB ([Type] -> [Var] -> UniqSM ([Var], [CoreBind])) -- Bind these src-level vars, returning the -- rep-level vars to bind in the pattern mkDataConRep :: DynFlags -> FamInstEnvs -> Name -> Maybe [HsImplBang] -- See Note [Bangs on imported data constructors] -> DataCon -> UniqSM DataConRep mkDataConRep dflags fam_envs wrap_name mb_bangs data_con | not wrapper_reqd = return NoDataConRep | otherwise = do { wrap_args <- mapM newLocal wrap_arg_tys ; wrap_body <- mk_rep_app (wrap_args `zip` dropList eq_spec unboxers) initial_wrap_app ; let wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty wrap_info wrap_info = noCafIdInfo `setArityInfo` wrap_arity -- It's important to specify the arity, so that partial -- applications are treated as values `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` wrap_unf `setStrictnessInfo` wrap_sig -- We need to get the CAF info right here because TidyPgm -- does not tidy the IdInfo of implicit bindings (like the wrapper) -- so it not make sure that the CAF info is sane wrap_sig = mkClosedStrictSig wrap_arg_dmds (dataConCPR data_con) wrap_arg_dmds = map mk_dmd arg_ibangs mk_dmd str | isBanged str = evalDmd | otherwise = topDmd -- The Cpr info can be important inside INLINE rhss, where the -- wrapper constructor isn't inlined. -- And the argument strictness can be important too; we -- may not inline a constructor when it is partially applied. -- For example: -- data W = C !Int !Int !Int -- ...(let w = C x in ...(w p q)...)... -- we want to see that w is strict in its two arguments wrap_unf = mkInlineUnfolding (Just wrap_arity) wrap_rhs wrap_tvs = (univ_tvs `minusList` map eqSpecTyVar eq_spec) ++ ex_tvs wrap_rhs = mkLams wrap_tvs $ mkLams wrap_args $ wrapFamInstBody tycon res_ty_args $ wrap_body ; return (DCR { dcr_wrap_id = wrap_id , dcr_boxer = mk_boxer boxers , dcr_arg_tys = rep_tys , dcr_stricts = rep_strs , dcr_bangs = arg_ibangs }) } where (univ_tvs, ex_tvs, eq_spec, theta, orig_arg_tys, _orig_res_ty) = dataConFullSig data_con res_ty_args = substTyVars (mkTvSubstPrs (map eqSpecPair eq_spec)) univ_tvs tycon = dataConTyCon data_con -- The representation TyCon (not family) wrap_ty = dataConUserType data_con ev_tys = eqSpecPreds eq_spec ++ theta all_arg_tys = ev_tys ++ orig_arg_tys ev_ibangs = map (const HsLazy) ev_tys orig_bangs = dataConSrcBangs data_con wrap_arg_tys = theta ++ orig_arg_tys wrap_arity = length wrap_arg_tys -- The wrap_args are the arguments *other than* the eq_spec -- Because we are going to apply the eq_spec args manually in the -- wrapper arg_ibangs = case mb_bangs of Nothing -> zipWith (dataConSrcToImplBang dflags fam_envs) orig_arg_tys orig_bangs Just bangs -> bangs (rep_tys_w_strs, wrappers) = unzip (zipWith dataConArgRep all_arg_tys (ev_ibangs ++ arg_ibangs)) (unboxers, boxers) = unzip wrappers (rep_tys, rep_strs) = unzip (concat rep_tys_w_strs) wrapper_reqd = not (isNewTyCon tycon) -- Newtypes have only a worker && (any isBanged (ev_ibangs ++ arg_ibangs) -- Some forcing/unboxing (includes eq_spec) || isFamInstTyCon tycon -- Cast result || (not $ null eq_spec)) -- GADT initial_wrap_app = Var (dataConWorkId data_con) `mkTyApps` res_ty_args `mkVarApps` ex_tvs `mkCoApps` map (mkReflCo Nominal . eqSpecType) eq_spec mk_boxer :: [Boxer] -> DataConBoxer mk_boxer boxers = DCB (\ ty_args src_vars -> do { let (ex_vars, term_vars) = splitAtList ex_tvs src_vars subst1 = zipTvSubst univ_tvs ty_args subst2 = extendTvSubstList subst1 ex_tvs (mkTyVarTys ex_vars) ; (rep_ids, binds) <- go subst2 boxers term_vars ; return (ex_vars ++ rep_ids, binds) } ) go _ [] src_vars = ASSERT2( null src_vars, ppr data_con ) return ([], []) go subst (UnitBox : boxers) (src_var : src_vars) = do { (rep_ids2, binds) <- go subst boxers src_vars ; return (src_var : rep_ids2, binds) } go subst (Boxer boxer : boxers) (src_var : src_vars) = do { (rep_ids1, arg) <- boxer subst ; (rep_ids2, binds) <- go subst boxers src_vars ; return (rep_ids1 ++ rep_ids2, NonRec src_var arg : binds) } go _ (_:_) [] = pprPanic "mk_boxer" (ppr data_con) mk_rep_app :: [(Id,Unboxer)] -> CoreExpr -> UniqSM CoreExpr mk_rep_app [] con_app = return con_app mk_rep_app ((wrap_arg, unboxer) : prs) con_app = do { (rep_ids, unbox_fn) <- unboxer wrap_arg ; expr <- mk_rep_app prs (mkVarApps con_app rep_ids) ; return (unbox_fn expr) } {- Note [Bangs on imported data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We pass Maybe [HsImplBang] to mkDataConRep to make use of HsImplBangs from imported modules. - Nothing <=> use HsSrcBangs - Just bangs <=> use HsImplBangs For imported types we can't work it all out from the HsSrcBangs, because we want to be very sure to follow what the original module (where the data type was declared) decided, and that depends on what flags were enabled when it was compiled. So we record the decisions in the interface file. The HsImplBangs passed are in 1-1 correspondence with the dataConOrigArgTys of the DataCon. -} ------------------------- newLocal :: Type -> UniqSM Var newLocal ty = do { uniq <- getUniqueM ; return (mkSysLocalOrCoVar (fsLit "dt") uniq ty) } -- | Unpack/Strictness decisions from source module dataConSrcToImplBang :: DynFlags -> FamInstEnvs -> Type -> HsSrcBang -> HsImplBang dataConSrcToImplBang dflags fam_envs arg_ty (HsSrcBang ann unpk NoSrcStrict) | xopt LangExt.StrictData dflags -- StrictData => strict field = dataConSrcToImplBang dflags fam_envs arg_ty (HsSrcBang ann unpk SrcStrict) | otherwise -- no StrictData => lazy field = HsLazy dataConSrcToImplBang _ _ _ (HsSrcBang _ _ SrcLazy) = HsLazy dataConSrcToImplBang dflags fam_envs arg_ty (HsSrcBang _ unpk_prag SrcStrict) | not (gopt Opt_OmitInterfacePragmas dflags) -- Don't unpack if -fomit-iface-pragmas -- Don't unpack if we aren't optimising; rather arbitrarily, -- we use -fomit-iface-pragmas as the indication , let mb_co = topNormaliseType_maybe fam_envs arg_ty -- Unwrap type families and newtypes arg_ty' = case mb_co of { Just (_,ty) -> ty; Nothing -> arg_ty } , isUnpackableType dflags fam_envs arg_ty' , (rep_tys, _) <- dataConArgUnpack arg_ty' , case unpk_prag of NoSrcUnpack -> gopt Opt_UnboxStrictFields dflags || (gopt Opt_UnboxSmallStrictFields dflags && length rep_tys <= 1) -- See Note [Unpack one-wide fields] srcUnpack -> isSrcUnpacked srcUnpack = case mb_co of Nothing -> HsUnpack Nothing Just (co,_) -> HsUnpack (Just co) | otherwise -- Record the strict-but-no-unpack decision = HsStrict -- | Wrappers/Workers and representation following Unpack/Strictness -- decisions dataConArgRep :: Type -> HsImplBang -> ([(Type,StrictnessMark)] -- Rep types ,(Unboxer,Boxer)) dataConArgRep arg_ty HsLazy = ([(arg_ty, NotMarkedStrict)], (unitUnboxer, unitBoxer)) dataConArgRep arg_ty HsStrict = ([(arg_ty, MarkedStrict)], (seqUnboxer, unitBoxer)) dataConArgRep arg_ty (HsUnpack Nothing) | (rep_tys, wrappers) <- dataConArgUnpack arg_ty = (rep_tys, wrappers) dataConArgRep _ (HsUnpack (Just co)) | let co_rep_ty = pSnd (coercionKind co) , (rep_tys, wrappers) <- dataConArgUnpack co_rep_ty = (rep_tys, wrapCo co co_rep_ty wrappers) ------------------------- wrapCo :: Coercion -> Type -> (Unboxer, Boxer) -> (Unboxer, Boxer) wrapCo co rep_ty (unbox_rep, box_rep) -- co :: arg_ty ~ rep_ty = (unboxer, boxer) where unboxer arg_id = do { rep_id <- newLocal rep_ty ; (rep_ids, rep_fn) <- unbox_rep rep_id ; let co_bind = NonRec rep_id (Var arg_id `Cast` co) ; return (rep_ids, Let co_bind . rep_fn) } boxer = Boxer $ \ subst -> do { (rep_ids, rep_expr) <- case box_rep of UnitBox -> do { rep_id <- newLocal (TcType.substTy subst rep_ty) ; return ([rep_id], Var rep_id) } Boxer boxer -> boxer subst ; let sco = substCoUnchecked subst co ; return (rep_ids, rep_expr `Cast` mkSymCo sco) } ------------------------ seqUnboxer :: Unboxer seqUnboxer v = return ([v], \e -> Case (Var v) v (exprType e) [(DEFAULT, [], e)]) unitUnboxer :: Unboxer unitUnboxer v = return ([v], \e -> e) unitBoxer :: Boxer unitBoxer = UnitBox ------------------------- dataConArgUnpack :: Type -> ( [(Type, StrictnessMark)] -- Rep types , (Unboxer, Boxer) ) dataConArgUnpack arg_ty | Just (tc, tc_args) <- splitTyConApp_maybe arg_ty , Just con <- tyConSingleAlgDataCon_maybe tc -- NB: check for an *algebraic* data type -- A recursive newtype might mean that -- 'arg_ty' is a newtype , let rep_tys = dataConInstArgTys con tc_args = ASSERT( isVanillaDataCon con ) ( rep_tys `zip` dataConRepStrictness con ,( \ arg_id -> do { rep_ids <- mapM newLocal rep_tys ; let unbox_fn body = Case (Var arg_id) arg_id (exprType body) [(DataAlt con, rep_ids, body)] ; return (rep_ids, unbox_fn) } , Boxer $ \ subst -> do { rep_ids <- mapM (newLocal . TcType.substTyUnchecked subst) rep_tys ; return (rep_ids, Var (dataConWorkId con) `mkTyApps` (substTysUnchecked subst tc_args) `mkVarApps` rep_ids ) } ) ) | otherwise = pprPanic "dataConArgUnpack" (ppr arg_ty) -- An interface file specified Unpacked, but we couldn't unpack it isUnpackableType :: DynFlags -> FamInstEnvs -> Type -> Bool -- True if we can unpack the UNPACK the argument type -- See Note [Recursive unboxing] -- We look "deeply" inside rather than relying on the DataCons -- we encounter on the way, because otherwise we might well -- end up relying on ourselves! isUnpackableType dflags fam_envs ty | Just (tc, _) <- splitTyConApp_maybe ty , Just con <- tyConSingleAlgDataCon_maybe tc , isVanillaDataCon con = ok_con_args (unitNameSet (getName tc)) con | otherwise = False where ok_arg tcs (ty, bang) = not (attempt_unpack bang) || ok_ty tcs norm_ty where norm_ty = topNormaliseType fam_envs ty ok_ty tcs ty | Just (tc, _) <- splitTyConApp_maybe ty , let tc_name = getName tc = not (tc_name `elemNameSet` tcs) && case tyConSingleAlgDataCon_maybe tc of Just con | isVanillaDataCon con -> ok_con_args (tcs `extendNameSet` getName tc) con _ -> True | otherwise = True ok_con_args tcs con = all (ok_arg tcs) (dataConOrigArgTys con `zip` dataConSrcBangs con) -- NB: dataConSrcBangs gives the *user* request; -- We'd get a black hole if we used dataConImplBangs attempt_unpack (HsSrcBang _ SrcUnpack NoSrcStrict) = xopt LangExt.StrictData dflags attempt_unpack (HsSrcBang _ SrcUnpack SrcStrict) = True attempt_unpack (HsSrcBang _ NoSrcUnpack SrcStrict) = True -- Be conservative attempt_unpack (HsSrcBang _ NoSrcUnpack NoSrcStrict) = xopt LangExt.StrictData dflags -- Be conservative attempt_unpack _ = False {- Note [Unpack one-wide fields] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The flag UnboxSmallStrictFields ensures that any field that can (safely) be unboxed to a word-sized unboxed field, should be so unboxed. For example: data A = A Int# newtype B = B A data C = C !B data D = D !C data E = E !() data F = F !D data G = G !F !F All of these should have an Int# as their representation, except G which should have two Int#s. However data T = T !(S Int) data S = S !a Here we can represent T with an Int#. Note [Recursive unboxing] ~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data R = MkR {-# UNPACK #-} !S Int data S = MkS {-# UNPACK #-} !Int The representation arguments of MkR are the *representation* arguments of S (plus Int); the rep args of MkS are Int#. This is all fine. But be careful not to try to unbox this! data T = MkT {-# UNPACK #-} !T Int Because then we'd get an infinite number of arguments. Here is a more complicated case: data S = MkS {-# UNPACK #-} !T Int data T = MkT {-# UNPACK #-} !S Int Each of S and T must decide independently whether to unpack and they had better not both say yes. So they must both say no. Also behave conservatively when there is no UNPACK pragma data T = MkS !T Int with -funbox-strict-fields or -funbox-small-strict-fields we need to behave as if there was an UNPACK pragma there. But it's the *argument* type that matters. This is fine: data S = MkS S !Int because Int is non-recursive. ************************************************************************ * * Wrapping and unwrapping newtypes and type families * * ************************************************************************ -} wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr -- The wrapper for the data constructor for a newtype looks like this: -- newtype T a = MkT (a,Int) -- MkT :: forall a. (a,Int) -> T a -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a) -- where CoT is the coercion TyCon associated with the newtype -- -- The call (wrapNewTypeBody T [a] e) returns the -- body of the wrapper, namely -- e `cast` (CoT [a]) -- -- If a coercion constructor is provided in the newtype, then we use -- it, otherwise the wrap/unwrap are both no-ops -- -- If the we are dealing with a newtype *instance*, we have a second coercion -- identifying the family instance with the constructor of the newtype -- instance. This coercion is applied in any case (ie, composed with the -- coercion constructor of the newtype or applied by itself). wrapNewTypeBody tycon args result_expr = ASSERT( isNewTyCon tycon ) wrapFamInstBody tycon args $ mkCast result_expr (mkSymCo co) where co = mkUnbranchedAxInstCo Representational (newTyConCo tycon) args [] -- When unwrapping, we do *not* apply any family coercion, because this will -- be done via a CoPat by the type checker. We have to do it this way as -- computing the right type arguments for the coercion requires more than just -- a spliting operation (cf, TcPat.tcConPat). unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr unwrapNewTypeBody tycon args result_expr = ASSERT( isNewTyCon tycon ) mkCast result_expr (mkUnbranchedAxInstCo Representational (newTyConCo tycon) args []) -- If the type constructor is a representation type of a data instance, wrap -- the expression into a cast adjusting the expression type, which is an -- instance of the representation type, to the corresponding instance of the -- family instance type. -- See Note [Wrappers for data instance tycons] wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr wrapFamInstBody tycon args body | Just co_con <- tyConFamilyCoercion_maybe tycon = mkCast body (mkSymCo (mkUnbranchedAxInstCo Representational co_con args [])) | otherwise = body -- Same as `wrapFamInstBody`, but for type family instances, which are -- represented by a `CoAxiom`, and not a `TyCon` wrapTypeFamInstBody :: CoAxiom br -> Int -> [Type] -> [Coercion] -> CoreExpr -> CoreExpr wrapTypeFamInstBody axiom ind args cos body = mkCast body (mkSymCo (mkAxInstCo Representational axiom ind args cos)) wrapTypeUnbranchedFamInstBody :: CoAxiom Unbranched -> [Type] -> [Coercion] -> CoreExpr -> CoreExpr wrapTypeUnbranchedFamInstBody axiom = wrapTypeFamInstBody axiom 0 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr unwrapFamInstScrut tycon args scrut | Just co_con <- tyConFamilyCoercion_maybe tycon = mkCast scrut (mkUnbranchedAxInstCo Representational co_con args []) -- data instances only | otherwise = scrut unwrapTypeFamInstScrut :: CoAxiom br -> Int -> [Type] -> [Coercion] -> CoreExpr -> CoreExpr unwrapTypeFamInstScrut axiom ind args cos scrut = mkCast scrut (mkAxInstCo Representational axiom ind args cos) unwrapTypeUnbranchedFamInstScrut :: CoAxiom Unbranched -> [Type] -> [Coercion] -> CoreExpr -> CoreExpr unwrapTypeUnbranchedFamInstScrut axiom = unwrapTypeFamInstScrut axiom 0 {- ************************************************************************ * * \subsection{Primitive operations} * * ************************************************************************ -} mkPrimOpId :: PrimOp -> Id mkPrimOpId prim_op = id where (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op ty = mkSpecForAllTys tyvars (mkFunTys arg_tys res_ty) name = mkWiredInName gHC_PRIM (primOpOcc prim_op) (mkPrimOpIdUnique (primOpTag prim_op)) (AnId id) UserSyntax id = mkGlobalId (PrimOpId prim_op) name ty info info = noCafIdInfo `setRuleInfo` mkRuleInfo (maybeToList $ primOpRules name prim_op) `setArityInfo` arity `setStrictnessInfo` strict_sig `setInlinePragInfo` neverInlinePragma -- We give PrimOps a NOINLINE pragma so that we don't -- get silly warnings from Desugar.dsRule (the inline_shadows_rule -- test) about a RULE conflicting with a possible inlining -- cf Trac #7287 -- For each ccall we manufacture a separate CCallOpId, giving it -- a fresh unique, a type that is correct for this particular ccall, -- and a CCall structure that gives the correct details about calling -- convention etc. -- -- The *name* of this Id is a local name whose OccName gives the full -- details of the ccall, type and all. This means that the interface -- file reader can reconstruct a suitable Id mkFCallId :: DynFlags -> Unique -> ForeignCall -> Type -> Id mkFCallId dflags uniq fcall ty = ASSERT( isEmptyVarSet (tyCoVarsOfType ty) ) -- A CCallOpId should have no free type variables; -- when doing substitutions won't substitute over it mkGlobalId (FCallId fcall) name ty info where occ_str = showSDoc dflags (braces (ppr fcall <+> ppr ty)) -- The "occurrence name" of a ccall is the full info about the -- ccall; it is encoded, but may have embedded spaces etc! name = mkFCallName uniq occ_str info = noCafIdInfo `setArityInfo` arity `setStrictnessInfo` strict_sig (bndrs, _) = tcSplitPiTys ty arity = count isAnonTyBinder bndrs strict_sig = mkClosedStrictSig (replicate arity topDmd) topRes -- the call does not claim to be strict in its arguments, since they -- may be lifted (foreign import prim) and the called code doesn't -- necessarily force them. See Trac #11076. {- ************************************************************************ * * \subsection{DictFuns and default methods} * * ************************************************************************ Note [Dict funs and default methods] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Dict funs and default methods are *not* ImplicitIds. Their definition involves user-written code, so we can't figure out their strictness etc based on fixed info, as we can for constructors and record selectors (say). NB: See also Note [Exported LocalIds] in Id -} mkDictFunId :: Name -- Name to use for the dict fun; -> [TyVar] -> ThetaType -> Class -> [Type] -> Id -- Implements the DFun Superclass Invariant (see TcInstDcls) -- See Note [Dict funs and default methods] mkDictFunId dfun_name tvs theta clas tys = mkExportedLocalId (DFunId is_nt) dfun_name dfun_ty where is_nt = isNewTyCon (classTyCon clas) dfun_ty = mkDictFunTy tvs theta clas tys mkDictFunTy :: [TyVar] -> ThetaType -> Class -> [Type] -> Type mkDictFunTy tvs theta clas tys = mkSpecSigmaTy tvs theta (mkClassPred clas tys) {- ************************************************************************ * * \subsection{Un-definable} * * ************************************************************************ These Ids can't be defined in Haskell. They could be defined in unfoldings in the wired-in GHC.Prim interface file, but we'd have to ensure that they were definitely, definitely inlined, because there is no curried identifier for them. That's what mkCompulsoryUnfolding does. If we had a way to get a compulsory unfolding from an interface file, we could do that, but we don't right now. unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that just gets expanded into a type coercion wherever it occurs. Hence we add it as a built-in Id with an unfolding here. The type variables we use here are "open" type variables: this means they can unify with both unlifted and lifted types. Hence we provide another gun with which to shoot yourself in the foot. -} lazyIdName, unsafeCoerceName, nullAddrName, seqName, realWorldName, voidPrimIdName, coercionTokenName, magicDictName, coerceName, proxyName, dollarName, oneShotName, runRWName :: Name unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId voidPrimIdName = mkWiredInIdName gHC_PRIM (fsLit "void#") voidPrimIdKey voidPrimId lazyIdName = mkWiredInIdName gHC_MAGIC (fsLit "lazy") lazyIdKey lazyId coercionTokenName = mkWiredInIdName gHC_PRIM (fsLit "coercionToken#") coercionTokenIdKey coercionTokenId magicDictName = mkWiredInIdName gHC_PRIM (fsLit "magicDict") magicDictKey magicDictId coerceName = mkWiredInIdName gHC_PRIM (fsLit "coerce") coerceKey coerceId proxyName = mkWiredInIdName gHC_PRIM (fsLit "proxy#") proxyHashKey proxyHashId dollarName = mkWiredInIdName gHC_BASE (fsLit "$") dollarIdKey dollarId oneShotName = mkWiredInIdName gHC_MAGIC (fsLit "oneShot") oneShotKey oneShotId runRWName = mkWiredInIdName gHC_MAGIC (fsLit "runRW#") runRWKey runRWId dollarId :: Id -- Note [dollarId magic] dollarId = pcMiscPrelId dollarName ty (noCafIdInfo `setUnfoldingInfo` unf) where fun_ty = mkFunTy alphaTy openBetaTy ty = mkSpecForAllTys [runtimeRep2TyVar, alphaTyVar, openBetaTyVar] $ mkFunTy fun_ty fun_ty unf = mkInlineUnfolding (Just 2) rhs [f,x] = mkTemplateLocals [fun_ty, alphaTy] rhs = mkLams [runtimeRep2TyVar, alphaTyVar, openBetaTyVar, f, x] $ App (Var f) (Var x) ------------------------------------------------ proxyHashId :: Id proxyHashId = pcMiscPrelId proxyName ty (noCafIdInfo `setUnfoldingInfo` evaldUnfolding) -- Note [evaldUnfoldings] where -- proxy# :: forall k (a:k). Proxy# k a bndrs = mkTemplateKiTyVars [liftedTypeKind] (\ks -> ks) [k,t] = mkTyVarTys bndrs ty = mkSpecForAllTys bndrs (mkProxyPrimTy k t) ------------------------------------------------ unsafeCoerceId :: Id unsafeCoerceId = pcMiscPrelId unsafeCoerceName ty info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding rhs -- unsafeCoerce# :: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep) -- (a :: TYPE r1) (b :: TYPE r2). -- a -> b bndrs = mkTemplateKiTyVars [runtimeRepTy, runtimeRepTy] (\ks -> map tYPE ks) [_, _, a, b] = mkTyVarTys bndrs ty = mkSpecForAllTys bndrs (mkFunTy a b) [x] = mkTemplateLocals [a] rhs = mkLams (bndrs ++ [x]) $ Cast (Var x) (mkUnsafeCo Representational a b) ------------------------------------------------ nullAddrId :: Id -- nullAddr# :: Addr# -- The reason is is here is because we don't provide -- a way to write this literal in Haskell. nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding (Lit nullAddrLit) ------------------------------------------------ seqId :: Id -- See Note [seqId magic] seqId = pcMiscPrelId seqName ty info where info = noCafIdInfo `setInlinePragInfo` inline_prag `setUnfoldingInfo` mkCompulsoryUnfolding rhs `setRuleInfo` mkRuleInfo [seq_cast_rule] inline_prag = alwaysInlinePragma `setInlinePragmaActivation` ActiveAfter "0" 0 -- Make 'seq' not inline-always, so that simpleOptExpr -- (see CoreSubst.simple_app) won't inline 'seq' on the -- LHS of rules. That way we can have rules for 'seq'; -- see Note [seqId magic] ty = mkSpecForAllTys [alphaTyVar,betaTyVar] (mkFunTy alphaTy (mkFunTy betaTy betaTy)) [x,y] = mkTemplateLocals [alphaTy, betaTy] rhs = mkLams [alphaTyVar,betaTyVar,x,y] (Case (Var x) x betaTy [(DEFAULT, [], Var y)]) -- See Note [Built-in RULES for seq] -- NB: ru_nargs = 3, not 4, to match the code in -- Simplify.rebuildCase which tries to apply this rule seq_cast_rule = BuiltinRule { ru_name = fsLit "seq of cast" , ru_fn = seqName , ru_nargs = 3 , ru_try = match_seq_of_cast } match_seq_of_cast :: RuleFun -- See Note [Built-in RULES for seq] match_seq_of_cast _ _ _ [Type _, Type res_ty, Cast scrut co] = Just (fun `App` scrut) where fun = Lam x $ Lam y $ Case (Var x) x res_ty [(DEFAULT,[],Var y)] -- Generate a Case directly, not a call to seq, which -- might be ill-kinded if res_ty is unboxed [x,y] = mkTemplateLocals [scrut_ty, res_ty] scrut_ty = pFst (coercionKind co) match_seq_of_cast _ _ _ _ = Nothing ------------------------------------------------ lazyId :: Id -- See Note [lazyId magic] lazyId = pcMiscPrelId lazyIdName ty info where info = noCafIdInfo ty = mkSpecForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy) oneShotId :: Id -- See Note [The oneShot function] oneShotId = pcMiscPrelId oneShotName ty info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding rhs ty = mkSpecForAllTys [ runtimeRep1TyVar, runtimeRep2TyVar , openAlphaTyVar, openBetaTyVar ] (mkFunTy fun_ty fun_ty) fun_ty = mkFunTy openAlphaTy openBetaTy [body, x] = mkTemplateLocals [fun_ty, openAlphaTy] x' = setOneShotLambda x rhs = mkLams [ runtimeRep1TyVar, runtimeRep2TyVar , openAlphaTyVar, openBetaTyVar , body, x'] $ Var body `App` Var x runRWId :: Id -- See Note [runRW magic] in this module runRWId = pcMiscPrelId runRWName ty info where info = noCafIdInfo `setInlinePragInfo` neverInlinePragma `setStrictnessInfo` strict_sig `setArityInfo` 1 strict_sig = mkClosedStrictSig [strictApply1Dmd] topRes -- Important to express its strictness, -- since it is not inlined until CorePrep -- Also see Note [runRW arg] in CorePrep -- State# RealWorld stateRW = mkTyConApp statePrimTyCon [realWorldTy] -- (# State# RealWorld, o #) ret_ty = mkTupleTy Unboxed [stateRW, openAlphaTy] -- State# RealWorld -> (# State# RealWorld, o #) arg_ty = stateRW `mkFunTy` ret_ty -- (State# RealWorld -> (# State# RealWorld, o #)) -- -> (# State# RealWorld, o #) ty = mkSpecForAllTys [runtimeRep1TyVar, openAlphaTyVar] $ arg_ty `mkFunTy` ret_ty -------------------------------------------------------------------------------- magicDictId :: Id -- See Note [magicDictId magic] magicDictId = pcMiscPrelId magicDictName ty info where info = noCafIdInfo `setInlinePragInfo` neverInlinePragma ty = mkSpecForAllTys [alphaTyVar] alphaTy -------------------------------------------------------------------------------- coerceId :: Id coerceId = pcMiscPrelId coerceName ty info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding rhs eqRTy = mkTyConApp coercibleTyCon [ liftedTypeKind , alphaTy, betaTy ] eqRPrimTy = mkTyConApp eqReprPrimTyCon [ liftedTypeKind , liftedTypeKind , alphaTy, betaTy ] ty = mkSpecForAllTys [alphaTyVar, betaTyVar] $ mkFunTys [eqRTy, alphaTy] betaTy [eqR,x,eq] = mkTemplateLocals [eqRTy, alphaTy, eqRPrimTy] rhs = mkLams [alphaTyVar, betaTyVar, eqR, x] $ mkWildCase (Var eqR) eqRTy betaTy $ [(DataAlt coercibleDataCon, [eq], Cast (Var x) (mkCoVarCo eq))] {- Note [dollarId magic] ~~~~~~~~~~~~~~~~~~~~~ The only reason that ($) is wired in is so that its type can be forall (a:*, b:Open). (a->b) -> a -> b That is, the return type can be unboxed. E.g. this is OK foo $ True where foo :: Bool -> Int# because ($) doesn't inspect or move the result of the call to foo. See Trac #8739. There is a special typing rule for ($) in TcExpr, so the type of ($) isn't looked at there, BUT Lint subsequently (and rightly) complains if sees ($) applied to Int# (say), unless we give it a wired-in type as we do here. Note [Unsafe coerce magic] ~~~~~~~~~~~~~~~~~~~~~~~~~~ We define a *primitive* GHC.Prim.unsafeCoerce# and then in the base library we define the ordinary function Unsafe.Coerce.unsafeCoerce :: forall (a:*) (b:*). a -> b unsafeCoerce x = unsafeCoerce# x Notice that unsafeCoerce has a civilized (albeit still dangerous) polymorphic type, whose type args have kind *. So you can't use it on unboxed values (unsafeCoerce 3#). In contrast unsafeCoerce# is even more dangerous because you *can* use it on unboxed things, (unsafeCoerce# 3#) :: Int. Its type is forall (a:OpenKind) (b:OpenKind). a -> b Note [seqId magic] ~~~~~~~~~~~~~~~~~~ 'GHC.Prim.seq' is special in several ways. a) In source Haskell its second arg can have an unboxed type x `seq` (v +# w) But see Note [Typing rule for seq] in TcExpr, which explains why we give seq itself an ordinary type seq :: forall a b. a -> b -> b and treat it as a language construct from a typing point of view. b) Its fixity is set in LoadIface.ghcPrimIface c) It has quite a bit of desugaring magic. See DsUtils.hs Note [Desugaring seq (1)] and (2) and (3) d) There is some special rule handing: Note [User-defined RULES for seq] Note [User-defined RULES for seq] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Roman found situations where he had case (f n) of _ -> e where he knew that f (which was strict in n) would terminate if n did. Notice that the result of (f n) is discarded. So it makes sense to transform to case n of _ -> e Rather than attempt some general analysis to support this, I've added enough support that you can do this using a rewrite rule: RULE "f/seq" forall n. seq (f n) = seq n You write that rule. When GHC sees a case expression that discards its result, it mentally transforms it to a call to 'seq' and looks for a RULE. (This is done in Simplify.rebuildCase.) As usual, the correctness of the rule is up to you. VERY IMPORTANT: to make this work, we give the RULE an arity of 1, not 2. If we wrote RULE "f/seq" forall n e. seq (f n) e = seq n e with rule arity 2, then two bad things would happen: - The magical desugaring done in Note [seqId magic] item (c) for saturated application of 'seq' would turn the LHS into a case expression! - The code in Simplify.rebuildCase would need to actually supply the value argument, which turns out to be awkward. Note [Built-in RULES for seq] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We also have the following built-in rule for seq seq (x `cast` co) y = seq x y This eliminates unnecessary casts and also allows other seq rules to match more often. Notably, seq (f x `cast` co) y --> seq (f x) y and now a user-defined rule for seq (see Note [User-defined RULES for seq]) may fire. Note [lazyId magic] ~~~~~~~~~~~~~~~~~~~ lazy :: forall a?. a? -> a? (i.e. works for unboxed types too) 'lazy' is used to make sure that a sub-expression, and its free variables, are truly used call-by-need, with no code motion. Key examples: * pseq: pseq a b = a `seq` lazy b We want to make sure that the free vars of 'b' are not evaluated before 'a', even though the expression is plainly strict in 'b'. * catch: catch a b = catch# (lazy a) b Again, it's clear that 'a' will be evaluated strictly (and indeed applied to a state token) but we want to make sure that any exceptions arising from the evaluation of 'a' are caught by the catch (see Trac #11555). Implementing 'lazy' is a bit tricky: * It must not have a strictness signature: by being a built-in Id, all the info about lazyId comes from here, not from GHC.Base.hi. This is important, because the strictness analyser will spot it as strict! * It must not have an unfolding: it gets "inlined" by a HACK in CorePrep. It's very important to do this inlining *after* unfoldings are exposed in the interface file. Otherwise, the unfolding for (say) pseq in the interface file will not mention 'lazy', so if we inline 'pseq' we'll totally miss the very thing that 'lazy' was there for in the first place. See Trac #3259 for a real world example. * Suppose CorePrep sees (catch# (lazy e) b). At all costs we must avoid using call by value here: case e of r -> catch# r b Avoiding that is the whole point of 'lazy'. So in CorePrep (which generate the 'case' expression for a call-by-value call) we must spot the 'lazy' on the arg (in CorePrep.cpeApp), and build a 'let' instead. * lazyId is defined in GHC.Base, so we don't *have* to inline it. If it appears un-applied, we'll end up just calling it. Note [runRW magic] ~~~~~~~~~~~~~~~~~~ Some definitions, for instance @runST@, must have careful control over float out of the bindings in their body. Consider this use of @runST@, f x = runST ( \ s -> let (a, s') = newArray# 100 [] s (_, s'') = fill_in_array_or_something a x s' in freezeArray# a s'' ) If we inline @runST@, we'll get: f x = let (a, s') = newArray# 100 [] realWorld#{-NB-} (_, s'') = fill_in_array_or_something a x s' in freezeArray# a s'' And now if we allow the @newArray#@ binding to float out to become a CAF, we end up with a result that is totally and utterly wrong: f = let (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!! in \ x -> let (_, s'') = fill_in_array_or_something a x s' in freezeArray# a s'' All calls to @f@ will share a {\em single} array! Clearly this is nonsense and must be prevented. This is what @runRW#@ gives us: by being inlined extremely late in the optimization (right before lowering to STG, in CorePrep), we can ensure that no further floating will occur. This allows us to safely inline things like @runST@, which are otherwise needlessly expensive (see #10678 and #5916). While the definition of @GHC.Magic.runRW#@, we override its type in @MkId@ to be open-kinded, runRW# :: forall (r1 :: RuntimeRep). (o :: TYPE r) => (State# RealWorld -> (# State# RealWorld, o #)) -> (# State# RealWorld, o #) Note [The oneShot function] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the context of making left-folds fuse somewhat okish (see ticket #7994 and Note [Left folds via right fold]) it was determined that it would be useful if library authors could explicitly tell the compiler that a certain lambda is called at most once. The oneShot function allows that. 'oneShot' is open kinded, i.e. the type variables can refer to unlifted types as well (Trac #10744); e.g. oneShot (\x:Int# -> x +# 1#) Like most magic functions it has a compulsary unfolding, so there is no need for a real definition somewhere. We have one in GHC.Magic for the convenience of putting the documentation there. It uses `setOneShotLambda` on the lambda's binder. That is the whole magic: A typical call looks like oneShot (\y. e) after unfolding the definition `oneShot = \f \x[oneshot]. f x` we get (\f \x[oneshot]. f x) (\y. e) --> \x[oneshot]. ((\y.e) x) --> \x[oneshot] e[x/y] which is what we want. It is only effective if the one-shot info survives as long as possible; in particular it must make it into the interface in unfoldings. See Note [Preserve OneShotInfo] in CoreTidy. Also see https://ghc.haskell.org/trac/ghc/wiki/OneShot. Note [magicDictId magic] ~~~~~~~~~~~~~~~~~~~~~~~~~ The identifier `magicDict` is just a place-holder, which is used to implement a primitve that we cannot define in Haskell but we can write in Core. It is declared with a place-holder type: magicDict :: forall a. a The intention is that the identifier will be used in a very specific way, to create dictionaries for classes with a single method. Consider a class like this: class C a where f :: T a We are going to use `magicDict`, in conjunction with a built-in Prelude rule, to cast values of type `T a` into dictionaries for `C a`. To do this, we define a function like this in the library: data WrapC a b = WrapC (C a => Proxy a -> b) withT :: (C a => Proxy a -> b) -> T a -> Proxy a -> b withT f x y = magicDict (WrapC f) x y The purpose of `WrapC` is to avoid having `f` instantiated. Also, it avoids impredicativity, because `magicDict`'s type cannot be instantiated with a forall. The field of `WrapC` contains a `Proxy` parameter which is used to link the type of the constraint, `C a`, with the type of the `Wrap` value being made. Next, we add a built-in Prelude rule (see prelude/PrelRules.hs), which will replace the RHS of this definition with the appropriate definition in Core. The rewrite rule works as follows: magicDict @t (wrap @a @b f) x y ----> f (x `cast` co a) y The `co` coercion is the newtype-coercion extracted from the type-class. The type class is obtain by looking at the type of wrap. ------------------------------------------------------------- @realWorld#@ used to be a magic literal, \tr{void#}. If things get nasty as-is, change it back to a literal (@Literal@). voidArgId is a Local Id used simply as an argument in functions where we just want an arg to avoid having a thunk of unlifted type. E.g. x = \ void :: Void# -> (# p, q #) This comes up in strictness analysis Note [evaldUnfoldings] ~~~~~~~~~~~~~~~~~~~~~~ The evaldUnfolding makes it look that some primitive value is evaluated, which in turn makes Simplify.interestingArg return True, which in turn makes INLINE things applied to said value likely to be inlined. -} realWorldPrimId :: Id -- :: State# RealWorld realWorldPrimId = pcMiscPrelId realWorldName realWorldStatePrimTy (noCafIdInfo `setUnfoldingInfo` evaldUnfolding -- Note [evaldUnfoldings] `setOneShotInfo` stateHackOneShot) voidPrimId :: Id -- Global constant :: Void# voidPrimId = pcMiscPrelId voidPrimIdName voidPrimTy (noCafIdInfo `setUnfoldingInfo` evaldUnfolding) -- Note [evaldUnfoldings] voidArgId :: Id -- Local lambda-bound :: Void# voidArgId = mkSysLocal (fsLit "void") voidArgIdKey voidPrimTy coercionTokenId :: Id -- :: () ~ () coercionTokenId -- Used to replace Coercion terms when we go to STG = pcMiscPrelId coercionTokenName (mkTyConApp eqPrimTyCon [liftedTypeKind, liftedTypeKind, unitTy, unitTy]) noCafIdInfo pcMiscPrelId :: Name -> Type -> IdInfo -> Id pcMiscPrelId name ty info = mkVanillaGlobalWithInfo name ty info -- We lie and say the thing is imported; otherwise, we get into -- a mess with dependency analysis; e.g., core2stg may heave in -- random calls to GHCbase.unpackPS__. If GHCbase is the module -- being compiled, then it's just a matter of luck if the definition -- will be in "the right place" to be in scope.
vTurbine/ghc
compiler/basicTypes/MkId.hs
Haskell
bsd-3-clause
59,709
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.HTools.Instance ( testHTools_Instance , genInstanceSmallerThanNode , genInstanceMaybeBiggerThanNode , genInstanceOnNodeList , genInstanceList , Instance.Instance(..) ) where import Prelude () import Ganeti.Prelude import Control.Arrow ((&&&)) import Control.Monad (liftM) import Test.QuickCheck hiding (Result) import Test.Ganeti.TestHTools (nullISpec) import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.HTools.Types () import Ganeti.BasicTypes import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Loader as Loader import qualified Ganeti.HTools.Types as Types -- * Arbitrary instances -- | Generates a random instance with maximum and minimum disk/mem/cpu values. genInstanceWithin :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Maybe Int -> Gen Instance.Instance genInstanceWithin min_mem min_dsk min_cpu min_spin max_mem max_dsk max_cpu max_spin = do name <- genFQDN mem <- choose (min_mem, max_mem) dsk <- choose (min_dsk, max_dsk) run_st <- arbitrary pn <- arbitrary sn <- arbitrary vcpus <- choose (min_cpu, max_cpu) dt <- arbitrary spindles <- case max_spin of Nothing -> genMaybe $ choose (min_spin, maxSpindles) Just ls -> liftM Just $ choose (min_spin, ls) forthcoming <- arbitrary let disk = Instance.Disk dsk spindles return $ Instance.create name mem dsk [disk] vcpus run_st [] True pn sn dt 1 [] forthcoming -- | Generate an instance with maximum disk/mem/cpu values. genInstanceSmallerThan :: Int -> Int -> Int -> Maybe Int -> Gen Instance.Instance genInstanceSmallerThan = genInstanceWithin 1 0 1 0 -- | Generates an instance smaller than a node. genInstanceSmallerThanNode :: Node.Node -> Gen Instance.Instance genInstanceSmallerThanNode node = genInstanceSmallerThan (Node.availMem node `div` 2) (Node.availDisk node `div` 2) (Node.availCpu node `div` 2) (if Node.exclStorage node then Just $ Node.fSpindlesForth node `div` 2 else Nothing) -- | Generates an instance possibly bigger than a node. -- In any case, that instance will be bigger than the node's ipolicy's lower -- bound. genInstanceMaybeBiggerThanNode :: Node.Node -> Gen Instance.Instance genInstanceMaybeBiggerThanNode node = let minISpec = runListHead nullISpec Types.minMaxISpecsMinSpec . Types.iPolicyMinMaxISpecs $ Node.iPolicy node in genInstanceWithin (Types.iSpecMemorySize minISpec) (Types.iSpecDiskSize minISpec) (Types.iSpecCpuCount minISpec) (Types.iSpecSpindleUse minISpec) (Node.availMem node + Types.unitMem * 2) (Node.availDisk node + Types.unitDsk * 3) (Node.availCpu node + Types.unitCpu * 4) (if Node.exclStorage node then Just $ Node.fSpindles node + Types.unitSpindle * 5 else Nothing) -- | Generates an instance with nodes on a node list. -- The following rules are respected: -- 1. The instance is never bigger than its primary node -- 2. If possible the instance has different pnode and snode -- 3. Else disk templates which require secondary nodes are disabled genInstanceOnNodeList :: Node.List -> Gen Instance.Instance genInstanceOnNodeList nl = do let nsize = Container.size nl pnode <- choose (0, nsize-1) let (snodefilter, dtfilter) = if nsize >= 2 then ((/= pnode), const True) else (const True, not . Instance.hasSecondary) snode <- choose (0, nsize-1) `suchThat` snodefilter i <- genInstanceSmallerThanNode (Container.find pnode nl) `suchThat` dtfilter return $ i { Instance.pNode = pnode, Instance.sNode = snode } -- | Generates an instance list given an instance generator. genInstanceList :: Gen Instance.Instance -> Gen Instance.List genInstanceList igen = fmap (snd . Loader.assignIndices) names_instances where names_instances = map (Instance.name &&& id) <$> listOf igen -- let's generate a random instance instance Arbitrary Instance.Instance where arbitrary = genInstanceSmallerThan maxMem maxDsk maxCpu Nothing -- * Test cases -- Simple instance tests, we only have setter/getters prop_creat :: Instance.Instance -> Property prop_creat inst = Instance.name inst ==? Instance.alias inst prop_setIdx :: Instance.Instance -> Types.Idx -> Property prop_setIdx inst idx = Instance.idx (Instance.setIdx inst idx) ==? idx prop_setName :: Instance.Instance -> String -> Bool prop_setName inst name = Instance.name newinst == name && Instance.alias newinst == name where newinst = Instance.setName inst name prop_setAlias :: Instance.Instance -> String -> Bool prop_setAlias inst name = Instance.name newinst == Instance.name inst && Instance.alias newinst == name where newinst = Instance.setAlias inst name prop_setPri :: Instance.Instance -> Types.Ndx -> Property prop_setPri inst pdx = Instance.pNode (Instance.setPri inst pdx) ==? pdx prop_setSec :: Instance.Instance -> Types.Ndx -> Property prop_setSec inst sdx = Instance.sNode (Instance.setSec inst sdx) ==? sdx prop_setBoth :: Instance.Instance -> Types.Ndx -> Types.Ndx -> Bool prop_setBoth inst pdx sdx = Instance.pNode si == pdx && Instance.sNode si == sdx where si = Instance.setBoth inst pdx sdx prop_shrinkMG :: Instance.Instance -> Property prop_shrinkMG inst = Instance.mem inst >= 2 * Types.unitMem ==> case Instance.shrinkByType inst Types.FailMem of Ok inst' -> Instance.mem inst' ==? Instance.mem inst - Types.unitMem Bad msg -> failTest msg prop_shrinkMF :: Instance.Instance -> Property prop_shrinkMF inst = forAll (choose (0, 2 * Types.unitMem - 1)) $ \mem -> let inst' = inst { Instance.mem = mem} in isBad $ Instance.shrinkByType inst' Types.FailMem prop_shrinkCG :: Instance.Instance -> Property prop_shrinkCG inst = Instance.vcpus inst >= 2 * Types.unitCpu ==> case Instance.shrinkByType inst Types.FailCPU of Ok inst' -> Instance.vcpus inst' ==? Instance.vcpus inst - Types.unitCpu Bad msg -> failTest msg prop_shrinkCF :: Instance.Instance -> Property prop_shrinkCF inst = forAll (choose (0, 2 * Types.unitCpu - 1)) $ \vcpus -> let inst' = inst { Instance.vcpus = vcpus } in isBad $ Instance.shrinkByType inst' Types.FailCPU prop_shrinkDG :: Instance.Instance -> Property prop_shrinkDG inst = Instance.dsk inst >= 2 * Types.unitDsk ==> case Instance.shrinkByType inst Types.FailDisk of Ok inst' -> Instance.dsk inst' ==? Instance.dsk inst - Types.unitDsk Bad msg -> failTest msg prop_shrinkDF :: Instance.Instance -> Property prop_shrinkDF inst = forAll (choose (0, 2 * Types.unitDsk - 1)) $ \dsk -> let inst' = inst { Instance.dsk = dsk , Instance.disks = [Instance.Disk dsk Nothing] } in isBad $ Instance.shrinkByType inst' Types.FailDisk prop_setMovable :: Instance.Instance -> Bool -> Property prop_setMovable inst m = Instance.movable inst' ==? m where inst' = Instance.setMovable inst m testSuite "HTools/Instance" [ 'prop_creat , 'prop_setIdx , 'prop_setName , 'prop_setAlias , 'prop_setPri , 'prop_setSec , 'prop_setBoth , 'prop_shrinkMG , 'prop_shrinkMF , 'prop_shrinkCG , 'prop_shrinkCF , 'prop_shrinkDG , 'prop_shrinkDF , 'prop_setMovable ]
leshchevds/ganeti
test/hs/Test/Ganeti/HTools/Instance.hs
Haskell
bsd-2-clause
9,291
module Compiler.Simplify where import Data.Generics.PlateData import Compiler.Type import Data.List import Data.Maybe simplify :: Program1 -> Program2 simplify = addDollar . reform . freezeRules -- change rule application rule(arg) to rule_arg and replace all bits freezeRules :: Program1 -> Program1 freezeRules xs = map useDyn $ staticRules ++ dynInvoke where (staticRules,dynRules) = partition (\(Stmt1 a b c) -> null b) xs dynNames = [(a, (b,c)) | Stmt1 a b c <- dynRules] dynInvoke = [gen name arg res |Call1 name (Just arg) bind <- nub $ universeBi staticRules ,Just res <- [lookup name dynNames]] gen name arg (var,bod) = Stmt1 (getName name arg) "" (transformBi f bod) where f (Call1 v Nothing Nothing) | v == var = arg f x = x useDyn = transformBi f where f (Call1 v (Just x) y) | v `elem` map fst dynNames = Call1 (getName v x) Nothing y f x = x getName name (Literal1 x) = name ++ "_" ++ fromMaybe x (lookup x reps) where reps = [("'","squot"),("\"","dquot")] reform :: Program1 -> Program2 reform = concatMap reformStmt reformStmt (Stmt1 a "" (Choice1 xs)) | fst (last xs) == Call1 "_" Nothing Nothing = Stmt2 a (Choice2 (zipWith f [1..] $ init xs) (g $ length xs)) : zipWith (\i (_,v) -> Stmt2 (g i) (reformSeq v)) [1..] xs where f i (Literal1 x,_) = (x, g i) g i = a ++ "_" ++ show i reformStmt (Stmt1 a "" x) = [Stmt2 a $ reformSeq x] reformSeq (Seq1 act xs) = Seq2 act (map reformItem xs) reformItem (Literal1 x) = Literal2 x reformItem (Call1 name (Just (Literal1 x)) y) | name `elem` prims = Prim2 name x y reformItem (Call1 name Nothing y) = Rule2 name y addDollar :: Program2 -> Program2 addDollar = transformBi f where f (Seq2 act xs) | all (isNothing . getBind) xs && length (filter (isJust . getBind) ys) == 1 = Seq2 act ys where ys = transformBi (const $ Just (1::Int)) xs f x = x
silkapp/tagsoup
dead/parser/Compiler/old/Simplify.hs
Haskell
bsd-3-clause
2,095
-- ---------------------------------------------------------------------------- -- | Handle conversion of CmmData to LLVM code. -- module LlvmCodeGen.Data ( genLlvmData, resolveLlvmDatas, resolveLlvmData ) where #include "HsVersions.h" import Llvm import LlvmCodeGen.Base import BlockId import CLabel import OldCmm import FastString import qualified Outputable import Data.List (foldl') -- ---------------------------------------------------------------------------- -- * Constants -- -- | The string appended to a variable name to create its structure type alias structStr :: LMString structStr = fsLit "_struct" -- ---------------------------------------------------------------------------- -- * Top level -- -- | Pass a CmmStatic section to an equivalent Llvm code. Can't -- complete this completely though as we need to pass all CmmStatic -- sections before all references can be resolved. This last step is -- done by 'resolveLlvmData'. genLlvmData :: LlvmEnv -> (Section, CmmStatics) -> LlvmUnresData genLlvmData env (sec, Statics lbl xs) = let static = map genData xs label = strCLabel_llvm env lbl types = map getStatTypes static getStatTypes (Left x) = cmmToLlvmType $ cmmLitType x getStatTypes (Right x) = getStatType x strucTy = LMStruct types alias = LMAlias ((label `appendFS` structStr), strucTy) in (lbl, sec, alias, static) resolveLlvmDatas :: LlvmEnv -> [LlvmUnresData] -> (LlvmEnv, [LlvmData]) resolveLlvmDatas env ldata = foldl' res (env, []) ldata where res (e, xs) ll = let (e', nd) = resolveLlvmData e ll in (e', nd:xs) -- | Fix up CLabel references now that we should have passed all CmmData. resolveLlvmData :: LlvmEnv -> LlvmUnresData -> (LlvmEnv, LlvmData) resolveLlvmData env (lbl, sec, alias, unres) = let (env', static, refs) = resDatas env unres ([], []) struct = Just $ LMStaticStruc static alias label = strCLabel_llvm env lbl link = if (externallyVisibleCLabel lbl) then ExternallyVisible else Internal const = isSecConstant sec glob = LMGlobalVar label alias link Nothing Nothing const in (env', ((glob,struct):refs, [alias])) -- | Should a data in this section be considered constant isSecConstant :: Section -> Bool isSecConstant Text = True isSecConstant ReadOnlyData = True isSecConstant RelocatableReadOnlyData = True isSecConstant ReadOnlyData16 = True isSecConstant Data = False isSecConstant UninitialisedData = False isSecConstant (OtherSection _) = False -- ---------------------------------------------------------------------------- -- ** Resolve Data/CLabel references -- -- | Resolve data list resDatas :: LlvmEnv -> [UnresStatic] -> ([LlvmStatic], [LMGlobal]) -> (LlvmEnv, [LlvmStatic], [LMGlobal]) resDatas env [] (stats, glob) = (env, stats, glob) resDatas env (cmm:rest) (stats, globs) = let (env', nstat, nglob) = resData env cmm in resDatas env' rest (stats ++ [nstat], globs ++ nglob) -- | Resolve an individual static label if it needs to be. -- -- We check the 'LlvmEnv' to see if the reference has been defined in this -- module. If it has we can retrieve its type and make a pointer, otherwise -- we introduce a generic external definition for the referenced label and -- then make a pointer. resData :: LlvmEnv -> UnresStatic -> (LlvmEnv, LlvmStatic, [LMGlobal]) resData env (Right stat) = (env, stat, []) resData env (Left cmm@(CmmLabel l)) = let label = strCLabel_llvm env l ty = funLookup label env lmty = cmmToLlvmType $ cmmLitType cmm in case ty of -- Make generic external label defenition and then pointer to it Nothing -> let glob@(var, _) = genStringLabelRef label env' = funInsert label (pLower $ getVarType var) env ptr = LMStaticPointer var in (env', LMPtoI ptr lmty, [glob]) -- Referenced data exists in this module, retrieve type and make -- pointer to it. Just ty' -> let var = LMGlobalVar label (LMPointer ty') ExternallyVisible Nothing Nothing False ptr = LMStaticPointer var in (env, LMPtoI ptr lmty, []) resData env (Left (CmmLabelOff label off)) = let (env', var, glob) = resData env (Left (CmmLabel label)) offset = LMStaticLit $ LMIntLit (toInteger off) llvmWord in (env', LMAdd var offset, glob) resData env (Left (CmmLabelDiffOff l1 l2 off)) = let (env1, var1, glob1) = resData env (Left (CmmLabel l1)) (env2, var2, glob2) = resData env1 (Left (CmmLabel l2)) var = LMSub var1 var2 offset = LMStaticLit $ LMIntLit (toInteger off) llvmWord in (env2, LMAdd var offset, glob1 ++ glob2) resData _ _ = panic "resData: Non CLabel expr as left type!" -- ---------------------------------------------------------------------------- -- * Generate static data -- -- | Handle static data genData :: CmmStatic -> UnresStatic genData (CmmString str) = let v = map (\x -> LMStaticLit $ LMIntLit (fromIntegral x) i8) str ve = v ++ [LMStaticLit $ LMIntLit 0 i8] in Right $ LMStaticArray ve (LMArray (length ve) i8) genData (CmmUninitialised bytes) = Right $ LMUninitType (LMArray bytes i8) genData (CmmStaticLit lit) = genStaticLit lit -- | Generate Llvm code for a static literal. -- -- Will either generate the code or leave it unresolved if it is a 'CLabel' -- which isn't yet known. genStaticLit :: CmmLit -> UnresStatic genStaticLit (CmmInt i w) = Right $ LMStaticLit (LMIntLit i (LMInt $ widthInBits w)) genStaticLit (CmmFloat r w) = Right $ LMStaticLit (LMFloatLit (fromRational r) (widthToLlvmFloat w)) -- Leave unresolved, will fix later genStaticLit c@(CmmLabel _ ) = Left $ c genStaticLit c@(CmmLabelOff _ _) = Left $ c genStaticLit c@(CmmLabelDiffOff _ _ _) = Left $ c genStaticLit (CmmBlock b) = Left $ CmmLabel $ infoTblLbl b genStaticLit (CmmHighStackMark) = panic "genStaticLit: CmmHighStackMark unsupported!" -- ----------------------------------------------------------------------------- -- * Misc -- -- | Error Function panic :: String -> a panic s = Outputable.panic $ "LlvmCodeGen.Data." ++ s
nomeata/ghc
compiler/llvmGen/LlvmCodeGen/Data.hs
Haskell
bsd-3-clause
6,479
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Blackbox.Tests ( tests , remove , removeDir ) where ------------------------------------------------------------------------------ import Control.Exception (catch, finally, throwIO) import Control.Monad import Control.Monad.Trans import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy.Char8 as L import Data.Monoid import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.Encoding as T import Network.Http.Client import Prelude hiding (catch) import System.Directory import System.FilePath import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit import Test.HUnit hiding (Test, path) ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ testServer :: String testServer = "http://127.0.0.1" ------------------------------------------------------------------------------ testPort :: String testPort = "9753" ------------------------------------------------------------------------------ -- | The server uri, without the leading slash. testServerUri :: String testServerUri = testServer ++ ":" ++ testPort ------------------------------------------------------------------------------ -- | The server url, with the leading slash. testServerUrl :: String testServerUrl = testServerUri ++ "/" -------------------- -- TEST LOADER -- -------------------- ------------------------------------------------------------------------------ tests :: Test tests = testGroup "non-cabal-tests" [ requestTest "hello" "hello world" , requestTest "index" "index page\n" , requestTest "" "index page\n" , requestTest "splicepage" "splice page contents of the app splice\n" , requestTest "routeWithSplice" "routeWithSplice: foo snaplet data stringz" , requestTest "routeWithConfig" "routeWithConfig: topConfigValue" , requestTest "foo/foopage" "foo template page\n" , requestTest "foo/fooConfig" "fooValue" , requestTest "foo/fooRootUrl" "foo" , requestTest "barconfig" "barValue" , requestTest "bazpage" "baz template page <barsplice></barsplice>\n" , requestTest "bazpage2" "baz template page contents of the bar splice\n" , requestTest "bazpage3" "baz template page <barsplice></barsplice>\n" , requestTest "bazpage4" "baz template page <barsplice></barsplice>\n" , requestTest "barrooturl" "url" , requestExpectingError "bazbadpage" 500 "A web handler threw an exception. Details:\nTemplate \"cpyga\" not found." , requestTest "foo/fooSnapletName" "foosnaplet" , fooConfigPathTest -- Test the embedded snaplet , requestTest "embed/heist/embeddedpage" "embedded snaplet page <asplice></asplice>\n" , requestTest "embed/aoeuhtns" "embedded snaplet page splice value42\n" , requestTest "embed/heist/onemoredir/extra" "This is an extra template\n" -- This set of tests highlights the differences in the behavior of the -- get... functions from MonadSnaplet. , fooHandlerConfigTest , barHandlerConfigTest , bazpage5Test , bazConfigTest , requestTest "sessionDemo" "[(\"foo\",\"bar\")]\n" , reloadTest ] ------------------------------------------------------------------------------ testName :: String -> String testName uri = "internal/" ++ uri --testName = id ------------------------------------------------------------------------------ requestTest :: String -> Text -> Test requestTest url desired = testCase (testName url) $ requestTest' url desired ------------------------------------------------------------------------------ requestTest' :: String -> Text -> IO () requestTest' url desired = do actual <- get (S.pack $ testServerUrl ++ url) concatHandler assertEqual url desired (T.decodeUtf8 $ L.fromChunks [actual]) ------------------------------------------------------------------------------ requestExpectingError :: String -> Int -> Text -> Test requestExpectingError url status desired = testCase (testName url) $ requestExpectingError' url status desired ------------------------------------------------------------------------------ requestExpectingError' :: String -> Int -> Text -> IO () requestExpectingError' url status desired = do let fullUrl = testServerUrl ++ url get (S.pack fullUrl) $ \resp is -> do assertEqual ("Status code: "++fullUrl) status (getStatusCode resp) res <- concatHandler resp is assertEqual fullUrl desired (T.decodeUtf8 $ L.fromChunks [res]) ------------------------------------------------------------------------------ fooConfigPathTest :: Test fooConfigPathTest = testCase (testName "foo/fooFilePath") $ do b <- liftM L.unpack $ grab "/foo/fooFilePath" assertRelativelyTheSame b "snaplets/foosnaplet" ------------------------------------------------------------------------------ assertRelativelyTheSame :: FilePath -> FilePath -> IO () assertRelativelyTheSame p expected = do b <- makeRelativeToCurrentDirectory p assertEqual ("expected " ++ expected) expected b ------------------------------------------------------------------------------ grab :: MonadIO m => String -> m L.ByteString grab path = liftIO $ liftM (L.fromChunks . (:[])) $ get (S.pack $ testServerUri ++ path) concatHandler ------------------------------------------------------------------------------ testWithCwd :: String -> (String -> L.ByteString -> Assertion) -> Test testWithCwd uri f = testCase (testName uri) $ testWithCwd' uri f ------------------------------------------------------------------------------ testWithCwd' :: String -> (String -> L.ByteString -> Assertion) -> Assertion testWithCwd' uri f = do b <- grab slashUri cwd <- getCurrentDirectory f cwd b where slashUri = '/' : uri ------------------------------------------------------------------------------ fooHandlerConfigTest :: Test fooHandlerConfigTest = testWithCwd "foo/handlerConfig" $ \cwd b -> do let response = L.fromChunks [ "([\"app\"],\"" , S.pack cwd , "/snaplets/foosnaplet\"," , "Just \"foosnaplet\",\"A demonstration " , "snaplet called foo.\",\"foo\")" ] assertEqual "" response b ------------------------------------------------------------------------------ barHandlerConfigTest :: Test barHandlerConfigTest = testWithCwd "bar/handlerConfig" $ \cwd b -> do let response = L.fromChunks [ "([\"app\"],\"" , S.pack cwd , "/snaplets/baz\"," , "Just \"baz\",\"An example snaplet called " , "bar.\",\"\")" ] assertEqual "" response b ------------------------------------------------------------------------------ -- bazpage5 uses barsplice bound by renderWithSplices at request time bazpage5Test :: Test bazpage5Test = testWithCwd "bazpage5" $ \cwd b -> do let response = L.fromChunks [ "baz template page ([\"app\"],\"" , S.pack cwd , "/snaplets/baz\"," , "Just \"baz\",\"An example snaplet called " , "bar.\",\"\")\n" ] assertEqual "" (T.decodeUtf8 response) (T.decodeUtf8 b) ------------------------------------------------------------------------------ -- bazconfig uses two splices, appconfig and fooconfig. appconfig is bound with -- the non type class version of addSplices in the main app initializer. -- fooconfig is bound by addSplices in fooInit. bazConfigTest :: Test bazConfigTest = testWithCwd "bazconfig" $ \cwd b -> do let response = L.fromChunks [ "baz config page ([],\"" , S.pack cwd , "\",Just \"app\"," -- TODO, right? , "\"Test application\",\"\") " , "([\"app\"],\"" , S.pack cwd , "/snaplets/foosnaplet\"," , "Just \"foosnaplet\",\"A demonstration snaplet " , "called foo.\",\"foo\")\n" ] assertEqual "" (T.decodeUtf8 response) (T.decodeUtf8 b) ------------------------------------------------------------------------------ expect404 :: String -> IO () expect404 url = do get (S.pack $ testServerUrl ++ url) $ \resp i -> do case getStatusCode resp of 404 -> return () _ -> assertFailure "expected 404" ------------------------------------------------------------------------------ request404Test :: String -> Test request404Test url = testCase (testName url) $ expect404 url remove :: FilePath -> IO () remove f = do exists <- doesFileExist f when exists $ removeFile f removeDir :: FilePath -> IO () removeDir d = do exists <- doesDirectoryExist d when exists $ removeDirectoryRecursive "snaplets/foosnaplet" ------------------------------------------------------------------------------ reloadTest :: Test reloadTest = testCase "internal/reload-test" $ do let goodTplOrig = "good.tpl" let badTplOrig = "bad.tpl" let goodTplNew = "snaplets" </> "heist" </> "templates" </> "good.tpl" let badTplNew = "snaplets" </> "heist" </> "templates" </> "bad.tpl" goodExists <- doesFileExist goodTplNew badExists <- doesFileExist badTplNew assertBool "good.tpl exists" (not goodExists) assertBool "bad.tpl exists" (not badExists) expect404 "bad" copyFile badTplOrig badTplNew expect404 "good" expect404 "bad" flip finally (remove badTplNew) $ testWithCwd' "admin/reload" $ \cwd' b -> do let cwd = S.pack cwd' let response = T.concat [ "Error reloading site!\n\nInitializer " , "threw an exception...\n" , T.pack cwd' , "/snaplets/heist" , "/templates/bad.tpl \"" , T.pack cwd' , "/snaplets/heist/templates" , "/bad.tpl\" (line 2, column 1):\nunexpected " , "end of input\nexpecting \"=\", \"/\" or " , "\">\"\n\n...but before it died it generated " , "the following output:\nInitializing app @ /\n" , "Initializing heist @ /heist\n\n" ] assertEqual "admin/reload" response (T.decodeUtf8 b) copyFile goodTplOrig goodTplNew testWithCwd' "admin/reload" $ \cwd' b -> do -- TODO/NOTE: Needs cleanup let cwd = S.pack cwd' let response = L.fromChunks [ "Initializing app @ /\nInitializing heist @ ", "/heist\n...loaded 9 templates from ", cwd, "/snaplets/heist/templates\nInitializing CookieSession ", "@ /session\nInitializing foosnaplet @ /foo\n...adding 1 ", "templates from ", cwd, "/snaplets/foosnaplet/templates with route prefix ", "foo/\nInitializing baz @ /\n...adding 2 templates from ", cwd, "/snaplets/baz/templates with route prefix /\nInitializing ", "embedded @ /\nInitializing heist @ /heist\n...loaded ", "1 templates from ", cwd, "/snaplets/embedded/snaplets/heist/templates\n...adding ", "1 templates from ", cwd, "/snaplets/embedded/extra-templates with route prefix ", "onemoredir/\n...adding 0 templates from ", cwd, "/templates with route prefix extraTemplates/\n", "Initializing JsonFileAuthManager @ ", "/auth\nSite successfully reloaded.\n" ] assertEqual "admin/reload" response b requestTest' "good" "Good template\n"
sopvop/snap
test/suite/Blackbox/Tests.hs
Haskell
bsd-3-clause
12,605
{-# LANGUAGE DataKinds, PolyKinds, TypeOperators, TypeFamilies , TypeApplications, TypeInType #-} module DumpParsedAst where import Data.Kind data Peano = Zero | Succ Peano type family Length (as :: [k]) :: Peano where Length (a : as) = Succ (Length as) Length '[] = Zero -- vis kind app data T f (a :: k) = MkT (f a) type family F1 (a :: k) (f :: k -> Type) :: Type where F1 @Peano a f = T @Peano f a main = putStrLn "hello"
sdiehl/ghc
testsuite/tests/parser/should_compile/DumpParsedAst.hs
Haskell
bsd-3-clause
456
module HLint.Generalise where import Data.Monoid import Control.Monad warn = concatMap ==> (=<<) warn = liftM ==> fmap warn = map ==> fmap warn = a ++ b ==> a `Data.Monoid.mappend` b
bergmark/hlint
data/Generalise.hs
Haskell
bsd-3-clause
186
module Type where newtype TVar = TV String deriving (Show, Eq, Ord) data Type = TVar TVar | TCon String | TArr Type Type deriving (Show, Eq, Ord) infixr `TArr` data Scheme = Forall [TVar] Type deriving (Show, Eq, Ord) typeInt :: Type typeInt = TCon "Int" typeBool :: Type typeBool = TCon "Bool"
yupferris/write-you-a-haskell
chapter7/poly/src/Type.hs
Haskell
mit
314
<?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="az-AZ"> <title>Passive Scan Rules - Alpha | 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>İndeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Axtar</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>
kingthorin/zap-extensions
addOns/pscanrulesAlpha/src/main/javahelp/org/zaproxy/zap/extension/pscanrulesAlpha/resources/help_az_AZ/helpset_az_AZ.hs
Haskell
apache-2.0
988
module A1 where import D1 (sumSquares, fringe) import D1 import C1 import B1 main :: (Tree Int) -> Bool main t = isSame (sumSquares (fringe t)) ((sumSquares (B1.myFringe t)) + (sumSquares (C1.myFringe t)))
SAdams601/HaRe
old/testing/mkImpExplicit/A1_AstOut.hs
Haskell
bsd-3-clause
234
-- | Register coalescing. module RegAlloc.Graph.Coalesce ( regCoalesce, slurpJoinMovs ) where import GhcPrelude import RegAlloc.Liveness import Instruction import Reg import Cmm import Bag import Digraph import UniqFM import UniqSet import UniqSupply import Data.List -- | Do register coalescing on this top level thing -- -- For Reg -> Reg moves, if the first reg dies at the same time the -- second reg is born then the mov only serves to join live ranges. -- The two regs can be renamed to be the same and the move instruction -- safely erased. regCoalesce :: Instruction instr => [LiveCmmDecl statics instr] -> UniqSM [LiveCmmDecl statics instr] regCoalesce code = do let joins = foldl' unionBags emptyBag $ map slurpJoinMovs code let alloc = foldl' buildAlloc emptyUFM $ bagToList joins let patched = map (patchEraseLive (sinkReg alloc)) code return patched -- | Add a v1 = v2 register renaming to the map. -- The register with the lowest lexical name is set as the -- canonical version. buildAlloc :: UniqFM Reg -> (Reg, Reg) -> UniqFM Reg buildAlloc fm (r1, r2) = let rmin = min r1 r2 rmax = max r1 r2 in addToUFM fm rmax rmin -- | Determine the canonical name for a register by following -- v1 = v2 renamings in this map. sinkReg :: UniqFM Reg -> Reg -> Reg sinkReg fm r = case lookupUFM fm r of Nothing -> r Just r' -> sinkReg fm r' -- | Slurp out mov instructions that only serve to join live ranges. -- -- During a mov, if the source reg dies and the destination reg is -- born then we can rename the two regs to the same thing and -- eliminate the move. slurpJoinMovs :: Instruction instr => LiveCmmDecl statics instr -> Bag (Reg, Reg) slurpJoinMovs live = slurpCmm emptyBag live where slurpCmm rs CmmData{} = rs slurpCmm rs (CmmProc _ _ _ sccs) = foldl' slurpBlock rs (flattenSCCs sccs) slurpBlock rs (BasicBlock _ instrs) = foldl' slurpLI rs instrs slurpLI rs (LiveInstr _ Nothing) = rs slurpLI rs (LiveInstr instr (Just live)) | Just (r1, r2) <- takeRegRegMoveInstr instr , elementOfUniqSet r1 $ liveDieRead live , elementOfUniqSet r2 $ liveBorn live -- only coalesce movs between two virtuals for now, -- else we end up with allocatable regs in the live -- regs list.. , isVirtualReg r1 && isVirtualReg r2 = consBag (r1, r2) rs | otherwise = rs
ezyang/ghc
compiler/nativeGen/RegAlloc/Graph/Coalesce.hs
Haskell
bsd-3-clause
2,760
module Existential where -- Hmm, this is universal quantification, not existential. data U = U (forall a . (a,a->Int,Int->a,a->a->a)) -- This is existential quantification data E = forall a . {-Eq a =>-} E (a,a->Int,Int->a,a->a->a) e = E (1,id,id,(+)) -- OK: f (E (x,toint,fromint,op)) = toint (x `op` x) -- Error: it assumes that the existentially quantified type is Bool --g (E (x,toint,fromint,op)) = toint (False `op` x) -- Error: assuming two different existentially quantifier variables are the same --h (E (_,toint,_,_)) (E (x,_,_,_)) = toint x -- Error: the existentially quantified type variable escapes -- (and becomes universally quantified) --j (E (x,_,_,_)) = x
forste/haReFork
tools/base/tests/Existential.hs
Haskell
bsd-3-clause
682
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Program.Builtin -- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- The module defines all the known built-in 'Program's. -- -- Where possible we try to find their version numbers. -- module Distribution.Simple.Program.Builtin ( -- * The collection of unconfigured and configured programs builtinPrograms, -- * Programs that Cabal knows about ghcProgram, ghcPkgProgram, ghcjsProgram, ghcjsPkgProgram, lhcProgram, lhcPkgProgram, hmakeProgram, jhcProgram, haskellSuiteProgram, haskellSuitePkgProgram, uhcProgram, gccProgram, arProgram, stripProgram, happyProgram, alexProgram, hsc2hsProgram, c2hsProgram, cpphsProgram, hscolourProgram, haddockProgram, greencardProgram, ldProgram, tarProgram, cppProgram, pkgConfigProgram, hpcProgram, ) where import Distribution.Simple.Program.Find import Distribution.Simple.Program.Internal import Distribution.Simple.Program.Run import Distribution.Simple.Program.Types import Distribution.Simple.Utils import Distribution.Compat.Exception import Distribution.Verbosity import Distribution.Version import Data.Char ( isDigit ) import qualified Data.Map as Map -- ------------------------------------------------------------ -- * Known programs -- ------------------------------------------------------------ -- | The default list of programs. -- These programs are typically used internally to Cabal. builtinPrograms :: [Program] builtinPrograms = [ -- compilers and related progs ghcProgram , ghcPkgProgram , ghcjsProgram , ghcjsPkgProgram , haskellSuiteProgram , haskellSuitePkgProgram , hmakeProgram , jhcProgram , lhcProgram , lhcPkgProgram , uhcProgram , hpcProgram -- preprocessors , hscolourProgram , haddockProgram , happyProgram , alexProgram , hsc2hsProgram , c2hsProgram , cpphsProgram , greencardProgram -- platform toolchain , gccProgram , arProgram , stripProgram , ldProgram , tarProgram -- configuration tools , pkgConfigProgram ] ghcProgram :: Program ghcProgram = (simpleProgram "ghc") { programFindVersion = findProgramVersion "--numeric-version" id, -- Workaround for https://ghc.haskell.org/trac/ghc/ticket/8825 -- (spurious warning on non-english locales) programPostConf = \_verbosity ghcProg -> do let ghcProg' = ghcProg { programOverrideEnv = ("LANGUAGE", Just "en") : programOverrideEnv ghcProg } -- Only the 7.8 branch seems to be affected. Fixed in 7.8.4. affectedVersionRange = intersectVersionRanges (laterVersion $ Version [7,8,0] []) (earlierVersion $ Version [7,8,4] []) return $ maybe ghcProg (\v -> if withinRange v affectedVersionRange then ghcProg' else ghcProg) (programVersion ghcProg) } ghcPkgProgram :: Program ghcPkgProgram = (simpleProgram "ghc-pkg") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "ghc-pkg --version" gives a string like -- "GHC package manager version 6.4.1" case words str of (_:_:_:_:ver:_) -> ver _ -> "" } ghcjsProgram :: Program ghcjsProgram = (simpleProgram "ghcjs") { programFindVersion = findProgramVersion "--numeric-ghcjs-version" id } -- note: version is the version number of the GHC version that ghcjs-pkg was built with ghcjsPkgProgram :: Program ghcjsPkgProgram = (simpleProgram "ghcjs-pkg") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "ghcjs-pkg --version" gives a string like -- "GHCJS package manager version 6.4.1" case words str of (_:_:_:_:ver:_) -> ver _ -> "" } lhcProgram :: Program lhcProgram = (simpleProgram "lhc") { programFindVersion = findProgramVersion "--numeric-version" id } lhcPkgProgram :: Program lhcPkgProgram = (simpleProgram "lhc-pkg") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "lhc-pkg --version" gives a string like -- "LHC package manager version 0.7" case words str of (_:_:_:_:ver:_) -> ver _ -> "" } hmakeProgram :: Program hmakeProgram = (simpleProgram "hmake") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "hmake --version" gives a string line -- "/usr/local/bin/hmake: 3.13 (2006-11-01)" case words str of (_:ver:_) -> ver _ -> "" } jhcProgram :: Program jhcProgram = (simpleProgram "jhc") { programFindVersion = findProgramVersion "--version" $ \str -> -- invoking "jhc --version" gives a string like -- "jhc 0.3.20080208 (wubgipkamcep-2) -- compiled by ghc-6.8 on a x86_64 running linux" case words str of (_:ver:_) -> ver _ -> "" } uhcProgram :: Program uhcProgram = (simpleProgram "uhc") { programFindVersion = findProgramVersion "--version-dotted" id } hpcProgram :: Program hpcProgram = (simpleProgram "hpc") { programFindVersion = findProgramVersion "version" $ \str -> case words str of (_ : _ : _ : ver : _) -> ver _ -> "" } -- This represents a haskell-suite compiler. Of course, the compiler -- itself probably is not called "haskell-suite", so this is not a real -- program. (But we don't know statically the name of the actual compiler, -- so this is the best we can do.) -- -- Having this Program value serves two purposes: -- -- 1. We can accept options for the compiler in the form of -- -- --haskell-suite-option(s)=... -- -- 2. We can find a program later using this static id (with -- requireProgram). -- -- The path to the real compiler is found and recorded in the ProgramDb -- during the configure phase. haskellSuiteProgram :: Program haskellSuiteProgram = (simpleProgram "haskell-suite") { -- pretend that the program exists, otherwise it won't be in the -- "configured" state programFindLocation = \_verbosity _searchPath -> return $ Just ("haskell-suite-dummy-location", []) } -- This represent a haskell-suite package manager. See the comments for -- haskellSuiteProgram. haskellSuitePkgProgram :: Program haskellSuitePkgProgram = (simpleProgram "haskell-suite-pkg") { programFindLocation = \_verbosity _searchPath -> return $ Just ("haskell-suite-pkg-dummy-location", []) } happyProgram :: Program happyProgram = (simpleProgram "happy") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "happy --version" gives a string like -- "Happy Version 1.16 Copyright (c) ...." case words str of (_:_:ver:_) -> ver _ -> "" } alexProgram :: Program alexProgram = (simpleProgram "alex") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "alex --version" gives a string like -- "Alex version 2.1.0, (c) 2003 Chris Dornan and Simon Marlow" case words str of (_:_:ver:_) -> takeWhile (\x -> isDigit x || x == '.') ver _ -> "" } gccProgram :: Program gccProgram = (simpleProgram "gcc") { programFindVersion = findProgramVersion "-dumpversion" id } arProgram :: Program arProgram = simpleProgram "ar" stripProgram :: Program stripProgram = (simpleProgram "strip") { programFindVersion = \verbosity -> findProgramVersion "--version" stripExtractVersion (lessVerbose verbosity) } hsc2hsProgram :: Program hsc2hsProgram = (simpleProgram "hsc2hs") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "hsc2hs --version" gives a string like "hsc2hs version 0.66" case words str of (_:_:ver:_) -> ver _ -> "" } c2hsProgram :: Program c2hsProgram = (simpleProgram "c2hs") { programFindVersion = findProgramVersion "--numeric-version" id } cpphsProgram :: Program cpphsProgram = (simpleProgram "cpphs") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "cpphs --version" gives a string like "cpphs 1.3" case words str of (_:ver:_) -> ver _ -> "" } hscolourProgram :: Program hscolourProgram = (simpleProgram "hscolour") { programFindLocation = \v p -> findProgramOnSearchPath v p "HsColour", programFindVersion = findProgramVersion "-version" $ \str -> -- Invoking "HsColour -version" gives a string like "HsColour 1.7" case words str of (_:ver:_) -> ver _ -> "" } haddockProgram :: Program haddockProgram = (simpleProgram "haddock") { programFindVersion = findProgramVersion "--version" $ \str -> -- Invoking "haddock --version" gives a string like -- "Haddock version 0.8, (c) Simon Marlow 2006" case words str of (_:_:ver:_) -> takeWhile (`elem` ('.':['0'..'9'])) ver _ -> "" } greencardProgram :: Program greencardProgram = simpleProgram "greencard" ldProgram :: Program ldProgram = simpleProgram "ld" tarProgram :: Program tarProgram = (simpleProgram "tar") { -- See #1901. Some versions of 'tar' (OpenBSD, NetBSD, ...) don't support the -- '--format' option. programPostConf = \verbosity tarProg -> do tarHelpOutput <- getProgramInvocationOutput verbosity (programInvocation tarProg ["--help"]) -- Some versions of tar don't support '--help'. `catchIO` (\_ -> return "") let k = "Supports --format" v = if ("--format" `isInfixOf` tarHelpOutput) then "YES" else "NO" m = Map.insert k v (programProperties tarProg) return $ tarProg { programProperties = m } } cppProgram :: Program cppProgram = simpleProgram "cpp" pkgConfigProgram :: Program pkgConfigProgram = (simpleProgram "pkg-config") { programFindVersion = findProgramVersion "--version" id }
tolysz/prepare-ghcjs
spec-lts8/cabal/Cabal/Distribution/Simple/Program/Builtin.hs
Haskell
bsd-3-clause
10,350
module T7848 where data A = (:&&) Int Int | A Int Int x (+) ((&)@z) ((:&&) a b) (c :&& d) (e `A` f) (A g h) = y where infixl 3 `y` y _ = (&) {-# INLINE (&) #-} {-# SPECIALIZE (&) :: a #-} (&) = x
gridaphobe/ghc
testsuite/tests/parser/should_fail/T7848.hs
Haskell
bsd-3-clause
233
module Test.Scher.Property ( forAll , Property (verify) ) where import Test.Scher.Generic import Test.Scher.Symbolic import System.IO.Unsafe import System.Random import Data.IORef class Property b where verify :: b -> IO () instance Property Bool where verify b = assert b forAll :: (Symbolic a, Property b) => String -> (a -> b) -> All a b forAll = All instance (Symbolic a, Property b) => Property (All a b) where verify (All name f) = do arg <- run $ make name verify $ f arg instance (Symbolic a, Property b) => Property (a -> b) where verify f = do name <- genSym arg <- run $ make name verify $ f arg data All a b = All String (a -> b) counter :: IORef Int counter = unsafePerformIO $ newIORef 0 genSym :: IO String genSym = do num <- getStdRandom (random) :: IO Int return $ "#AUTO-" ++ show (abs num)
m-alvarez/scher
Test/Scher/Property.hs
Haskell
mit
858
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-} module Web.Mackerel.Types.Host where import Control.Applicative ((<|>)) import Data.Aeson import qualified Data.Aeson as Aeson import Data.Aeson.TH (deriveJSON, constructorTagModifier, fieldLabelModifier) import Data.Aeson.Types (Parser, typeMismatch) import Data.Char (toLower) import Data.Default (Default(..)) import qualified Data.HashMap.Lazy as HM import Data.Maybe (isJust) import qualified Data.Text as Text import Web.Mackerel.Internal.TH data HostId = HostId String deriving (Eq, Show) instance FromJSON HostId where parseJSON (Aeson.String hostId) = return $ HostId $ Text.unpack hostId parseJSON o = typeMismatch "HostId" o instance ToJSON HostId where toJSON (HostId hostId) = toJSON hostId data HostMetaCloud = HostMetaCloud { metaCloudProvider :: String, metaCloudMetadata :: HM.HashMap String Value } deriving (Eq, Show) $(deriveJSON options { fieldLabelModifier = map toLower . drop 9 } ''HostMetaCloud) data HostMetaCpu = HostMetaCpu { metaCpuCacheSize :: Maybe String, metaCpuCoreId :: Maybe String, metaCpuCores :: Maybe String, metaCpuFamily :: Maybe String, metaCpuMhz :: Maybe String, metaCpuModel :: Maybe String, metaCpuModelName :: Maybe String, metaCpuPhysicalId :: Maybe String, metaCpuStepping :: Maybe String, metaCpuVendorId :: Maybe String } deriving (Eq, Show) instance FromJSON HostMetaCpu where parseJSON (Object o) = HostMetaCpu <$> o .:? "cache_size" <*> o .:? "core_id" <*> o .:? "cores" <*> o .:? "family" <*> (o .:? "mhz" <|> fmap show <$> (o .:? "mhz" :: Parser (Maybe Integer))) <*> (o .:? "model" <|> fmap show <$> (o .:? "model" :: Parser (Maybe Integer))) <*> o .:? "model_name" <*> o .:? "physical_id" <*> o .:? "stepping" <*> o .:? "vendor_id" parseJSON o = typeMismatch "HostMetaCpu" o instance ToJSON HostMetaCpu where toJSON (HostMetaCpu cacheSize coreId cores family mhz model modelName physicalId stepping vendorId) = object [ key .= value | (key, value) <- [ ("cache_size", cacheSize), ("core_id", coreId), ("cores", cores), ("family", family), ("mhz", mhz), ("model", model), ("model_name", modelName), ("physical_id", physicalId), ("stepping", stepping), ("vendor_id", vendorId) ], isJust value ] data HostMeta = HostMeta { metaAgentName :: Maybe String, metaAgentRevision :: Maybe String, metaAgentVersion :: Maybe String, metaBlockDevice :: Maybe (HM.HashMap String (HM.HashMap String String)), metaCpu :: Maybe [HostMetaCpu], metaFilesystem :: Maybe (HM.HashMap String (HM.HashMap String Value)), metaKernel :: Maybe (HM.HashMap String String), metaMemory :: Maybe (HM.HashMap String String), metaCloud :: Maybe HostMetaCloud } deriving (Eq, Show) instance Default HostMeta where def = HostMeta def def def def def def def def def $(deriveJSON options { fieldLabelModifier = \xs -> let ys = drop 4 xs in if take 5 ys == "Agent" then kebabCase ys else snakeCase ys } ''HostMeta) data HostStatus = HostStatusWorking | HostStatusStandby | HostStatusMaintenance | HostStatusPoweroff deriving Eq instance Show HostStatus where show HostStatusWorking = "working" show HostStatusStandby = "standby" show HostStatusMaintenance = "maintenance" show HostStatusPoweroff = "poweroff" instance Read HostStatus where readsPrec _ xs = [ (hs, drop (length str) xs) | (hs, str) <- pairs', take (length str) xs == str ] where pairs' = [(HostStatusWorking, "working"), (HostStatusStandby, "standby"), (HostStatusMaintenance, "maintenance"), (HostStatusPoweroff, "poweroff")] $(deriveJSON options { constructorTagModifier = map toLower . drop 10 } ''HostStatus) data HostInterface = HostInterface { hostInterfaceName :: String, hostInterfaceMacAddress :: Maybe String, hostInterfaceIpv4Addresses :: Maybe [String], hostInterfaceIpv6Addresses :: Maybe [String] } deriving (Eq, Show) $(deriveJSON options { fieldLabelModifier = (\(c:cs) -> toLower c : cs) . drop 13 } ''HostInterface) data Host = Host { hostId :: HostId, hostName :: String, hostDisplayName :: Maybe String, hostStatus :: HostStatus, hostMemo :: String, hostRoles :: HM.HashMap String [String], hostIsRetired :: Bool, hostCreatedAt :: Integer, hostMeta :: HostMeta, hostInterfaces :: [HostInterface] } deriving (Eq, Show) $(deriveJSON options ''Host) data HostCreate = HostCreate { hostCreateName :: String, hostCreateDisplayName :: Maybe String, hostCreateCustomIdentifier :: Maybe String, hostCreateMeta :: HostMeta, hostCreateInterfaces :: Maybe [HostInterface], hostCreateRoleFullnames :: Maybe [String], hostCreateChecks :: Maybe [String] } deriving (Eq, Show) instance Default HostCreate where def = HostCreate def def def def def def def $(deriveJSON options { fieldLabelModifier = (\(c:cs) -> toLower c : cs) . drop 10 } ''HostCreate)
itchyny/mackerel-client-hs
src/Web/Mackerel/Types/Host.hs
Haskell
mit
5,116
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Game where import Data.Monoid ((<>)) import Control.Concurrent (MVar, newEmptyMVar, putMVar) import Control.Monad.State import qualified Data.ByteString.Char8 as B import Data.Char (toLower) import Data.Maybe (listToMaybe) import System.Random (randomRIO) data GameState = GameState { robots :: [Robot], mvar :: MVar GameState } data Robot = Robot { rId :: ID, pos :: Position, status :: RobotState, kind :: RobotKind } deriving (Eq) data RobotState = Off | Idle | Performing Action deriving (Eq) data Action = Access | Move | Query | Scan | Spawn | Start deriving (Eq, Show) data RobotKind = Headquarters | Engineer | Specialist | Factory deriving (Eq, Show) data Direction = North | East | South | West type Position = (Int, Int) type Area = (Position, Position) type Circle = (Position, Int) type ID = B.ByteString -- poor man’s json formatter (for fun!) jsonifyRobot :: Robot -> B.ByteString jsonifyRobot robot = "{" <> field "type" (kindToString . kind) <> "," <> field "uuid" rId <> "," <> field "x" (B.pack . show . fst . pos) <> "," <> field "y" (B.pack . show . snd . pos) <> "," <> field "status" (jsonifyState . status) <> "}" where field str fun = "\"" <> str <> "\":\"" <> fun robot <> "\"" jsonifyState Off = "off" jsonifyState Idle = "idle" jsonifyState (Performing action) = firstLower . B.pack $ show action kindToString :: RobotKind -> B.ByteString kindToString = firstLower . B.pack . show firstLower :: B.ByteString -> B.ByteString firstLower str = (B.singleton . toLower $ B.head str) <> B.tail str stringToKind :: B.ByteString -> Maybe RobotKind stringToKind "engineer" = Just Engineer stringToKind "headquarters" = Just Headquarters stringToKind "specialist" = Just Specialist stringToKind "factory" = Just Factory stringToKind _ = Nothing stringToDirection :: B.ByteString -> Maybe Direction stringToDirection "north" = Just North stringToDirection "east" = Just East stringToDirection "west" = Just West stringToDirection "south" = Just South stringToDirection _ = Nothing initialMVar :: IO (MVar GameState) initialMVar = do mvar <- newEmptyMVar putMVar mvar (GameState [] mvar) return mvar collision :: Position -> GameState -> Maybe Robot collision position state = listToMaybe . filter ((== position) . pos) $ robots state lookupRobot :: ID -> GameState -> Maybe Robot lookupRobot ident state = listToMaybe . filter ((== ident) . rId) $ robots state spawnRobot :: Robot -> GameState -> GameState spawnRobot robot state = state { robots = robot : robots state } changeRobot :: ID -> (Robot -> Robot) -> GameState -> GameState changeRobot uuid fun state = state { robots = map mapFun $ robots state } where mapFun robot | rId robot == uuid = fun robot | otherwise = robot move :: Direction -> Position -> Position move dir (x, y) = (x + dx, y + dy) where dx = case dir of East -> 1 West -> -1 _ -> 0 dy = case dir of North -> 1 South -> -1 _ -> 0 moveRobot :: Direction -> Robot -> Robot moveRobot dir rob = rob { pos = move dir $ pos rob } setStatus :: (MonadState GameState m) => ID -> RobotState -> m () setStatus robotID status = modify . changeRobot robotID $ \r -> r { status = status } randomPosition :: Area -> IO Position randomPosition ((x1,y1),(x2,y2))= do x <- randomRIO (x1, x2) y <- randomRIO (y1, y2) return (x, y) randomPositionInCircle :: Circle -> IO Position randomPositionInCircle arg@((x,y), r) = do pos <- randomPosition ((x - r, y - r), (x + r, y + r)) if distance (x,y) pos <= fromIntegral r then return pos else randomPositionInCircle arg distance :: (Floating a) => Position -> Position -> a distance (x1,y1) (x2,y2)= sqrt $ (fromIntegral x1 - fromIntegral x2) ** 2 + (fromIntegral y1 - fromIntegral y2) ** 2
shak-mar/botstrats
server/Game.hs
Haskell
mit
4,115
module Banjo where areYouPlayingBanjo :: String -> String areYouPlayingBanjo name@('R':xs) = name ++ " plays banjo" areYouPlayingBanjo name@('r':xs) = name ++ " plays banjo" areYouPlayingBanjo name = name ++ " does not play banjo"
dzeban/haskell-exercises
Banjo.hs
Haskell
mit
232
{-# LANGUAGE ExistentialQuantification, Rank2Types #-} module Control.Monad.Trans.Store where import qualified Data.Map as M import Control.Monad import Control.Monad.Hoist import Control.Monad.Trans -- The semantics of store should be that it continues as soon as the reference -- has been calculated, but that the entire operation shouldn't complete until -- all of the store operations have completed. data Step k v m a = Done a | Get k (v -> StoreT k v m a) | Store v (k -> StoreT k v m a) data StoreT k v m a = StoreT { runStoreT :: m (Step k v m a) } instance Monad m => Monad (StoreT k v m) where return = StoreT . return . Done m >>= f = StoreT $ do step <- runStoreT m case step of Done x -> runStoreT $ f x Get k c -> return $ Get k (\i -> c i >>= f) Store v c -> return $ Store v (\i -> c i >>= f) instance MonadTrans (StoreT k v) where lift m = StoreT $ liftM Done m instance MonadIO m => MonadIO (StoreT k v m) where liftIO m = StoreT $ liftM Done (liftIO m) instance MonadHoist (StoreT k v) where hoist f m = StoreT $ do step <- f $ runStoreT m case step of Done a -> return $ Done a Get k c -> return $ Get k $ hoist f . c Store v c -> return $ Store v $ hoist f . c get :: Monad m => k -> StoreT k a m a get k = StoreT $ return $ Get k return store :: Monad m => v -> StoreT a v m a store v = StoreT $ return $ Store v return keyChange :: Monad m => (k0 -> k1) -> (k1 -> k0) -> StoreT k0 v m a -> StoreT k1 v m a keyChange forwards backwards op = StoreT $ do step <- runStoreT op case step of Done a -> return $ Done a Get k c -> return $ Get (forwards k) (keyChange forwards backwards . c) Store v c -> return $ Store v (keyChange forwards backwards . c . backwards) valueChange :: Monad m => (v0 -> v1) -> (v1 -> v0) -> StoreT k v0 m a -> StoreT k v1 m a valueChange forwards backwards op = StoreT $ do step <- runStoreT op case step of Done a -> return $ Done a Get k c -> return $ Get k (valueChange forwards backwards . c . backwards) Store v c -> return $ Store (forwards v) (valueChange forwards backwards . c) cache :: (Ord k, Monad m) => StoreT k v m a -> StoreT k v m a cache op = do cache' M.empty op where cache' m op' = do step <- lift $ runStoreT op' case step of Done a -> return a Get k c -> do case M.lookup k m of Just v -> cache' m $ c v Nothing -> do v <- get k cache' (M.insert k v m) $ c v Store v c -> do k <- store v cache' (M.insert k v m) $ c k
DanielWaterworth/siege
src/Control/Monad/Trans/Store.hs
Haskell
mit
2,617
{-# LANGUAGE OverloadedStrings, RecordWildCards #-} module Main where import Text.XML.HXT.Core main = do runX (readDocument [ withValidate no, withParseHTML yes, withInputEncoding utf8 ] "" >>> processChildren (process1 `when` isElem) >>> writeDocument [] "-" ) process1 :: ArrowXml a => a XmlTree XmlTree process1 = addNav >>> processTopDown ( (returnA <+> (followingSiblingAxis >>> filterAxis (hasName "p") ) ) `when` withoutNav (hasName "p") ) >>> remNav deleteExtraParas :: ArrowXml a => a XmlTree XmlTree deleteExtraParas = addNav >>> (getChildren >>> withoutNav (isElem >>> hasName "p")) >>> remNav addText :: ArrowXml a => a XmlTree XmlTree addText = replaceChildren (getChildren <+> txt " test") {- process = deep (isElem >>> hasName "p") >>> withNav (followingSiblingAxis >>> filterAxis (isElem >>> hasName "p")) -}
danchoi/hxt-nav
Main.hs
Haskell
mit
1,011
main = print $ (foldl1 cross $ map (`map` [1..]) [t, p, h]) !! 2 t n = n * ( n + 1) `div` 2 p n = n * (3 * n - 1) `div` 2 h n = n * (2 * n - 1) -- Lazily intersects ordered lists cross a@(x:xs) b@(y:ys) | x > y = cross a ys | x < y = cross xs b | otherwise = x : cross xs ys
nickspinale/euler
complete/045.hs
Haskell
mit
293
module Azure.BlobStorage.Util where import qualified Blaze.ByteString.Builder as Builder import Control.Applicative import Control.Monad.Reader hiding (forM) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Base64 as Base64 import qualified Data.ByteString.Char8 as Char8 import qualified Data.ByteString.Lazy as LBS import qualified Data.Char as Char import Data.Conduit import Data.Maybe (fromMaybe) import Data.Monoid import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Time (getCurrentTime, formatTime) import Network.HTTP.Conduit import Prelude import Safe (readMay) import System.Locale (defaultTimeLocale) -- | Use the read instance to remove escaping. If that fails, then -- just return the original. unescapeText :: Text -> Text unescapeText input = fromMaybe input $ readMay $ "\"" ++ Text.unpack input ++ "\"" asciiLowercase :: ByteString -> ByteString asciiLowercase = Char8.map Char.toLower toStrict :: LBS.ByteString -> ByteString toStrict = BS.concat . LBS.toChunks fromStrict :: BS.ByteString -> LBS.ByteString fromStrict = LBS.fromChunks . (: []) encodeBase64Text :: Text -> Text encodeBase64Text = Text.decodeUtf8 . Base64.encode . Text.encodeUtf8 strip :: ByteString -> ByteString strip = snd . Char8.span Char.isSpace . fst . Char8.spanEnd Char.isSpace pad :: Int -> Text -> Text -> Text pad n c bs = Text.replicate (n - Text.length bs) c <> bs rfc1123Time :: IO String rfc1123Time = formatTime defaultTimeLocale "%a, %d %b %Y %H:%M:%S GMT" <$> getCurrentTime -- | Conduit which coalesces results of the specified byte-length. -- The last result may be shorter than the specified length. splitBytes :: Monad m => Int -> Conduit ByteString m RequestBody splitBytes stride = go 0 mempty where go l b = do mx <- await case mx of Nothing -> when (l > 0) $ yield $ RequestBodyBuilder (fromIntegral l) b Just x -> do let l' = l + BS.length x if l' < stride then go l' (b <> Builder.fromByteString x) else do let (before, after) = BS.splitAt (stride - l) x yield $ RequestBodyBuilder (fromIntegral stride) (b <> Builder.fromByteString before) when (BS.length after > 0) $ leftover after go 0 mempty
fpco/schoolofhaskell.com
src/Azure/BlobStorage/Util.hs
Haskell
mit
2,517
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} module Ch15.SupplyClass ( S.Supply , S.runSupply , S.runRandomSupply , MonadSupply (..) ) where import qualified Ch15.Supply as S class (Monad m) => (MonadSupply s) m | m -> s where next :: m (Maybe s) instance MonadSupply s (S.Supply s) where next = S.next showTwo_class :: (Show s, Monad m, MonadSupply s m) => m String showTwo_class = showTwo <$> next <*> next where showTwo x y = (show "a: " ++ show x ++ ", b: " ++ show y)
futtetennista/IntroductionToFunctionalProgramming
RWH/src/ch15/SupplyClass.hs
Haskell
mit
677
module Main where import Data.List import Light.Cameras import Light.Film import Light.Filters import Light.Geometry f :: Film f = film (16, 12) (boxFilter (1, 1)) p1, p2 :: PerspectiveCamera p1 = perspectiveCamera f (pi/3) p2 = perspectiveCamera f (pi/2) o :: OrthographicCamera o = orthographicCamera f 1 getRays :: (Camera c) => c -> [Ray] getRays camera = let (fw, fh) = (filmDimensions.cameraFilm) camera in [cameraRay camera (fromIntegral x + 0.5, fromIntegral y + 0.5) | x <- [0..fw-1], y <- [0..fh-1]] main :: IO () main = do putStrLn "graphics_toolkit (\"fltk\");" putStrLn "clf" drawPerspectivePlot 1 "Perspective (60)" p1 drawPerspectivePlot 2 "Perspective (90)" p2 drawOrthographicPlot 3 "Orthographic" o drawPerspectivePlot :: Int -> String -> PerspectiveCamera -> IO () drawPerspectivePlot ix title camera = let fovY = perspectiveVerticalFOV camera (_,fh) = (filmDimensions.cameraFilm) camera in drawPlot ix title camera (fromIntegral fh / (2 * tan (fovY/2))) drawOrthographicPlot :: Int -> String -> OrthographicCamera -> IO () drawOrthographicPlot ix title camera = let (fw, fh) = (filmDimensions.cameraFilm) camera in drawPlot ix title camera (fromIntegral (min fw fh)) drawPlot :: (Camera c) => Int -> String -> c -> Double -> IO () drawPlot ix title camera imagePlaneHeight = do putStrLn $ "figure (" ++ show ix ++ ");" putStrLn $ "x = linspace (" ++ intercalate ", " (map show [-fw/2, fw/2, fw+1]) ++ ");" putStrLn $ "y = linspace (" ++ intercalate ", " (map show [-fh/2, fh/2, fh+1]) ++ ");" putStrLn "[xx, yy] = meshgrid(x, y);" putStrLn $ "zz = (xx.*0).+" ++ show imagePlaneHeight ++ ";" putStrLn "mesh (xx, yy, zz);" putStrLn "hold on;" putStrLn "grid off;" putStrLn "box off;" putStrLn $ "axis ([" ++ intercalate ", " (map show [-dim/2, dim/2, -dim/2, dim/2, 0, dim]) ++ "], \"square\");" putStrLn "daspect ([1, 1, 1]);" putStrLn "pbaspect ([1, 1, 1]);" putStrLn $ "title (\"" ++ title ++ "\");" putStrLn $ "ox = [" ++ intercalate ", " (map show ox) ++ "];" putStrLn $ "oy = [" ++ intercalate ", " (map show oy) ++ "];" putStrLn $ "oz = [" ++ intercalate ", " (map show oz) ++ "];" putStrLn $ "dx = [" ++ intercalate ", " (map show vx) ++ "];" putStrLn $ "dy = [" ++ intercalate ", " (map show vy) ++ "];" putStrLn $ "dz = [" ++ intercalate ", " (map show vz) ++ "];" putStrLn "q = quiver3 (ox, oy, oz, dx, dy, dz, 0);" putStrLn "set (q, \"maxheadsize\", 0);" putStrLn "hold off;" where fw = (fromIntegral.fst.filmDimensions.cameraFilm) camera fh = (fromIntegral.snd.filmDimensions.cameraFilm) camera dim = foldl max 0 [fw, fh, imagePlaneHeight] + 4 rays = getRays camera ox = map (px.rayOrigin) rays oy = map (py.rayOrigin) rays oz = map (pz.rayOrigin) rays vx = map (\r -> (dx $ rayDirection r)*imagePlaneHeight*1.2/(dz $ rayDirection r)) rays vy = map (\r -> (dy $ rayDirection r)*imagePlaneHeight*1.2/(dz $ rayDirection r)) rays vz = map (\r -> (dz $ rayDirection r)*imagePlaneHeight*1.2/(dz $ rayDirection r)) rays
jtdubs/Light
src/App/CameraDiagrams.hs
Haskell
mit
3,326
{-# LANGUAGE OverloadedStrings #-} module Day13 (day13, day13', run) where import Data.Attoparsec.Text ( Parser(..) , char , decimal , endOfLine , isHorizontalSpace , many' , option , parseOnly , string , takeTill ) import Data.Function (on) import Data.List (groupBy, nub, sortBy) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map (empty, fromList, keys, union) import Data.Monoid (Sum(..)) import Data.Set (Set) import qualified Data.Set as Set (delete, fromList) import Data.Text (Text, pack) import Graph -- Parsing types and type synonyms for the problem at hand type Person = Text type Happiness = Sum Int data Source = Source (Edge Person) Happiness deriving (Show, Eq) type SourceData = EdgeWeightMap Person Happiness sourceEdge :: Source -> Edge Person sourceEdge (Source e _) = e sourceHappiness :: Source -> Happiness sourceHappiness (Source _ h) = h compileMap :: [Source] -> SourceData compileMap [] = Map.empty compileMap xs = Map.fromList . map collapseSameSources . groupBy ((==) `on` sourceEdge) . sortBy (compare `on` sourceEdge) $ xs collapseSameSources :: [Source] -> (Edge Person, Happiness) collapseSameSources [] = undefined collapseSameSources xs@(x:_) = (sourceEdge x, mconcat . map sourceHappiness $ xs) parseSourceData :: Parser SourceData parseSourceData = do sources <- many' parseSource return $ compileMap sources parseSource :: Parser Source parseSource = do a <- takeTill isHorizontalSpace string " would " gainOrLose <- takeTill isHorizontalSpace char ' ' h <- decimal string " happiness units by sitting next to " b <- takeTill (== '.') char '.' option () endOfLine let happiness = if gainOrLose == "gain" then h else (-h) return $ Source (Edge (Node a) (Node b)) (Sum happiness) allPeople :: SourceData -> [Person] allPeople = nub . concatMap (\(Edge (Node a) (Node b)) -> [a, b]) . Map.keys bestFullCycle :: SourceData -> Maybe (Traversal Person Happiness) bestFullCycle g = case allPeople g of [] -> Just $ Traversal [] mempty (x:_) -> bestTraversal' g compare start start rest where start = Just $ Node x rest = Set.delete (Node x) (Set.fromList . map Node . allPeople $ g) day13 :: String -> Int day13 input = case parseOnly parseSourceData . pack $ input of (Left _) -> -1 (Right sourceData) -> case bestFullCycle sourceData of Nothing -> -2 (Just t) -> getSum . traversalWeight $ t addSelf :: SourceData -> SourceData addSelf g = Map.union (Map.fromList selfEdges) g where self = Node "Self" selfEdges = map (\p -> (Edge self (Node p), 0)) $ allPeople g day13' :: String -> Int day13' input = case parseOnly parseSourceData . pack $ input of (Left _) -> -1 (Right sourceData) -> case bestFullCycle $ addSelf sourceData of Nothing -> -2 (Just t) -> getSum . traversalWeight $ t -- Input run :: IO () run = do putStrLn "Day 13 results: " input <- readFile "inputs/day13.txt" putStrLn $ " " ++ show (day13 input) putStrLn $ " " ++ show (day13' input)
brianshourd/adventOfCode2015
src/Day13.hs
Haskell
mit
3,167
module U.Util.Components where import qualified Data.Graph as Graph import qualified Data.Map as Map import qualified Data.Set as Set import Data.Set (Set) import Data.Maybe (fromMaybe) -- | Order bindings by dependencies and group into components. -- Each component consists of > 1 bindings, each of which depends -- transitively on all other bindings in the component. -- -- 1-element components may or may not depend on themselves. -- -- The order is such that a component at index i will not depend -- on components and indexes > i. But a component at index i does not -- _necessarily_ depend on any components at earlier indices. -- -- Example: -- -- let rec -- ping n = pong (n + 1); -- pong n = ping (n + 1); -- g = id 42; -- y = id "hi" -- id x = x; -- in ping g -- -- `components` would produce `[[ping,pong], [id], [g], [y]]` -- Notice that `id` comes before `g` and `y` in the output, since -- both `g` and `y` depend on `id`. -- -- Uses Tarjan's algorithm: -- https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm components :: Ord v => (t -> Set v) -> [(v, t)] -> [[(v, t)]] components freeVars bs = let varIds = Map.fromList (map fst bs `zip` reverse [(1 :: Int) .. length bs]) -- something horribly wrong if this bombs varId v = fromMaybe msg $ Map.lookup v varIds where msg = error "Components.components bug" -- use ints as keys for graph to preserve original source order as much as -- possible graph = [ ((v, b), varId v, deps b) | (v, b) <- bs ] vars = Set.fromList (map fst bs) deps b = varId <$> Set.toList (Set.intersection vars (freeVars b)) in Graph.flattenSCC <$> Graph.stronglyConnComp graph
unisonweb/platform
codebase2/util/U/Util/Components.hs
Haskell
mit
1,739
k = 1000000007 ans m 0 = 1 ans m 1 = m ans m n = let n' = n `div` 2 x = ans m n' y = ans m (n-2*n') in (x * x * y) `mod` k main = do l <- getLine let (m:n:_) = map read $ words l :: [Integer] o = ans m n print o
a143753/AOJ
NTL_1_B.hs
Haskell
apache-2.0
249
import Prelude data Tree a = Node (Tree a) a (Tree a) | Empty deriving Show areTreesEqual :: Tree Int -> Tree Int -> Bool areTreesEqual Empty Empty = True areTreesEqual Empty _ = False areTreesEqual _ Empty = False areTreesEqual (Node leftTree1 a rightTree1) (Node leftTree2 b rightTree2) = if a == b then (areTreesEqual leftTree1 leftTree2) && (areTreesEqual rightTree1 rightTree2) else False main :: IO () main = do -- let a = Empty b = Empty in putStrLn $ show (areTreesEqual a b) let a = Empty b = Node Empty 3 (Node Empty 2 Empty) in putStrLn $ show (areTreesEqual a b) let a = Node Empty 3 (Node Empty 2 Empty) b = Empty in putStrLn $ show (areTreesEqual a b) let a = Node Empty 3 (Node Empty 2 Empty) b = Node Empty 3 (Node Empty 2 Empty) in putStrLn $ show (areTreesEqual a b) let a = Node Empty 3 (Node Empty 2 Empty) b = Node (Node Empty 3 (Node Empty 4 Empty)) 3 (Node Empty 2 Empty) in putStrLn $ show (areTreesEqual a b)
omefire/HaskellProjects
areTreesEqual.hs
Haskell
apache-2.0
1,047
module Explession where level:: Int -> String -> Int level lv (head:tail) | head == '(' && lv >= 0 = level (lv + 1) tail | head == ')' && lv >= 0 = level (lv - 1) tail | otherwise = lv level lv ([]) = lv {- - Checks whether an expression contains a balanced amount of brackets - Example: - isBalanced "( ( text2 ) and ( test3 ) )" == True - isBalanced " ( text1 ) text2)" == False -} isBalanced:: String -> Bool isBalanced str = level 0 filteredStr == 0 where filteredStr = filter (\a -> a =='(' || a == ')') str
art4ul/HaskellSandbox
Expression.hs
Haskell
apache-2.0
574
module Data.Binary.Get.Machine where import Data.ByteString (ByteString) import Data.Binary.Get (Decoder(..), Get, pushChunk, runGetIncremental) import Data.Machine (MachineT(..), ProcessT, Step(Await, Yield), Is(Refl), stopped) processGet :: Monad m => Get a -> ProcessT m ByteString a processGet getA = processDecoder (runGetIncremental getA) processDecoder :: Monad m => Decoder a -> ProcessT m ByteString a processDecoder decA = MachineT . return $ Await f Refl stopped where f xs = case pushChunk decA xs of -- TODO Add `Fail` case Done _ _ a -> MachineT . return $ Yield a stopped decA' -> processDecoder decA'
aloiscochard/thinkgear
src/Data/Binary/Get/Machine.hs
Haskell
apache-2.0
645
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QAbstractTextDocumentLayout.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:18 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QAbstractTextDocumentLayout ( qAbstractTextDocumentLayout ,QblockBoundingRect(..), QqblockBoundingRect(..) ,QdocumentChanged(..) ,QdocumentSize(..), QqdocumentSize(..) ,QdrawInlineObject(..), QqdrawInlineObject(..) ,QformatIndex(..) ,QframeBoundingRect(..), QqframeBoundingRect(..) ,handlerForObject ,QhitTest(..), QqhitTest(..) ,paintDevice ,QpositionInlineObject(..) ,registerHandler ,QresizeInlineObject(..) ,QsetPaintDevice(..) ,qAbstractTextDocumentLayout_delete ,qAbstractTextDocumentLayout_deleteLater ) where import Foreign.C.Types 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 instance QuserMethod (QAbstractTextDocumentLayout ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QAbstractTextDocumentLayout_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QAbstractTextDocumentLayout_userMethod" qtc_QAbstractTextDocumentLayout_userMethod :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> IO () instance QuserMethod (QAbstractTextDocumentLayoutSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QAbstractTextDocumentLayout_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QAbstractTextDocumentLayout ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QAbstractTextDocumentLayout_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QAbstractTextDocumentLayout_userMethodVariant" qtc_QAbstractTextDocumentLayout_userMethodVariant :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QAbstractTextDocumentLayoutSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QAbstractTextDocumentLayout_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj qAbstractTextDocumentLayout :: (QTextDocument t1) -> IO (QAbstractTextDocumentLayout ()) qAbstractTextDocumentLayout (x1) = withQAbstractTextDocumentLayoutResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout" qtc_QAbstractTextDocumentLayout :: Ptr (TQTextDocument t1) -> IO (Ptr (TQAbstractTextDocumentLayout ())) instance QanchorAt (QAbstractTextDocumentLayout a) ((PointF)) where anchorAt x0 (x1) = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QAbstractTextDocumentLayout_anchorAt_qth cobj_x0 cpointf_x1_x cpointf_x1_y foreign import ccall "qtc_QAbstractTextDocumentLayout_anchorAt_qth" qtc_QAbstractTextDocumentLayout_anchorAt_qth :: Ptr (TQAbstractTextDocumentLayout a) -> CDouble -> CDouble -> IO (Ptr (TQString ())) instance QqanchorAt (QAbstractTextDocumentLayout a) ((QPointF t1)) where qanchorAt x0 (x1) = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_anchorAt cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_anchorAt" qtc_QAbstractTextDocumentLayout_anchorAt :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPointF t1) -> IO (Ptr (TQString ())) class QblockBoundingRect x0 x1 where blockBoundingRect :: x0 -> x1 -> IO (RectF) class QqblockBoundingRect x0 x1 where qblockBoundingRect :: x0 -> x1 -> IO (QRectF ()) instance QqblockBoundingRect (QAbstractTextDocumentLayout ()) ((QTextBlock t1)) where qblockBoundingRect x0 (x1) = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_blockBoundingRect_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_blockBoundingRect_h" qtc_QAbstractTextDocumentLayout_blockBoundingRect_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextBlock t1) -> IO (Ptr (TQRectF ())) instance QqblockBoundingRect (QAbstractTextDocumentLayoutSc a) ((QTextBlock t1)) where qblockBoundingRect x0 (x1) = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_blockBoundingRect_h cobj_x0 cobj_x1 instance QblockBoundingRect (QAbstractTextDocumentLayout ()) ((QTextBlock t1)) where blockBoundingRect x0 (x1) = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_blockBoundingRect_qth_h cobj_x0 cobj_x1 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h foreign import ccall "qtc_QAbstractTextDocumentLayout_blockBoundingRect_qth_h" qtc_QAbstractTextDocumentLayout_blockBoundingRect_qth_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextBlock t1) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO () instance QblockBoundingRect (QAbstractTextDocumentLayoutSc a) ((QTextBlock t1)) where blockBoundingRect x0 (x1) = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_blockBoundingRect_qth_h cobj_x0 cobj_x1 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h instance Qdocument (QAbstractTextDocumentLayout a) (()) where document x0 () = withQTextDocumentResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_document cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_document" qtc_QAbstractTextDocumentLayout_document :: Ptr (TQAbstractTextDocumentLayout a) -> IO (Ptr (TQTextDocument ())) class QdocumentChanged x0 x1 where documentChanged :: x0 -> x1 -> IO () instance QdocumentChanged (QAbstractTextDocumentLayout ()) ((Int, Int, Int)) where documentChanged x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentChanged_h cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) foreign import ccall "qtc_QAbstractTextDocumentLayout_documentChanged_h" qtc_QAbstractTextDocumentLayout_documentChanged_h :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> CInt -> CInt -> IO () instance QdocumentChanged (QAbstractTextDocumentLayoutSc a) ((Int, Int, Int)) where documentChanged x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentChanged_h cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) class QdocumentSize x0 x1 where documentSize :: x0 -> x1 -> IO (SizeF) class QqdocumentSize x0 x1 where qdocumentSize :: x0 -> x1 -> IO (QSizeF ()) instance QqdocumentSize (QAbstractTextDocumentLayout ()) (()) where qdocumentSize x0 () = withQSizeFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentSize_h cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_documentSize_h" qtc_QAbstractTextDocumentLayout_documentSize_h :: Ptr (TQAbstractTextDocumentLayout a) -> IO (Ptr (TQSizeF ())) instance QqdocumentSize (QAbstractTextDocumentLayoutSc a) (()) where qdocumentSize x0 () = withQSizeFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentSize_h cobj_x0 instance QdocumentSize (QAbstractTextDocumentLayout ()) (()) where documentSize x0 () = withSizeFResult $ \csizef_ret_w csizef_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentSize_qth_h cobj_x0 csizef_ret_w csizef_ret_h foreign import ccall "qtc_QAbstractTextDocumentLayout_documentSize_qth_h" qtc_QAbstractTextDocumentLayout_documentSize_qth_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr CDouble -> Ptr CDouble -> IO () instance QdocumentSize (QAbstractTextDocumentLayoutSc a) (()) where documentSize x0 () = withSizeFResult $ \csizef_ret_w csizef_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_documentSize_qth_h cobj_x0 csizef_ret_w csizef_ret_h instance Qdraw (QAbstractTextDocumentLayout ()) ((QPainter t1, PaintContext t2)) where draw x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractTextDocumentLayout_draw_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QAbstractTextDocumentLayout_draw_h" qtc_QAbstractTextDocumentLayout_draw_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPainter t1) -> Ptr (TPaintContext t2) -> IO () instance Qdraw (QAbstractTextDocumentLayoutSc a) ((QPainter t1, PaintContext t2)) where draw x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractTextDocumentLayout_draw_h cobj_x0 cobj_x1 cobj_x2 class QdrawInlineObject x0 x1 where drawInlineObject :: x0 -> x1 -> IO () class QqdrawInlineObject x0 x1 where qdrawInlineObject :: x0 -> x1 -> IO () instance QqdrawInlineObject (QAbstractTextDocumentLayout ()) ((QPainter t1, QRectF t2, QTextInlineObject t3, Int, QTextFormat t5)) where qdrawInlineObject x0 (x1, x2, x3, x4, x5) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QAbstractTextDocumentLayout_drawInlineObject_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 (toCInt x4) cobj_x5 foreign import ccall "qtc_QAbstractTextDocumentLayout_drawInlineObject_h" qtc_QAbstractTextDocumentLayout_drawInlineObject_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPainter t1) -> Ptr (TQRectF t2) -> Ptr (TQTextInlineObject t3) -> CInt -> Ptr (TQTextFormat t5) -> IO () instance QqdrawInlineObject (QAbstractTextDocumentLayoutSc a) ((QPainter t1, QRectF t2, QTextInlineObject t3, Int, QTextFormat t5)) where qdrawInlineObject x0 (x1, x2, x3, x4, x5) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QAbstractTextDocumentLayout_drawInlineObject_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 (toCInt x4) cobj_x5 instance QdrawInlineObject (QAbstractTextDocumentLayout ()) ((QPainter t1, RectF, QTextInlineObject t3, Int, QTextFormat t5)) where drawInlineObject x0 (x1, x2, x3, x4, x5) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QAbstractTextDocumentLayout_drawInlineObject_qth_h cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h cobj_x3 (toCInt x4) cobj_x5 foreign import ccall "qtc_QAbstractTextDocumentLayout_drawInlineObject_qth_h" qtc_QAbstractTextDocumentLayout_drawInlineObject_qth_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPainter t1) -> CDouble -> CDouble -> CDouble -> CDouble -> Ptr (TQTextInlineObject t3) -> CInt -> Ptr (TQTextFormat t5) -> IO () instance QdrawInlineObject (QAbstractTextDocumentLayoutSc a) ((QPainter t1, RectF, QTextInlineObject t3, Int, QTextFormat t5)) where drawInlineObject x0 (x1, x2, x3, x4, x5) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QAbstractTextDocumentLayout_drawInlineObject_qth_h cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h cobj_x3 (toCInt x4) cobj_x5 instance Qformat (QAbstractTextDocumentLayout ()) ((Int)) (IO (QTextCharFormat ())) where format x0 (x1) = withQTextCharFormatResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_format cobj_x0 (toCInt x1) foreign import ccall "qtc_QAbstractTextDocumentLayout_format" qtc_QAbstractTextDocumentLayout_format :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> IO (Ptr (TQTextCharFormat ())) instance Qformat (QAbstractTextDocumentLayoutSc a) ((Int)) (IO (QTextCharFormat ())) where format x0 (x1) = withQTextCharFormatResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_format cobj_x0 (toCInt x1) class QformatIndex x0 x1 where formatIndex :: x0 -> x1 -> IO (Int) instance QformatIndex (QAbstractTextDocumentLayout ()) ((Int)) where formatIndex x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_formatIndex cobj_x0 (toCInt x1) foreign import ccall "qtc_QAbstractTextDocumentLayout_formatIndex" qtc_QAbstractTextDocumentLayout_formatIndex :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> IO CInt instance QformatIndex (QAbstractTextDocumentLayoutSc a) ((Int)) where formatIndex x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_formatIndex cobj_x0 (toCInt x1) class QframeBoundingRect x0 x1 where frameBoundingRect :: x0 -> x1 -> IO (RectF) class QqframeBoundingRect x0 x1 where qframeBoundingRect :: x0 -> x1 -> IO (QRectF ()) instance QqframeBoundingRect (QAbstractTextDocumentLayout ()) ((QTextFrame t1)) where qframeBoundingRect x0 (x1) = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_frameBoundingRect_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_frameBoundingRect_h" qtc_QAbstractTextDocumentLayout_frameBoundingRect_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextFrame t1) -> IO (Ptr (TQRectF ())) instance QqframeBoundingRect (QAbstractTextDocumentLayoutSc a) ((QTextFrame t1)) where qframeBoundingRect x0 (x1) = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_frameBoundingRect_h cobj_x0 cobj_x1 instance QframeBoundingRect (QAbstractTextDocumentLayout ()) ((QTextFrame t1)) where frameBoundingRect x0 (x1) = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_frameBoundingRect_qth_h cobj_x0 cobj_x1 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h foreign import ccall "qtc_QAbstractTextDocumentLayout_frameBoundingRect_qth_h" qtc_QAbstractTextDocumentLayout_frameBoundingRect_qth_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextFrame t1) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO () instance QframeBoundingRect (QAbstractTextDocumentLayoutSc a) ((QTextFrame t1)) where frameBoundingRect x0 (x1) = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_frameBoundingRect_qth_h cobj_x0 cobj_x1 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h handlerForObject :: QAbstractTextDocumentLayout a -> ((Int)) -> IO (QTextObjectInterface ()) handlerForObject x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_handlerForObject cobj_x0 (toCInt x1) foreign import ccall "qtc_QAbstractTextDocumentLayout_handlerForObject" qtc_QAbstractTextDocumentLayout_handlerForObject :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> IO (Ptr (TQTextObjectInterface ())) class QhitTest x0 x1 where hitTest :: x0 -> x1 -> IO (Int) class QqhitTest x0 x1 where qhitTest :: x0 -> x1 -> IO (Int) instance QhitTest (QAbstractTextDocumentLayout ()) ((PointF, HitTestAccuracy)) where hitTest x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QAbstractTextDocumentLayout_hitTest_qth_h cobj_x0 cpointf_x1_x cpointf_x1_y (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QAbstractTextDocumentLayout_hitTest_qth_h" qtc_QAbstractTextDocumentLayout_hitTest_qth_h :: Ptr (TQAbstractTextDocumentLayout a) -> CDouble -> CDouble -> CLong -> IO CInt instance QhitTest (QAbstractTextDocumentLayoutSc a) ((PointF, HitTestAccuracy)) where hitTest x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QAbstractTextDocumentLayout_hitTest_qth_h cobj_x0 cpointf_x1_x cpointf_x1_y (toCLong $ qEnum_toInt x2) instance QqhitTest (QAbstractTextDocumentLayout ()) ((QPointF t1, HitTestAccuracy)) where qhitTest x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_hitTest_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QAbstractTextDocumentLayout_hitTest_h" qtc_QAbstractTextDocumentLayout_hitTest_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPointF t1) -> CLong -> IO CInt instance QqhitTest (QAbstractTextDocumentLayoutSc a) ((QPointF t1, HitTestAccuracy)) where qhitTest x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_hitTest_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) instance QpageCount (QAbstractTextDocumentLayout ()) (()) where pageCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_pageCount_h cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_pageCount_h" qtc_QAbstractTextDocumentLayout_pageCount_h :: Ptr (TQAbstractTextDocumentLayout a) -> IO CInt instance QpageCount (QAbstractTextDocumentLayoutSc a) (()) where pageCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_pageCount_h cobj_x0 paintDevice :: QAbstractTextDocumentLayout a -> (()) -> IO (QPaintDevice ()) paintDevice x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_paintDevice cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_paintDevice" qtc_QAbstractTextDocumentLayout_paintDevice :: Ptr (TQAbstractTextDocumentLayout a) -> IO (Ptr (TQPaintDevice ())) class QpositionInlineObject x0 x1 where positionInlineObject :: x0 -> x1 -> IO () instance QpositionInlineObject (QAbstractTextDocumentLayout ()) ((QTextInlineObject t1, Int, QTextFormat t3)) where positionInlineObject x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractTextDocumentLayout_positionInlineObject_h cobj_x0 cobj_x1 (toCInt x2) cobj_x3 foreign import ccall "qtc_QAbstractTextDocumentLayout_positionInlineObject_h" qtc_QAbstractTextDocumentLayout_positionInlineObject_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextInlineObject t1) -> CInt -> Ptr (TQTextFormat t3) -> IO () instance QpositionInlineObject (QAbstractTextDocumentLayoutSc a) ((QTextInlineObject t1, Int, QTextFormat t3)) where positionInlineObject x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractTextDocumentLayout_positionInlineObject_h cobj_x0 cobj_x1 (toCInt x2) cobj_x3 registerHandler :: QAbstractTextDocumentLayout a -> ((Int, QObject t2)) -> IO () registerHandler x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractTextDocumentLayout_registerHandler cobj_x0 (toCInt x1) cobj_x2 foreign import ccall "qtc_QAbstractTextDocumentLayout_registerHandler" qtc_QAbstractTextDocumentLayout_registerHandler :: Ptr (TQAbstractTextDocumentLayout a) -> CInt -> Ptr (TQObject t2) -> IO () class QresizeInlineObject x0 x1 where resizeInlineObject :: x0 -> x1 -> IO () instance QresizeInlineObject (QAbstractTextDocumentLayout ()) ((QTextInlineObject t1, Int, QTextFormat t3)) where resizeInlineObject x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractTextDocumentLayout_resizeInlineObject_h cobj_x0 cobj_x1 (toCInt x2) cobj_x3 foreign import ccall "qtc_QAbstractTextDocumentLayout_resizeInlineObject_h" qtc_QAbstractTextDocumentLayout_resizeInlineObject_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTextInlineObject t1) -> CInt -> Ptr (TQTextFormat t3) -> IO () instance QresizeInlineObject (QAbstractTextDocumentLayoutSc a) ((QTextInlineObject t1, Int, QTextFormat t3)) where resizeInlineObject x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QAbstractTextDocumentLayout_resizeInlineObject_h cobj_x0 cobj_x1 (toCInt x2) cobj_x3 class QsetPaintDevice x1 where setPaintDevice :: QAbstractTextDocumentLayout a -> x1 -> IO () instance QsetPaintDevice ((QPaintDevice t1)) where setPaintDevice x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_setPaintDevice cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_setPaintDevice" qtc_QAbstractTextDocumentLayout_setPaintDevice :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQPaintDevice t1) -> IO () instance QsetPaintDevice ((QWidget t1)) where setPaintDevice x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_setPaintDevice_widget cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_setPaintDevice_widget" qtc_QAbstractTextDocumentLayout_setPaintDevice_widget :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQWidget t1) -> IO () qAbstractTextDocumentLayout_delete :: QAbstractTextDocumentLayout a -> IO () qAbstractTextDocumentLayout_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_delete cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_delete" qtc_QAbstractTextDocumentLayout_delete :: Ptr (TQAbstractTextDocumentLayout a) -> IO () qAbstractTextDocumentLayout_deleteLater :: QAbstractTextDocumentLayout a -> IO () qAbstractTextDocumentLayout_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_deleteLater cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_deleteLater" qtc_QAbstractTextDocumentLayout_deleteLater :: Ptr (TQAbstractTextDocumentLayout a) -> IO () instance QchildEvent (QAbstractTextDocumentLayout ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_childEvent" qtc_QAbstractTextDocumentLayout_childEvent :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QAbstractTextDocumentLayoutSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QAbstractTextDocumentLayout ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_connectNotify" qtc_QAbstractTextDocumentLayout_connectNotify :: Ptr (TQAbstractTextDocumentLayout a) -> CWString -> IO () instance QconnectNotify (QAbstractTextDocumentLayoutSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QAbstractTextDocumentLayout ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_customEvent" qtc_QAbstractTextDocumentLayout_customEvent :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QAbstractTextDocumentLayoutSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QAbstractTextDocumentLayout ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_disconnectNotify" qtc_QAbstractTextDocumentLayout_disconnectNotify :: Ptr (TQAbstractTextDocumentLayout a) -> CWString -> IO () instance QdisconnectNotify (QAbstractTextDocumentLayoutSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_disconnectNotify cobj_x0 cstr_x1 instance Qevent (QAbstractTextDocumentLayout ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_event_h" qtc_QAbstractTextDocumentLayout_event_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QAbstractTextDocumentLayoutSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_event_h cobj_x0 cobj_x1 instance QeventFilter (QAbstractTextDocumentLayout ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractTextDocumentLayout_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QAbstractTextDocumentLayout_eventFilter_h" qtc_QAbstractTextDocumentLayout_eventFilter_h :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QAbstractTextDocumentLayoutSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractTextDocumentLayout_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QAbstractTextDocumentLayout ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_receivers" qtc_QAbstractTextDocumentLayout_receivers :: Ptr (TQAbstractTextDocumentLayout a) -> CWString -> IO CInt instance Qreceivers (QAbstractTextDocumentLayoutSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractTextDocumentLayout_receivers cobj_x0 cstr_x1 instance Qsender (QAbstractTextDocumentLayout ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_sender cobj_x0 foreign import ccall "qtc_QAbstractTextDocumentLayout_sender" qtc_QAbstractTextDocumentLayout_sender :: Ptr (TQAbstractTextDocumentLayout a) -> IO (Ptr (TQObject ())) instance Qsender (QAbstractTextDocumentLayoutSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractTextDocumentLayout_sender cobj_x0 instance QtimerEvent (QAbstractTextDocumentLayout ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractTextDocumentLayout_timerEvent" qtc_QAbstractTextDocumentLayout_timerEvent :: Ptr (TQAbstractTextDocumentLayout a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QAbstractTextDocumentLayoutSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractTextDocumentLayout_timerEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QAbstractTextDocumentLayout.hs
Haskell
bsd-2-clause
28,773
{-# LANGUAGE BangPatterns #-} import Control.Concurrent.STM as S import qualified STMContainers.Map as TMap import qualified ListT as LT import qualified Data.ByteString.Char8 as L import Control.Monad import Debug.Trace import System.Random import Control.Concurrent.Async import Options type Key = Int type StoredObject = L.ByteString data Change = Update Key StoredObject | Remove Key deriving (Show, Eq) type AppState = (TMap.Map Key StoredObject, TVar [Change]) traceKey :: [Change] -> [Key] traceKey changes = [ case c of Update key _ -> key Remove key -> key | c <- changes ] update :: AppState -> [Change] -> Bool -> IO AppState update appState !changes useChangeLog = atomically $ do let (tm, changeLog) = appState sequence_ [ case c of Update key val -> do v <- TMap.lookup key tm case v of Nothing -> TMap.insert val key tm Just _ -> return () Remove key -> TMap.delete key tm | c <- changes ] when useChangeLog $ modifyTVar' changeLog (\log_ -> changes ++ log_) -- trace ("processing: " ++ show (traceKey changes)) $ return (tm, changeLog) randString :: Int -> IO L.ByteString randString n = liftM (L.pack . take n . randomRs ('a','z')) newStdGen randStringFake n = return $ L.pack $ replicate n 'z' randInt :: Int -> IO Int randInt n = liftM (fst . randomR (1, n)) newStdGen randUpdateSet :: Int -> IO [Change] randUpdateSet n = do !i <- randInt n replicateM i $ do (!k1, !v1) <- (,) <$> randInt 4000000000 <*> randStringFake 1000 return $ Update k1 v1 updater :: AppState -> Int -> Bool -> IO () updater state changes useChangeLog = replicateM_ changes $ do !changeSet <- randUpdateSet 250 void $ update state changeSet useChangeLog data Opts = Opts Int Int Bool instance Options Opts where defineOptions = pure Opts <*> simpleOption "threads" 10 "Number of threads" <*> simpleOption "changes" 50 "Number of changes" <*> simpleOption "use-change-log" True "Use change log or not" main :: IO () main = runCommand $ \(Opts threads changes useChangeLog) _ -> do initState <- atomically $ (,) <$> TMap.new <*> newTVar [] as <- replicateM threads $ async $ updater initState changes useChangeLog mapM_ wait as -- force all the data to be calculated s <- atomically $ LT.toList $ TMap.stream $ fst initState trace ("length = " ++ show (length s)) $ return ()
lolepezy/rpki-pub-server
test/changeLog/changeLogList.hs
Haskell
bsd-2-clause
2,612
{-# LANGUAGE RecordWildCards #-} -- | A map from hashable keys to values. module Data.DAWG.Gen.HashMap ( Hash (..) , HashMap (..) , empty , lookup , insertUnsafe , lookupUnsafe , deleteUnsafe ) where import Prelude hiding (lookup) -- import Control.Applicative ((<$>), (<*>)) -- import Data.Binary (Binary, Get, put, get) import qualified Data.Map as M import qualified Data.IntMap as I --------------------------------------------------------------- -- Hash Class --------------------------------------------------------------- -- | Class for types which provide hash values. class Ord a => Hash a where hash :: a -> Int instance Hash Int where hash = id instance Hash Bool where hash b = hash $ if b then 1 :: Int else 0 instance Hash a => Hash (Maybe a) where hash (Just x) | h < 0 = h | otherwise = h + 1 where h = hash x hash Nothing = 0 --------------------------------------------------------------- -- HashMap Values --------------------------------------------------------------- -- | Value in a HashMap. data Value a b = Single !a !b | Multi !(M.Map a b) deriving (Show, Eq, Ord) -- | Value Binary instance. -- instance (Ord a, Binary a, Binary b) => Binary (Value a b) where -- put (Single x y) = put (1 :: Int) >> put x >> put y -- put (Multi m) = put (2 :: Int) >> put m -- get = do -- x <- get :: Get Int -- case x of -- 1 -> Single <$> get <*> get -- _ -> Multi <$> get -- | Find element associated to a value key. find :: Ord a => a -> Value a b -> Maybe b find x (Single x' y) = if x == x' then Just y else Nothing find x (Multi m) = M.lookup x m -- | Unsafe `find` version. -- Assumption: element is a member of the 'Value'. findUnsafe :: Ord a => a -> Value a b -> Maybe b findUnsafe _ (Single _ y) = Just y -- unsafe findUnsafe x (Multi m) = M.lookup x m -- | Convert a regular map into a hash value (and into a 'Single' -- form if possible). trySingle :: M.Map a b -> Value a b trySingle m = if M.size m == 1 then uncurry Single (M.findMin m) else Multi m -- | Insert (key, valye) pair into a hash value. embed :: Ord a => a -> b -> Value a b -> Value a b embed x y (Single x' y') = Multi $ M.fromList [(x, y), (x', y')] embed x y (Multi m) = Multi $ M.insert x y m -- | Delete element from a value. Return 'Nothing' if the resultant -- value is empty. It is unsafe because, if the value is -- `Single`, it assumes that it contains the given key. ejectUnsafe :: Ord a => a -> Value a b -> Maybe (Value a b) ejectUnsafe _ (Single _ _) = Nothing -- unsafe ejectUnsafe x (Multi m) = (Just . trySingle) (M.delete x m) --------------------------------------------------------------- -- HashMap --------------------------------------------------------------- -- | A map from /a/ keys to /b/ elements where keys instantiate the -- 'Hash' type class. Key/element pairs are kept in 'Value' objects -- which takes care of potential hash collisions. data HashMap a b = HashMap { size :: {-# UNPACK #-} !Int , hashMap :: !(I.IntMap (Value a b)) } deriving (Show, Eq, Ord) -- instance (Ord a, Binary a, Binary b) => Binary (HashMap a b) where -- put HashMap{..} = put size >> put hashMap -- get = HashMap <$> get <*> get -- | Empty map. empty :: HashMap a b empty = HashMap 0 I.empty -- | Lookup element in the map. lookup :: Hash a => a -> HashMap a b -> Maybe b lookup x (HashMap _ m) = I.lookup (hash x) m >>= find x -- | Unsafe version of `lookup`. -- Assumption: element is present in the map. lookupUnsafe :: Hash a => a -> HashMap a b -> b lookupUnsafe x (HashMap _ m) = fromJust (I.lookup (hash x) m >>= findUnsafe x) -- | Insert a new element. The function doesn't check -- if the element is already present in the map. -- Q: What's the unsafe element? If the only unsafety here is -- that the HashMap size is incremented anyway, maybe it would be -- better to make it safe? insertUnsafe :: Hash a => a -> b -> HashMap a b -> HashMap a b insertUnsafe x y (HashMap n m) = let i = hash x f (Just v) = embed x y v f Nothing = Single x y in HashMap (n + 1) $ I.alter (Just . f) i m -- | Assumption: element is present in the map. deleteUnsafe :: Hash a => a -> HashMap a b -> HashMap a b deleteUnsafe x (HashMap n m) = HashMap (n - 1) $ I.update (ejectUnsafe x) (hash x) m --------------------------------------------------------------- -- Utils --------------------------------------------------------------- -- | A custom version of `fromJust`. fromJust :: Maybe a -> a fromJust (Just x) = x fromJust Nothing = error "fromJust: Nothing" {-# INLINE fromJust #-}
kawu/dawg-ord
src/Data/DAWG/Gen/HashMap.hs
Haskell
bsd-2-clause
4,762
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.OpCodes ( testOpCodes , OpCodes.OpCode(..) ) where import Test.HUnit as HUnit import Test.QuickCheck as QuickCheck import Control.Applicative import Control.Monad import Data.Char import Data.List import qualified Data.Map as Map import qualified Text.JSON as J import Text.Printf (printf) import Test.Ganeti.Objects () import Test.Ganeti.Query.Language () import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.Types (genReasonTrail) import Ganeti.BasicTypes import qualified Ganeti.Constants as C import qualified Ganeti.ConstantUtils as CU import qualified Ganeti.OpCodes as OpCodes import Ganeti.Types import Ganeti.OpParams import Ganeti.JSON {-# ANN module "HLint: ignore Use camelCase" #-} -- * Arbitrary instances arbitraryOpTagsGet :: Gen OpCodes.OpCode arbitraryOpTagsGet = do kind <- arbitrary OpCodes.OpTagsSet kind <$> genTags <*> genOpCodesTagName kind arbitraryOpTagsSet :: Gen OpCodes.OpCode arbitraryOpTagsSet = do kind <- arbitrary OpCodes.OpTagsSet kind <$> genTags <*> genOpCodesTagName kind arbitraryOpTagsDel :: Gen OpCodes.OpCode arbitraryOpTagsDel = do kind <- arbitrary OpCodes.OpTagsDel kind <$> genTags <*> genOpCodesTagName kind $(genArbitrary ''OpCodes.ReplaceDisksMode) $(genArbitrary ''DiskAccess) instance Arbitrary OpCodes.DiskIndex where arbitrary = choose (0, C.maxDisks - 1) >>= OpCodes.mkDiskIndex instance Arbitrary INicParams where arbitrary = INicParams <$> genMaybe genNameNE <*> genMaybe genName <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genName <*> genMaybe genNameNE <*> genMaybe genNameNE instance Arbitrary IDiskParams where arbitrary = IDiskParams <$> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> arbitrary <*> genMaybe genNameNE <*> genAndRestArguments instance Arbitrary RecreateDisksInfo where arbitrary = oneof [ pure RecreateDisksAll , RecreateDisksIndices <$> arbitrary , RecreateDisksParams <$> arbitrary ] instance Arbitrary DdmOldChanges where arbitrary = oneof [ DdmOldIndex <$> arbitrary , DdmOldMod <$> arbitrary ] instance (Arbitrary a) => Arbitrary (SetParamsMods a) where arbitrary = oneof [ pure SetParamsEmpty , SetParamsDeprecated <$> arbitrary , SetParamsNew <$> arbitrary ] instance Arbitrary ExportTarget where arbitrary = oneof [ ExportTargetLocal <$> genNodeNameNE , ExportTargetRemote <$> pure [] ] arbitraryDataCollector :: Gen (Container Bool) arbitraryDataCollector = do els <- listOf . elements $ CU.toList C.dataCollectorNames activation <- vector $ length els return . GenericContainer . Map.fromList $ zip els activation arbitraryDataCollectorInterval :: Gen (Maybe (Container Int)) arbitraryDataCollectorInterval = do els <- listOf . elements $ CU.toList C.dataCollectorNames intervals <- vector $ length els genMaybe . return . containerFromList $ zip els intervals instance Arbitrary OpCodes.OpCode where arbitrary = do op_id <- elements OpCodes.allOpIDs case op_id of "OP_TEST_DELAY" -> OpCodes.OpTestDelay <$> arbitrary <*> arbitrary <*> genNodeNamesNE <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_REPLACE_DISKS" -> OpCodes.OpInstanceReplaceDisks <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> genDiskIndices <*> genMaybe genNodeNameNE <*> return Nothing <*> genMaybe genNameNE "OP_INSTANCE_FAILOVER" -> OpCodes.OpInstanceFailover <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNodeNameNE <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNameNE "OP_INSTANCE_MIGRATE" -> OpCodes.OpInstanceMigrate <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNodeNameNE <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> arbitrary <*> arbitrary "OP_TAGS_GET" -> arbitraryOpTagsGet "OP_TAGS_SEARCH" -> OpCodes.OpTagsSearch <$> genNameNE "OP_TAGS_SET" -> arbitraryOpTagsSet "OP_TAGS_DEL" -> arbitraryOpTagsDel "OP_CLUSTER_POST_INIT" -> pure OpCodes.OpClusterPostInit "OP_CLUSTER_RENEW_CRYPTO" -> OpCodes.OpClusterRenewCrypto <$> arbitrary <*> arbitrary "OP_CLUSTER_DESTROY" -> pure OpCodes.OpClusterDestroy "OP_CLUSTER_QUERY" -> pure OpCodes.OpClusterQuery "OP_CLUSTER_VERIFY" -> OpCodes.OpClusterVerify <$> arbitrary <*> arbitrary <*> genListSet Nothing <*> genListSet Nothing <*> arbitrary <*> genMaybe genNameNE "OP_CLUSTER_VERIFY_CONFIG" -> OpCodes.OpClusterVerifyConfig <$> arbitrary <*> arbitrary <*> genListSet Nothing <*> arbitrary "OP_CLUSTER_VERIFY_GROUP" -> OpCodes.OpClusterVerifyGroup <$> genNameNE <*> arbitrary <*> arbitrary <*> genListSet Nothing <*> genListSet Nothing <*> arbitrary "OP_CLUSTER_VERIFY_DISKS" -> pure OpCodes.OpClusterVerifyDisks "OP_GROUP_VERIFY_DISKS" -> OpCodes.OpGroupVerifyDisks <$> genNameNE "OP_CLUSTER_REPAIR_DISK_SIZES" -> OpCodes.OpClusterRepairDiskSizes <$> genNodeNamesNE "OP_CLUSTER_CONFIG_QUERY" -> OpCodes.OpClusterConfigQuery <$> genFieldsNE "OP_CLUSTER_RENAME" -> OpCodes.OpClusterRename <$> genNameNE "OP_CLUSTER_SET_PARAMS" -> OpCodes.OpClusterSetParams <$> arbitrary -- force <*> emptyMUD -- hv_state <*> emptyMUD -- disk_state <*> genMaybe genName -- vg_name <*> genMaybe arbitrary -- enabled_hypervisors <*> genMaybe genEmptyContainer -- hvparams <*> emptyMUD -- beparams <*> genMaybe genEmptyContainer -- os_hvp <*> genMaybe genEmptyContainer -- osparams <*> genMaybe genEmptyContainer -- osparams_private_cluster <*> genMaybe genEmptyContainer -- diskparams <*> genMaybe arbitrary -- candidate_pool_size <*> genMaybe arbitrary -- max_running_jobs <*> genMaybe arbitrary -- max_tracked_jobs <*> arbitrary -- uid_pool <*> arbitrary -- add_uids <*> arbitrary -- remove_uids <*> arbitrary -- maintain_node_health <*> arbitrary -- prealloc_wipe_disks <*> arbitrary -- nicparams <*> emptyMUD -- ndparams <*> emptyMUD -- ipolicy <*> genMaybe genPrintableAsciiString -- drbd_helper <*> genMaybe genPrintableAsciiString -- default_iallocator <*> emptyMUD -- default_iallocator_params <*> genMaybe genMacPrefix -- mac_prefix <*> genMaybe genPrintableAsciiString -- master_netdev <*> arbitrary -- master_netmask <*> genMaybe (listOf genPrintableAsciiStringNE) -- reserved_lvs <*> genMaybe (listOf ((,) <$> arbitrary <*> genPrintableAsciiStringNE)) -- hidden_os <*> genMaybe (listOf ((,) <$> arbitrary <*> genPrintableAsciiStringNE)) -- blacklisted_os <*> arbitrary -- use_external_mip_script <*> arbitrary -- enabled_disk_templates <*> arbitrary -- modify_etc_hosts <*> genMaybe genName -- file_storage_dir <*> genMaybe genName -- shared_file_storage_dir <*> genMaybe genName -- gluster_file_storage_dir <*> genMaybe genPrintableAsciiString -- install_image <*> genMaybe genPrintableAsciiString -- instance_communication_network <*> genMaybe genPrintableAsciiString -- zeroing_image <*> genMaybe (listOf genPrintableAsciiStringNE) -- compression_tools <*> arbitrary -- enabled_user_shutdown <*> genMaybe arbitraryDataCollector -- enabled_data_collectors <*> arbitraryDataCollectorInterval -- data_collector_interval "OP_CLUSTER_REDIST_CONF" -> pure OpCodes.OpClusterRedistConf "OP_CLUSTER_ACTIVATE_MASTER_IP" -> pure OpCodes.OpClusterActivateMasterIp "OP_CLUSTER_DEACTIVATE_MASTER_IP" -> pure OpCodes.OpClusterDeactivateMasterIp "OP_QUERY" -> OpCodes.OpQuery <$> arbitrary <*> arbitrary <*> genNamesNE <*> pure Nothing "OP_QUERY_FIELDS" -> OpCodes.OpQueryFields <$> arbitrary <*> genMaybe genNamesNE "OP_OOB_COMMAND" -> OpCodes.OpOobCommand <$> genNodeNamesNE <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> (arbitrary `suchThat` (>0)) "OP_NODE_REMOVE" -> OpCodes.OpNodeRemove <$> genNodeNameNE <*> return Nothing "OP_NODE_ADD" -> OpCodes.OpNodeAdd <$> genNodeNameNE <*> emptyMUD <*> emptyMUD <*> genMaybe genNameNE <*> genMaybe genNameNE <*> arbitrary <*> genMaybe genNameNE <*> arbitrary <*> arbitrary <*> emptyMUD <*> arbitrary "OP_NODE_QUERYVOLS" -> OpCodes.OpNodeQueryvols <$> genNamesNE <*> genNodeNamesNE "OP_NODE_QUERY_STORAGE" -> OpCodes.OpNodeQueryStorage <$> genNamesNE <*> arbitrary <*> genNodeNamesNE <*> genMaybe genNameNE "OP_NODE_MODIFY_STORAGE" -> OpCodes.OpNodeModifyStorage <$> genNodeNameNE <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> pure emptyJSObject "OP_REPAIR_NODE_STORAGE" -> OpCodes.OpRepairNodeStorage <$> genNodeNameNE <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> arbitrary "OP_NODE_SET_PARAMS" -> OpCodes.OpNodeSetParams <$> genNodeNameNE <*> return Nothing <*> arbitrary <*> emptyMUD <*> emptyMUD <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> emptyMUD <*> arbitrary "OP_NODE_POWERCYCLE" -> OpCodes.OpNodePowercycle <$> genNodeNameNE <*> return Nothing <*> arbitrary "OP_NODE_MIGRATE" -> OpCodes.OpNodeMigrate <$> genNodeNameNE <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNodeNameNE <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNameNE "OP_NODE_EVACUATE" -> OpCodes.OpNodeEvacuate <$> arbitrary <*> genNodeNameNE <*> return Nothing <*> genMaybe genNodeNameNE <*> return Nothing <*> genMaybe genNameNE <*> arbitrary "OP_INSTANCE_CREATE" -> OpCodes.OpInstanceCreate <$> genFQDN -- instance_name <*> arbitrary -- force_variant <*> arbitrary -- wait_for_sync <*> arbitrary -- name_check <*> arbitrary -- ignore_ipolicy <*> arbitrary -- opportunistic_locking <*> pure emptyJSObject -- beparams <*> arbitrary -- disks <*> arbitrary -- disk_template <*> genMaybe genNameNE -- group_name <*> arbitrary -- file_driver <*> genMaybe genNameNE -- file_storage_dir <*> pure emptyJSObject -- hvparams <*> arbitrary -- hypervisor <*> genMaybe genNameNE -- iallocator <*> arbitrary -- identify_defaults <*> arbitrary -- ip_check <*> arbitrary -- conflicts_check <*> arbitrary -- mode <*> arbitrary -- nics <*> arbitrary -- no_install <*> pure emptyJSObject -- osparams <*> genMaybe arbitraryPrivateJSObj -- osparams_private <*> genMaybe arbitraryPrivateJSObj -- osparams_secret <*> genMaybe genNameNE -- os_type <*> genMaybe genNodeNameNE -- pnode <*> return Nothing -- pnode_uuid <*> genMaybe genNodeNameNE -- snode <*> return Nothing -- snode_uuid <*> genMaybe (pure []) -- source_handshake <*> genMaybe genNodeNameNE -- source_instance_name <*> arbitrary -- source_shutdown_timeout <*> genMaybe genNodeNameNE -- source_x509_ca <*> return Nothing -- src_node <*> genMaybe genNodeNameNE -- src_node_uuid <*> genMaybe genNameNE -- src_path <*> genPrintableAsciiString -- compress <*> arbitrary -- start <*> (genTags >>= mapM mkNonEmpty) -- tags <*> arbitrary -- instance_communication <*> arbitrary -- helper_startup_timeout <*> arbitrary -- helper_shutdown_timeout "OP_INSTANCE_MULTI_ALLOC" -> OpCodes.OpInstanceMultiAlloc <$> arbitrary <*> genMaybe genNameNE <*> pure [] "OP_INSTANCE_REINSTALL" -> OpCodes.OpInstanceReinstall <$> genFQDN <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> genMaybe (pure emptyJSObject) <*> genMaybe arbitraryPrivateJSObj <*> genMaybe arbitraryPrivateJSObj "OP_INSTANCE_REMOVE" -> OpCodes.OpInstanceRemove <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary "OP_INSTANCE_RENAME" -> OpCodes.OpInstanceRename <$> genFQDN <*> return Nothing <*> genNodeNameNE <*> arbitrary <*> arbitrary "OP_INSTANCE_STARTUP" -> OpCodes.OpInstanceStartup <$> genFQDN <*> -- instance_name return Nothing <*> -- instance_uuid arbitrary <*> -- force arbitrary <*> -- ignore_offline_nodes pure emptyJSObject <*> -- hvparams pure emptyJSObject <*> -- beparams arbitrary <*> -- no_remember arbitrary <*> -- startup_paused arbitrary -- shutdown_timeout "OP_INSTANCE_SHUTDOWN" -> OpCodes.OpInstanceShutdown <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_REBOOT" -> OpCodes.OpInstanceReboot <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_MOVE" -> OpCodes.OpInstanceMove <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> genNodeNameNE <*> return Nothing <*> genPrintableAsciiString <*> arbitrary "OP_INSTANCE_CONSOLE" -> OpCodes.OpInstanceConsole <$> genFQDN <*> return Nothing "OP_INSTANCE_ACTIVATE_DISKS" -> OpCodes.OpInstanceActivateDisks <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary "OP_INSTANCE_DEACTIVATE_DISKS" -> OpCodes.OpInstanceDeactivateDisks <$> genFQDN <*> return Nothing <*> arbitrary "OP_INSTANCE_RECREATE_DISKS" -> OpCodes.OpInstanceRecreateDisks <$> genFQDN <*> return Nothing <*> arbitrary <*> genNodeNamesNE <*> return Nothing <*> genMaybe genNameNE "OP_INSTANCE_QUERY_DATA" -> OpCodes.OpInstanceQueryData <$> arbitrary <*> genNodeNamesNE <*> arbitrary "OP_INSTANCE_SET_PARAMS" -> OpCodes.OpInstanceSetParams <$> genFQDN -- instance_name <*> return Nothing -- instance_uuid <*> arbitrary -- force <*> arbitrary -- force_variant <*> arbitrary -- ignore_ipolicy <*> arbitrary -- nics <*> arbitrary -- disks <*> pure emptyJSObject -- beparams <*> arbitrary -- runtime_mem <*> pure emptyJSObject -- hvparams <*> arbitrary -- disk_template <*> pure emptyJSObject -- ext_params <*> arbitrary -- file_driver <*> genMaybe genNameNE -- file_storage_dir <*> genMaybe genNodeNameNE -- pnode <*> return Nothing -- pnode_uuid <*> genMaybe genNodeNameNE -- remote_node <*> return Nothing -- remote_node_uuid <*> genMaybe genNameNE -- os_name <*> pure emptyJSObject -- osparams <*> genMaybe arbitraryPrivateJSObj -- osparams_private <*> arbitrary -- wait_for_sync <*> arbitrary -- offline <*> arbitrary -- conflicts_check <*> arbitrary -- hotplug <*> arbitrary -- hotplug_if_possible <*> arbitrary -- instance_communication "OP_INSTANCE_GROW_DISK" -> OpCodes.OpInstanceGrowDisk <$> genFQDN <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_CHANGE_GROUP" -> OpCodes.OpInstanceChangeGroup <$> genFQDN <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> genMaybe (resize maxNodes (listOf genNameNE)) "OP_GROUP_ADD" -> OpCodes.OpGroupAdd <$> genNameNE <*> arbitrary <*> emptyMUD <*> genMaybe genEmptyContainer <*> emptyMUD <*> emptyMUD <*> emptyMUD "OP_GROUP_ASSIGN_NODES" -> OpCodes.OpGroupAssignNodes <$> genNameNE <*> arbitrary <*> genNodeNamesNE <*> return Nothing "OP_GROUP_SET_PARAMS" -> OpCodes.OpGroupSetParams <$> genNameNE <*> arbitrary <*> emptyMUD <*> genMaybe genEmptyContainer <*> emptyMUD <*> emptyMUD <*> emptyMUD "OP_GROUP_REMOVE" -> OpCodes.OpGroupRemove <$> genNameNE "OP_GROUP_RENAME" -> OpCodes.OpGroupRename <$> genNameNE <*> genNameNE "OP_GROUP_EVACUATE" -> OpCodes.OpGroupEvacuate <$> genNameNE <*> arbitrary <*> genMaybe genNameNE <*> genMaybe genNamesNE <*> arbitrary <*> arbitrary "OP_OS_DIAGNOSE" -> OpCodes.OpOsDiagnose <$> genFieldsNE <*> genNamesNE "OP_EXT_STORAGE_DIAGNOSE" -> OpCodes.OpOsDiagnose <$> genFieldsNE <*> genNamesNE "OP_BACKUP_PREPARE" -> OpCodes.OpBackupPrepare <$> genFQDN <*> return Nothing <*> arbitrary "OP_BACKUP_EXPORT" -> OpCodes.OpBackupExport <$> genFQDN <*> return Nothing <*> genPrintableAsciiString <*> arbitrary <*> arbitrary <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> genMaybe (pure []) <*> genMaybe genNameNE <*> arbitrary <*> arbitrary <*> arbitrary "OP_BACKUP_REMOVE" -> OpCodes.OpBackupRemove <$> genFQDN <*> return Nothing "OP_TEST_ALLOCATOR" -> OpCodes.OpTestAllocator <$> arbitrary <*> arbitrary <*> genNameNE <*> genMaybe (pure []) <*> genMaybe (pure []) <*> arbitrary <*> genMaybe genNameNE <*> (genTags >>= mapM mkNonEmpty) <*> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> arbitrary <*> genMaybe genNodeNamesNE <*> arbitrary <*> genMaybe genNamesNE <*> arbitrary <*> arbitrary <*> genMaybe genNameNE "OP_TEST_JQUEUE" -> OpCodes.OpTestJqueue <$> arbitrary <*> arbitrary <*> resize 20 (listOf genFQDN) <*> arbitrary "OP_TEST_DUMMY" -> OpCodes.OpTestDummy <$> pure J.JSNull <*> pure J.JSNull <*> pure J.JSNull <*> pure J.JSNull "OP_NETWORK_ADD" -> OpCodes.OpNetworkAdd <$> genNameNE <*> genIPv4Network <*> genMaybe genIPv4Address <*> pure Nothing <*> pure Nothing <*> genMaybe genMacPrefix <*> genMaybe (listOf genIPv4Address) <*> arbitrary <*> (genTags >>= mapM mkNonEmpty) "OP_NETWORK_REMOVE" -> OpCodes.OpNetworkRemove <$> genNameNE <*> arbitrary "OP_NETWORK_SET_PARAMS" -> OpCodes.OpNetworkSetParams <$> genNameNE <*> genMaybe genIPv4Address <*> pure Nothing <*> pure Nothing <*> genMaybe genMacPrefix <*> genMaybe (listOf genIPv4Address) <*> genMaybe (listOf genIPv4Address) "OP_NETWORK_CONNECT" -> OpCodes.OpNetworkConnect <$> genNameNE <*> genNameNE <*> arbitrary <*> genNameNE <*> genPrintableAsciiString <*> arbitrary "OP_NETWORK_DISCONNECT" -> OpCodes.OpNetworkDisconnect <$> genNameNE <*> genNameNE "OP_RESTRICTED_COMMAND" -> OpCodes.OpRestrictedCommand <$> arbitrary <*> genNodeNamesNE <*> return Nothing <*> genNameNE _ -> fail $ "Undefined arbitrary for opcode " ++ op_id instance Arbitrary OpCodes.CommonOpParams where arbitrary = OpCodes.CommonOpParams <$> arbitrary <*> arbitrary <*> arbitrary <*> resize 5 arbitrary <*> genMaybe genName <*> genReasonTrail -- * Helper functions -- | Empty JSObject. emptyJSObject :: J.JSObject J.JSValue emptyJSObject = J.toJSObject [] -- | Empty maybe unchecked dictionary. emptyMUD :: Gen (Maybe (J.JSObject J.JSValue)) emptyMUD = genMaybe $ pure emptyJSObject -- | Generates an empty container. genEmptyContainer :: (Ord a) => Gen (GenericContainer a b) genEmptyContainer = pure . GenericContainer $ Map.fromList [] -- | Generates list of disk indices. genDiskIndices :: Gen [DiskIndex] genDiskIndices = do cnt <- choose (0, C.maxDisks) genUniquesList cnt arbitrary -- | Generates a list of node names. genNodeNames :: Gen [String] genNodeNames = resize maxNodes (listOf genFQDN) -- | Generates a list of node names in non-empty string type. genNodeNamesNE :: Gen [NonEmptyString] genNodeNamesNE = genNodeNames >>= mapM mkNonEmpty -- | Gets a node name in non-empty type. genNodeNameNE :: Gen NonEmptyString genNodeNameNE = genFQDN >>= mkNonEmpty -- | Gets a name (non-fqdn) in non-empty type. genNameNE :: Gen NonEmptyString genNameNE = genName >>= mkNonEmpty -- | Gets a list of names (non-fqdn) in non-empty type. genNamesNE :: Gen [NonEmptyString] genNamesNE = resize maxNodes (listOf genNameNE) -- | Returns a list of non-empty fields. genFieldsNE :: Gen [NonEmptyString] genFieldsNE = genFields >>= mapM mkNonEmpty -- | Generate a 3-byte MAC prefix. genMacPrefix :: Gen NonEmptyString genMacPrefix = do octets <- vectorOf 3 $ choose (0::Int, 255) mkNonEmpty . intercalate ":" $ map (printf "%02x") octets -- | JSObject of arbitrary data. -- -- Since JSValue does not implement Arbitrary, I'll simply generate -- (String, String) objects. arbitraryPrivateJSObj :: Gen (J.JSObject (Private J.JSValue)) arbitraryPrivateJSObj = constructor <$> (fromNonEmpty <$> genNameNE) <*> (fromNonEmpty <$> genNameNE) where constructor k v = showPrivateJSObject [(k, v)] -- | Arbitrary instance for MetaOpCode, defined here due to TH ordering. $(genArbitrary ''OpCodes.MetaOpCode) -- | Small helper to check for a failed JSON deserialisation isJsonError :: J.Result a -> Bool isJsonError (J.Error _) = True isJsonError _ = False -- * Test cases -- | Check that opcode serialization is idempotent. prop_serialization :: OpCodes.OpCode -> Property prop_serialization = testSerialisation -- | Check that Python and Haskell defined the same opcode list. case_AllDefined :: HUnit.Assertion case_AllDefined = do py_stdout <- runPython "from ganeti import opcodes\n\ \from ganeti import serializer\n\ \import sys\n\ \print serializer.Dump([opid for opid in opcodes.OP_MAPPING])\n" "" >>= checkPythonResult py_ops <- case J.decode py_stdout::J.Result [String] of J.Ok ops -> return ops J.Error msg -> HUnit.assertFailure ("Unable to decode opcode names: " ++ msg) -- this already raised an expection, but we need it -- for proper types >> fail "Unable to decode opcode names" let hs_ops = sort OpCodes.allOpIDs extra_py = py_ops \\ hs_ops extra_hs = hs_ops \\ py_ops HUnit.assertBool ("Missing OpCodes from the Haskell code:\n" ++ unlines extra_py) (null extra_py) HUnit.assertBool ("Extra OpCodes in the Haskell code code:\n" ++ unlines extra_hs) (null extra_hs) -- | Custom HUnit test case that forks a Python process and checks -- correspondence between Haskell-generated OpCodes and their Python -- decoded, validated and re-encoded version. -- -- Note that we have a strange beast here: since launching Python is -- expensive, we don't do this via a usual QuickProperty, since that's -- slow (I've tested it, and it's indeed quite slow). Rather, we use a -- single HUnit assertion, and in it we manually use QuickCheck to -- generate 500 opcodes times the number of defined opcodes, which -- then we pass in bulk to Python. The drawbacks to this method are -- two fold: we cannot control the number of generated opcodes, since -- HUnit assertions don't get access to the test options, and for the -- same reason we can't run a repeatable seed. We should probably find -- a better way to do this, for example by having a -- separately-launched Python process (if not running the tests would -- be skipped). case_py_compat_types :: HUnit.Assertion case_py_compat_types = do let num_opcodes = length OpCodes.allOpIDs * 100 opcodes <- genSample (vectorOf num_opcodes (arbitrary::Gen OpCodes.MetaOpCode)) let with_sum = map (\o -> (OpCodes.opSummary $ OpCodes.metaOpCode o, o)) opcodes serialized = J.encode opcodes -- check for non-ASCII fields, usually due to 'arbitrary :: String' mapM_ (\op -> when (any (not . isAscii) (J.encode op)) . HUnit.assertFailure $ "OpCode has non-ASCII fields: " ++ show op ) opcodes py_stdout <- runPython "from ganeti import opcodes\n\ \from ganeti import serializer\n\ \import sys\n\ \op_data = serializer.Load(sys.stdin.read())\n\ \decoded = [opcodes.OpCode.LoadOpCode(o) for o in op_data]\n\ \for op in decoded:\n\ \ op.Validate(True)\n\ \encoded = [(op.Summary(), op.__getstate__())\n\ \ for op in decoded]\n\ \print serializer.Dump(\ \ encoded,\ \ private_encoder=serializer.EncodeWithPrivateFields)" serialized >>= checkPythonResult let deserialised = J.decode py_stdout::J.Result [(String, OpCodes.MetaOpCode)] decoded <- case deserialised of J.Ok ops -> return ops J.Error msg -> HUnit.assertFailure ("Unable to decode opcodes: " ++ msg) -- this already raised an expection, but we need it -- for proper types >> fail "Unable to decode opcodes" HUnit.assertEqual "Mismatch in number of returned opcodes" (length decoded) (length with_sum) mapM_ (uncurry (HUnit.assertEqual "Different result after encoding/decoding") ) $ zip with_sum decoded -- | Custom HUnit test case that forks a Python process and checks -- correspondence between Haskell OpCodes fields and their Python -- equivalent. case_py_compat_fields :: HUnit.Assertion case_py_compat_fields = do let hs_fields = sort $ map (\op_id -> (op_id, OpCodes.allOpFields op_id)) OpCodes.allOpIDs py_stdout <- runPython "from ganeti import opcodes\n\ \import sys\n\ \from ganeti import serializer\n\ \fields = [(k, sorted([p[0] for p in v.OP_PARAMS]))\n\ \ for k, v in opcodes.OP_MAPPING.items()]\n\ \print serializer.Dump(fields)" "" >>= checkPythonResult let deserialised = J.decode py_stdout::J.Result [(String, [String])] py_fields <- case deserialised of J.Ok v -> return $ sort v J.Error msg -> HUnit.assertFailure ("Unable to decode op fields: " ++ msg) -- this already raised an expection, but we need it -- for proper types >> fail "Unable to decode op fields" HUnit.assertEqual "Mismatch in number of returned opcodes" (length hs_fields) (length py_fields) HUnit.assertEqual "Mismatch in defined OP_IDs" (map fst hs_fields) (map fst py_fields) mapM_ (\((py_id, py_flds), (hs_id, hs_flds)) -> do HUnit.assertEqual "Mismatch in OP_ID" py_id hs_id HUnit.assertEqual ("Mismatch in fields for " ++ hs_id) py_flds hs_flds ) $ zip hs_fields py_fields -- | Checks that setOpComment works correctly. prop_setOpComment :: OpCodes.MetaOpCode -> String -> Property prop_setOpComment op comment = let (OpCodes.MetaOpCode common _) = OpCodes.setOpComment comment op in OpCodes.opComment common ==? Just comment -- | Tests wrong (negative) disk index. prop_mkDiskIndex_fail :: QuickCheck.Positive Int -> Property prop_mkDiskIndex_fail (Positive i) = case mkDiskIndex (negate i) of Bad msg -> printTestCase "error message " $ "Invalid value" `isPrefixOf` msg Ok v -> failTest $ "Succeeded to build disk index '" ++ show v ++ "' from negative value " ++ show (negate i) -- | Tests a few invalid 'readRecreateDisks' cases. case_readRecreateDisks_fail :: Assertion case_readRecreateDisks_fail = do assertBool "null" $ isJsonError (J.readJSON J.JSNull::J.Result RecreateDisksInfo) assertBool "string" $ isJsonError (J.readJSON (J.showJSON "abc")::J.Result RecreateDisksInfo) -- | Tests a few invalid 'readDdmOldChanges' cases. case_readDdmOldChanges_fail :: Assertion case_readDdmOldChanges_fail = do assertBool "null" $ isJsonError (J.readJSON J.JSNull::J.Result DdmOldChanges) assertBool "string" $ isJsonError (J.readJSON (J.showJSON "abc")::J.Result DdmOldChanges) -- | Tests a few invalid 'readExportTarget' cases. case_readExportTarget_fail :: Assertion case_readExportTarget_fail = do assertBool "null" $ isJsonError (J.readJSON J.JSNull::J.Result ExportTarget) assertBool "int" $ isJsonError (J.readJSON (J.showJSON (5::Int))::J.Result ExportTarget) testSuite "OpCodes" [ 'prop_serialization , 'case_AllDefined , 'case_py_compat_types , 'case_py_compat_fields , 'prop_setOpComment , 'prop_mkDiskIndex_fail , 'case_readRecreateDisks_fail , 'case_readDdmOldChanges_fail , 'case_readExportTarget_fail ]
ganeti-github-testing/ganeti-test-1
test/hs/Test/Ganeti/OpCodes.hs
Haskell
bsd-2-clause
33,826
-- 228 import Data.List(sort) import Euler(splitOn) parseTris [] = [] parseTris (x:xs) = t : parseTris xs where xy = map read $ splitOn ',' x t = sort $ zipWith toTheta (map (xy!!) [0,2,4]) (map (xy!!) [1,3,5]) toTheta a b = atan2 b a containsOrigin xs | length xs /= 3 = error "containsOrigin: length" | otherwise = all (\x -> -pi < x && x < pi) [b-a, c-b, a-c+2*pi] where [a,b,c] = take 3 xs numWithOrigin ws = length $ filter id os where ts = parseTris ws os = map containsOrigin ts main = do contents <- readFile "../files/p102_triangles.txt" putStrLn $ show $ numWithOrigin $ lines contents
higgsd/euler
hs/102.hs
Haskell
bsd-2-clause
658
{-# LANGUAGE OverloadedStrings #-} module Appoint.Users where import Control.Lens import Control.Monad.Reader import Data.Monoid ((<>)) import Appoint.Types.Config import Appoint.Types.Users (User(..), Collaborators(..)) import qualified Data.Text as T import qualified Data.Vector as V import qualified GitHub.Data as GitHub import qualified GitHub.Endpoints.Repos.Collaborators as GitHub collaboratorsOn :: ReaderT Config IO (Either GitHub.Error (V.Vector GitHub.SimpleUser)) collaboratorsOn = do config <- ask liftIO $ GitHub.collaboratorsOn' (config ^. cAuth) (config ^. cOwner) (config ^. cRepo) mkUser :: GitHub.SimpleUser -> User mkUser u = User { userName = gitHubUserName u , profileURL = GitHub.getUrl (GitHub.simpleUserUrl u) } gitHubUserName :: GitHub.SimpleUser -> T.Text gitHubUserName = GitHub.untagName . GitHub.simpleUserLogin mkCollaborators :: GitHub.Name GitHub.Owner -> GitHub.Name GitHub.Repo -> [GitHub.SimpleUser] -> [Collaborators] mkCollaborators name' repo' users' = [ Collaborators { _path = GitHub.untagName name' <> "/" <> GitHub.untagName repo' , _users = map mkUser users' }]
rob-b/appoint
src/Appoint/Users.hs
Haskell
bsd-3-clause
1,168
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} module Futhark.Pass.ExtractKernels.BlockedKernel ( blockedReduction , blockedReductionStream , blockedMap , blockedScan , blockedSegmentedScan , blockedKernelSize , chunkLambda , mapKernel , mapKernelFromBody , KernelInput(..) , mapKernelSkeleton , newKernelSpace ) where import Control.Applicative import Control.Monad import Data.Maybe import Data.Monoid import qualified Data.HashMap.Lazy as HM import qualified Data.HashSet as HS import Prelude import Futhark.Representation.Kernels import Futhark.MonadFreshNames import Futhark.Tools import Futhark.Transform.Rename import Futhark.Transform.FirstOrderTransform (doLoopMapAccumL) import Futhark.Representation.AST.Attributes.Aliases import qualified Futhark.Analysis.Alias as Alias import Futhark.Util blockedReductionStream :: (MonadFreshNames m, HasScope Kernels m) => Pattern -> Certificates -> SubExp -> Commutativity -> Lambda -> Lambda -> [SubExp] -> [VName] -> m [Binding] blockedReductionStream pat cs w comm reduce_lam fold_lam nes arrs = runBinder_ $ do step_one_size <- blockedKernelSize w let one = constant (1 :: Int32) num_chunks = kernelWorkgroups step_one_size let (acc_idents, arr_idents) = splitAt (length nes) $ patternIdents pat step_one_pat <- basicPattern' [] <$> ((++) <$> mapM (mkIntermediateIdent num_chunks) acc_idents <*> pure arr_idents) let (_fold_chunk_param, _fold_acc_params, _fold_inp_params) = partitionChunkedFoldParameters (length nes) $ lambdaParams fold_lam fold_lam' <- kerneliseLambda nes fold_lam my_index <- newVName "my_index" other_offset <- newVName "other_offset" let my_index_param = Param my_index (Prim int32) other_offset_param = Param other_offset (Prim int32) reduce_lam' = reduce_lam { lambdaParams = my_index_param : other_offset_param : lambdaParams reduce_lam } params_to_arrs = zip (map paramName $ drop 1 $ lambdaParams fold_lam') arrs consumedArray v = fromMaybe v $ lookup v params_to_arrs consumed_in_fold = HS.map consumedArray $ consumedByLambda $ Alias.analyseLambda fold_lam arrs_copies <- forM arrs $ \arr -> if arr `HS.member` consumed_in_fold then letExp (baseString arr <> "_copy") $ PrimOp $ Copy arr else return arr step_one <- chunkedReduceKernel cs w step_one_size comm reduce_lam' fold_lam' nes arrs_copies addBinding =<< renameBinding (Let step_one_pat () $ Op step_one) step_two_pat <- basicPattern' [] <$> mapM (mkIntermediateIdent $ constant (1 :: Int32)) acc_idents let step_two_size = KernelSize one num_chunks one num_chunks one num_chunks step_two <- reduceKernel [] step_two_size reduce_lam' nes $ take (length nes) $ patternNames step_one_pat addBinding $ Let step_two_pat () $ Op step_two forM_ (zip (patternNames step_two_pat) (patternIdents pat)) $ \(arr, x) -> addBinding $ mkLet' [] [x] $ PrimOp $ Index [] arr [constant (0 :: Int32)] where mkIntermediateIdent chunk_size ident = newIdent (baseString $ identName ident) $ arrayOfRow (identType ident) chunk_size chunkedReduceKernel :: (MonadBinder m, Lore m ~ Kernels) => Certificates -> SubExp -> KernelSize -> Commutativity -> Lambda -> Lambda -> [SubExp] -> [VName] -> m (Kernel Kernels) chunkedReduceKernel cs w step_one_size comm reduce_lam' fold_lam' nes arrs = do let ordering = case comm of Commutative -> Disorder Noncommutative -> InOrder group_size = kernelWorkgroupSize step_one_size num_nonconcat = length nes (chunk_red_pes, chunk_map_pes, chunk_and_fold) <- blockedPerThread w step_one_size ordering fold_lam' num_nonconcat arrs space <- newKernelSpace (kernelWorkgroups step_one_size, group_size, kernelNumThreads step_one_size) [] let red_ts = map patElemType chunk_red_pes map_ts = map (rowType . patElemType) chunk_map_pes ts = red_ts ++ map_ts chunk_red_pes' <- forM red_ts $ \red_t -> do pe_name <- newVName "chunk_fold_red" return $ PatElem pe_name BindVar $ red_t `arrayOfRow` group_size let combine_reds = [ Combine pe' [(spaceLocalId space, group_size)] $ Var $ patElemName pe | (pe', pe) <- zip chunk_red_pes' chunk_red_pes ] final_red_pes <- forM (lambdaReturnType reduce_lam') $ \t -> do pe_name <- newVName "final_result" return $ PatElem pe_name BindVar t let reduce_chunk = GroupReduce final_red_pes group_size reduce_lam' $ zip nes $ map patElemName chunk_red_pes' red_rets <- forM final_red_pes $ \pe -> return $ ThreadsReturn (OneThreadPerGroup (constant (0::Int32))) $ Var $ patElemName pe map_rets <- forM chunk_map_pes $ \pe -> return $ ConcatReturns ordering w (kernelElementsPerThread step_one_size) $ patElemName pe let rets = red_rets ++ map_rets return $ Kernel cs space ts $ KernelBody (chunk_and_fold++combine_reds++[reduce_chunk]) rets reduceKernel :: (MonadBinder m, Lore m ~ Kernels) => Certificates -> KernelSize -> Lambda -> [SubExp] -> [VName] -> m (Kernel Kernels) reduceKernel cs step_two_size reduce_lam' nes arrs = do let group_size = kernelWorkgroupSize step_two_size red_ts = lambdaReturnType reduce_lam' space <- newKernelSpace (kernelWorkgroups step_two_size, group_size, kernelNumThreads step_two_size) [] let thread_id = spaceGlobalId space (copy_input, arrs_index) <- fmap unzip $ forM (zip red_ts arrs) $ \(t, arr) -> do arr_index <- newVName (baseString arr ++ "_index") return (Thread AllThreads $ Let (Pattern [] [PatElem arr_index BindVar t]) () $ PrimOp $ Index [] arr [Var thread_id] , arr_index) (combine_arrs, arrs') <- fmap unzip $ forM (zip red_ts arrs_index) $ \(red_t, arr_index) -> do arr' <- newVName $ baseString arr_index ++ "_combined" let pe = PatElem arr' BindVar $ red_t `arrayOfRow` group_size return (Combine pe [(spaceLocalId space, group_size)] (Var arr_index), arr') final_res_pes <- forM (lambdaReturnType reduce_lam') $ \t -> do pe_name <- newVName "final_result" return $ PatElem pe_name BindVar t let reduce = GroupReduce final_res_pes group_size reduce_lam' $ zip nes arrs' rets <- forM final_res_pes $ \pe -> return $ ThreadsReturn (OneThreadPerGroup (constant (0::Int32))) $ Var $ patElemName pe return $ Kernel cs space (lambdaReturnType reduce_lam') $ KernelBody (copy_input++combine_arrs++[reduce]) rets chunkLambda :: (MonadFreshNames m, HasScope Kernels m) => Pattern -> [SubExp] -> Lambda -> m Lambda chunkLambda pat nes fold_lam = do chunk_size <- newVName "chunk_size" let arr_idents = drop (length nes) $ patternIdents pat (fold_acc_params, fold_arr_params) = splitAt (length nes) $ lambdaParams fold_lam chunk_size_param = Param chunk_size (Prim int32) arr_chunk_params <- mapM (mkArrChunkParam $ Var chunk_size) fold_arr_params map_arr_params <- forM arr_idents $ \arr -> newParam (baseString (identName arr) <> "_in") $ setOuterSize (identType arr) (Var chunk_size) fold_acc_params' <- forM fold_acc_params $ \p -> newParam (baseString $ paramName p) $ paramType p let param_scope = scopeOfLParams $ fold_acc_params' ++ arr_chunk_params ++ map_arr_params (seq_loop, seq_loop_prologue) <- runBinder $ localScope param_scope $ doLoopMapAccumL [] (Var chunk_size) (Alias.analyseLambda fold_lam) (map (Var . paramName) fold_acc_params') (map paramName arr_chunk_params) (map paramName map_arr_params) dummys <- mapM (newIdent "dummy" . paramType) arr_chunk_params let seq_rt = let (acc_ts, arr_ts) = splitAt (length nes) $ lambdaReturnType fold_lam in acc_ts ++ map (`arrayOfRow` Var chunk_size) arr_ts res_idents = zipWith Ident (patternValueNames pat) seq_rt seq_loop_bnd = mkLet' [] (dummys++res_idents) seq_loop seq_body = mkBody (seq_loop_prologue++[seq_loop_bnd]) $ map (Var . identName) res_idents return Lambda { lambdaParams = chunk_size_param : fold_acc_params' ++ arr_chunk_params ++ map_arr_params , lambdaReturnType = seq_rt , lambdaBody = seq_body } where mkArrChunkParam chunk_size arr_param = newParam (baseString (paramName arr_param) <> "_chunk") $ arrayOfRow (paramType arr_param) chunk_size -- | Given a chunked fold lambda that takes its initial accumulator -- value as parameters, bind those parameters to the neutral element -- instead. Also fix the index computation. kerneliseLambda :: MonadFreshNames m => [SubExp] -> Lambda -> m Lambda kerneliseLambda nes lam = do thread_index <- newVName "thread_index" let thread_index_param = Param thread_index $ Prim int32 (fold_chunk_param, fold_acc_params, fold_inp_params) = partitionChunkedFoldParameters (length nes) $ lambdaParams lam mkAccInit p (Var v) | not $ primType $ paramType p = mkLet' [] [paramIdent p] $ PrimOp $ Copy v mkAccInit p x = mkLet' [] [paramIdent p] $ PrimOp $ SubExp x acc_init_bnds = zipWith mkAccInit fold_acc_params nes return lam { lambdaBody = insertBindings acc_init_bnds $ lambdaBody lam , lambdaParams = thread_index_param : fold_chunk_param : fold_inp_params } blockedReduction :: (MonadFreshNames m, HasScope Kernels m) => Pattern -> Certificates -> SubExp -> Commutativity -> Lambda -> Lambda -> [SubExp] -> [VName] -> m [Binding] blockedReduction pat cs w comm reduce_lam fold_lam nes arrs = runBinder_ $ do fold_lam' <- chunkLambda pat nes fold_lam let arr_idents = drop (length nes) $ patternIdents pat map_out_arrs <- forM arr_idents $ \(Ident name t) -> letExp (baseString name <> "_out_in") $ PrimOp $ Scratch (elemType t) (arrayDims t) mapM_ addBinding =<< blockedReductionStream pat cs w comm reduce_lam fold_lam' nes (arrs ++ map_out_arrs) blockedMap :: (MonadFreshNames m, HasScope Kernels m) => Pattern -> Certificates -> SubExp -> StreamOrd -> Lambda -> [SubExp] -> [VName] -> m (Binding, [Binding]) blockedMap concat_pat cs w ordering lam nes arrs = runBinder $ do kernel_size <- blockedKernelSize w let num_nonconcat = length (lambdaReturnType lam) - patternSize concat_pat num_groups = kernelWorkgroups kernel_size group_size = kernelWorkgroupSize kernel_size num_threads = kernelNumThreads kernel_size lam' <- kerneliseLambda nes lam (chunk_red_pes, chunk_map_pes, chunk_and_fold) <- blockedPerThread w kernel_size ordering lam' num_nonconcat arrs nonconcat_pat <- fmap (Pattern []) $ forM (take num_nonconcat $ lambdaReturnType lam) $ \t -> do name <- newVName "nonconcat" return $ PatElem name BindVar $ t `arrayOfRow` num_threads let pat = nonconcat_pat <> concat_pat ts = map patElemType chunk_red_pes ++ map (rowType . patElemType) chunk_map_pes nonconcat_rets <- forM chunk_red_pes $ \pe -> return $ ThreadsReturn AllThreads $ Var $ patElemName pe concat_rets <- forM chunk_map_pes $ \pe -> return $ ConcatReturns ordering w (kernelElementsPerThread kernel_size) $ patElemName pe space <- newKernelSpace (num_groups, group_size, num_threads) [] return $ Let pat () $ Op $ Kernel cs space ts $ KernelBody chunk_and_fold $ nonconcat_rets ++ concat_rets blockedPerThread :: MonadFreshNames m => SubExp -> KernelSize -> StreamOrd -> Lambda -> Int -> [VName] -> m ([PatElem], [PatElem], [KernelStm Kernels]) blockedPerThread w kernel_size ordering lam num_nonconcat arrs = do let (_, chunk_size, [], arr_params) = partitionChunkedKernelFoldParameters 0 $ lambdaParams lam split_bound <- forM arr_params $ \arr_param -> do let chunk_t = paramType arr_param `setOuterSize` Var (paramName chunk_size) return $ PatElem (paramName arr_param) BindVar chunk_t let chunk_stm = SplitArray (paramName chunk_size, split_bound) ordering w (kernelElementsPerThread kernel_size) arrs red_ts = take num_nonconcat $ lambdaReturnType lam map_ts = map rowType $ drop num_nonconcat $ lambdaReturnType lam chunk_red_pes <- forM red_ts $ \red_t -> do pe_name <- newVName "chunk_fold_red" return $ PatElem pe_name BindVar red_t chunk_map_pes <- forM map_ts $ \map_t -> do pe_name <- newVName "chunk_fold_map" return $ PatElem pe_name BindVar $ map_t `arrayOfRow` Var (paramName chunk_size) let (chunk_red_ses, chunk_map_ses) = splitAt num_nonconcat $ bodyResult $ lambdaBody lam fold_chunk = map (Thread AllThreads) (bodyBindings (lambdaBody lam)) ++ [ Thread AllThreads $ Let (Pattern [] [pe]) () $ PrimOp $ SubExp se | (pe,se) <- zip chunk_red_pes chunk_red_ses ] ++ [ Thread AllThreads $ Let (Pattern [] [pe]) () $ PrimOp $ SubExp se | (pe,se) <- zip chunk_map_pes chunk_map_ses ] return (chunk_red_pes, chunk_map_pes, chunk_stm : fold_chunk) blockedKernelSize :: (MonadBinder m, Lore m ~ Kernels) => SubExp -> m KernelSize blockedKernelSize w = do num_groups <- letSubExp "num_groups" $ Op NumGroups group_size <- letSubExp "group_size" $ Op GroupSize num_threads <- letSubExp "num_threads" $ PrimOp $ BinOp (Mul Int32) num_groups group_size per_thread_elements <- letSubExp "per_thread_elements" =<< eDivRoundingUp Int32 (eSubExp w) (eSubExp num_threads) return $ KernelSize num_groups group_size per_thread_elements w per_thread_elements num_threads blockedScan :: (MonadBinder m, Lore m ~ Kernels) => Pattern -> Certificates -> SubExp -> Lambda -> Lambda -> [SubExp] -> [VName] -> m () blockedScan pat cs w lam foldlam nes arrs = do first_scan_size <- blockedKernelSize w my_index <- newVName "my_index" other_index <- newVName "other_index" let num_groups = kernelWorkgroups first_scan_size group_size = kernelWorkgroupSize first_scan_size num_threads = kernelNumThreads first_scan_size my_index_param = Param my_index (Prim int32) other_index_param = Param other_index (Prim int32) first_scan_foldlam <- renameLambda foldlam { lambdaParams = my_index_param : other_index_param : lambdaParams foldlam } first_scan_lam <- renameLambda lam { lambdaParams = my_index_param : other_index_param : lambdaParams lam } let (scan_idents, arr_idents) = splitAt (length nes) $ patternIdents pat final_res_pat = Pattern [] $ take (length nes) $ patternValueElements pat first_scan_pat <- basicPattern' [] <$> (((.).(.)) (++) (++) <$> -- Dammit Haskell mapM (mkIntermediateIdent "seq_scanned" [w]) scan_idents <*> mapM (mkIntermediateIdent "group_sums" [num_groups]) scan_idents <*> pure arr_idents) addBinding $ Let first_scan_pat () $ Op $ ScanKernel cs w first_scan_size first_scan_lam first_scan_foldlam nes arrs let (sequentially_scanned, group_carry_out, _) = splitAt3 (length nes) (length nes) $ patternNames first_scan_pat let second_scan_size = KernelSize one num_groups one num_groups one num_groups second_scan_lam <- renameLambda first_scan_lam second_scan_lam_renamed <- renameLambda first_scan_lam group_carry_out_scanned <- letTupExp "group_carry_out_scanned" $ Op $ ScanKernel cs num_groups second_scan_size second_scan_lam second_scan_lam_renamed nes group_carry_out lam''' <- renameLambda lam j <- newVName "j" let (acc_params, arr_params) = splitAt (length nes) $ lambdaParams lam''' result_map_input = zipWith (mkKernelInput [Var j]) arr_params sequentially_scanned chunks_per_group <- letSubExp "chunks_per_group" =<< eDivRoundingUp Int32 (eSubExp w) (eSubExp num_threads) elems_per_group <- letSubExp "elements_per_group" $ PrimOp $ BinOp (Mul Int32) chunks_per_group group_size result_map_body <- runBodyBinder $ localScope (scopeOfLParams $ map kernelInputParam result_map_input) $ do group_id <- letSubExp "group_id" $ PrimOp $ BinOp (SQuot Int32) (Var j) elems_per_group let do_nothing = pure $ resultBody $ map (Var . paramName) arr_params add_carry_in = runBodyBinder $ do forM_ (zip acc_params group_carry_out_scanned) $ \(p, arr) -> do carry_in_index <- letSubExp "carry_in_index" $ PrimOp $ BinOp (Sub Int32) group_id one letBindNames'_ [paramName p] $ PrimOp $ Index [] arr [carry_in_index] return $ lambdaBody lam''' group_lasts <- letTupExp "final_result" =<< eIf (eCmpOp (CmpEq int32) (eSubExp zero) (eSubExp group_id)) do_nothing add_carry_in return $ resultBody $ map Var group_lasts (mapk_bnds, mapk) <- mapKernelFromBody [] w [(j, w)] result_map_input (lambdaReturnType lam) result_map_body mapM_ addBinding mapk_bnds letBind_ final_res_pat $ Op mapk where one = constant (1 :: Int32) zero = constant (0 :: Int32) mkIntermediateIdent desc shape ident = newIdent (baseString (identName ident) ++ "_" ++ desc) $ arrayOf (rowType $ identType ident) (Shape shape) NoUniqueness mkKernelInput indices p arr = KernelInput { kernelInputName = paramName p , kernelInputType = paramType p , kernelInputArray = arr , kernelInputIndices = indices } blockedSegmentedScan :: (MonadBinder m, Lore m ~ Kernels) => SubExp -> Pattern -> Certificates -> SubExp -> Lambda -> [(SubExp, VName)] -> m () blockedSegmentedScan segment_size pat cs w lam input = do x_flag <- newVName "x_flag" y_flag <- newVName "y_flag" let x_flag_param = Param x_flag $ Prim Bool y_flag_param = Param y_flag $ Prim Bool (x_params, y_params) = splitAt (length input) $ lambdaParams lam params = [x_flag_param] ++ x_params ++ [y_flag_param] ++ y_params body <- runBodyBinder $ localScope (scopeOfLParams params) $ do new_flag <- letSubExp "new_flag" $ PrimOp $ BinOp LogOr (Var x_flag) (Var y_flag) seg_res <- letTupExp "seg_res" $ If (Var y_flag) (resultBody $ map (Var . paramName) y_params) (lambdaBody lam) (staticShapes $ lambdaReturnType lam) return $ resultBody $ new_flag : map Var seg_res flags_i <- newVName "flags_i" flags_body <- runBodyBinder $ localScope (HM.singleton flags_i IndexInfo) $ do segment_index <- letSubExp "segment_index" $ PrimOp $ BinOp (SRem Int32) (Var flags_i) segment_size start_of_segment <- letSubExp "start_of_segment" $ PrimOp $ CmpOp (CmpEq int32) segment_index zero flag <- letSubExp "flag" $ If start_of_segment (resultBody [true]) (resultBody [false]) [Prim Bool] return $ resultBody [flag] (mapk_bnds, mapk) <- mapKernelFromBody [] w [(flags_i, w)] [] [Prim Bool] flags_body mapM_ addBinding mapk_bnds flags <- letExp "flags" $ Op mapk unused_flag_array <- newVName "unused_flag_array" let lam' = Lambda { lambdaParams = params , lambdaBody = body , lambdaReturnType = Prim Bool : lambdaReturnType lam } pat' = pat { patternValueElements = PatElem unused_flag_array BindVar (arrayOf (Prim Bool) (Shape [w]) NoUniqueness) : patternValueElements pat } (nes, arrs) = unzip input lam_renamed <- renameLambda lam' blockedScan pat' cs w lam' lam_renamed (false:nes) (flags:arrs) where zero = constant (0 :: Int32) true = constant True false = constant False mapKernelSkeleton :: (HasScope Kernels m, MonadFreshNames m) => SubExp -> [KernelInput] -> m ([Binding], (SubExp,SubExp,SubExp), [Binding]) mapKernelSkeleton w inputs = do group_size_v <- newVName "group_size" ((num_threads, num_groups), ksize_bnds) <- runBinder $ do letBindNames'_ [group_size_v] $ Op GroupSize numThreadsAndGroups w $ Var group_size_v read_input_bnds <- forM inputs $ \inp -> do let pe = PatElem (kernelInputName inp) BindVar $ kernelInputType inp return $ Let (Pattern [] [pe]) () $ PrimOp $ Index [] (kernelInputArray inp) (kernelInputIndices inp) let ksize = (num_groups, Var group_size_v, num_threads) return (ksize_bnds, ksize, read_input_bnds) -- Given the desired minium number of threads and the number of -- threads per group, compute the number of groups and total number of -- threads. numThreadsAndGroups :: MonadBinder m => SubExp -> SubExp -> m (SubExp, SubExp) numThreadsAndGroups w group_size = do num_groups <- letSubExp "num_groups" =<< eDivRoundingUp Int32 (eSubExp w) (eSubExp group_size) num_threads <- letSubExp "num_threads" $ PrimOp $ BinOp (Mul Int32) num_groups group_size return (num_threads, num_groups) mapKernel :: (HasScope Kernels m, MonadFreshNames m) => Certificates -> SubExp -> [(VName, SubExp)] -> [KernelInput] -> [Type] -> KernelBody Kernels -> m ([Binding], Kernel Kernels) mapKernel cs w ispace inputs rts (KernelBody kstms krets) = do (ksize_bnds, ksize, read_input_bnds) <- mapKernelSkeleton w inputs space <- newKernelSpace ksize ispace let kstms' = map (Thread ThreadsInSpace) read_input_bnds ++ kstms kbody' = KernelBody kstms' krets return (ksize_bnds, Kernel cs space rts kbody') mapKernelFromBody :: (HasScope Kernels m, MonadFreshNames m) => Certificates -> SubExp -> [(VName, SubExp)] -> [KernelInput] -> [Type] -> Body -> m ([Binding], Kernel Kernels) mapKernelFromBody cs w ispace inputs rts body = mapKernel cs w ispace inputs rts kbody where kbody = KernelBody kstms krets kstms = map (Thread ThreadsInSpace) $ bodyBindings body krets = map (ThreadsReturn ThreadsInSpace) $ bodyResult body data KernelInput = KernelInput { kernelInputName :: VName , kernelInputType :: Type , kernelInputArray :: VName , kernelInputIndices :: [SubExp] } kernelInputParam :: KernelInput -> Param Type kernelInputParam p = Param (kernelInputName p) (kernelInputType p) newKernelSpace :: MonadFreshNames m => (SubExp,SubExp,SubExp) -> [(VName, SubExp)] -> m KernelSpace newKernelSpace (num_groups, group_size, num_threads) dims = KernelSpace <$> newVName "global_tid" <*> newVName "local_tid" <*> newVName "group_id" <*> pure num_threads <*> pure num_groups <*> pure group_size <*> pure (FlatSpace dims)
mrakgr/futhark
src/Futhark/Pass/ExtractKernels/BlockedKernel.hs
Haskell
bsd-3-clause
24,449
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-} module Data.Number.LogFloat.Vector () where import Data.Number.LogFloat import Data.Vector.Unboxed import Control.Monad import qualified Data.Vector.Unboxed.Base import qualified Data.Vector.Generic.Mutable as M import qualified Data.Vector.Generic as G newtype instance MVector s LogFloat = MV_LogFloat (MVector s Double) newtype instance Vector LogFloat = V_LogFloat (Vector Double) instance Unbox LogFloat instance M.MVector MVector LogFloat where {-# INLINE basicLength #-} {-# INLINE basicUnsafeSlice #-} {-# INLINE basicOverlaps #-} {-# INLINE basicUnsafeNew #-} {-# INLINE basicUnsafeReplicate #-} {-# INLINE basicUnsafeRead #-} {-# INLINE basicUnsafeWrite #-} {-# INLINE basicClear #-} {-# INLINE basicSet #-} {-# INLINE basicUnsafeCopy #-} {-# INLINE basicUnsafeGrow #-} basicLength (MV_LogFloat v) = M.basicLength v basicUnsafeSlice i n (MV_LogFloat v) = MV_LogFloat $ M.basicUnsafeSlice i n v basicOverlaps (MV_LogFloat v1) (MV_LogFloat v2) = M.basicOverlaps v1 v2 basicUnsafeNew n = MV_LogFloat `liftM` M.basicUnsafeNew n basicUnsafeReplicate n rec = MV_LogFloat `liftM` M.basicUnsafeReplicate n (logFromLogFloat rec) basicUnsafeRead (MV_LogFloat v) i = logToLogFloat `liftM` M.basicUnsafeRead v i basicUnsafeWrite (MV_LogFloat v) i rec = M.basicUnsafeWrite v i $ logFromLogFloat rec basicClear (MV_LogFloat v) = M.basicClear v basicSet (MV_LogFloat v) rec = M.basicSet v $ logFromLogFloat rec basicUnsafeCopy (MV_LogFloat v1) (MV_LogFloat v2) = M.basicUnsafeCopy v1 v2 basicUnsafeMove (MV_LogFloat v1) (MV_LogFloat v2) = M.basicUnsafeMove v1 v2 basicUnsafeGrow (MV_LogFloat v) n = MV_LogFloat `liftM` M.basicUnsafeGrow v n instance G.Vector Vector LogFloat where {-# INLINE basicUnsafeFreeze #-} {-# INLINE basicUnsafeThaw #-} {-# INLINE basicLength #-} {-# INLINE basicUnsafeSlice #-} {-# INLINE basicUnsafeIndexM #-} {-# INLINE elemseq #-} basicUnsafeFreeze (MV_LogFloat v) = V_LogFloat `liftM` G.basicUnsafeFreeze v basicUnsafeThaw (V_LogFloat v) = MV_LogFloat `liftM` G.basicUnsafeThaw v basicLength (V_LogFloat v) = G.basicLength v basicUnsafeSlice i n (V_LogFloat v) = V_LogFloat $ G.basicUnsafeSlice i n v basicUnsafeIndexM (V_LogFloat v) i = logToLogFloat `liftM` G.basicUnsafeIndexM v i basicUnsafeCopy (MV_LogFloat mv) (V_LogFloat v) = G.basicUnsafeCopy mv v elemseq _ rec y = G.elemseq (undefined :: Vector Double) (logFromLogFloat rec) y
bgamari/logfloat-unboxed
Data/Number/LogFloat/Vector.hs
Haskell
bsd-3-clause
2,503
module Handler.CampaignNew where import Import import Import.Premium (hasPremium) import Import.Semantic (renderSemantic) campaignForm :: UserId -> Form Campaign campaignForm user = renderSemantic $ Campaign <$> areq textField "Name" Nothing <*> pure user getCampaignNewR :: Handler Html getCampaignNewR = do Entity uid user <- requireAuth prem <- hasPremium user unless prem $ do ownedCamps <- runDB $ count [CampaignOwnerId ==. uid] when (ownedCamps >= 1) $ do setMessage "Campaign limit reached. Upgrade to Premium for unlimited campaigns." redirect HomeR (campaignWidget, enctype) <- generateFormPost $ campaignForm uid defaultLayout $ do setTitle "New Campaign" $(widgetFile "campaignnew") postCampaignNewR :: Handler Html postCampaignNewR = do user <- requireAuthId ((res,_), _) <- runFormPost $ campaignForm user case res of FormSuccess campaignData -> do camp <- runDB $ insert campaignData setMessage . toHtml $ campaignName campaignData <> " created" redirect . EntriesR $ EntryListR camp _ -> defaultLayout $ do setMessage "Error creating entry." $(widgetFile "error")
sulami/hGM
Handler/CampaignNew.hs
Haskell
bsd-3-clause
1,210
module Forum.Internal (module X) where import Forum.Internal.SQL as X import Forum.Internal.Class as X import Forum.Internal.Types as X import Forum.Internal.Decoding as X
turingjump/forum
src/Forum/Internal.hs
Haskell
bsd-3-clause
173
{- | Copyright : 2014 Tomáš Musil License : BSD-3 Stability : experimental Portability : portable Nearest Neighbour heuristic for TSP. -} module Problems.TSP.NN ( optimize ) where import Control.Arrow --import Data.List.Stream --import Prelude hiding ((++), lines, map, minimum, splitAt, sum, repeat, tail, take, words, zip) --TODO zrušit explicitní rekurzi a zkusit znovu import qualified Data.Set as Set import Problems.TSP import qualified Problems.TSP.TwoOpt as Topt findPath :: Size -> FDist -> Vertex -> Path findPath n dist origin = origin : fp dist origin origin (Set.delete origin (Set.fromAscList [1..n])) fp dist frst lst unv | not (Set.null unv) = nearest : fp dist frst nearest (Set.delete nearest unv) where nearest = snd (minimum (map dist' (Set.elems unv))) dist' x = (dist (lst, x), x) fp _ frst _ _ = [frst] allPaths :: FDist -> Size -> [Path] --allPaths dist n = map (findPath n dist) [1..n] allPaths dist n = map (Topt.optimize dist . findPath n dist) [1..n] pathLen :: FDist -> Path -> Distance pathLen dist path = sum . map dist $ zip path (tail path) optimize :: FDist -> Int -> (Distance, Path) optimize dist = minimum . allPathlens dist allPathlens :: FDist -> Int -> [(Distance, Path)] allPathlens dist n = map (pathLen dist &&& id) $ allPaths dist n
tomasmcz/discrete-opt
src/Problems/TSP/NN.hs
Haskell
bsd-3-clause
1,320
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell import Language.Haskell.Liquid.Prelude foo x y | compare x y == EQ = liquidAssertB (x == y) | compare x y == LT = liquidAssertB (x < y) | compare x y == GT = liquidAssertB (x > y) prop = foo n m where n = choose 0 m = choose 1
spinda/liquidhaskell
tests/gsoc15/unknown/pos/compare1.hs
Haskell
bsd-3-clause
299
{-| Module : Werewolf.Command.Unvote Description : Handler for the unvote subcommand. Copyright : (c) Henry J. Wylde, 2016 License : BSD3 Maintainer : public@hjwylde.com Handler for the unvote subcommand. -} module Werewolf.Command.Unvote ( -- * Handle handle, ) where import Control.Lens import Control.Monad.Except import Control.Monad.Extra import Control.Monad.Random import Control.Monad.State import Control.Monad.Writer import Data.Text (Text) import Game.Werewolf import Game.Werewolf.Command import Game.Werewolf.Command.Villager as Villager import Game.Werewolf.Command.Werewolf as Werewolf import Game.Werewolf.Engine import Game.Werewolf.Message.Error import Werewolf.System handle :: (MonadIO m, MonadRandom m) => Text -> Text -> m () handle callerName tag = do unlessM (doesGameExist tag) $ exitWith failure { messages = [noGameRunningMessage callerName] } game <- readGame tag command <- case game ^. stage of VillagesTurn -> return $ Villager.unvoteCommand callerName WerewolvesTurn -> return $ Werewolf.unvoteCommand callerName _ -> exitWith failure { messages = [playerCannotDoThatRightNowMessage callerName] } result <- runExceptT . runWriterT $ execStateT (apply command >> checkStage >> checkGameOver) game case result of Left errorMessages -> exitWith failure { messages = errorMessages } Right (game', messages) -> writeOrDeleteGame tag game' >> exitWith success { messages = messages }
hjwylde/werewolf
app/Werewolf/Command/Unvote.hs
Haskell
bsd-3-clause
1,584
module Main where import MixedTypesNumPrelude -- import qualified Prelude as P -- import Control.Applicative (liftA2) import System.Environment import AERN2.MP -- import qualified AERN2.MP.Ball as MPBall import AERN2.Poly.Cheb import AERN2.Poly.Cheb.Maximum import AERN2.Poly.Cheb.MaxNaive import qualified AERN2.Local as Local import qualified AERN2.Local.Poly as Local import AERN2.Local.DPoly main :: IO () main = do args <- getArgs (computationDescription, result) <- processArgs args putStrLn $ computationDescription putStrLn $ "result = " ++ show result putStrLn $ "accuracy: " ++ show (getAccuracy result) putStrLn $ "precision = " ++ show (getPrecision result) processArgs :: [String] -> IO (String, MPBall) processArgs [alg, fun] = let desc = "Computing maximum of "++(funName fun)++" over [-1,1] using "++(algName alg)++"." in case alg of "A" -> do let f = case fun of "0" -> let x = setAccuracyGuide (bits 70) _chPolyX in sin(10*x) + cos(20*x) + 7*x^!3 "1" -> let x = setAccuracyGuide (bits 80) _chPolyX in 10*sin(10*x)^!2 + 20*cos(20*x)^!2 "2" -> let x = setAccuracyGuide (bits 70) _chPolyX in sin(10*sin(10*x) + 20*x^!2) + cos(20*x) _ -> error "unkown function code." return (desc, AERN2.Poly.Cheb.MaxNaive.maxNaive f (-1.0) (1.0) (bits 70)) "B" -> do let f = case fun of "0" -> let x = setAccuracyGuide (bits 70) _chPolyX in sin(10*x) + cos(20*x) + 7*x^!3 "1" -> let x = setAccuracyGuide (bits 80) _chPolyX in 10*sin(10*x)^!2 + 20*cos(20*x)^!2 "2" -> let x = setAccuracyGuide (bits 70) _chPolyX in sin(10*sin(10*x) + 20*x^!2) + cos(20*x) _ -> error "unkown function code." return (desc, AERN2.Poly.Cheb.Maximum.maximumOptimised f (mpBall $ -1) (mpBall 1) 5 5) "C" -> do let x = Local.variable let f = case fun of "0" -> sin(10*x) + cos(20*x) + 7*x^!3 "1" -> 10*sin(10*x)^!2 + 20*cos(20*x)^!2 "2" -> sin(10*sin(10*x) + 20*x^!2) + cos(20*x) _ -> error "unkown function code." return (desc, Local.maximum f (mpBall $ -1) (mpBall 1) (bits 53)) "D" -> do let x = Local.variable let f = case fun of "0" -> DPoly (sin(10*x) + cos(20*x) + 7*x^!3) (\z -> sin(10*z) + cos(20*z) + 7*z^!3) (\z -> 10*cos(10*z) - 20*sin(20*z) + 21*z^!2) "1" -> DPoly (10*sin(10*x)^!2 + 20*cos(20*x)^!2) (\z -> 10*sin(10*z)^!2 + 20*cos(20*z)^!2) (\z -> 200*sin(10*z)*cos(10*z) - 800*cos(20*z)*sin(20*z)) "2" -> DPoly (sin(10*sin(10*x) + 20*x^!2) + cos(20*x)) (\z -> sin(10*sin(10*z) + 20*z^!2) + cos(20*z)) (\z -> cos(10*sin(10*z) + 20*z^!2)*(100*cos(10*z) + 40*z) - 20*sin(20*z)) _ -> error "unkown function code." return (desc, Local.maximum f (mpBall $ -1) (mpBall 1) (bits 53)) _ -> error "unkown algorithm code." processArgs _ = error "usage: <algorithm code> <function code>" algName :: String -> String algName "A" = "naive maximisation" algName "B" = "maximisation with global approximations" algName "C" = "maximisation with local approximations" algName "D" = "maximisation with local approximations and enrichments" algName _ = undefined funName :: String -> String funName "0" = "sin(10*x) + cos(20*x) + 7*x^3" funName "1" = "10*sin(10*x)^2 + 20*cos(20*x)^2" funName "2" = "sin(10*sin(10*x) + 20*x^2) + cos(20*x)" funName _ = undefined
michalkonecny/aern2
aern2-fnreps/main/waac-benchmarks.hs
Haskell
bsd-3-clause
3,999
module Data.Symbol.UnitTest(tests) where import Data.Symbol import Test.HUnit tests = TestList [ "name (symbol i s) = s" ~: "s" ~?= (name (symbol 1 "s")), "(symbol 1 s) == (symbol 1 s)" ~: assertBool "" ((symbol 1 "s") == (symbol 1 "s")), "unused == unused" ~: assertBool "" (unused == unused), "(symbol 1 s) != (symbol 2 s)" ~: assertBool "" ((symbol 1 "s") /= (symbol 2 "s")), "unused != (symbol 2 s)" ~: assertBool "" (unused /= (symbol 2 "s")), "(symbol 1 s) != unused" ~: assertBool "" ((symbol 1 "s") /= unused), "(symbol 1 s) < (symbol 2 s)" ~: assertBool "" ((symbol 1 "s") < (symbol 2 "s")), "(symbol 2 s) > (symbol 1 s)" ~: assertBool "" ((symbol 2 "s") > (symbol 1 "s")), "unused < (symbol 2 s)" ~: assertBool "" (unused < (symbol 2 "s")), "(symbol 2 s) > unused" ~: assertBool "" ((symbol 2 "s") > unused), "number (symbol 1 s) = 1" ~: 1 ~?= (number (symbol 1 "s")) ]
emc2/proglang-util
Data/Symbol/UnitTest.hs
Haskell
bsd-3-clause
937
module M06MultipleChildren where import Rumpus {- You can call spawnChild as many times as you like. Let's create a field of dreams: ``` -} start :: Start start = do forM_ [0..99] $ \i -> do let x = (fromIntegral (i `mod` 10) - 5) * 0.1 z = (fromIntegral (i `div` 10) - 5) * 0.1 spawnChild $ do myColor ==> colorHSL 0.5 0.7 0.7 myShape ==> Sphere myPose ==> position (V3 0 1 0) mySize ==> 0.05 myUpdate ==> do t <- getNow let t2 = t + fromIntegral i setPosition (V3 x (sin t2 * 0.05 + 0.5) (z - 0.5)) setColor (colorHSL (sin (t2/2)) 0.7 0.7) {- ``` -}
lukexi/rumpus
pristine/Coding Guide/M06MultipleChildren.hs
Haskell
bsd-3-clause
759
module Main where import Language main :: IO () main = putStr $ unlines [show vs ++ " -> " ++ show (interpret peg time_env) | (vs, time_env) <- iterations labels] where (labels, peg) = figure_3_c iterations [] = [([], emptyTimeEnv)] iterations (l:ls) = do v <- [0..10] fmap ((v:) `pair` insertTimeEnv l v) (iterations ls) pair f g (a, b) = (f a, g b) figure_2_a :: ([Label], PEG Int) figure_2_a = ([l], n1) where n1 = Lift2 (*) n2 (Const 5) n2 = Theta l (Const 0) n3 n3 = Phi delta n4 n5 n4 = Lift2 (+) (Const 3) n5 n5 = Lift2 (+) (Const 1) n2 l = 1 delta = Lift2 (<=) n2 (Const 10) figure_3_a :: ([Label], PEG Int) figure_3_a = ([l], n1) where n1 = Eval l n2 n4 n2 = Theta l (Const 0) n3 n3 = Lift2 (+) (Const 2) n2 n4 = Pass l n5 n5 = Lift2 (>=) n2 (Const 29) l = 1 figure_3_b :: ([Label], PEG Int) figure_3_b = ([l1, l2], n1) where n1 = Theta l2 n2 n3 n2 = Theta l1 (Const 0) n4 n3 = Lift2 (+) (Const 1) n1 n4 = Eval l2 n1 n5 n5 = Pass l2 n6 n6 = Lift2 (>=) n7 (Const (10 :: Int)) n7 = Theta l2 (Const 0) n8 n8 = Lift2 (+) (Const 1) n7 l1 = 1 l2 = 2 figure_3_c :: ([Label], PEG Int) figure_3_c = ([l1, l2], n1) where n1 = Lift2 (+) n2 n5 n2 = Lift2 (*) (Const 10) n3 n3 = Theta l1 (Const 0) n4 n4 = Lift2 (+) (Const 1) n3 n5 = Theta l2 (Const 0) n6 n6 = Lift2 (+) (Const 1) n5 l1 = 1 l2 = 2
batterseapower/pegs
Main.hs
Haskell
bsd-3-clause
1,529
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Main where import Control.Applicative import Control.Monad.Loops import Control.Monad.State.Strict import qualified Data.Attoparsec.Char8 as A import qualified Data.ByteString.Char8 as B import Data.List.Zipper import System.Environment newtype BF a = BF { unBF :: StateT (Zipper Int) IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadState (Zipper Int)) runBF :: BF a -> IO a runBF m = evalStateT (unBF m) $ fromList $ replicate 30000 0 bf :: A.Parser (BF ()) bf = (sequence_ <$>) . many $ A.char '>' *> return (modify right) <|> A.char '<' *> return (modify left) <|> A.char '+' *> return (modify $ \z -> replace (cursor z + 1) z) <|> A.char '-' *> return (modify $ \z -> replace (cursor z - 1) z) <|> A.char '.' *> return (gets cursor >>= liftIO . putChar . toEnum) <|> A.char ',' *> return (liftIO getChar >>= modify . replace . fromEnum) <|> whileM_ ((/= 0) <$> gets cursor) <$> (A.char '[' *> bf <* A.char ']') <|> A.notChar ']' *> bf main :: IO () main = do [file] <- getArgs progn <- B.readFile file case A.parseOnly bf progn of Left err -> error err Right p -> runBF p
tanakh/brainfuck
main.hs
Haskell
bsd-3-clause
1,182
{-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Forum.Internal.Decoding where import Bookkeeper import Hasql.Class (Decodable(decode)) import Hasql.Decoders (Row) import Data.Proxy instance (All Decodable entries) => Decodable (Book' Identity entries) where decode = decodeBook decodeBook :: All Decodable entries => Row (Book' Identity entries) decodeBook = bsequence $ bmapConstraint (Proxy :: Proxy Decodable) decodeProxy bproxies where decodeProxy :: Decodable a => Proxy a -> Row a decodeProxy _ = decode
turingjump/forum
src/Forum/Internal/Decoding.hs
Haskell
bsd-3-clause
560
{-# LANGUAGE TupleSections #-} module KMeans ( Point , Cluster , localKMeans , distrKMeans , createGnuPlot , __remoteTable ) where import System.IO import Data.List (minimumBy) import Data.Function (on) import Data.Array (Array, (!), bounds) import qualified Data.Map as Map (fromList, elems, toList, size) import Control.Distributed.Process import Control.Distributed.Process.Closure import MapReduce import PolyDistrMapReduce hiding (__remoteTable) type Point = (Double, Double) type Cluster = (Double, Double) average :: Fractional a => [a] -> a average xs = sum xs / fromIntegral (length xs) distanceSq :: Point -> Point -> Double distanceSq (x1, y1) (x2, y2) = a * a + b * b where a = x2 - x1 b = y2 - y1 nearest :: Point -> [Cluster] -> Cluster nearest p = minimumBy (compare `on` distanceSq p) center :: [Point] -> Point center ps = let (xs, ys) = unzip ps in (average xs, average ys) kmeans :: Array Int Point -> MapReduce (Int, Int) [Cluster] Cluster Point ([Point], Point) kmeans points = MapReduce { mrMap = \(lo, hi) cs -> [ let p = points ! i in (nearest p cs, p) | i <- [lo .. hi] ] , mrReduce = \_ ps -> (ps, center ps) } localKMeans :: Array Int Point -> [Cluster] -> Int -> Map Cluster ([Point], Point) localKMeans points cs iterations = go (iterations - 1) where mr :: [Cluster] -> Map Cluster ([Point], Point) mr = localMapReduce (kmeans points) . trivialSegmentation go :: Int -> Map Cluster ([Point], Point) go 0 = mr cs go n = mr . map snd . Map.elems . go $ n - 1 trivialSegmentation :: [Cluster] -> Map (Int, Int) [Cluster] trivialSegmentation cs' = Map.fromList [(bounds points, cs')] dictIn :: SerializableDict ((Int, Int), [Cluster]) dictIn = SerializableDict dictOut :: SerializableDict [(Cluster, Point)] dictOut = SerializableDict remotable ['kmeans, 'dictIn, 'dictOut] distrKMeans :: Array Int Point -> [Cluster] -> [NodeId] -> Int -> Process (Map Cluster ([Point], Point)) distrKMeans points cs mappers iterations = distrMapReduce $(mkStatic 'dictIn) $(mkStatic 'dictOut) ($(mkClosure 'kmeans) points) mappers (go (iterations - 1)) where go :: Int -> (Map (Int, Int) [Cluster] -> Process (Map Cluster ([Point], Point))) -> Process (Map Cluster ([Point], Point)) go 0 iteration = iteration (Map.fromList $ map (, cs) segments) go n iteration = do clusters <- go (n - 1) iteration let centers = map snd $ Map.elems clusters iteration (Map.fromList $ map (, centers) segments) segments :: [(Int, Int)] segments = let (lo, _) = bounds points in dividePoints numPoints lo dividePoints :: Int -> Int -> [(Int, Int)] dividePoints pointsLeft offset | pointsLeft <= pointsPerMapper = [(offset, offset + pointsLeft - 1)] | otherwise = let offset' = offset + pointsPerMapper in (offset, offset' - 1) : dividePoints (pointsLeft - pointsPerMapper) offset' pointsPerMapper :: Int pointsPerMapper = ceiling (toRational numPoints / toRational (length mappers)) numPoints :: Int numPoints = let (lo, hi) = bounds points in hi - lo + 1 -- | Create a gnuplot data file for the output of the k-means algorithm -- -- To plot the data, use -- -- > plot "<<filename>>" u 1:2:3 with points palette createGnuPlot :: Map KMeans.Cluster ([KMeans.Point], KMeans.Point) -> Handle -> IO () createGnuPlot clusters h = mapM_ printPoint . flatten . zip colors . Map.toList $ clusters where printPoint (x, y, color) = hPutStrLn h $ show x ++ " " ++ show y ++ " " ++ show color flatten :: [(Float, (KMeans.Cluster, ([KMeans.Point], KMeans.Point)))] -> [(Double, Double, Float)] flatten = concatMap (\(color, (_, (points, _))) -> map (\(x, y) -> (x, y, color)) points) colors :: [Float] colors = [0, 1 / fromIntegral (Map.size clusters) .. 1]
haskell-distributed/distributed-process-demos
src/MapReduce/KMeans.hs
Haskell
bsd-3-clause
4,139
{-# LANGUAGE CPP #-} -- | This module reexports the six necessary type classes that every 'Rule' type must support. -- You can use this module to define new rules without depending on the @binary@, @deepseq@ and @hashable@ packages. module Development.Shake.Classes( Show(..), Typeable(..), Eq(..), Hashable(..), Binary(..), NFData(..) ) where import Data.Hashable import Data.Typeable import Data.Binary import Control.DeepSeq
nh2/shake
Development/Shake/Classes.hs
Haskell
bsd-3-clause
440
module Methods where import qualified Data.ByteString.Lazy.Char8 as C import qualified Data.ByteString.Lazy as L import Data.List import System.IO import Data.Word import Data.Binary.Get import Data.Int import Memory assure :: Maybe a -> a assure (Just a) = a assure _ = error "Error: can't convert Nothing to value" assure' :: String -> Maybe a -> a assure' _ (Just a) = a assure' errorMsg _ = error errorMsg select :: Bool -> a -> a -> a select True x _ = x select False _ x = x isGreater :: Maybe Int -> Int -> Bool isGreater Nothing _ = False isGreater (Just a) b = a > b sub :: Maybe Int -> Int -> Maybe Int sub Nothing _ = Nothing sub (Just a) b = Just $ a - b pick :: [String] -> Maybe Int -> Maybe String pick _ Nothing = Nothing pick strings (Just i) = Just $ strings !! i deleteAt :: Int -> [a] -> [a] deleteAt index list = take index list ++ tail (drop index list) findStringIndex :: [String] -> String -> Int findStringIndex [] _ = -1 findStringIndex (string : r_strings) stringToFind | string == stringToFind = 0 | otherwise = 1 + findStringIndex r_strings stringToFind printList :: Show a => [a] -> IO () printList [] = putStr "[]" printList list = putStr "[" >> go (init list) >> (putStr . show . last) list >> putStr "]" where go [] = return () go (x : xs) = (putStr . show) x >> putStr ", " >> go xs printStringList :: [String] -> IO () printStringList = foldr ((>>) . putStrLn) (return ()) printByteStringList :: [L.ByteString] -> IO () printByteStringList list = putStr "[" >> foldr ((>>) . C.putStr) (return ()) (intersperse (C.pack ", ") list) >> putStr "]" boolToInt :: Bool -> Int boolToInt True = 1 boolToInt False = 0 printState :: ([String], [String], [TD]) -> IO () printState (strings, _, tDs) = printTypeDescs tDs >> eL 2 printState' :: ([String], [String], [TD]) -> IO () printState' (strings, _, tDs) = mapM_ print strings >> putStrLn "%%%%%%%%" >> printTypeDescs tDs >> eL 2 tDs'toString :: [TD] -> String tDs'toString [] = [] tDs'toString ((TD id name count fieldDescs subtypes _) : r_tDs) = " ### Type " ++ show id ++ " : " ++ name ++ " ###\n" ++ concatMap fDs'toString fieldDescs ++ "\nNumber of Subtypes: " ++ show (length subtypes) ++ tDs'toString subtypes >> tDs'toString r_tDs fDs'toString :: FD -> String fDs'toString (name, d, (rawD, _, _)) = " > Field " ++ name ++ ": \n" ++ d'toString rawD ++ " -> " ++ list'toString d ++ "\n" list'toString :: Show a => [a] -> String list'toString [] = "[]" list'toString list = "[" ++ go (init list) ++ (show . last) list ++ "]" where go [] = "" go (x : xs) = show x ++ ", " ++ go xs d'toString :: L.ByteString -> String d'toString d = list'toString (runGet getter d) where getter = repeatGet ((fromIntegral . C.length) d) getWord8 printTypeDescs :: [TD] -> IO () printTypeDescs [] = return () printTypeDescs ((TD id name count fDs subtypes _) : r_tDs) = putStrLn (" ### Type " ++ show id ++ " : " ++ name ++ " ###") >> eL 1 >> mapM_ printFD fDs >> eL 1 >> putStr "Number of Subtypes: " >> print (length subtypes) >> printTypeDescs subtypes >> printTypeDescs r_tDs printFD :: FD -> IO () printFD (name, d, (rawD, _, _)) = putStr (" > Field " ++ name ++ ": ") >> printData rawD >> putStr " -> " >> printList d >> eL 1 printData :: L.ByteString -> IO () printData d' = printList (runGet getter d') where getter = repeatGet ((fromIntegral . C.length) d') getWord8 convertData :: L.ByteString -> [Word8] convertData d = runGet getter d where getter = repeatGet ((fromIntegral . C.length) d) getWord8 printRealData :: Get [Something] -> L.ByteString -> IO () printRealData getter string = printList (runGet getter string) >> eL 1 printTestName :: String -> IO () printTestName string = eL 2 >> putStrLn minuses >> putStrLn ("-- Test " ++ string ++ " --") >> putStrLn minuses where minuses = replicate (11 + length string) '-' eL :: Int -> IO () eL 0 = return () eL i = putStrLn "" >> eL (i-1) isJust :: Maybe a -> Bool isJust (Just _) = True isJust Nothing = False subIndex :: Int -> Int subIndex i = i-1 repeatGet :: Int -> Get a -> Get [a] repeatGet 0 _ = return [] repeatGet i getter = getter >>= \d -> repeatGet (i-1) getter >>= \rest -> return (d : rest) remodel :: [Get a] -> Get [a] remodel [] = return [] remodel (getter : rest) = getter >>= \a -> remodel rest >>= \r -> return (a : r) remodel' :: (Get a, Get a) -> Get (a, a) remodel' (g1, g2) = g1 >>= \v1 -> g2 >>= \v2 -> return (v1, v2) -- replaces an element at a specific index in a list, returns the changed list replace' :: Int -> a -> [a] -> [a] replace' _ _ [] = [] replace' 0 newElem (x : r_list) = newElem : r_list replace' i newElem (x : r_list) = x : replace' (i-1) newElem r_list replaceSection :: Int -> Int -> a -> [a] -> [a] replaceSection 0 count newElem list = replicate count newElem ++ drop count list replaceSection i count newElem (e : r_list) = e : replaceSection (i-1) count newElem r_list -- cutSlice [1,2,3,4,5,6,7,8,9] (3, 5) = ([1,2,3,9],[4,5,6,7,8]) cutSlice :: [a] -> (Int, Int) -> ([a], [a]) cutSlice xs (offset, count) = (xsA1 ++ xsA2, xsB) where (xsA1, xsR) = splitAt offset xs (xsB, xsA2) = splitAt count xsR splitGet :: (Int, Int) -> Get [a] -> (Get [a], Get [a]) splitGet (offset, count) getter = (dropMid offset count `fmap` getter, subList offset count `fmap` getter) subList :: Int -> Int -> [a] -> [a] subList offset count = take count . drop offset dropMid :: Int -> Int -> [a] -> [a] dropMid offset count list = take offset list ++ drop (count + offset) list appendMaybe :: Maybe [a] -> [a] -> [a] appendMaybe Nothing = id appendMaybe (Just list1) = (++) list1 -- replaces element at a given index in a list r :: Int -> a -> [a] -> [a] r index elem list = take index list ++ [elem] ++ drop (index + 1) list -- follows a pointer to its target -- this procedure operates on two modes, starting on mode 1 -- in mode 1, search for the tD with the correct id (as given by (fst ref)) -- in mode 2, go back downward through the respective subtree, searching for the right instance -- the mode is signaled by the attribute ssc; ssc < 0 -> enter mode 2 (and stay there) -- until then ssc equals the sum of the counts of all local super types reach :: Ref -> [TD] -> ([FD], String, Int) reach ref tDs = (fDs, name, pos) where (TD id name count fDs s_tDs rec, pos) = assure $ go 0 ref tDs go :: Int -> (Int, Int) -> [TD] -> (Maybe (TD, Int)) go _ _ [] = Nothing go (-1) (_, i2) (TD id name count fDs s_tDs record : r_f_tDs) -- ||| Mode 2 ||| | i2 < count = Just $ (TD id name count fDs s_tDs record, i2) -- index applies locally -> SUCCESS | otherwise = case (go (-1) (undefined, i2 - count) s_tDs) -- index too high -> subtract it and call downward of Just res -> Just res Nothing -> case (go (-1) (undefined, i2 - count) r_f_tDs) of Just res -> Just res -- call forward Nothing -> Nothing go ssc (i1, i2) (TD id name count fDs s_tDs record : r_f_tDs) -- ||| Mode 1 ||| | id == i1 = go (-1) (undefined, i2 - ssc) [TD id name count fDs s_tDs record] -- found tD with id -> SWITCH TO MODE 2, self-call | otherwise = case (go (ssc + count) (i1, i2) s_tDs) -- didn't find tD yet -> keep looking, call downward of Just res -> Just res Nothing -> case (go ssc (i1, i2) s_tDs) of Just res -> Just res -- call forward Nothing -> Nothing lengthBS :: L.ByteString -> Int lengthBS = fromIntegral . L.length fst' (a,b,c) = a snd' (a,b,c) = b trd' (a,b,c) = c fst'' (a,b,c,d) = a snd'' (a,b,c,d) = b trd'' (a,b,c,d) = c fth'' (a,b,c,d) = d -- ghci macro p :: String -> String p name = "C:/input/" ++ name ++ ".sf" getFDs :: TD -> [FD] getFDs (TD _ _ _ fDs _ _) = fDs a = L.append fI :: Word64 -> Int fI = fromIntegral
skill-lang/skill
deps/haskell/Methods.hs
Haskell
bsd-3-clause
8,340
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE LiberalTypeSynonyms #-} {-# LANGUAGE ImpredicativeTypes #-} {-# OPTIONS_GHC -fno-warn-missing-methods #-} module Lib ( ) where import Data.Comp import Data.Comp.Derive import Data.Comp.Ops import Data.Comp.Render import Data.Comp.TermRewriting (matchRules,matchRule,appRule,reduce,appTRS,parallelStep,parTopStep,Step,Rule) import Data.Rewriting.Rules import Data.Rewriting.FirstOrder (bottomUp) import Data.Rewriting.HigherOrder import Data.String(IsString(..)) import Data.Maybe(fromMaybe) import qualified Data.Set as Set import Data.Map import Derive1 import Control.Monad (guard,(>=>),(<=<)) import Control.Monad.Reader import Control.Monad.Writer import Debug.Trace data STUDENT a = Student a a a a deriving Show data MAJOR a = English | Math | Physics deriving Show newtype LIT b a = L {unL ::b} deriving Show data NUM a = Plus a a | Minus a a | Times a a | Negate a | Divide a a deriving Show data LIST a = NIL | CONS a a deriving (Show,Eq,Ord) --[ $(derive [makeFunctor,makeTraversable,makeFoldable, makeEqF,makeOrdF,makeShowF,smartConstructors,makeShowConstr] [''STUDENT,''LIT,''MAJOR,''NUM]) $(derive [makeFunctor,makeTraversable,makeFoldable, makeEqF,makeOrdF,makeShowF,smartConstructors,makeShowConstr] [''LIST]) $(derive [makeEqF,makeShowF,smartConstructors,makeShowConstr] [''WILD]) $(derive [smartRep] [''STUDENT,''LIT,''MAJOR,''LIST]) $(derive [smartRep'] [''STUDENT,''LIT,''MAJOR,''LIST]) $(derive [makeOrdF] [''VAR,''LAM,''APP]) --] type SIG = LIST :+: NUM :+: STUDENT :+: MAJOR :+: LIT Int :+: LIT String :+: LIT Float :+: ADDONS type ADDONS = VAR :+: LAM :+: APP -- Not needed as written, but allow higher order rewrite rules. newtype Expr f a = Expr {unExpr :: Term f} deriving Functor -- Restricted smart constructors [ student :: (Rep r,STUDENT :<: PF r) => r Int -> r String -> r Int -> r (MAJOR b) -> r b student = rStudent l :: (LIT a :<: PF r, Rep r) => a -> r a l = rL s :: (LIT a :<: PF' r, Rep' r) => a -> r a s = sL --] deriving instance Functor (LHS f) deriving instance Functor (RHS f) instance (LIT a :<: PF' (r f),Functor (r f),Num a,Rep' (r f)) => Num (r (f :: * -> *) a) where --[ fromInteger = s . fromInteger abs (fromRep' -> a) = s $ fromMaybe 0 $ do a' <- project a return $ abs $ unL a' instance (LIT a :<: PF' (r f),Functor (r f),Fractional a,Rep' (r f)) => Fractional (r (f :: * -> *) a) where fromRational = s . fromRational instance (LIT String :<: PF' (r f),Functor (r f),Rep' (r f)) => IsString (r (f :: * -> *) String) where fromString = s . fromString --] type STUFF f = (VAR :<: f,LAM :<: f,APP :<: f,VAR :<: PF (LHS f),LAM :<: PF (LHS f)) matchML :: (Functor f,Foldable f,EqF f,STUFF f) => [LHS f a] -> Term (f :&: Set.Set Name) -> ReaderT AlphaEnv (WriterT (Subst (f :&: Set.Set Name)) Maybe) () matchML lhss t = do mapM_ (\x -> matchM x t) lhss matchL :: (Functor f,Foldable f,EqF f, STUFF f) => [LHS f a] -> Term (f :&: Set.Set Name) -> Maybe (Subst (f :&: Set.Set Name)) matchL lhs = solveSubstAlpha <=< execWriterT . flip runReaderT oEmpty . matchML lhs rewrite' --[ :: ( VAR :<: f , LAM :<: f , APP :<: f , VAR :<: PF (LHS' f) , LAM :<: PF (LHS' f) , VAR :<: PF (RHS f) , LAM :<: PF (RHS f) , Traversable f, EqF f,OrdF f,Render f , g ~ (f :&: Set.Set Name) ) => (Term g -> Term g -> Term g) -- ^ Application operator -> Data.Rewriting.Rules.Rule (LHS' f) (RHS f) -> Term g -> Maybe (Term g) --] rewrite' app (Rule lhs'@(LHS' conds lhss) rhs) t = do subst <- matchL lhss t --trace (showTerm $ unLHS $ head $ lhss) (Just undefined) case conds of Nothing -> return () Just c -> do cont <- unBOOL (unTerm c) subst guard cont substitute app subst rhs -- Render and Show and Rep Expr [ instance Render NUM instance Render LIST instance Render STUDENT instance Show b => Render (LIT b) instance Render MAJOR instance Render WILD instance (MetaRep f ~ MetaId) => Render (META f) instance (MetaRep f ~ MetaId) => ShowConstr (META f) where showConstr (Meta (MVar (MetaId rep))) = show rep instance Rep (Expr f) where type PF (Expr f) = f toRep = Expr fromRep = unExpr instance Rep (LHS' f) where type PF (LHS' f) = WILD :+: META (LHS f) :+: f toRep = LHS'' . (:[]) . LHS fromRep = unLHS . head . unLHS' --] data LHS' f a = LHS' { unC :: Maybe (Conditional f), unLHS' :: [LHS f a] } --Term (WILD :+: (META (LHS' f) :+: f))} pattern LHS'' a = LHS' Nothing a data BOOL f a = Boolean {unBOOL :: Data.Rewriting.Rules.Subst (f :&: Set.Set Name) -> Maybe Bool} | a :&& a | Not a type Conditional f = Term (BOOL f) --[ guarded a b = LHS' (Just b) a boolHelper boolFun f g = Term $ Boolean $ \subs -> do f' <- unBOOL (unTerm f) subs g' <- unBOOL (unTerm g) subs return (f' `boolFun` g') (.&&) = boolHelper (&&) (.||) = boolHelper (||) infixr 4 .&& , .|| notB f = Boolean $ unBOOL f >=> return . not ordHelp :: (Traversable f,Ord a,VAR :<: f,LAM :<: f,VAR :<: PF (RHS f),LAM :<: PF (RHS f),APP :<: f,OrdF f) => [Ordering] -> RHS f a -> RHS f a -> Term (BOOL f) ordHelp ords a b = Term $ Boolean $ \subs -> do a' <- substitute app subs a b' <- substitute app subs b return $ elem (compareF (stripAnn a') (stripAnn b')) ords (.<) = ordHelp [LT] (.>) = ordHelp [GT] (.>=) = ordHelp [GT,EQ] (.<=) = ordHelp [LT,EQ] (.==) = ordHelp [EQ] (.|) = guarded infixr 2 .| -- ] {- ex :: Expr SIG a ex = student 2 "NOT matched" 2 rEnglish -} --student_rule3 :: _ => MetaId Int -> Rule (LHS' f) rhs student_rule x y= [student (meta x) __ (meta y) rEnglish ] .| meta x .> 0 .&& meta y .> meta x ===> student (meta x) "matched!" (meta x) rMath student_rule2 x y= [student (meta x) __ (meta y) rEnglish ,student 2 __ (meta x) rEnglish] .| meta x .== meta y ===> student (meta x) "matched!" (meta x) rMath instance Functor f => Rep (Cxt NoHole f) where type PF (Cxt NoHole f) = f toRep = toCxt fromRep r = fmap (const ()) r f,f2 :: Cxt Hole SIG String f = iStudent (Hole "num") (Hole "only") (iL (2::Int)) iEnglish --f = iStudent (Hole "num") (Hole "only") (iL (2::Int)) iEnglish f2 = iStudent (iL (9::Int)) (iCONS (Hole "only") (Hole "only")) (Hole "num") iEnglish f3 :: Cxt NoHole SIG () f3 = iStudent (iL (5::Int)) (iL ("start"::String)) (iL (2::Int)) iEnglish g = iL (5 ::Int) g2 = iL (7 ::Int) m r cxt conds = do (c,mapping) <- matchRule r cxt guard $ conds mapping return (c,mapping) m2 r cxt = do (c,mapping) <- matchRule r cxt guard $ and $ fmap (\(a@(V t f),_) -> f mapping) $ toList mapping return (c,mapping) g3 = iL (5 ::Int) g4,g5 :: Cxt Hole (LIT Int) (V Hole (LIT Int) String Int) g4 = iL (7 ::Int) g5 = iL (7 ::Int) --g5 = v "num" (< iL (5::Int)) data V h f v a = V v (Map (V h f v a) (Cxt h f a) -> Bool) pattern Stud a b c d <- Term (proj -> Just ((Student a b c d))) _s,_id :: (SIG :<: f,STUDENT :<: f,Functor f) => Cxt h f a -> Cxt h f a -> Cxt h f a Stud _ b c d `_id` (deepProject -> Just (a:: Cxt h SIG a)) = iStudent (prep a) (prep b) (prep c) (prep d) Stud _ b c d `_s` (deepProject -> Just (a:: Cxt h SIG a)) = iStudent (prep a) (prep b) (prep c) (prep d) -- _s :: LHS' SIG a -> LHS' SIG a -> LHS' SIG a prep = deepInject data Expr2 h f a b = Expr2 {unExpr2 :: Cxt h f a} deriving Show data Hole2 h f a = H String [([Ordering],Cxt h f (Hole2 h f a))] | Wild instance Eq (Hole2 h f a) where H a _ == H b _ = a == b instance Ord (Hole2 h f a) where H a _ `compare` H b _ = a `compare` b instance (ShowF f,Functor f) => Show (Hole2 h f a) where show (H s b) = "Hole2 " ++ show s ++ " " ++ show b --type LHS2 h f a b = LHS2 {unLHS2 :: Cxt h f (Hole2 h f a)} deriving Show newtype LHS2 h a f b = LHS2 {unLHS2 :: Cxt h f (Hole2 h f a)} deriving (Show,Functor) sstudent :: (STUDENT :<: PF' r,Rep' r) => r Int -> r String -> r Int -> r (MAJOR a) -> r a sstudent = sStudent lhs2 :: LHS2 Hole a SIG b lhs2 = sstudent ("id" ..< 3) ("s" ..= "hi") __ __ (==>) :: LHS2 Hole a f b -> LHS2 Hole a g b -> (Context f (Hole2 Hole f a) ,Context g (Hole2 Hole g a)) LHS2 a ==> LHS2 b = (a,b) v a func term = LHS2 $ Hole (H a [(func,term)]) h a = LHS2 $ Hole (H a []) (..<),(..=),(..>),(..!=) :: (Functor f,Traversable f) => String -> LHS2 Hole a f b -> LHS2 Hole a f b a ..< b = v a [LT] $ c b c b = maybe (error "undefined coerce") id $ deepProject $ fromRep' b a ..= b = v a [EQ] $ c b a ..> b = v a [GT] $ c b a ..!= b = v a [LT,GT] $ c b instance WildCard (LHS2 Hole a f) where __ = LHS2 $ Hole $ Wild instance Functor f => Rep' (Cxt NoHole f) where type PF' (Cxt NoHole f) = f type PHOLE' (Cxt NoHole f) = () type PHOLE'' (Cxt NoHole f) = NoHole toRep' = toCxt fromRep' = fmap (const ()) instance (Functor f) => Rep' (LHS2 h a f) where type PF' (LHS2 h a f) = f type PHOLE' (LHS2 h a f) = Hole2 h f a type PHOLE'' (LHS2 h a f) = h toRep' = LHS2 fromRep' = unLHS2 instance Rep' (LHS f) where type PF' (LHS f) = (WILD :+: META (LHS f) :+: f) type PHOLE' (LHS f) = () type PHOLE'' (LHS f) = NoHole toRep' = LHS fromRep' = unLHS instance Rep' (RHS f) where type PF' (RHS f) = (META (RHS f) :+: f) type PHOLE' (RHS f) = () type PHOLE'' (RHS f) = NoHole toRep' = RHS fromRep' = unRHS type HoledCxt h f a = Cxt h f (Hole2 h f a) example = sstudent ("x" ..< 2) "hi" ("y" ..!= h "x") sMath ==> sstudent (h "y") "MATCHED" (h "x") sEnglish main = do --drawTerm $ reduce (parallelStep [(g,g2),(f,f2)]) f3 --putStrLn $ show $ ( d4 :: Expr2 Hole SIG (V Hole SIG String (Cxt Hole L2 )) b) --putStrLn $ show $ m2 (g5,g4) g3 mapM_ drawTerm $ appRule' example $ (sstudent 1 "hi" 0 sMath :: Term SIG) {- putStrLn $ show $ m (f,f2) f3 (\mp -> mp ! "num" < iL (6 :: Int)) let e = unExpr ex drawTerm $ rewriteWith (reduce $ rewrite' app $ quantify student_rule) e drawTerm $ rewriteWith (reduce $ rewrite' app $ quantify student_rule2) e -} appRule' :: (Ord a,OrdF f,Show a,ShowF f,v ~ Hole2 Hole f a,Ord v, EqF f, Eq a, Functor f, Foldable f) => Data.Comp.TermRewriting.Rule f f v -> Step (Cxt h f a) appRule' rule t = do (res, subst) <- matchRule rule t trace (concatMap (\(a,b) -> show a ++ "::::" ++ show b) $ toList subst) (Just undefined) let x = concatMap (\(H v conds,b) -> fmap (\(ords,cond) -> elem (compare b (substHoles' cond subst)) ords ) conds) $ toList subst trace (show x) $ return () if and x then return $ substHoles' res subst else return t
tomberek/RETE
src/RETE/Lib4.hs
Haskell
bsd-3-clause
11,486
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} -- {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} #ifndef MIN_VERSION_transformers #define MIN_VERSION_transformers(x,y,z) 4 #endif -- -- #ifdef MIN_VERSION_GLASGOW_HASKELL -- -- #if MIN_VERSION_GLASGOW_HASKELL(8,0,1,0) -- -- -- ghc >= 8.0.1 -- -- {-# LANGUAGE StandaloneDeriving #-} -- -- #else -- -- -- older ghc versions, but MIN_VERSION_GLASGOW_HASKELL defined -- -- #endif -- -- #else -- -- -- MIN_VERSION_GLASGOW_HASKELL not even defined yet (ghc <= 7.8.x) -- -- #endif -- for debugging -- {-# LANGUAGE InstanceSigs #-} -- {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | -- Copyright : (c) Andreas Reuleaux 2015 -- License : BSD2 -- Maintainer: Andreas Reuleaux <rx@a-rx.info> -- Stability : experimental -- Portability: non-portable -- -- This module provides Pire's syntax, -- ie. Pire's flavour of Pi-forall syntax: -- expressions, annotations, ... (mutally recursive defs) module Pire.Syntax.Expr where -- import Data.List import Control.Monad #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) -- #if (MIN_VERSION_transformers(0,5,0)) import Data.Functor.Classes import Data.Eq.Deriving (deriveEq1) import Data.Ord.Deriving (deriveOrd1) import Text.Show.Deriving (deriveShow1) import Text.Show (showListWith) import Text.Read.Deriving (deriveRead1) #else import Prelude.Extras #endif import Bound import Bound.Name import Bound.Scope import Data.Bifoldable import Data.Bifunctor import Data.Bitraversable import Text.Trifecta.Delta (Delta) import Pire.Syntax.Ws import Pire.Syntax.Token import Pire.Syntax.Nm import Pire.Syntax.Binder import Pire.Syntax.Eps import Pire.Syntax.Pattern -- import Pire.Syntax.GetNm() -- import Debug.Trace import Control.Lens import Data.Typeable hiding (Refl) import Pire.Syntax.NatPrime infixl 9 :@ data Expr t a = V a | Nat' (PossiblyVar t) | Ws_ (Expr t a) (Ws t) -- -- | WildcardSeen_ (Expr t a) -- -- | WildcardInferred_ Integer | BndV t (Expr t a) -- bracketed var, eg. [ v ], originally defined as -- BracketedV_ (BracketOpen...) a Ws (BracketClose...) -- but later needed any kind of expr within brackets anyway, for args ie. | Brackets_ (Token 'BracketOpenTy t) (Expr t a) (Token 'BracketCloseTy t) -- parenthesized term, useful for printing | Paren (Expr t a) | Paren_ (Token 'ParenOpenTy t) (Expr t a) (Token 'ParenCloseTy t) | Type | Type_ t (Ws t) | (Expr t a) :@ (Expr t a) | ErasedApp (Expr t a) (Expr t a) | Lam t (Scope () (Expr t) a) | Lam_ (Token 'LamTokTy t) (Binder t) (Token 'DotTy t) (Scope () (Expr t) a) -- defs w/ (original) Name s - they are not really needed, but convenient to have: -- (in the following a prime as in Lam' indicates a Scope w/ (original) Name s) -- this would seem a natural def according to the Bound.Name docs: -- -- | Lam' t (Scope (Name a ()) (Expr t) a) -- however it gets in the way of automatically deriving Functor, Foldable, and Traversable below -- this I came up w/ instead - worked for a while -- (but wasn't too sure, if it makes sense in the first place): -- -- | Lam' t (Scope (Name t ()) (Expr t) a) -- however, as then discovered, this gets in the way of making Expr bitraversable below, -- which is not only nice to have (eg. for Text2String) -- but essential for our position/range calculations -- so we resort to using a fixed data type: String (or T.Text or whatever) | Lam' t (Scope (Name String ()) (Expr t) a) -- and the corresponding plural version: | Lams' [t] (Scope (Name String Int) (Expr t) a) -- the caveat is that, that desugaring (so far generic: for any kind of Expr), -- becomes tied to String (or...) that way, ie. if we want to desugar Lams' to Lam' etc. -- (or we would need different versions of desugaring functions, for String, T.Text etc) -- so Scopes w/ Names are really not that useful (and not really needed anyway), -- they are just convenient to have when starting out w/ Bound. -- That's why they are not used in the following defs of other Exprs -- (in particular there are not white space aware versions of the above: Lam'_, Lams'_ ) -- Lam' and Lams' kept here nevertheless, just for experimentation | ErasedLam t (Scope () (Expr t) a) | ErasedLam_ (Token 'LamTokTy t) (Binder t) (Token 'DotTy t) (Scope () (Expr t) a) -- desugaring is handled here explicitly, -- ie. a lambda with multiple binders will become a Lams: -- (plural s, white space aware: Lams_), desugared to Lam (Lam_) -- these are superseded by the following LamPAs, -- which cover also the notion of a RuntimeP/ErasedP pattern (P), -- as well as an annotation (A), to sum up: -- Lams are desugared to Lam -- Lams_ to Lam_ -- LamPAs to LamPA -- LamPAs_ to LamPA_ - one would think (and maybe LamPA_ should be added), -- but desugaring is really needed only for untie (conversion to PiForall data structures), -- and there we have long thrown away the white space w/ forget | Lams [t] (Scope Int (Expr t) a) | Lams_ (Token 'LamTokTy t) [Binder t] (Token 'DotTy t) (Scope Int (Expr t) a) | LamPA Eps t (Annot t a) (Scope () (Expr t) a) #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) | LamPAs [(Eps, t, Annot t a)] (Scope Int (Expr t) a) #else | LamPAs [(Eps, t, Annot t a)] (Scope Int (Expr t) a) #endif -- need this as well for List 2 Vect: the notion of a yet to be filled in var | LamPAs' [(Eps, PossiblyVar t, Annot t a)] (Scope Int (Expr t) a) | LamPAs_ (Token 'LamTokTy t) [(Eps, Binder t, Annot t a)] (Token 'DotTy t) (Scope Int (Expr t) a) -- the simplest kind of Pi type | Pi t (Expr t a) (Scope () (Expr t) a) | Pi_ (Expr t a) (Token 'ArrowTy t) (Scope () (Expr t) a) -- keep track of pattern (instead of Pi/ErasedPi), similar to LamPA/LamPAs -- pi's are binders (binding type: embed), hence the use of t -- get rid of scopes w/ orig Names -- -- | PiP Eps t (Expr t a) (Scope (Name t ()) (Expr t) a) | PiP Eps t (Expr t a) (Scope () (Expr t) a) -- -- Pi_ (Ann_ ...) -- -- reuse Ann_ for the binding in Pi_ here, thereby making its def simple -- -- need to keep track maybe, if we actually have seen some parens/colon -- -- idea so far: if not, than the name will start with _: _/_1/_2 etc -- -- maybe use some (new) flag for Ann_ instead -- get rid of scope's w/ orig Names -- -- | PiP_ Eps (Expr t a) (Arrow t) (Scope (Name t ()) (Expr t) a) | PiP_ Eps (Expr t a) (Token 'ArrowTy t) (Scope () (Expr t) a) -- just a trifecta delta -- when untied, this will become a Parsec/PiForall Pos -- not to be confused with the data type Pos of Refactor/Range.hs | Position Delta (Expr t a) -- an axiom 'TRUSTME', inhabits all types | TrustMe (Annot t a) | TrustMe_ t (Ws t) (Annot t a) -- unit -- The type with a single inhabitant `One` | TyUnit | TyUnit_ t (Ws t) -- The inhabitant, written `tt` | LitUnit | LitUnit_ t (Ws t) -- boolean expressions -- The type with two inhabitants | TyBool | TyBool_ t (Ws t) -- True and False | LitBool Bool | LitBool_ Bool t (Ws t) -- if expression for eliminating booleans | If (Expr t a) (Expr t a) (Expr t a) (Annot t a) | If_ (Token 'IfTokTy t) (Expr t a) (Token 'ThenTokTy t) (Expr t a) (Token 'ElseTokTy t) (Expr t a) (Annot t a) -- sigma types -- `{ x : A | B }` -- -- | Sigma (Bind (TName, Embed Term) Term) | Sigma t (Expr t a) (Scope () (Expr t) a) | Sigma_ (Token 'BraceOpenTy t) (Binder t) (Token 'ColonTy t) (Expr t a) (Token 'VBarTy t) (Scope () (Expr t) a) (Token 'BraceCloseTy t) -- introduction for sigmas `( a , b )` | Prod (Expr t a) (Expr t a) (Annot t a) | Prod_ (Token 'ParenOpenTy t) (Expr t a) (Token 'CommaTy t) (Expr t a) (Token 'ParenCloseTy t) (Annot t a) -- elimination form `pcase p of (x,y) -> p` -- -- | Pcase Term (Bind (TName, TName) Term) Annot -- rethink if scope is well defined ! -- todo: rethink Scope for both Pcase and Pcase_ -- maybe () is not enough ? -- -- | Pcase (Expr t a) (t, t) (Scope () (Expr t) a) (Annot t a) | Pcase (Expr t a) (t, t) (Scope Int (Expr t) a) (Annot t a) -- -- | Pcase_ (PcaseTok t) (Expr t a) (Of t) -- -- (ParenOpen t) (Binder t) (Comma t) (Binder t) (ParenClose t) -- -- (Arrow t) (Scope () (Expr t) a) (Annot t a) | Pcase_ (Token 'PcaseTokTy t) (Expr t a) (Token 'OfTy t) (Token 'ParenOpenTy t) (Binder t) (Token 'CommaTy t) (Binder t) (Token 'ParenCloseTy t) (Token 'ArrowTy t) (Scope Int (Expr t) a) (Annot t a) -- -- | Let {-# UNPACK #-} !Int [Scope Int Exp a] (Scope Int Exp a) -- let w/ scope - closer to the def above -- -- | LetS (Scope (Name String ()) Exp a) (Scope (Name String ()) Exp a) -- ! in pi-forall: binding type: embed | Let t (Expr t a) (Scope () (Expr t) a) | Let_ (Token 'LetTokTy t) (Binder t) (Token 'EqualTy t) (Expr t a) (Token 'InTy t) (Scope () (Expr t) a) -- Equality type `a = b` | TyEq (Expr t a) (Expr t a) | TyEq_ (Expr t a) (Token 'EqualTy t) (Expr t a) -- Proof of equality | Refl (Annot t a) -- the whitespace aware version is now just -- Ws_ (Refl (Annot t a)) (Ws t) -- but maybe not a good idea: the ws is before the annot! | Refl_ t (Ws t) (Annot t a) -- equality elimination | Subst (Expr t a) (Expr t a) (Annot t a) | Subst_ (Token 'SubstTokTy t) (Expr t a) (Token 'ByTy t) (Expr t a) (Annot t a) -- witness to an equality contradiction | Contra (Expr t a) (Annot t a) | Contra_ (Token 'ContraTokTy t) (Expr t a) (Annot t a) -- datatypes -- type constructors (fully applied) -- -- | TCon t [Expr t a] -- -- | TCon_ (Nm t) [Expr t a] | TCon a [Expr t a] | TCon_ (Nm t a) [Expr t a] -- -- | TCon a [Expr t a] -- -- | TCon_ (Expr t a) [Expr t a] -- term constructors | DCon t [Arg t a] (Annot t a) | DCon_ (Nm1 t) [Arg t a] (Annot t a) -- don't want implicit desugaring for nats -- (so keep the orig) | Nat Integer | Nat_ Integer t (Ws t) -- case analysis -- (fully applied, erased arguments first) -- -- | Case (Expr t a) [Match t a] (Annot t a) | Case (Expr t a) [Match t a] (Annot t a) -- -- | Case_ (Token 'CaseTokTy t) (Expr t a) (Token 'OfTy t) -- -- (Maybe (Token 'BraceOpenTy t)) [(Match t a, Maybe (Token 'SemiColonTy t))] (Maybe (Token 'BraceCloseTy t)) -- -- (Annot t a) | Case_ (Token 'CaseTokTy t) (Expr t a) (Token 'OfTy t) (Maybe (Token 'BraceOpenTy t)) [(Maybe (Token 'SemiColonTy t), Match t a)] (Maybe (Token 'BraceCloseTy t)) (Annot t a) -- -- | CaseIndented_ (Token 'CaseTokTy t) (Expr t a) (Token 'OfTy t) [Match t a] (Annot t a) -- -- | CaseWithBraces_ (Token 'CaseTokTy t) (Expr t a) (Token 'OfTy t) -- -- (Token 'BraceOpenTy t) [(Match t a, Maybe (Token 'SemiColonTy t))] (Token 'BraceCloseTy t) -- -- (Annot t a) -- Annotated terms `( x : A )` | Ann (Expr t a) (Expr t a) -- originally just -- | Ann_ ParenOpen (Exp_ a) Colon (Exp_ a) ParenClose -- but need to be more specific here: -- have witnessed an annotation / or just inferred it (think of "_ : A"), in parens / brackets -- -- todo: rework this comment (only parts still valid) -- can't really make up my mind if the x should be a binder here -- my current take is: no, it's not (there is no Scope involved), -- ie. it's a binder only in the case of a Pi-type à la: (x:A) -> B -- ie. the ...Bnd  variants are used for Pi-types in PiP_... -- and [later]: as I can't make up my mind, if x should be a binder, -- these constructors come in pairs now: one, where it isn't a binder, -- and one where it is -- reuse Paren_ + Brackets_ for Ann_ as well -- eg. -- Ann_ $ Paren_ (ParenOpen...) (WitnessedAnnEx_ ...)(ParenClose...) -- Ann_ $ Brackets_ (BracketOpen...)(Witnessed...) (BracketClose...) -- Ann_ $ InferredAnnBnd_ -- always make clear however that it's an Ann_ (wrap it in Ann_) -- to not confuse annotations with a simple Paren_ exprs eg. | WitnessedAnnEx_ (Expr t a) (Token 'ColonTy t) (Expr t a) | InferredAnnBnd_ (Binder t) (Expr t a) | WitnessedAnnBnd_ (Binder t) (Token 'ColonTy t) (Expr t a) | Ann_ (Expr t a) deriving (Functor,Foldable,Traversable) extract :: Expr t a -> a extract (V a) = a extract (Ws_ ex _) = extract ex extract (Brackets_ _ ex _) = extract ex extract _ = error "tried to extract from other than V. Ws_, or Brackets_" instance Applicative (Expr t) where pure = V (<*>) = ap instance Monad (Expr t) where return = V Nat' x >>= _ = Nat' x V a >>= f = f a Ws_ x ws >>= f = Ws_ (x >>= f) ws (x :@ y) >>= f = (x >>= f) :@ (y >>= f) ErasedApp x y >>= f = ErasedApp (x >>= f) (y >>= f) Type >>= _ = Type (Type_ ty ws) >>= _ = Type_ ty ws BndV v ex >>= f = BndV v (ex >>= f) Lam n s >>= f = Lam n (s >>>= f) Lam_ lamtok v dot s >>= f = Lam_ lamtok v dot (s >>>= f) -- missing ErasedLam / ErasedLam_ Lams ns s >>= f = Lams ns (s >>>= f) Lams_ lamtok ns dot s >>= f = Lams_ lamtok ns dot (s >>>= f) Lam' n s >>= f = Lam' n (s >>>= f) Lams' ns s >>= f = Lams' ns (s >>>= f) LamPA pat n (Annot ann) scope >>= f = LamPA pat n (Annot $ (>>= f) <$> ann) (scope >>>= f) LamPA _ _ (Annot_ {}) _ >>= _ = error "LamPA w/ Annot_" LamPAs nas s >>= f = LamPAs [ (pat, n, Annot $ (>>= f) <$> ann) | (pat, n, Annot ann) <- nas] (s >>>= f) LamPAs_ lamtok nas dottok s >>= f = LamPAs_ lamtok [ (pat, n, (Annot_ ((>>= f) <$> ann) ws)) | (pat, n, Annot_ ann ws) <- nas] dottok (s >>>= f) ErasedLam n s >>= f = ErasedLam n (s >>>= f) ErasedLam_ lamtok v dot s >>= f = Lam_ lamtok v dot (s >>>= f) TrustMe (Annot ann) >>= f = TrustMe (Annot $ (>>= f) <$> ann) TrustMe (Annot_ {}) >>= _ = error "TrustMe w/ Annot_" TrustMe_ tme ws (Annot_ ann ws') >>= f = TrustMe_ tme ws (Annot_ ((>>= f) <$> ann) ws') TrustMe_ _ _ (Annot {}) >>= _ = error "TrustMe_ w/ Annot" Position p e >>= f = Position p (e >>= f) Pi nm ty sc >>= f = Pi nm (ty >>= f) (sc >>>= f) Pi_ ann arr sc >>= f = Pi_ (ann >>= f) arr (sc >>>= f) PiP eps n e s >>= f = PiP eps n (e >>= f) (s >>>= f) PiP_ eps n arr s >>= f = PiP_ eps (n >>= f) arr (s >>>= f) TyUnit >>= _ = TyUnit TyUnit_ ty ws >>= _ = TyUnit_ ty ws LitUnit >>= _ = LitUnit LitUnit_ tt ws >>= _ = LitUnit_ tt ws TyBool >>= _ = TyBool TyBool_ tb ws >>= _ = TyBool_ tb ws LitBool b >>= _ = LitBool b LitBool_ b lb ws >>= _ = LitBool_ b lb ws Sigma str' ex scope >>= f = Sigma str' (ex >>= f) (scope >>>= f) Sigma_ bo str' col ex vb scope bc >>= f = Sigma_ bo str' col (ex >>= f) vb (scope >>>= f) bc Prod a b (Annot ann) >>= f = Prod (a >>=f ) (b >>= f) (Annot $ (>>= f) <$> ann) Prod _ _ (Annot_ {}) >>= _ = error "Prod w/ Annot_" Prod_ po a cmm b pc (Annot_ ann ws) >>= f = Prod_ po (a >>=f ) cmm (b >>= f) pc (Annot_ ((>>= f) <$> ann) ws) Prod_ _ _ _ _ _ (Annot {}) >>= _ = error "Prod_ w/ Annot" -- -- elimination form `pcase p of (x,y) -> p` Pcase ex (s, t) sc (Annot ann) >>= f = Pcase (ex >>=f) (s, t) (sc >>>=f) (Annot $ (>>= f) <$> ann) Pcase_ pcase ex of' po s comma t pc arr sc (Annot_ ann ws) >>= f = Pcase_ pcase (ex >>= f) of' po s comma t pc arr (sc >>>= f) (Annot_ ((>>= f) <$> ann) ws) -- Let n bs e >>= f = Let n (map (>>>= f) bs) (e >>>= f) Let n b e >>= f = Let n (b >>= f) (e >>>= f) Let_ let' n eq b in' e >>= f = Let_ let' n eq (b >>= f) in' (e >>>= f) -- matches are binders: thus leave the pattern pat as is Case e ms (Annot ann) >>= f = Case (e >>= f) [Match (bpattern pat) (s >>>= f) | (Match pat s) <- ms] (Annot $ (>>= f) <$> ann) where bpattern (PatVar tt) = PatVar tt -- bpattern (PatVar tt) = PatVar $ a2b tt -- bpattern (PatCon aa ls) = PatCon (a2b aa) [ (bpattern p, eps) | (p, eps) <- ls] bpattern (PatCon aa ls) = PatCon (a2b aa) [ (eps, bpattern p) | (eps, p) <- ls] -- -- bpattern (PatVar_ nm) = PatVar_ $ bnm nm bpattern (PatVar_ nm) = PatVar_ $ nm -- bpattern (PatCon_ nm ls) = PatCon_ (bnm nm) [ (bpattern p, eps) | (p, eps) <- ls] bpattern (PatCon_ nm ls) = PatCon_ (bnm nm) [ (eps, bpattern p) | (eps, p) <- ls] bpattern (NatPatVar n) = NatPatVar n a2b = extract . f bnm (Nm_ aa ws') = Nm_ (a2b aa) ws' -- -- Case_ ctok e oftok bo ms bc (Annot_ ann ws) >>= -- -- f = Case_ -- -- ctok -- -- (e >>= f) -- -- oftok -- -- bo -- -- [(Match_ (bpattern pat) arr (s >>>= f), semi) | (Match_ pat arr s, semi) <- ms] -- -- bc -- -- (Annot_ ((>>= f) <$> ann) ws) -- -- where -- -- bpattern (PatVar tt) = PatVar tt -- -- -- bpattern (PatVar tt) = PatVar $ a2b tt -- -- bpattern (PatCon aa ls) = PatCon (a2b aa) [ (bpattern p, eps) | (p, eps) <- ls] -- -- -- bpattern (PatCon aa ls) = PatCon aa [ (bpattern p, eps) | (p, eps) <- ls] -- -- -- -- bpattern (PatVar_ nm) = PatVar_ $ bnm nm -- -- bpattern (PatVar_ nm) = PatVar_ $ nm -- -- bpattern (PatCon_ nm ls) = PatCon_ (bnm nm) [ (bpattern p, eps) | (p, eps) <- ls] -- -- bpattern (PatInBrackets_ bo' pat bc') = PatInBrackets_ bo' (bpattern pat) bc' -- -- bpattern (PatInParens_ po pat pc) = PatInParens_ po (bpattern pat) pc -- -- bpattern (NatPatVar n) = NatPatVar n -- -- -- TODO -- -- -- more cases ... -- -- a2b = extract . f -- -- bnm (Nm_ aa ws') = Nm_ (a2b aa) ws' Case_ ctok e oftok bo ms bc (Annot_ ann ws) >>= f = Case_ ctok (e >>= f) oftok bo [(semi, Match_ (bpattern pat) arr (s >>>= f)) | (semi, Match_ pat arr s) <- ms] bc (Annot_ ((>>= f) <$> ann) ws) where bpattern (PatVar tt) = PatVar tt -- bpattern (PatVar tt) = PatVar $ a2b tt -- bpattern (PatCon aa ls) = PatCon (a2b aa) [ (bpattern p, eps) | (p, eps) <- ls] bpattern (PatCon aa ls) = PatCon (a2b aa) [ (eps, bpattern p) | (eps, p) <- ls] -- -- bpattern (PatVar_ nm) = PatVar_ $ bnm nm bpattern (PatVar_ nm) = PatVar_ $ nm -- bpattern (PatCon_ nm ls) = PatCon_ (bnm nm) [ (bpattern p, eps) | (p, eps) <- ls] bpattern (PatCon_ nm ls) = PatCon_ (bnm nm) [ (eps, bpattern p) | (eps, p) <- ls] bpattern (PatInBrackets_ bo' pat bc') = PatInBrackets_ bo' (bpattern pat) bc' bpattern (PatInParens_ po pat pc) = PatInParens_ po (bpattern pat) pc bpattern (NatPatVar n) = NatPatVar n -- TODO -- more cases ... a2b = extract . f bnm (Nm_ aa ws') = Nm_ (a2b aa) ws' -- CaseIndented_ ctok e oftok ms (Annot_ ann ws) >>= -- f = CaseIndented_ -- ctok -- (e >>= f) -- oftok -- [Match_ pat arr (s >>>= f) | Match_ pat arr s <- ms] -- (Annot_ ((>>= f) <$> ann) ws) -- CaseWithBraces_ ctok e oftok bo ms bc (Annot_ ann ws) >>= -- f = CaseWithBraces_ -- ctok -- (e >>= f) -- oftok -- bo -- [(Match_ pat arr (s >>>= f), semi) | (Match_ pat arr s, semi) <- ms] -- bc -- (Annot_ ((>>= f) <$> ann) ws) -- TCon s es >>= f = TCon s (map (>>= f) es) -- TCon_ s es >>= f = TCon_ s (map (>>= f) es) TCon s es >>= f = TCon (a2b s) (map (>>= f) es) where a2b = extract . f TCon_ s es >>= f = TCon_ (bnm s) (map (>>= f) es) where a2b = extract . f bnm (Nm_ aa ws') = Nm_ (a2b aa) ws' -- -- TCon s es >>= f = TCon (s >>= f) (map (>>= f) es) -- -- TCon_ s es >>= f = TCon_ (s >>= f) (map (>>= f) es) DCon s as (Annot ann) >>= f = DCon s [ Arg pat (e >>= f) | (Arg pat e) <- as] (Annot $ (>>= f) <$> ann) DCon_ s as (Annot_ ann ws) >>= f = DCon_ s [ Arg pat (e >>= f) | (Arg pat e) <- as] (Annot_ ((>>= f) <$> ann) ws) If cond t e (Annot ann) >>= f = If (cond >>= f) (t >>= f) (e >>= f) (Annot $ (>>= f) <$> ann) If_ iftok cond thentok t etok e (Annot_ ann ws) >>= f = If_ iftok (cond >>= f) thentok (t >>= f) etok (e >>= f) (Annot_ ((>>= f) <$> ann) ws) Paren e >>= f = Paren (e >>= f) Paren_ po e pc >>= f = Paren_ po (e >>= f) pc Nat n >>= _ = Nat n Nat_ nmbr tok ws >>= _ = Nat_ nmbr tok ws TyEq a b >>= f = TyEq (a >>= f) (b >>= f) TyEq_ a eq b >>= f = TyEq_ (a >>= f) eq (b >>= f) Subst a b (Annot ann) >>= f = Subst (a >>= f) (b >>= f) (Annot $ (>>= f) <$> ann) Subst_ subst a by b (Annot_ ann ws) >>= f = Subst_ subst (a >>= f) by (b >>= f) (Annot_ ((>>= f) <$> ann) ws) Contra a (Annot ann) >>= f = Contra (a >>= f) (Annot $ (>>= f) <$> ann) Contra_ ctok a (Annot_ ann ws) >>= f = Contra_ ctok (a >>= f) (Annot_ ((>>= f) <$> ann) ws) Refl (Annot ann) >>= f = Refl (Annot $ (>>= f) <$> ann) Refl_ rfl ws (Annot_ ann ws') >>= f = Refl_ rfl ws (Annot_ ((>>= f) <$> ann) ws') Ann a b >>= f = Ann (a >>= f) (b >>= f) -- exmpl -- lams_ ["x", "y"] $ (V_ "b" $ Ws "{-foo-}") -- lam_ "x" $ (V_ "b" $ Ws "{-foo-}") Brackets_ bo e bc >>= f = Brackets_ bo (e >>= f) bc -- -- WitnessedAnnInParens_ po ex col ty pc >>= f = WitnessedAnnInParens_ po (ex >>= f) col (ty >>= f) pc -- -- WitnessedAnnInParensBnd_ po b col ty pc >>= f = WitnessedAnnInParensBnd_ po b col (ty >>= f) pc -- -- WitnessedAnnInBrackets_ bo ex col ty bc >>= f = WitnessedAnnInBrackets_ bo (ex >>= f) col (ty >>= f) bc -- -- WitnessedAnnInBracketsBnd_ bo bnd col ty bc >>= f = WitnessedAnnInBracketsBnd_ bo bnd col (ty >>= f) bc -- -- InferredAnn_ ex ty >>= f = InferredAnn_ (ex >>= f) (ty >>= f) -- -- InferredAnnBnd_ bnd ty >>= f = InferredAnnBnd_ bnd (ty >>= f) -- -- InferredAnnInBrackets_ bo ex ty bc >>= f = InferredAnnInBrackets_ bo (ex >>= f) (ty >>= f) bc -- -- InferredAnnInBracketsBnd_ bo ex ty bc >>= f = InferredAnnInBracketsBnd_ bo ex (ty >>= f) bc -- AnnInParens_ bt po ex col ty pc >>= f = AnnInParens_ bt po (ex >>= f) col (ty >>= f) pc -- AnnInParensBnd_ bt po b col ty pc >>= f = AnnInParensBnd_ bt po b col (ty >>= f) pc -- AnnInBrackets_ bt bo ex col ty bc >>= f = AnnInBrackets_ bt bo (ex >>= f) col (ty >>= f) bc -- AnnInBracketsBnd_ bt bo bnd col ty bc >>= f = AnnInBracketsBnd_ bt bo bnd col (ty >>= f) bc WitnessedAnnEx_ ex col ty >>= f = WitnessedAnnEx_ (ex >>= f) col (ty >>= f) InferredAnnBnd_ bnd ty >>= f = InferredAnnBnd_ bnd (ty >>= f) WitnessedAnnBnd_ bnd col ty >>= f = WitnessedAnnBnd_ bnd col (ty >>= f) Ann_ ann >>= f = Ann_ (ann >>= f) instance Bifunctor Expr where bimap = bimapDefault instance Bifoldable Expr where bifoldMap = bifoldMapDefault -- (silence $ runExceptT $ getModules_ ["samples"] "M") >>= return . (\m -> fromRight' $ (ezipper $ Mod m) >>= lineColumn 6 5 >>= focus) . last . fromRight' -- _decls mm instance Bitraversable Expr where {-# INLINE bitraverse #-} -- for debugging: require Show b -- bitraverse :: Applicative f => (a -> f c) -> (b -> f d) -> Expr a b -> f (Expr c d) -- bitraverse :: (Applicative f, Show b) => (a -> f c) -> (b -> f d) -> Expr a b -> f (Expr c d) bitraverse f g = bt where bt (V a) = V <$> g a bt (Nat' x ) = Nat' <$> traverse f x bt (Ws_ x ws) = Ws_ <$> bt x <*> traverse f ws bt (Brackets_ bo x bc) = Brackets_ <$> traverse f bo <*> bt x <*> traverse f bc bt (Paren x) = Paren <$> bt x bt (Paren_ po x pc) = Paren_ <$> traverse f po <*> bt x <*> traverse f pc bt (Type) = pure Type bt (Type_ tt ws) = Type_ <$> f tt <*> traverse f ws bt (l :@ r) = (:@) <$> bt l <*> bt r bt (ErasedApp l r) = ErasedApp <$> bt l <*> bt r bt (BndV v ex) = BndV <$> f v <*> bt ex bt (Nat n) = Nat <$> pure n bt (Nat_ n ntxt ws) = Nat_ <$> pure n <*> f ntxt <*> traverse f ws bt (Lam p b) = Lam <$> f p <*> bitraverseScope f g b bt (Lam_ lamtok binder dot sc) = Lam_ <$> traverse f lamtok <*> traverse f binder <*> traverse f dot <*> bitraverseScope f g sc -- bt (Lam' p b) = Lam' <$> f p <*> bitraverseScope f g b bt (ErasedLam p b) = ErasedLam <$> f p <*> bitraverseScope f g b -- bt (Lams ts b) = Lams <$> traverse (traverse f) ts <*> bitraverseScope f g b bt (Lams ts b) = Lams <$> traverse f ts <*> bitraverseScope f g b bt (LamPA eps bnd annot sc) = LamPA <$> pure eps <*> f bnd <*> bitraverseAnnot f g annot <*> bitraverseScope f g sc bt (LamPAs ps sc) = LamPAs <$> btTripleList ps <*> bitraverseScope f g sc where btTriple (eps, nm, annot) = (,,) <$> pure eps <*> f nm <*> bitraverseAnnot f g annot btTripleList trs = traverse btTriple trs bt (LamPAs' ps sc) = LamPAs' <$> btTripleList ps <*> bitraverseScope f g sc where btTriple (eps, nm, annot) = (,,) <$> pure eps <*> traverse f nm <*> bitraverseAnnot f g annot btTripleList trs = traverse btTriple trs bt (LamPAs_ lamtok ps dot sc) = LamPAs_ <$> traverse f lamtok <*> btTripleList ps <*> traverse f dot <*> bitraverseScope f g sc where btTriple (eps, binder, annot) = (,,) <$> pure eps <*> traverse f binder <*> bitraverseAnnot f g annot btTripleList trs = traverse btTriple trs bt (Lams_ {}) = error "bt: Lams__" bt (If a b c annot) = If <$> bt a <*> bt b <*> bt c <*> bitraverse f g annot bt (If_ iftok a thentok b elsetok c annot) = If_ <$> traverse f iftok <*> bt a <*> traverse f thentok <*> bt b <*> traverse f elsetok <*> bt c <*> bitraverse f g annot bt (Position d b) = Position d <$> bt b bt (Pi nm ty sc) = Pi <$> f nm <*> bt ty <*> bitraverseScope f g sc bt (Pi_ ex arr sc) = Pi_ <$> bt ex <*> traverse f arr <*> bitraverseScope f g sc bt (PiP eps nm ty sc) = PiP <$> pure eps <*> f nm <*> bt ty <*> bitraverseScope f g sc bt (PiP_ eps ex arr sc) = PiP_ <$> pure eps <*> bt ex <*> traverse f arr <*> bitraverseScope f g sc bt (Ann ex ty) = Ann <$> bt ex <*> bt ty bt (WitnessedAnnEx_ ex colon ty) = WitnessedAnnEx_ <$> bt ex <*> traverse f colon <*> bt ty bt (InferredAnnBnd_ bnd ty) = InferredAnnBnd_ <$> traverse f bnd <*> bt ty bt (WitnessedAnnBnd_ bnd colon ty) = WitnessedAnnBnd_ <$> traverse f bnd <*> traverse f colon <*> bt ty bt (Ann_ ex) = Ann_ <$> bt ex -- -- bt (TCon tt exprs) = TCon <$> f tt <*> traverse bt exprs -- -- bt (TCon_ nm exprs) = TCon_ <$> traverse f nm <*> traverse bt exprs bt (TCon aa exprs) = TCon <$> g aa <*> traverse bt exprs bt (TCon_ nm exprs) = TCon_ <$> bitraverseNm f g nm <*> traverse bt exprs bt (DCon tt args annot) = DCon <$> f tt <*> traverse (bitraverseArg f g) args <*> bitraverseAnnot f g annot bt (DCon_ nm args annot) = DCon_ <$> traverse f nm <*> traverse (bitraverseArg f g) args <*> bitraverseAnnot f g annot -- better way of debugging ? - unfortunately we don't have Show b... -- bt other = error $ "bt: " ++ (show $ other) -- bt other = trace (show other) $ error $ "bt: " bt (TrustMe annot) = TrustMe <$> bitraverse f g annot bt (TrustMe_ tt ws annot) = TrustMe_ <$> f tt <*> traverse f ws <*> bitraverse f g annot -- -- bt (TyUnit {}) = error "bt: TyUnit" -- -- bt (TyUnit_ {}) = error "bt: TyUnit_" bt (TyUnit) = pure TyUnit bt (TyUnit_ tt ws) = TyUnit_ <$> f tt <*> traverse f ws bt (LitUnit) = pure LitUnit bt (LitUnit_ tt ws) = LitUnit_ <$> f tt <*> traverse f ws bt (LitBool b) = LitBool <$> pure b bt (LitBool_ b tok ws) = LitBool_ <$> pure b <*> f tok <*> traverse f ws bt TyBool = pure TyBool bt (TyBool_ tok ws) = TyBool_ <$> f tok <*> traverse f ws bt (Lam' {}) = error "bt: Lam'" bt (Lams' {}) = error "bt: Lams'" bt (Subst ex1 ex2 annot) = Subst <$> bt ex1 <*> bt ex2 <*> bitraverse f g annot bt (Subst_ subst ex1 by ex2 annot) = Subst_ <$> traverse f subst <*> bt ex1 <*> traverse f by <*> bt ex2 <*> bitraverse f g annot -- -- -- witness to an equality contradiction -- -- | Contra (Expr t a) (Annot t a) -- -- | Contra_ (ContraTok t) (Expr t a) (Annot t a) bt (Contra ex annot) = Contra <$> bt ex <*> bitraverse f g annot bt (Contra_ contratok ex annot) = Contra_ <$> traverse f contratok <*> bt ex <*> bitraverse f g annot bt (Sigma nm ex sc) = Sigma <$> f nm <*> bt ex <*> bitraverseScope f g sc bt (Sigma_ bo bndr col ex vbar sc bc) = Sigma_ <$> traverse f bo <*> traverse f bndr <*> traverse f col <*> bt ex <*> traverse f vbar <*> bitraverseScope f g sc <*> traverse f bc bt (TyEq ex1 ex2) = TyEq <$> bt ex1 <*> bt ex2 bt (TyEq_ ex1 eq ex2) = TyEq_ <$> bt ex1 <*> traverse f eq <*> bt ex2 bt (Refl annot) = Refl <$> bitraverseAnnot f g annot bt (Refl_ tt ws annot) = Refl_ <$> f tt <*> traverse f ws <*> bitraverseAnnot f g annot bt (Prod ex1 ex2 annot) = Prod <$> bt ex1 <*> bt ex2 <*> bitraverse f g annot bt (Prod_ po ex1 comma ex2 pc annot) = Prod_ <$> traverse f po <*> bt ex1 <*> traverse f comma <*> bt ex2 <*> traverse f pc <*> bitraverse f g annot -- -- bt (Let bs ss) = Let <$> traverse (bitraverse f g) bs <*> bitraverseScope f g ss bt (Let nm ex sc) = Let <$> f nm <*> bt ex <*> bitraverseScope f g sc bt (Let_ lettok bndr eq ex intok sc) = Let_ <$> traverse f lettok <*> traverse f bndr <*> traverse f eq <*> bt ex <*> traverse f intok <*> bitraverseScope f g sc bt (Pcase scrut (x, a) sc annot) = Pcase <$> bt scrut <*> ((,) <$> f x <*> f a) <*> bitraverseScope f g sc <*> bitraverseAnnot f g annot bt (Pcase_ pcase ex of' po s comma t pc arr sc annot) = Pcase_ <$> traverse f pcase <*> bt ex <*> traverse f of' <*> traverse f po <*> traverse f s <*> traverse f comma <*> traverse f t <*> traverse f pc <*> traverse f arr <*> bitraverseScope f g sc <*> bitraverse f g annot bt (Case ex matches annot) = Case <$> bitraverseExpr f g ex <*> traverse (bitraverseMatch f g) matches <*> bitraverseAnnot f g annot -- -- bt (Case_ casetok ex oftok mayopen matches mayclose annot) = -- -- Case_ -- -- <$> traverse f casetok -- -- <*> bitraverseExpr f g ex -- -- <*> traverse f oftok -- -- <*> traverse (traverse f) mayopen -- -- <*> btPairs matches -- -- <*> traverse (traverse f) mayclose -- -- <*> bitraverseAnnot f g annot -- -- where -- -- btPair (match, maysemi) = (,) <$> bitraverseMatch f g match <*> traverse (traverse f) maysemi -- -- btPairs ps = traverse btPair ps bt (Case_ casetok ex oftok mayopen matches mayclose annot) = Case_ <$> traverse f casetok <*> bitraverseExpr f g ex <*> traverse f oftok <*> traverse (traverse f) mayopen <*> btPairs matches <*> traverse (traverse f) mayclose <*> bitraverseAnnot f g annot where btPair (maysemi, match) = (,) <$> traverse (traverse f) maysemi <*> bitraverseMatch f g match btPairs ps = traverse btPair ps -- -- bt (CaseIndented_ casetok ex oftok matches annot) = -- -- CaseIndented_ -- -- <$> traverse f casetok -- -- <*> bitraverseExpr f g ex -- -- <*> traverse f oftok -- -- <*> traverse (bitraverseMatch f g) matches -- -- <*> bitraverseAnnot f g annot -- -- bt (CaseWithBraces_ casetok ex oftok bo matches bc annot) = -- -- CaseWithBraces_ -- -- <$> traverse f casetok -- -- <*> bitraverseExpr f g ex -- -- <*> traverse f oftok -- -- <*> traverse f bo -- -- <*> btPairs matches -- -- <*> traverse f bc -- -- <*> bitraverseAnnot f g annot -- -- where -- -- btPair (match, maysemi) = (,) <$> bitraverseMatch f g match <*> traverse (traverse f) maysemi -- -- btPairs ps = traverse btPair ps bitraverseExpr :: Applicative f => (a -> f c) -> (b -> f d) -> Expr a b -> f (Expr c d) bitraverseExpr = bitraverse -- for the sake of writing this in the least verbose manner: -- using record wild cards for data constructors that are not declared with record fields here, -- works fine, but is not allowed according to -- https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/syntax-extns.html -- hope this will not break in the future wsAware :: Expr t a -> Bool wsAware (V _) = False wsAware (Ws_ {}) = True wsAware (x :@ _) = wsAware x wsAware (ErasedApp x _) = wsAware x wsAware (Position _ x) = wsAware x wsAware (Lam {}) = False wsAware (Lam_ {}) = True wsAware (Lam' {}) = False wsAware (Lams' {}) = False wsAware (LamPA {}) = False -- doesn't exist -- wsAware (LamPA_ {}) = True wsAware (LamPAs {}) = False wsAware (LamPAs_ {}) = True wsAware (PiP {}) = False wsAware (PiP_ {}) = True wsAware (Sigma {}) = False wsAware (Sigma_ {}) = True wsAware (If {}) = False wsAware (If_ {}) = True wsAware (Prod {}) = False wsAware (Prod_ {}) = True wsAware (Case {}) = False -- -- wsAware (Case_ {}) = True -- -- wsAware (CaseIndented_ {}) = True -- -- wsAware (CaseWithBraces_ {}) = True wsAware (Pcase {}) = False wsAware (Pcase_ {}) = True wsAware (Nat_ {}) = True wsAware (Nat {}) = False wsAware (TCon {}) = False wsAware (TCon_ {}) = True wsAware (TyEq {}) = False wsAware (TyEq_ {}) = True wsAware (Ann {}) = False wsAware (WitnessedAnnEx_ {}) = True wsAware (InferredAnnBnd_ {}) = True wsAware (WitnessedAnnBnd_ {}) = True wsAware (Ann_ {}) = True -- no catch all so far: let it break -- -- an 'Annot' is optional type information data Annot t a = Annot (Maybe (Expr t a)) | Annot_ (Maybe (Expr t a)) (Ws t) deriving (Functor,Foldable,Traversable) instance Applicative (Annot t) where pure = Annot . Just . V (<*>) = ap -- todo: think about the other cases -- or maybe better make Annot/Annot_ newtypes and automatically derive Monad, Applicative -- Monad really needed ? instance Monad (Annot t) where return = Annot . Just . V Annot (Nothing) >>= _ = Annot (Nothing) instance Bifunctor Annot where bimap = bimapDefault instance Bifoldable Annot where bifoldMap = bifoldMapDefault instance Bitraversable Annot where bitraverse f g (Annot mayex) = Annot <$> traverse (bitraverseExpr f g) mayex bitraverse f g (Annot_ mayex ws) = Annot_ <$> traverse (bitraverseExpr f g) mayex <*> traverse f ws bitraverseAnnot :: Applicative f => (a -> f c) -> (b -> f d) -> Annot a b -> f (Annot c d) bitraverseAnnot = bitraverse data Match t a = Match (Pattern t a) (Scope Int (Expr t) a) | Match_ (Pattern t a) (Token 'ArrowTy t) (Scope Int (Expr t) a) deriving (Functor,Foldable,Traversable) instance Bifunctor Match where bimap = bimapDefault instance Bifoldable Match where bifoldMap = bifoldMapDefault instance Bitraversable Match where bitraverse f g (Match pattern sc) = Match <$> (bitraverse f g pattern) <*> bitraverseScope f g sc bitraverse f g (Match_ pattern arr sc) = Match_ <$> bitraverse f g pattern <*> traverse f arr <*> bitraverseScope f g sc bitraverseMatch :: Applicative f => (a -> f c) -> (b -> f d) -> Match a b -> f (Match c d) bitraverseMatch = bitraverse -- an argument is tagged with whether it should be erased data Arg t a = Arg Eps (Expr t a) deriving (Functor,Foldable,Traversable) instance Bifunctor Arg where bimap = bimapDefault instance Bifoldable Arg where bifoldMap = bifoldMapDefault instance Bitraversable Arg where bitraverse f g (Arg eps ex) = Arg <$> pure eps <*> bitraverseExpr f g ex bitraverseArg :: Applicative f => (a -> f c) -> (b -> f d) -> Arg a b -> f (Arg c d) bitraverseArg = bitraverse -- some lenses for common tasks: get the binders etc -- exmpls -- (nopos $ parse expr_ "\\ a b c . f a b" ) ^. bndrs bndrs :: Lens' (Expr t a) [Binder t] bndrs = lens getter setter where getter = (\case { ; (Pcase_ _ _ _ _ b _ b2 _ _ _ _) -> [b, b2] ; (Lam_ _ b _ _) -> [b] ; (Let_ _ b _ _ _ _) -> [b] ; (Sigma_ _ bndr _ _ _ _ _) -> [bndr] ; (WitnessedAnnBnd_ bndr _ _ ) -> [bndr] ; (InferredAnnBnd_ bndr _ ) -> [bndr] ; (PiP_ _ ex _ _) -> getter ex ; (Paren_ _ ex _ ) -> getter ex ; (Brackets_ _ ex _ ) -> getter ex ; (Ann_ ex) -> getter ex ; (LamPAs_ _ triples _ _) -> (^. _2) <$> triples -- ... ; _ -> error "bndrs > getter: missing Expr" }) -- haven't tried the setter yet, exmples? setter = (\e newbs -> case e of { ; Pcase_ pcasetok ex oftok po _ comma _ pc arr sc annot -> Pcase_ pcasetok ex oftok po (newbs !! 0) comma (newbs !! 1) pc arr sc annot ; Lam_ lamtok _ dot sc -> Lam_ lamtok (newbs !! 0) dot sc ; Let_ lettok _ eq ex in' sc -> Let_ lettok (newbs !! 0) eq ex in' sc ; Sigma_ bo _ colon ex vbar sc bc -> Sigma_ bo (newbs !! 0) colon ex vbar sc bc ; WitnessedAnnBnd_ _ col ex -> WitnessedAnnBnd_ (newbs !! 0) col ex ; InferredAnnBnd_ _ ex -> InferredAnnBnd_ (newbs !! 0) ex ; PiP_ eps ex arr sc -> PiP_ eps (setter ex newbs) arr sc ; Paren_ po ex pc -> Paren_ po (setter ex newbs) pc ; Brackets_ bo ex bc -> Brackets_ bo (setter ex newbs) bc ; Ann_ ex -> Ann_ (setter ex newbs) -- OK ? ; LamPAs_ lamtok triples dot sc -> LamPAs_ lamtok [(eps, newbs !! y, annot) | (eps, _, annot) <- triples, y <- [0..]] dot sc -- ... ; other -> other }) -- instance MkVisible t => GetNm (Expr t a) t where -- name' (InferredAnnBnd_ bndr _) = name' bndr -- name' (WitnessedAnnBnd_ bndr _ _) = name' bndr -- name' (WitnessedAnnEx_ ex _ _) = name' ex -- name' (Ws_ ex _) = name' ex -- -- name' (V x) = x -- name' (Ann_ ex) = name' ex -- name' (Paren_ _ ex _) = name' ex -- name' (Brackets_ _ ex _) = name' ex -- at the bottom of the file -- http://stackoverflow.com/questions/20876147/haskell-template-haskell-and-the-scope #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) -- #if MIN_VERSION_transformers(0,5,0) -- instance Eq t => Eq1 ((,,) Eps t) where -- liftEq eq (someEps, someT, more) (otherEps, otherT, other) = eq someEps otherEps && eq someT otherT && eq more other -- instance Eq t => Eq1 (Expr t) where -- liftEq eq (Lam n sc) (Lam n' sc') = n == n' && liftEq eq sc sc' -- data Triple t a = Triple Eps t (Annot t a) -- deriveEq1 ''Triple -- need Eq1 for triples as well -- defined here in a similar fashion as Eq for (,) in -- https://hackage.haskell.org/package/base-4.9.0.0/docs/src/Data.Functor.Classes.html class Eq3 g where liftEq3 :: (a -> b -> Bool) -> (c -> d -> Bool) -> (e -> f -> Bool) -> g a c e -> g b d f -> Bool instance Eq3 (,,) where liftEq3 e1 e2 e3 (x1, y1, z1) (x2, y2, z2) = e1 x1 x2 && e2 y1 y2 && e3 z1 z2 instance (Eq a, Eq b) => Eq1 ((,,) a b) where liftEq = liftEq3 (==) (==) -- class (Eq3 g) => Ord3 g where liftCompare3 :: (a -> b -> Ordering) -> (c -> d -> Ordering) -> (e -> f -> Ordering) -> g a c e -> g b d f -> Ordering instance Ord3 (,,) where liftCompare3 comp1 comp2 comp3 (x1, y1, z1) (x2, y2, z2) = comp1 x1 x2 `mappend` comp2 y1 y2 `mappend` comp3 z1 z2 instance (Ord a, Ord b) => Ord1 ((,,) a b) where liftCompare = liftCompare3 compare compare -- class Show3 f where liftShowsPrec3 :: (Int -> a -> ShowS) -> ([a] -> ShowS) -> (Int -> b -> ShowS) -> ([b] -> ShowS) -> (Int -> c -> ShowS) -> ([c] -> ShowS) -> Int -> f a b c -> ShowS liftShowList3 :: (Int -> a -> ShowS) -> ([a] -> ShowS) -> (Int -> b -> ShowS) -> ([b] -> ShowS) -> (Int -> c -> ShowS) -> ([c] -> ShowS) -> [f a b c] -> ShowS liftShowList3 sp1 sl1 sp2 sl2 sp3 sl3 = showListWith (liftShowsPrec3 sp1 sl1 sp2 sl2 sp3 sl3 0) instance Show3 (,,) where liftShowsPrec3 sp1 _ sp2 _ sp3 _ _ (x, y, z) = showChar '(' . sp1 0 x . showChar ',' . sp2 0 y . showChar ',' . sp3 0 z . showChar ')' instance (Show a, Show b) => Show1 ((,,) a b) where liftShowsPrec = liftShowsPrec3 showsPrec showList showsPrec showList deriveEq1 ''Expr deriveOrd1 ''Expr deriveShow1 ''Expr -- deriveRead1 ''Expr deriving instance (Eq t, Eq a) => Eq (Expr t a) -- deriving instance (Ord t, Ord a, Typeable t) => Ord (Expr t a) deriving instance (Ord t, Ord a) => Ord (Expr t a) deriving instance (Show t, Show a) => Show (Expr t a) -- deriving instance (Read t, Read a) => Read (Expr t a) #else instance Eq t => Eq1 (Expr t) instance (Ord t, Typeable t) => Ord1 (Expr t) -- instance Ord t => Ord1 (Expr t) instance Show t => Show1 (Expr t) -- instance Read t => Read1 (Expr t) deriving instance (Eq t, Eq a) => Eq (Expr t a) deriving instance (Ord t, Ord a, Typeable t) => Ord (Expr t a) -- deriving instance (Ord t, Ord a) => Ord (Expr t a) deriving instance (Show t, Show a) => Show (Expr t a) -- deriving instance (Read t, Read a, Read Delta, Read (PossiblyVar t)) => Read (Expr t a) #endif #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) -- #if (MIN_VERSION_transformers(0,5,0)) deriveEq1 ''Annot deriveOrd1 ''Annot deriveShow1 ''Annot -- deriveRead1 ''Annot deriving instance (Eq t, Eq a) => Eq (Annot t a) deriving instance (Ord t, Ord a) => Ord (Annot t a) -- deriving instance (Ord t, Ord a, Typeable t) => Ord (Annot t a) deriving instance (Show t, Show a) => Show (Annot t a) -- deriving instance (Read t, Read a) => Read (Annot t a) #else instance Eq t => Eq1 (Annot t) -- instance (Ord t, Typeable t) => Ord1 (Annot t) -- instance Ord t => Ord1 (Annotr t) instance Show t => Show1 (Annot t) -- instance Read t => Read1 (Annotr t) deriving instance (Eq t, Eq a) => Eq (Annot t a) deriving instance (Ord t, Ord a, Typeable t) => Ord (Annot t a) -- deriving instance (Ord t, Ord a) => Ord (Annot t a) deriving instance (Show t, Show a) => Show (Annot t a) #endif #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) -- #if (MIN_VERSION_transformers(0,5,0)) deriveEq1 ''Arg deriveOrd1 ''Arg deriveShow1 ''Arg -- deriveRead1 ''Arg deriving instance (Eq t, Eq a) => Eq (Arg t a) deriving instance (Ord t, Ord a) => Ord (Arg t a) -- deriving instance (Ord t, Ord a, Typeable t) => Ord (Arg t a) deriving instance (Show t, Show a) => Show (Arg t a) -- deriving instance (Read t, Read a) => Read (Arg t a) #else instance Eq t => Eq1 (Arg t) -- instance (Ord t, Typeable t) => Ord1 (Arg t) -- instance Ord t => Ord1 (Argr t) instance Show t => Show1 (Arg t) -- instance Read t => Read1 (Argr t) deriving instance (Eq t, Eq a) => Eq (Arg t a) deriving instance (Ord t, Ord a, Typeable t) => Ord (Arg t a) -- deriving instance (Ord t, Ord a) => Ord (Arg t a) deriving instance (Show t, Show a) => Show (Arg t a) #endif #if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0)) -- #if (MIN_VERSION_transformers(0,5,0)) deriveEq1 ''Match deriveOrd1 ''Match deriveShow1 ''Match -- deriveRead1 ''Match deriving instance (Eq t, Eq a) => Eq (Match t a) deriving instance (Ord t, Ord a) => Ord (Match t a) -- deriving instance (Ord t, Ord a, Typeable t) => Ord (Match t a) deriving instance (Show t, Show a) => Show (Match t a) -- deriving instance (Read t, Read a) => Read (Match t a) #else instance Eq t => Eq1 (Match t) instance (Ord t, Typeable t) => Ord1 (Match t) -- instance Ord t => Ord1 (Match t) instance Show t => Show1 (Match t) -- instance Read t => Read1 (Match t) deriving instance (Eq t, Eq a) => Eq (Match t a) deriving instance (Ord t, Ord a, Typeable t) => Ord (Match t a) -- deriving instance (Ord t, Ord a) => Ord (Match t a) deriving instance (Show t, Show a) => Show (Match t a) #endif
reuleaux/pire
src/Pire/Syntax/Expr.hs
Haskell
bsd-3-clause
48,148
{-| Module : Graphics.Sudbury.Protocol.Runtime Description : Protocol data without docs: can project XML protocols to runtime protocols Copyright : (c) Auke Booij, 2015-2017 License : MIT Maintainer : auke@tulcod.com Stability : experimental Portability : POSIX -} module Graphics.Sudbury.Protocol.Runtime where
abooij/sudbury
Graphics/Sudbury/Protocol/Runtime.hs
Haskell
mit
326
------------------------------------------------------------------------- -- -- MakeTree.hs -- -- Turn a frequency table into a Huffman tree -- -- (c) Addison-Wesley, 1996-2011. -- ------------------------------------------------------------------------- module MakeTree ( makeTree ) where import Types ( Tree(Leaf,Node), Bit(L,R), HCode, Table ) -- Convert the trees to a list, then amalgamate into a single -- tree. makeTree :: [ (Char,Int) ] -> Tree makeTree = makeCodes . toTreeList -- Huffman codes are created bottom up: look for the least -- two frequent letters, make these a new "isAlpha" (i.e. tree) -- and repeat until one tree formed. -- The function toTreeList makes the initial data structure. toTreeList :: [ (Char,Int) ] -> [ Tree ] toTreeList = map (uncurry Leaf) -- The value of a tree. value :: Tree -> Int value (Leaf _ n) = n value (Node n _ _) = n -- Pair two trees. pair :: Tree -> Tree -> Tree pair t1 t2 = Node (v1+v2) t1 t2 where v1 = value t1 v2 = value t2 -- Insert a tree in a list of trees sorted by ascending value. insTree :: Tree -> [Tree] -> [Tree] insTree t [] = [t] insTree t (t1:ts) | (value t <= value t1) = t:t1:ts | otherwise = t1 : insTree t ts -- -- Amalgamate the front two elements of the list of trees. amalgamate :: [ Tree ] -> [ Tree ] amalgamate ( t1 : t2 : ts ) = insTree (pair t1 t2) ts -- Make codes: amalgamate the whole list. makeCodes :: [Tree] -> Tree makeCodes [t] = t makeCodes ts = makeCodes (amalgamate ts)
Numberartificial/workflow
snipets/src/Craft/Chapter15/MakeTree.hs
Haskell
mit
1,891
{- Copyright 2019 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} program = drawingOf(blank) 5 = 2 + 2
alphalambda/codeworld
codeworld-compiler/test/testcases/varlessPattern/source.hs
Haskell
apache-2.0
648
{-# OPTIONS -#include <windows.h> #-} {-# OPTIONS -#include "SafeArrayPrim.h" #-} -- Automatically generated by HaskellDirect (ihc.exe), version 0.20 -- Created: 20:11 Pacific Standard Time, Tuesday 16 December, 2003 -- Command line: -fno-qualified-names -fhs-to-c -fno-export-lists --gen-headers -fout-pointers-are-not-refs --gen-headers -c SafeArray.idl -o SafeArray.hs module SafeArray where import Prelude import Com (checkHR) import Foreign.ForeignPtr (ForeignPtr, withForeignPtr) import Foreign.Ptr (Ptr, FunPtr, castPtr) import HDirect (nullFinaliser, writefptr, readPtr, sizeofPtr, writeWord32, writeInt32, addNCastPtr, readWord32, readInt32, allocBytes, free, doThenFree, sizeofForeignPtr, marshalllist, trivialFree, freeref, sizeofInt32, marshallref) import IOExts (unsafePerformIO) import Int (Int32) import Pointer (makeFO) import StdTypes (VARTYPE) import Word (Word32, Word16) {- BEGIN_C_CODE #if defined(__MINGW32__) || defined(__CYGWIN32__) END_C_CODE-} {- BEGIN_C_CODE #include <w32api.h> END_C_CODE-} {- BEGIN_C_CODE #endif END_C_CODE-} {- BEGIN_C_CODE #if !defined(_MSC_VER) && __W32API_MAJOR_VERSION == 1 END_C_CODE-} -- -------------------------------------------------- -- -- interface SAFEARRAY -- -- -------------------------------------------------- newtype SAFEARRAY = SAFEARRAY (ForeignPtr SAFEARRAY) foreign label "primSafeArrayDestroy" addrOf_SAFEARRAY_primSafeArrayDestroy :: FunPtr (Ptr SAFEARRAY -> IO ()) marshallSAFEARRAY :: SAFEARRAY -> IO (ForeignPtr SAFEARRAY) marshallSAFEARRAY (SAFEARRAY v) = return (v) unmarshallSAFEARRAY :: Bool -> Ptr SAFEARRAY -> IO SAFEARRAY unmarshallSAFEARRAY finaliseMe__ v = do v <- makeFO v (case finaliseMe__ of False -> nullFinaliser True -> addrOf_SAFEARRAY_primSafeArrayDestroy) return (SAFEARRAY v) writeSAFEARRAY :: Ptr (Ptr SAFEARRAY) -> SAFEARRAY -> IO () writeSAFEARRAY ptr (SAFEARRAY v) = writefptr ptr v readSAFEARRAY :: Bool -> Ptr SAFEARRAY -> IO SAFEARRAY readSAFEARRAY finaliseMe__ ptr = do v <- readPtr ptr v <- makeFO v (case finaliseMe__ of False -> nullFinaliser True -> addrOf_SAFEARRAY_primSafeArrayDestroy) return (SAFEARRAY v) sizeofSAFEARRAY :: Word32 sizeofSAFEARRAY = sizeofPtr addrToSAFEARRAY :: Ptr a -> SAFEARRAY addrToSAFEARRAY v = unsafePerformIO (makeFO (castPtr v) addrOf_SAFEARRAY_primSafeArrayDestroy >>= \ v -> return (SAFEARRAY v)) data SAFEARRAYBOUND = TagSAFEARRAYBOUND {cElements :: Word32, lLbound :: Int32} writeSAFEARRAYBOUND :: Ptr SAFEARRAYBOUND -> SAFEARRAYBOUND -> IO () writeSAFEARRAYBOUND ptr (TagSAFEARRAYBOUND cElements lLbound) = let pf0 = ptr pf1 = addNCastPtr pf0 0 in do writeWord32 pf1 cElements let pf2 = addNCastPtr pf1 4 writeInt32 pf2 lLbound readSAFEARRAYBOUND :: Ptr SAFEARRAYBOUND -> IO SAFEARRAYBOUND readSAFEARRAYBOUND ptr = let pf0 = ptr pf1 = addNCastPtr pf0 0 in do cElements <- readWord32 pf1 let pf2 = addNCastPtr pf1 4 lLbound <- readInt32 pf2 return (TagSAFEARRAYBOUND cElements lLbound) sizeofSAFEARRAYBOUND :: Word32 sizeofSAFEARRAYBOUND = 8 safeArrayAccessData :: SAFEARRAY -> IO (Ptr ()) safeArrayAccessData psa = do ppvData <- allocBytes (fromIntegral sizeofPtr) psa <- marshallSAFEARRAY psa o_safeArrayAccessData <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayAccessData psa ppvData) checkHR o_safeArrayAccessData doThenFree free readPtr ppvData foreign import stdcall "SafeArrayAccessData" prim_SafeArray_safeArrayAccessData :: Ptr SAFEARRAY -> Ptr (Ptr ()) -> IO Int32 safeArrayAllocData :: SAFEARRAY -> IO () safeArrayAllocData psa = do psa <- marshallSAFEARRAY psa o_safeArrayAllocData <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayAllocData psa) checkHR o_safeArrayAllocData foreign import stdcall "SafeArrayAllocData" prim_SafeArray_safeArrayAllocData :: Ptr SAFEARRAY -> IO Int32 safeArrayAllocDescriptor :: Word32 -> IO SAFEARRAY safeArrayAllocDescriptor cDims = do ppsaOut <- allocBytes (fromIntegral sizeofForeignPtr) o_safeArrayAllocDescriptor <- prim_SafeArray_safeArrayAllocDescriptor cDims ppsaOut checkHR o_safeArrayAllocDescriptor doThenFree free (readSAFEARRAY True) ppsaOut foreign import stdcall "SafeArrayAllocDescriptor" prim_SafeArray_safeArrayAllocDescriptor :: Word32 -> Ptr (Ptr SAFEARRAY) -> IO Int32 safeArrayCopy :: SAFEARRAY -> IO SAFEARRAY safeArrayCopy psa = do ppsaOut <- allocBytes (fromIntegral sizeofForeignPtr) psa <- marshallSAFEARRAY psa o_safeArrayCopy <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayCopy psa ppsaOut) checkHR o_safeArrayCopy doThenFree free (readSAFEARRAY True) ppsaOut foreign import stdcall "SafeArrayCopy" prim_SafeArray_safeArrayCopy :: Ptr SAFEARRAY -> Ptr (Ptr SAFEARRAY) -> IO Int32 safeArrayCreate :: VARTYPE -> [SAFEARRAYBOUND] -> IO SAFEARRAY safeArrayCreate vt rgsabound = let cDims = (fromIntegral (length rgsabound) :: Word32) in do rgsabound <- marshalllist sizeofSAFEARRAYBOUND writeSAFEARRAYBOUND rgsabound o_safeArrayCreate <- prim_SafeArray_safeArrayCreate vt cDims rgsabound freeref trivialFree rgsabound unmarshallSAFEARRAY True o_safeArrayCreate foreign import stdcall "SafeArrayCreate" prim_SafeArray_safeArrayCreate :: Word16 -> Word32 -> Ptr SAFEARRAYBOUND -> IO (Ptr SAFEARRAY) safeArrayDestroy :: SAFEARRAY -> IO () safeArrayDestroy psa = do psa <- marshallSAFEARRAY psa o_safeArrayDestroy <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayDestroy psa) checkHR o_safeArrayDestroy foreign import stdcall "SafeArrayDestroy" prim_SafeArray_safeArrayDestroy :: Ptr SAFEARRAY -> IO Int32 safeArrayDestroyData :: SAFEARRAY -> IO () safeArrayDestroyData psa = do psa <- marshallSAFEARRAY psa o_safeArrayDestroyData <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayDestroyData psa) checkHR o_safeArrayDestroyData foreign import stdcall "SafeArrayDestroyData" prim_SafeArray_safeArrayDestroyData :: Ptr SAFEARRAY -> IO Int32 safeArrayDestroyDescriptor :: SAFEARRAY -> IO () safeArrayDestroyDescriptor psa = do psa <- marshallSAFEARRAY psa o_safeArrayDestroyDescriptor <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayDestroyDescriptor psa) checkHR o_safeArrayDestroyDescriptor foreign import stdcall "SafeArrayDestroyDescriptor" prim_SafeArray_safeArrayDestroyDescriptor :: Ptr SAFEARRAY -> IO Int32 safeArrayGetDim :: SAFEARRAY -> IO Word32 safeArrayGetDim psa = do psa <- marshallSAFEARRAY psa withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayGetDim psa) foreign import stdcall "SafeArrayGetDim" prim_SafeArray_safeArrayGetDim :: Ptr SAFEARRAY -> IO Word32 safeArrayGetElement :: SAFEARRAY -> Ptr Int32 -> Ptr () -> IO () safeArrayGetElement psa rgIndices pv = do psa <- marshallSAFEARRAY psa o_safeArrayGetElement <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayGetElement psa rgIndices pv) checkHR o_safeArrayGetElement foreign import stdcall "SafeArrayGetElement" prim_SafeArray_safeArrayGetElement :: Ptr SAFEARRAY -> Ptr Int32 -> Ptr () -> IO Int32 safeArrayGetElemsize :: SAFEARRAY -> IO Word32 safeArrayGetElemsize psa = do psa <- marshallSAFEARRAY psa withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayGetElemsize psa) foreign import stdcall "SafeArrayGetElemsize" prim_SafeArray_safeArrayGetElemsize :: Ptr SAFEARRAY -> IO Word32 safeArrayGetLBound :: SAFEARRAY -> Word32 -> IO Int32 safeArrayGetLBound psa nDim = do plLbound <- allocBytes (fromIntegral sizeofInt32) psa <- marshallSAFEARRAY psa o_safeArrayGetLBound <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayGetLBound psa nDim plLbound) checkHR o_safeArrayGetLBound doThenFree free readInt32 plLbound foreign import stdcall "SafeArrayGetLBound" prim_SafeArray_safeArrayGetLBound :: Ptr SAFEARRAY -> Word32 -> Ptr Int32 -> IO Int32 safeArrayGetUBound :: SAFEARRAY -> Word32 -> IO Int32 safeArrayGetUBound psa nDim = do plLbound <- allocBytes (fromIntegral sizeofInt32) psa <- marshallSAFEARRAY psa o_safeArrayGetUBound <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayGetUBound psa nDim plLbound) checkHR o_safeArrayGetUBound doThenFree free readInt32 plLbound foreign import stdcall "SafeArrayGetUBound" prim_SafeArray_safeArrayGetUBound :: Ptr SAFEARRAY -> Word32 -> Ptr Int32 -> IO Int32 safeArrayLock :: SAFEARRAY -> IO () safeArrayLock psa = do psa <- marshallSAFEARRAY psa o_safeArrayLock <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayLock psa) checkHR o_safeArrayLock foreign import stdcall "SafeArrayLock" prim_SafeArray_safeArrayLock :: Ptr SAFEARRAY -> IO Int32 safeArrayPtrOfIndex :: SAFEARRAY -> Ptr Int32 -> IO (Ptr ()) safeArrayPtrOfIndex psa rgIndices = do ppvData <- allocBytes (fromIntegral sizeofPtr) psa <- marshallSAFEARRAY psa o_safeArrayPtrOfIndex <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayPtrOfIndex psa rgIndices ppvData) checkHR o_safeArrayPtrOfIndex doThenFree free readPtr ppvData foreign import stdcall "SafeArrayPtrOfIndex" prim_SafeArray_safeArrayPtrOfIndex :: Ptr SAFEARRAY -> Ptr Int32 -> Ptr (Ptr ()) -> IO Int32 safeArrayPutElement :: SAFEARRAY -> Ptr Int32 -> Ptr () -> IO () safeArrayPutElement psa rgIndices pv = do psa <- marshallSAFEARRAY psa o_safeArrayPutElement <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayPutElement psa rgIndices pv) checkHR o_safeArrayPutElement foreign import stdcall "SafeArrayPutElement" prim_SafeArray_safeArrayPutElement :: Ptr SAFEARRAY -> Ptr Int32 -> Ptr () -> IO Int32 safeArrayRedim :: SAFEARRAY -> SAFEARRAYBOUND -> IO () safeArrayRedim psa psaboundNew = do psa <- marshallSAFEARRAY psa psaboundNew <- marshallref (allocBytes (fromIntegral sizeofSAFEARRAYBOUND)) writeSAFEARRAYBOUND psaboundNew o_safeArrayRedim <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayRedim psa psaboundNew) free psaboundNew checkHR o_safeArrayRedim foreign import stdcall "SafeArrayRedim" prim_SafeArray_safeArrayRedim :: Ptr SAFEARRAY -> Ptr SAFEARRAYBOUND -> IO Int32 safeArrayUnaccessData :: SAFEARRAY -> IO () safeArrayUnaccessData psa = do psa <- marshallSAFEARRAY psa o_safeArrayUnaccessData <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayUnaccessData psa) checkHR o_safeArrayUnaccessData foreign import stdcall "SafeArrayUnaccessData" prim_SafeArray_safeArrayUnaccessData :: Ptr SAFEARRAY -> IO Int32 safeArrayUnlock :: SAFEARRAY -> IO () safeArrayUnlock psa = do psa <- marshallSAFEARRAY psa o_safeArrayUnlock <- withForeignPtr psa (\ psa -> prim_SafeArray_safeArrayUnlock psa) checkHR o_safeArrayUnlock foreign import stdcall "SafeArrayUnlock" prim_SafeArray_safeArrayUnlock :: Ptr SAFEARRAY -> IO Int32 {- BEGIN_C_CODE #endif END_C_CODE-}
sof/hdirect
comlib/SafeArray.hs
Haskell
bsd-3-clause
12,123
-- | Parallel Arrays. --- -- Parallel arrays use a fixed generic representation. All data stored in -- them is converted to the generic representation, and we have a small -- number of operators that work on arrays of these generic types. -- -- Representation types include Ints, Floats, Tuples and Sums, so arrays of -- these types can be stored directly. However, user defined algebraic data -- needs to be converted as we don't have operators that work directly on -- arrays of these types. -- -- The top-level PArray type is built up from several type families and -- clases: -- -- PArray - This is the top level type. It holds an array length, -- and array data in the generic representation (PData). -- -- PRepr - Family of types that can be converted to the generic -- representation. We supply instances for basic types -- like Ints Floats etc, but the vectoriser needs to make -- the instances for user-defined data types itself. -- PA class - Contains methods to convert to and from the generic -- representation (PData). -- -- PData - Family of types that can be stored directly in parallel -- arrays. We supply all the PData instances we need here -- in the library. -- PR class - Contains methods that work directly on parallel arrays. -- Most of these are just wrappers for the corresponding -- U.Array operators. -- -- Scalar class - Contains methods to convert between the generic -- representation (PData) and plain U.Arrays. -- -- Note that the PRepr family and PA class are related. -- so are the PData family and PR class. -- -- For motivational material see: -- "An Approach to Fast Arrays in Haskell", Chakravarty and Keller, 2003 -- -- For discussion of how the mapping to generic types works see: -- "Instant Generics: Fast and Easy", Chakravarty, Ditu and Keller, 2009 -- module Data.Array.Parallel.PArray ( PArray, PA, Random(..), -- * Evaluation nf, -- * Constructors empty, singleton, replicate, (+:+), concat, nestUSegd, -- * Projections length, (!:), slice, -- * Update update, -- * Pack and Combine pack, bpermute, -- * Enumerations enumFromTo, indexed, -- * Tuples zip, unzip, -- * Conversions fromList, toList, fromUArray, toUArray, fromUArray2, fromUArray3 ) where import Data.Array.Parallel.Lifted.PArray import Data.Array.Parallel.PArray.PReprInstances () import Data.Array.Parallel.Lifted.Combinators import Data.Array.Parallel.Lifted.Scalar import Data.Array.Parallel.Base.Text import qualified Data.Array.Parallel.Unlifted as U import qualified System.Random as R import Prelude hiding ( length, replicate, zip, unzip, enumFromTo, concat ) -- NOTE: -- Most of these functions just export the corresponding "vectorised" -- function from "Data.Array.Parallel.Lifted.Closure". We don't export -- higher-order functions like map and filter because the versions -- from there want closures as their function parameters. -- -- Instead, we should probably move the first-order "vectorised" -- functions from D.A.P.L.Closure into this module, and just define -- the higher-order and lifted ones there. -- -- We still want to export these plain PArray functions to make it easier -- to convert between vectorised and unvectorised code in benchmarks. -- -- | O(1). An empty array, with no elements. empty :: PA a => PArray a {-# INLINE empty #-} empty = emptyPA -- | O(1). Retrieve a numbered element from an array. (!:) :: PA a => PArray a -> Int -> a {-# INLINE (!:) #-} (!:) = indexPA_v -- | O(1). Yield the length of an array. length :: PA a => PArray a -> Int {-# INLINE length #-} length = lengthPA_v -- | O(n). Produce an array containing copies of a given element. replicate :: PA a => Int -> a -> PArray a {-# INLINE replicate #-} replicate = replicatePA_v -- | O(1). Produce an array containing a single element. singleton :: PA a => a -> PArray a {-# INLINE singleton #-} singleton = singletonPA_v -- | O(1). Takes two arrays and returns an array of corresponding pairs. -- If one array is short, excess elements of the longer array are -- discarded. zip :: (PA a, PA b) => PArray a -> PArray b -> PArray (a,b) {-# INLINE zip #-} zip = zipPA_v -- | O(1). Transform an array into an array of the first components, -- and an array of the second components. unzip :: (PA a, PA b) => PArray (a,b) -> (PArray a, PArray b) {-# INLINE unzip #-} unzip = unzipPA_v -- | Select the elements of an array that have their tag set as True. -- -- @ -- packPA [12, 24, 42, 93] [True, False, False, True] -- = [24, 42] -- @ pack :: PA a => PArray a -> PArray Bool -> PArray a {-# INLINE pack #-} pack = packPA_v -- | Concatenate an array of arrays into a single array. concat :: PA a => PArray (PArray a) -> PArray a {-# INLINE concat #-} concat = concatPA_v -- | Append two arrays (+:+) :: PA a => PArray a -> PArray a -> PArray a {-# INLINE (+:+) #-} (+:+) = appPA_v -- | O(n). Tag each element of an array with its index. -- -- @indexed [42, 93, 13] = [(0, 42), (1, 93), (2, 13)]@ -- indexed :: PA a => PArray a -> PArray (Int, a) {-# INLINE indexed #-} indexed = indexedPA_v -- | Extract a subrange of elements from an array. -- The first argument is the starting index, while the second is the -- length of the slice. -- slice :: PA a => Int -> Int -> PArray a -> PArray a {-# INLINE slice #-} slice = slicePA_v -- | Copy the source array in the destination, using new values for the given indices. update :: PA a => PArray a -> PArray (Int,a) -> PArray a {-# INLINE update #-} update = updatePA_v -- | O(n). Backwards permutation of array elements. -- -- @bpermute [50, 60, 20, 30] [0, 3, 2] = [50, 30, 20]@ -- bpermute :: PA a => PArray a -> PArray Int -> PArray a {-# INLINE bpermute #-} bpermute = bpermutePA_v -- | O(n). Generate a range of @Int@s. enumFromTo :: Int -> Int -> PArray Int {-# INLINE enumFromTo #-} enumFromTo = enumFromToPA_v -- Conversion ----------------------------------------------------------------- -- | Create a `PArray` from a list. fromList :: PA a => [a] -> PArray a {-# INLINE fromList #-} fromList = fromListPA -- | Create a list from a `PArray`. toList :: PA a => PArray a -> [a] toList xs = [indexPA_v xs i | i <- [0 .. length xs - 1]] instance (PA a, Show a) => Show (PArray a) where showsPrec n xs = showsApp n "fromList<PArray>" (toList xs) -- Evaluation ----------------------------------------------------------------- -- | Ensure an array is fully evaluated. nf :: PA a => PArray a -> () nf = nfPA -- Randoms -------------------------------------------------------------------- class Random a where randoms :: R.RandomGen g => Int -> g -> PArray a randomRs :: R.RandomGen g => Int -> (a, a) -> g -> PArray a prim_randoms :: (Scalar a, R.Random a, R.RandomGen g) => Int -> g -> PArray a prim_randoms n = fromUArray . U.randoms n prim_randomRs :: (Scalar a, R.Random a, R.RandomGen g) => Int -> (a, a) -> g -> PArray a prim_randomRs n r = fromUArray . U.randomRs n r instance Random Int where randoms = prim_randoms randomRs = prim_randomRs instance Random Double where randoms = prim_randoms randomRs = prim_randomRs
mainland/dph
dph-lifted-copy/Data/Array/Parallel/PArray.hs
Haskell
bsd-3-clause
7,497