code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module S2E5 where increasing :: (Ord a, Num a) => [a] -> Bool increasing [] = True increasing [_] = True increasing (x:y:xs) | x <= y = increasing (y:xs) | otherwise = False weakIncr :: (Ord a, Fractional a) => [a] -> Bool weakIncr = weakIncr' . reverse weakIncr' :: (Ord a, Fractional a) => [a] -> Bool weakIncr' [] = True weakIncr' [_] = True weakIncr' (x:xs) = x > sum xs / fromIntegral (length xs) && weakIncr' xs
wouwouwou/module_8
src/main/haskell/series2/exercise5.hs
apache-2.0
442
0
9
105
226
118
108
12
1
insertAt :: a -> [a] -> Int -> [a] insertAt x ys 1 = x:ys insertAt x (y:ys) n = y : (insertAt x ys (n - 1))
alephnil/h99
21.hs
apache-2.0
108
0
9
28
80
42
38
3
1
-- Copyright 2016 TensorFlow authors. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. {-# LANGUAGE BangPatterns #-} {-| Module : TensorFlow.Internal.VarInt Description : Encoders and decoders for varint types. Originally taken from internal proto-lens code. -} module TensorFlow.Internal.VarInt ( getVarInt , putVarInt ) where import Data.Attoparsec.ByteString as Parse import Data.Bits import Data.ByteString.Lazy.Builder as Builder import Data.Word (Word64) -- | Decode an unsigned varint. getVarInt :: Parser Word64 getVarInt = loop 1 0 where loop !s !n = do b <- anyWord8 let n' = n + s * fromIntegral (b .&. 127) if (b .&. 128) == 0 then return n' else loop (128*s) n' -- | Encode a Word64. putVarInt :: Word64 -> Builder putVarInt n | n < 128 = Builder.word8 (fromIntegral n) | otherwise = Builder.word8 (fromIntegral $ n .&. 127 .|. 128) <> putVarInt (n `shiftR` 7)
tensorflow/haskell
tensorflow/src/TensorFlow/Internal/VarInt.hs
apache-2.0
1,490
0
15
334
250
140
110
21
2
{-# LANGUAGE OverloadedStrings #-} module Main ( main ) where import Marconi.V1.Http.Queue main :: IO () main = do x <- getQueue "http://166.78.254.33:8888/v1/" "queue" "project" putStr $ show x
FlaPer87/haskell-marconiclient
src/Main.hs
apache-2.0
209
0
8
43
56
30
26
9
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="fa-IR"> <title>TLS Debug | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
secdec/zap-extensions
addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_fa_IR/helpset_fa_IR.hs
apache-2.0
970
78
66
159
413
209
204
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-} -- | -- Module : Statistics.Distribution.CauchyLorentz -- Copyright : (c) 2011 Aleksey Khudyakov -- License : BSD3 -- -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : portable -- -- The Cauchy-Lorentz distribution. It's also known as Lorentz -- distribution or Breit–Wigner distribution. -- -- It doesn't have mean and variance. module Statistics.Distribution.CauchyLorentz ( CauchyDistribution , cauchyDistribMedian , cauchyDistribScale -- * Constructors , cauchyDistribution , cauchyDistributionE , standardCauchy ) where import Control.Applicative import Data.Aeson (FromJSON(..), ToJSON, Value(..), (.:)) import Data.Binary (Binary(..)) import Data.Maybe (fromMaybe) import Data.Data (Data, Typeable) import GHC.Generics (Generic) import qualified Statistics.Distribution as D import Statistics.Internal -- | Cauchy-Lorentz distribution. data CauchyDistribution = CD { -- | Central value of Cauchy-Lorentz distribution which is its -- mode and median. Distribution doesn't have mean so function -- is named after median. cauchyDistribMedian :: {-# UNPACK #-} !Double -- | Scale parameter of Cauchy-Lorentz distribution. It's -- different from variance and specify half width at half -- maximum (HWHM). , cauchyDistribScale :: {-# UNPACK #-} !Double } deriving (Eq, Typeable, Data, Generic) instance Show CauchyDistribution where showsPrec i (CD m s) = defaultShow2 "cauchyDistribution" m s i instance Read CauchyDistribution where readPrec = defaultReadPrecM2 "cauchyDistribution" cauchyDistributionE instance ToJSON CauchyDistribution instance FromJSON CauchyDistribution where parseJSON (Object v) = do m <- v .: "cauchyDistribMedian" s <- v .: "cauchyDistribScale" maybe (fail $ errMsg m s) return $ cauchyDistributionE m s parseJSON _ = empty instance Binary CauchyDistribution where put (CD m s) = put m >> put s get = do m <- get s <- get maybe (error $ errMsg m s) return $ cauchyDistributionE m s -- | Cauchy distribution cauchyDistribution :: Double -- ^ Central point -> Double -- ^ Scale parameter (FWHM) -> CauchyDistribution cauchyDistribution m s = fromMaybe (error $ errMsg m s) $ cauchyDistributionE m s -- | Cauchy distribution cauchyDistributionE :: Double -- ^ Central point -> Double -- ^ Scale parameter (FWHM) -> Maybe CauchyDistribution cauchyDistributionE m s | s > 0 = Just (CD m s) | otherwise = Nothing errMsg :: Double -> Double -> String errMsg _ s = "Statistics.Distribution.CauchyLorentz.cauchyDistribution: FWHM must be positive. Got " ++ show s -- | Standard Cauchy distribution. It's centered at 0 and have 1 FWHM standardCauchy :: CauchyDistribution standardCauchy = CD 0 1 instance D.Distribution CauchyDistribution where cumulative (CD m s) x = 0.5 + atan( (x - m) / s ) / pi instance D.ContDistr CauchyDistribution where density (CD m s) x = (1 / pi) / (s * (1 + y*y)) where y = (x - m) / s quantile (CD m s) p | p > 0 && p < 1 = m + s * tan( pi * (p - 0.5) ) | p == 0 = -1 / 0 | p == 1 = 1 / 0 | otherwise = error $ "Statistics.Distribution.CauchyLorentz.quantile: p must be in [0,1] range. Got: "++show p complQuantile (CD m s) p | p > 0 && p < 1 = m + s * tan( pi * (0.5 - p) ) | p == 0 = 1 / 0 | p == 1 = -1 / 0 | otherwise = error $ "Statistics.Distribution.CauchyLorentz.complQuantile: p must be in [0,1] range. Got: "++show p instance D.ContGen CauchyDistribution where genContVar = D.genContinuous instance D.Entropy CauchyDistribution where entropy (CD _ s) = log s + log (4*pi) instance D.MaybeEntropy CauchyDistribution where maybeEntropy = Just . D.entropy
bos/statistics
Statistics/Distribution/CauchyLorentz.hs
bsd-2-clause
4,036
0
12
987
1,009
531
478
79
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QTextList.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:14 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QTextList ( qTextList ,add ,itemNumber ,qTextList_delete ,qTextList_deleteLater ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base 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 (QTextList ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QTextList_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QTextList_userMethod" qtc_QTextList_userMethod :: Ptr (TQTextList a) -> CInt -> IO () instance QuserMethod (QTextListSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QTextList_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QTextList ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QTextList_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QTextList_userMethodVariant" qtc_QTextList_userMethodVariant :: Ptr (TQTextList a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QTextListSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QTextList_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj qTextList :: (QTextDocument t1) -> IO (QTextList ()) qTextList (x1) = withQTextListResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList cobj_x1 foreign import ccall "qtc_QTextList" qtc_QTextList :: Ptr (TQTextDocument t1) -> IO (Ptr (TQTextList ())) add :: QTextList a -> ((QTextBlock t1)) -> IO () add x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_add cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_add" qtc_QTextList_add :: Ptr (TQTextList a) -> Ptr (TQTextBlock t1) -> IO () instance Qcount (QTextList a) (()) where count x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextList_count cobj_x0 foreign import ccall "qtc_QTextList_count" qtc_QTextList_count :: Ptr (TQTextList a) -> IO CInt instance Qformat (QTextList a) (()) (IO (QTextListFormat ())) where format x0 () = withQTextListFormatResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextList_format cobj_x0 foreign import ccall "qtc_QTextList_format" qtc_QTextList_format :: Ptr (TQTextList a) -> IO (Ptr (TQTextListFormat ())) instance QqisEmpty (QTextList a) (()) where qisEmpty x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextList_isEmpty cobj_x0 foreign import ccall "qtc_QTextList_isEmpty" qtc_QTextList_isEmpty :: Ptr (TQTextList a) -> IO CBool instance Qitem (QTextList a) ((Int)) (IO (QTextBlock ())) where item x0 (x1) = withQTextBlockResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextList_item cobj_x0 (toCInt x1) foreign import ccall "qtc_QTextList_item" qtc_QTextList_item :: Ptr (TQTextList a) -> CInt -> IO (Ptr (TQTextBlock ())) itemNumber :: QTextList a -> ((QTextBlock t1)) -> IO (Int) itemNumber x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_itemNumber cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_itemNumber" qtc_QTextList_itemNumber :: Ptr (TQTextList a) -> Ptr (TQTextBlock t1) -> IO CInt instance QitemText (QTextList a) ((QTextBlock t1)) where itemText x0 (x1) = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_itemText cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_itemText" qtc_QTextList_itemText :: Ptr (TQTextList a) -> Ptr (TQTextBlock t1) -> IO (Ptr (TQString ())) instance Qremove (QTextList a) ((QTextBlock t1)) (IO ()) where remove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_remove cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_remove" qtc_QTextList_remove :: Ptr (TQTextList a) -> Ptr (TQTextBlock t1) -> IO () instance QremoveItem (QTextList a) ((Int)) where removeItem x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextList_removeItem cobj_x0 (toCInt x1) foreign import ccall "qtc_QTextList_removeItem" qtc_QTextList_removeItem :: Ptr (TQTextList a) -> CInt -> IO () instance QsetFormat (QTextList a) ((QTextListFormat t1)) where setFormat x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_setFormat cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_setFormat" qtc_QTextList_setFormat :: Ptr (TQTextList a) -> Ptr (TQTextListFormat t1) -> IO () qTextList_delete :: QTextList a -> IO () qTextList_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextList_delete cobj_x0 foreign import ccall "qtc_QTextList_delete" qtc_QTextList_delete :: Ptr (TQTextList a) -> IO () qTextList_deleteLater :: QTextList a -> IO () qTextList_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextList_deleteLater cobj_x0 foreign import ccall "qtc_QTextList_deleteLater" qtc_QTextList_deleteLater :: Ptr (TQTextList a) -> IO () instance QblockFormatChanged (QTextList ()) ((QTextBlock t1)) where blockFormatChanged x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_blockFormatChanged_h cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_blockFormatChanged_h" qtc_QTextList_blockFormatChanged_h :: Ptr (TQTextList a) -> Ptr (TQTextBlock t1) -> IO () instance QblockFormatChanged (QTextListSc a) ((QTextBlock t1)) where blockFormatChanged x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_blockFormatChanged_h cobj_x0 cobj_x1 instance QblockInserted (QTextList ()) ((QTextBlock t1)) where blockInserted x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_blockInserted_h cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_blockInserted_h" qtc_QTextList_blockInserted_h :: Ptr (TQTextList a) -> Ptr (TQTextBlock t1) -> IO () instance QblockInserted (QTextListSc a) ((QTextBlock t1)) where blockInserted x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_blockInserted_h cobj_x0 cobj_x1 instance QblockList (QTextList ()) (()) where blockList x0 () = withQListObjectRefResult $ \arr -> withObjectPtr x0 $ \cobj_x0 -> qtc_QTextList_blockList cobj_x0 arr foreign import ccall "qtc_QTextList_blockList" qtc_QTextList_blockList :: Ptr (TQTextList a) -> Ptr (Ptr (TQTextBlock ())) -> IO CInt instance QblockList (QTextListSc a) (()) where blockList x0 () = withQListObjectRefResult $ \arr -> withObjectPtr x0 $ \cobj_x0 -> qtc_QTextList_blockList cobj_x0 arr instance QblockRemoved (QTextList ()) ((QTextBlock t1)) where blockRemoved x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_blockRemoved_h cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_blockRemoved_h" qtc_QTextList_blockRemoved_h :: Ptr (TQTextList a) -> Ptr (TQTextBlock t1) -> IO () instance QblockRemoved (QTextListSc a) ((QTextBlock t1)) where blockRemoved x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_blockRemoved_h cobj_x0 cobj_x1 instance QchildEvent (QTextList ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_childEvent" qtc_QTextList_childEvent :: Ptr (TQTextList a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QTextListSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QTextList ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextList_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QTextList_connectNotify" qtc_QTextList_connectNotify :: Ptr (TQTextList a) -> CWString -> IO () instance QconnectNotify (QTextListSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextList_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QTextList ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_customEvent" qtc_QTextList_customEvent :: Ptr (TQTextList a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QTextListSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QTextList ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextList_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QTextList_disconnectNotify" qtc_QTextList_disconnectNotify :: Ptr (TQTextList a) -> CWString -> IO () instance QdisconnectNotify (QTextListSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextList_disconnectNotify cobj_x0 cstr_x1 instance Qevent (QTextList ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_event_h" qtc_QTextList_event_h :: Ptr (TQTextList a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QTextListSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_event_h cobj_x0 cobj_x1 instance QeventFilter (QTextList ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextList_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QTextList_eventFilter_h" qtc_QTextList_eventFilter_h :: Ptr (TQTextList a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QTextListSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextList_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QTextList ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextList_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QTextList_receivers" qtc_QTextList_receivers :: Ptr (TQTextList a) -> CWString -> IO CInt instance Qreceivers (QTextListSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextList_receivers cobj_x0 cstr_x1 instance Qsender (QTextList ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextList_sender cobj_x0 foreign import ccall "qtc_QTextList_sender" qtc_QTextList_sender :: Ptr (TQTextList a) -> IO (Ptr (TQObject ())) instance Qsender (QTextListSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextList_sender cobj_x0 instance QtimerEvent (QTextList ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QTextList_timerEvent" qtc_QTextList_timerEvent :: Ptr (TQTextList a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QTextListSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextList_timerEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QTextList.hs
bsd-2-clause
12,687
0
14
2,146
4,140
2,095
2,045
-1
-1
{-# LANGUAGE TypeSynonymInstances #-} module Interleaved where import qualified Data.Set as Set import Data.Set ((\\)) import Data.List (nub) import qualified Data.Map as Map import Data.Map ((!)) type Edge = (Int, Int) type Clique = Set.Set Int clique :: [Int] -> Clique clique = Set.fromList dim :: Clique -> Int dim c = (Set.size c) - 1 data State = S { vertices :: Set.Set Int, edges :: [Edge], cliques :: [Clique] } deriving (Eq, Show) state :: [Int] -> State state ints = S (Set.fromList ints) [] (map Set.singleton ints) addEdge :: Edge -> State -> State addEdge e@(s,t) st = st { edges = e : edges st, cliques = newC } where sCliques = [c | c <- cliques st, s `Set.member` c] tCliques = [c | c <- cliques st, t `Set.member` c] newCliques = nub [Set.insert s (Set.insert t (Set.intersection c d)) | c <- sCliques, d <- tCliques] candidates = newCliques ++ cliques st newC = [c | c <- candidates, null (filter (\s -> c `Set.isSubsetOf` s && c /= s) (candidates))] facets :: Clique -> [Clique] facets c = filter (not . Set.null) $ map ((c\\) . Set.singleton) (Set.toList c) newFacets :: [Clique] -> Clique -> [Clique] newFacets old c = filter (not . (\f -> any (f `Set.isSubsetOf`) old)) (facets c) allNewFacets :: [Clique] -> Clique -> [Clique] allNewFacets old c = nub $ newF ++ (concatMap (allNewFacets old) newF) where newF = newFacets old c newSimplices :: Edge -> State -> (State, [Clique]) newSimplices e oldS = (newS, simpl) where newS = addEdge e oldS newF = [c | c <- cliques newS, not (c `elem` (cliques oldS))] simpl = nub $ newF ++ (concatMap (allNewFacets (cliques oldS)) newF) type Vector = [Double] type GraphMap = Map.Map Double [(Int,Int)] l2d2 :: Vector -> Vector -> Double l2d2 v w = sum . map (^2) $ zipWith (-) v w weightedGraph :: (Vector -> Vector -> Double) -> [Vector] -> [(Double,Edge)] weightedGraph d vectors = concatMap (\(d,es) -> map (\e -> (d,e)) es) . Map.toAscList $ foldr (addEdgeGM d vectors) Map.empty [(i,j) | i <- [0..(length vectors)-1], j <- [0..(length vectors)-1], i < j] addEdgeGM :: (Vector -> Vector -> Double) -> [Vector] -> (Int, Int) -> GraphMap -> GraphMap addEdgeGM d vs (i,j) gm = Map.insertWith (++) (d (vs !! i) (vs !! j)) [(i,j)] gm type Chain = Map.Map Clique Double instance Num Chain where c + d = Map.filter (/=0) $ Map.unionWith (+) c d negate = Map.map negate c * d = Map.filter (/=0) $ Map.fromListWith (+) $ [(Set.union s t, x * y) | (s,x) <- Map.toList c, (t,y) <- Map.toList d] abs = undefined signum = undefined fromInteger n = Map.fromList [(Set.empty,fromInteger n)] constantC :: Double -> Chain constantC x = Map.fromList [(Set.empty,x)] chain :: Clique -> Chain chain c = Map.fromList [(c,1)] boundaryC :: Clique -> Chain boundaryC s = sum $ zipWith (*) (map chain (facets s)) (map (fromInteger . ((negate 1)^)) [0..]) boundary :: Chain -> Chain boundary s = sum $ map d keyvals where keyvals = Map.toList s d = \(k,v) -> (constantC v) * (boundaryC k) data Interval = I { birth :: Double, death :: Maybe Double, dimension :: Int } deriving (Eq, Show) data HomologyState = H { marked :: Map.Map (Double,Clique) Chain, graph :: State, edgeQ :: [(Edge, Double)], simplexQ :: [Clique], intervals :: [Interval], simplexAges :: Map.Map Clique Double } deriving (Eq, Show) initPH :: State -> [(Edge, Double)] -> HomologyState initPH st gr = H { marked = Map.empty, graph = st, edgeQ = gr, simplexQ = map Set.singleton (Set.toList $ vertices st), intervals = [], simplexAges = Map.fromList . map (\v -> (v,0.0::Double)) . map Set.singleton . Set.toList . vertices $ st } projectChain :: Chain -> [Clique] -> Chain projectChain s ts = Map.filterWithKey (\k _ -> k `elem` ts) s removePivots :: Chain -> Map.Map (Double,Clique) Chain -> Map.Map Clique Double -> Chain removePivots s ms sa = d where pcs = projectChain s (map snd (Map.keys ms)) d = reduceAll ms sa pcs reduceAll :: Map.Map (Double,Clique) Chain -> Map.Map Clique Double -> Chain -> Chain reduceAll ms sa ch = case Map.null ch of True -> ch False -> case Map.findMax (Map.filterWithKey (\k a -> k `elem` (Map.keys ch)) sa) of (k,v) -> case Map.lookup (v,k) ms of Nothing -> ch Just b | Map.null b -> ch | otherwise -> reduceAll ms sa (reduce k ch b) reduce :: Clique -> Chain -> Chain -> Chain reduce s p q = p - (constantC (1/(q!s)) * q) processNext :: HomologyState -> HomologyState processNext hs | null (simplexQ hs) && null (edgeQ hs) = hs | null (simplexQ hs) = let (e,t):eq = edgeQ hs g = graph hs sa = simplexAges hs (g',sq') = newSimplices e g sa' = Map.union sa (Map.fromList . map (\v -> (v,t)) $ sq') in hs { graph = g', simplexQ = reverse sq', simplexAges = sa', edgeQ = eq } | otherwise = let s:sq = simplexQ hs m = marked hs sa = simplexAges hs d = removePivots (boundaryC s) m sa result | Map.null d = hs { marked = Map.insert (sa!s,s) Map.empty m, simplexQ = sq } | otherwise = hs { marked = m', intervals = i', simplexQ = sq } where Just ((c,coeff),_) = Map.maxViewWithKey d i' = (I { birth=sa!c, death=Just (sa!s), dimension=dim c}) : (intervals hs) m' = Map.insert (sa!c,c) d m in result processN :: Int -> HomologyState -> HomologyState processN 0 hs = hs processN n hs = processN (n-1) (processNext hs) process :: HomologyState -> HomologyState process hs | nhs == hs = hs | otherwise = process nhs where nhs = processNext hs allIntervals :: HomologyState -> [Interval] allIntervals hs = intervals hs ++ ii where emptyMarked = Map.filter Map.null (marked hs) hoInterval :: ((Double,Clique),Chain) -> Interval hoInterval ((t,c),ch) = I { birth=t, death=Nothing, dimension=dim c} ii = map hoInterval (Map.toList emptyMarked)
michiexile/hplex
Math/Plex/Interleaved.hs
bsd-3-clause
6,378
0
18
1,803
2,872
1,554
1,318
147
3
----------------------------------------------------------------------------- -- Infer: Basic definitions for type inference -- -- Part of `Typing Haskell in Haskell', version of November 23, 2000 -- Copyright (c) Mark P Jones and the Oregon Graduate Institute -- of Science and Technology, 1999-2000 -- -- This program is distributed as Free Software under the terms -- in the file "License" that is included in the distribution -- of this software, copies of which may be obtained from: -- http://www.cse.ogi.edu/~mpj/thih/ -- ----------------------------------------------------------------------------- module Infer where import Pred import Assump import TIMonad type Infer e t = ClassEnv -> [Assump] -> e -> TI ([Pred], t) -----------------------------------------------------------------------------
elben/typing-haskell-in-haskell
Infer.hs
bsd-3-clause
846
0
10
140
62
44
18
5
0
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | Create new a new project directory populated with a basic working -- project. module Stack.New ( new , NewOpts(..) , defaultTemplateName , templateNameArgument , getTemplates , TemplateName , listTemplates) where import Control.Monad import Control.Monad.IO.Unlift import Control.Monad.Logger import Control.Monad.Trans.Writer.Strict import Data.Aeson import Data.Aeson.Types import qualified Data.ByteString as SB import qualified Data.ByteString.Lazy as LB import Data.Conduit import Data.Foldable (asum) import qualified Data.HashMap.Strict as HM import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe) import Data.Maybe.Extra (mapMaybeM) import Data.Monoid import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding.Error as T (lenientDecode) import qualified Data.Text.IO as T import qualified Data.Text.Lazy as LT import Data.Time.Calendar import Data.Time.Clock import Data.Typeable import qualified Data.Yaml as Yaml import Network.HTTP.Download import Network.HTTP.Simple import Path import Path.IO import Prelude import Stack.Constants import Stack.Types.Config import Stack.Types.PackageName import Stack.Types.StackT import Stack.Types.TemplateName import System.Process.Run import Text.Hastache import Text.Hastache.Context import Text.Printf import Text.ProjectTemplate -------------------------------------------------------------------------------- -- Main project creation -- | Options for creating a new project. data NewOpts = NewOpts { newOptsProjectName :: PackageName -- ^ Name of the project to create. , newOptsCreateBare :: Bool -- ^ Whether to create the project without a directory. , newOptsTemplate :: Maybe TemplateName -- ^ Name of the template to use. , newOptsNonceParams :: Map Text Text -- ^ Nonce parameters specified just for this invocation. } -- | Create a new project with the given options. new :: (StackM env m, HasConfig env) => NewOpts -> Bool -> m (Path Abs Dir) new opts forceOverwrite = do when (newOptsProjectName opts `elem` wiredInPackages) $ throwM $ Can'tUseWiredInName (newOptsProjectName opts) pwd <- getCurrentDir absDir <- if bare then return pwd else do relDir <- parseRelDir (packageNameString project) liftM (pwd </>) (return relDir) exists <- doesDirExist absDir configTemplate <- view $ configL.to configDefaultTemplate let template = fromMaybe defaultTemplateName $ asum [ cliOptionTemplate , configTemplate ] if exists && not bare then throwM (AlreadyExists absDir) else do templateText <- loadTemplate template (logUsing absDir template) files <- applyTemplate project template (newOptsNonceParams opts) absDir templateText when (not forceOverwrite && bare) $ checkForOverwrite (M.keys files) writeTemplateFiles files runTemplateInits absDir return absDir where cliOptionTemplate = newOptsTemplate opts project = newOptsProjectName opts bare = newOptsCreateBare opts logUsing absDir template templateFrom = let loading = case templateFrom of LocalTemp -> "Loading local" RemoteTemp -> "Downloading" in $logInfo (loading <> " template \"" <> templateName template <> "\" to create project \"" <> packageNameText project <> "\" in " <> if bare then "the current directory" else T.pack (toFilePath (dirname absDir)) <> " ...") data TemplateFrom = LocalTemp | RemoteTemp -- | Download and read in a template's text content. loadTemplate :: forall env m. (StackM env m, HasConfig env) => TemplateName -> (TemplateFrom -> m ()) -> m Text loadTemplate name logIt = do templateDir <- view $ configL.to templatesDir case templatePath name of AbsPath absFile -> logIt LocalTemp >> loadLocalFile absFile UrlPath s -> do req <- parseRequest s let rel = fromMaybe backupUrlRelPath (parseRelFile s) downloadTemplate req (templateDir </> rel) RelPath relFile -> catch (do f <- loadLocalFile relFile logIt LocalTemp return f) (\(e :: NewException) -> case relRequest relFile of Just req -> downloadTemplate req (templateDir </> relFile) Nothing -> throwM e ) where loadLocalFile :: Path b File -> m Text loadLocalFile path = do $logDebug ("Opening local template: \"" <> T.pack (toFilePath path) <> "\"") exists <- doesFileExist path if exists then liftIO (fmap (T.decodeUtf8With T.lenientDecode) (SB.readFile (toFilePath path))) else throwM (FailedToLoadTemplate name (toFilePath path)) relRequest :: MonadThrow n => Path Rel File -> n Request relRequest rel = parseRequest (defaultTemplateUrl <> "/" <> toFilePath rel) downloadTemplate :: Request -> Path Abs File -> m Text downloadTemplate req path = do logIt RemoteTemp _ <- catch (redownload req path) (throwM . FailedToDownloadTemplate name) loadLocalFile path backupUrlRelPath = $(mkRelFile "downloaded.template.file.hsfiles") -- | Apply and unpack a template into a directory. applyTemplate :: (StackM env m, HasConfig env) => PackageName -> TemplateName -> Map Text Text -> Path Abs Dir -> Text -> m (Map (Path Abs File) LB.ByteString) applyTemplate project template nonceParams dir templateText = do config <- view configL currentYear <- do now <- liftIO getCurrentTime (year, _, _) <- return $ toGregorian . utctDay $ now return $ T.pack . show $ year let context = M.union (M.union nonceParams extraParams) configParams where nameAsVarId = T.replace "-" "_" $ packageNameText project nameAsModule = T.filter (/= '-') $ T.toTitle $ packageNameText project extraParams = M.fromList [ ("name", packageNameText project) , ("name-as-varid", nameAsVarId) , ("name-as-module", nameAsModule) , ("year", currentYear) ] configParams = configTemplateParams config (applied,missingKeys) <- runWriterT (hastacheStr defaultConfig { muEscapeFunc = id } templateText (mkStrContextM (contextFunction context))) unless (S.null missingKeys) ($logInfo ("\n" <> T.pack (show (MissingParameters project template missingKeys (configUserConfigPath config))) <> "\n")) files :: Map FilePath LB.ByteString <- catch (execWriterT $ yield (T.encodeUtf8 (LT.toStrict applied)) $$ unpackTemplate receiveMem id ) (\(e :: ProjectTemplateException) -> throwM (InvalidTemplate template (show e))) when (M.null files) $ throwM (InvalidTemplate template "Template does not contain any files") let isPkgSpec f = ".cabal" `isSuffixOf` f || f == "package.yaml" unless (any isPkgSpec . M.keys $ files) $ throwM (InvalidTemplate template "Template does not contain a .cabal \ \or package.yaml file") liftM M.fromList (mapM (\(fp,bytes) -> do path <- parseRelFile fp return (dir </> path, bytes)) (M.toList files)) where -- | Does a lookup in the context and returns a moustache value, -- on the side, writes out a set of keys that were requested but -- not found. contextFunction :: Monad m => Map Text Text -> String -> WriterT (Set String) m (MuType (WriterT (Set String) m)) contextFunction context key = case M.lookup (T.pack key) context of Nothing -> do tell (S.singleton key) return MuNothing Just value -> return (MuVariable value) -- | Check if we're going to overwrite any existing files. checkForOverwrite :: (MonadIO m, MonadThrow m) => [Path Abs File] -> m () checkForOverwrite files = do overwrites <- filterM doesFileExist files unless (null overwrites) $ throwM (AttemptedOverwrites overwrites) -- | Write files to the new project directory. writeTemplateFiles :: MonadIO m => Map (Path Abs File) LB.ByteString -> m () writeTemplateFiles files = forM_ (M.toList files) (\(fp,bytes) -> do ensureDir (parent fp) liftIO (LB.writeFile (toFilePath fp) bytes)) -- | Run any initialization functions, such as Git. runTemplateInits :: (StackM env m, HasConfig env) => Path Abs Dir -> m () runTemplateInits dir = do menv <- getMinimalEnvOverride config <- view configL case configScmInit config of Nothing -> return () Just Git -> catch (callProcess $ Cmd (Just dir) "git" menv ["init"]) (\(_ :: ProcessExitedUnsuccessfully) -> $logInfo "git init failed to run, ignoring ...") -- | Display the set of templates accompanied with description if available. listTemplates :: StackM env m => m () listTemplates = do templates <- getTemplates templateInfo <- getTemplateInfo if not . M.null $ templateInfo then do let keySizes = map (T.length . templateName) $ S.toList templates padWidth = show $ maximum keySizes outputfmt = "%-" <> padWidth <> "s %s\n" headerfmt = "%-" <> padWidth <> "s %s\n" liftIO $ printf headerfmt ("Template"::String) ("Description"::String) forM_ (S.toList templates) (\x -> do let name = templateName x desc = fromMaybe "" $ liftM (mappend "- ") (M.lookup name templateInfo >>= description) liftIO $ printf outputfmt (T.unpack name) (T.unpack desc)) else mapM_ (liftIO . T.putStrLn . templateName) (S.toList templates) -- | Get the set of templates. getTemplates :: StackM env m => m (Set TemplateName) getTemplates = do req <- liftM setGithubHeaders (parseUrlThrow defaultTemplatesList) resp <- catch (httpJSON req) (throwM . FailedToDownloadTemplates) case getResponseStatusCode resp of 200 -> return $ unTemplateSet $ getResponseBody resp code -> throwM (BadTemplatesResponse code) getTemplateInfo :: StackM env m => m (Map Text TemplateInfo) getTemplateInfo = do req <- liftM setGithubHeaders (parseUrlThrow defaultTemplateInfoUrl) resp <- catch (liftM Right $ httpLbs req) (\(ex :: HttpException) -> return . Left $ "Failed to download template info. The HTTP error was: " <> show ex) case resp >>= is200 of Left err -> do liftIO . putStrLn $ err return M.empty Right resp' -> case Yaml.decodeEither (LB.toStrict $ getResponseBody resp') :: Either String Object of Left err -> throwM $ BadTemplateInfo err Right o -> return (M.mapMaybe (Yaml.parseMaybe Yaml.parseJSON) (M.fromList . HM.toList $ o) :: Map Text TemplateInfo) where is200 resp = case getResponseStatusCode resp of 200 -> return resp code -> Left $ "Unexpected status code while retrieving templates info: " <> show code newtype TemplateSet = TemplateSet { unTemplateSet :: Set TemplateName } instance FromJSON TemplateSet where parseJSON = fmap TemplateSet . parseTemplateSet -- | Parser the set of templates from the JSON. parseTemplateSet :: Value -> Parser (Set TemplateName) parseTemplateSet a = do xs <- parseJSON a fmap S.fromList (mapMaybeM parseTemplate xs) where parseTemplate v = do o <- parseJSON v name <- o .: "name" if ".hsfiles" `isSuffixOf` name then case parseTemplateNameFromString name of Left{} -> fail ("Unable to parse template name from " <> name) Right template -> return (Just template) else return Nothing -------------------------------------------------------------------------------- -- Defaults -- | The default template name you can use if you don't have one. defaultTemplateName :: TemplateName defaultTemplateName = $(mkTemplateName "new-template") -- | Default web root URL to download from. defaultTemplateUrl :: String defaultTemplateUrl = "https://raw.githubusercontent.com/commercialhaskell/stack-templates/master" -- | Default web URL to get a yaml file containing template metadata. defaultTemplateInfoUrl :: String defaultTemplateInfoUrl = "https://raw.githubusercontent.com/commercialhaskell/stack-templates/master/template-info.yaml" -- | Default web URL to list the repo contents. defaultTemplatesList :: String defaultTemplatesList = "https://api.github.com/repos/commercialhaskell/stack-templates/contents/" -------------------------------------------------------------------------------- -- Exceptions -- | Exception that might occur when making a new project. data NewException = FailedToLoadTemplate !TemplateName !FilePath | FailedToDownloadTemplate !TemplateName !DownloadException | FailedToDownloadTemplates !HttpException | BadTemplatesResponse !Int | AlreadyExists !(Path Abs Dir) | MissingParameters !PackageName !TemplateName !(Set String) !(Path Abs File) | InvalidTemplate !TemplateName !String | AttemptedOverwrites [Path Abs File] | FailedToDownloadTemplateInfo !HttpException | BadTemplateInfo !String | BadTemplateInfoResponse !Int | Can'tUseWiredInName !PackageName deriving (Typeable) instance Exception NewException instance Show NewException where show (FailedToLoadTemplate name path) = "Failed to load download template " <> T.unpack (templateName name) <> " from " <> path show (FailedToDownloadTemplate name (RedownloadFailed _ _ resp)) = case getResponseStatusCode resp of 404 -> "That template doesn't exist. Run `stack templates' to see a list of available templates." code -> "Failed to download template " <> T.unpack (templateName name) <> ": unknown reason, status code was: " <> show code show (AlreadyExists path) = "Directory " <> toFilePath path <> " already exists. Aborting." show (FailedToDownloadTemplates ex) = "Failed to download templates. The HTTP error was: " <> show ex show (BadTemplatesResponse code) = "Unexpected status code while retrieving templates list: " <> show code show (MissingParameters name template missingKeys userConfigPath) = intercalate "\n" [ "The following parameters were needed by the template but not provided: " <> intercalate ", " (S.toList missingKeys) , "You can provide them in " <> toFilePath userConfigPath <> ", like this:" , "templates:" , " params:" , intercalate "\n" (map (\key -> " " <> key <> ": value") (S.toList missingKeys)) , "Or you can pass each one as parameters like this:" , "stack new " <> packageNameString name <> " " <> T.unpack (templateName template) <> " " <> unwords (map (\key -> "-p \"" <> key <> ":value\"") (S.toList missingKeys))] show (InvalidTemplate name why) = "The template \"" <> T.unpack (templateName name) <> "\" is invalid and could not be used. " <> "The error was: \"" <> why <> "\"" show (AttemptedOverwrites fps) = "The template would create the following files, but they already exist:\n" <> unlines (map ((" " ++) . toFilePath) fps) <> "Use --force to ignore this, and overwite these files." show (FailedToDownloadTemplateInfo ex) = "Failed to download templates info. The HTTP error was: " <> show ex show (BadTemplateInfo err) = "Template info couldn't be parsed: " <> err show (BadTemplateInfoResponse code) = "Unexpected status code while retrieving templates info: " <> show code show (Can'tUseWiredInName name) = "The name \"" <> packageNameString name <> "\" is used by GHC wired-in packages, and so shouldn't be used as a package name"
martin-kolinek/stack
src/Stack/New.hs
bsd-3-clause
17,998
0
23
5,539
4,101
2,074
2,027
410
5
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RecordWildCards, FlexibleInstances, DefaultSignatures #-} ------------------------------------------------------------------------------ -- | -- Module: Database.PostgreSQL.Simple.FromRow -- Copyright: (c) 2012 Leon P Smith -- License: BSD3 -- Maintainer: Leon P Smith <leon@melding-monads.com> -- Stability: experimental -- -- The 'FromRow' typeclass, for converting a row of results -- returned by a SQL query into a more useful Haskell representation. -- -- Predefined instances are provided for tuples containing up to ten -- elements. The instances for 'Maybe' types return 'Nothing' if all -- the columns that would have been otherwise consumed are null, otherwise -- it attempts a regular conversion. -- ------------------------------------------------------------------------------ module Database.PostgreSQL.Simple.FromRow ( FromRow(..) , RowParser , field , fieldWith , numFieldsRemaining ) where import Prelude hiding (null) import Control.Applicative (Applicative(..), (<$>), (<|>), (*>), liftA2) import Control.Monad (replicateM, replicateM_) import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Reader import Control.Monad.Trans.Class import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B import Data.Vector (Vector) import qualified Data.Vector as V import Database.PostgreSQL.Simple.Types (Only(..)) import qualified Database.PostgreSQL.LibPQ as PQ import Database.PostgreSQL.Simple.Internal import Database.PostgreSQL.Simple.Compat import Database.PostgreSQL.Simple.FromField import Database.PostgreSQL.Simple.Ok import Database.PostgreSQL.Simple.Types ((:.)(..), Null) import Database.PostgreSQL.Simple.TypeInfo import GHC.Generics -- | A collection type that can be converted from a sequence of fields. -- Instances are provided for tuples up to 10 elements and lists of any length. -- -- Note that instances can be defined outside of postgresql-simple, which is -- often useful. For example, here's an instance for a user-defined pair: -- -- @ -- data User = User { name :: String, fileQuota :: Int } -- -- instance 'FromRow' User where -- fromRow = User \<$\> 'field' \<*\> 'field' -- @ -- -- The number of calls to 'field' must match the number of fields returned -- in a single row of the query result. Otherwise, a 'ConversionFailed' -- exception will be thrown. -- -- Note that 'field' evaluates its result to WHNF, so the caveats listed in -- mysql-simple and very early versions of postgresql-simple no longer apply. -- Instead, look at the caveats associated with user-defined implementations -- of 'fromField'. class FromRow a where fromRow :: RowParser a default fromRow :: (Generic a, GFromRow (Rep a)) => RowParser a fromRow = to <$> gfromRow getvalue :: PQ.Result -> PQ.Row -> PQ.Column -> Maybe ByteString getvalue result row col = unsafeDupablePerformIO (PQ.getvalue' result row col) nfields :: PQ.Result -> PQ.Column nfields result = unsafeDupablePerformIO (PQ.nfields result) getTypeInfoByCol :: Row -> PQ.Column -> Conversion TypeInfo getTypeInfoByCol Row{..} col = Conversion $ \conn -> do oid <- PQ.ftype rowresult col Ok <$> getTypeInfo conn oid getTypenameByCol :: Row -> PQ.Column -> Conversion ByteString getTypenameByCol row col = typname <$> getTypeInfoByCol row col fieldWith :: FieldParser a -> RowParser a fieldWith fieldP = RP $ do let unCol (PQ.Col x) = fromIntegral x :: Int r@Row{..} <- ask column <- lift get lift (put (column + 1)) let ncols = nfields rowresult if (column >= ncols) then lift $ lift $ do vals <- mapM (getTypenameByCol r) [0..ncols-1] let err = ConversionFailed (show (unCol ncols) ++ " values: " ++ show (map ellipsis vals)) Nothing "" ("at least " ++ show (unCol column + 1) ++ " slots in target type") "mismatch between number of columns to \ \convert and number in target type" conversionError err else do let !result = rowresult !typeOid = unsafeDupablePerformIO (PQ.ftype result column) !field = Field{..} lift (lift (fieldP field (getvalue result row column))) field :: FromField a => RowParser a field = fieldWith fromField ellipsis :: ByteString -> ByteString ellipsis bs | B.length bs > 15 = B.take 10 bs `B.append` "[...]" | otherwise = bs numFieldsRemaining :: RowParser Int numFieldsRemaining = RP $ do Row{..} <- ask column <- lift get return $! (\(PQ.Col x) -> fromIntegral x) (nfields rowresult - column) null :: RowParser Null null = field instance (FromField a) => FromRow (Only a) where fromRow = Only <$> field instance (FromField a) => FromRow (Maybe (Only a)) where fromRow = (null *> pure Nothing) <|> (Just <$> fromRow) instance (FromField a, FromField b) => FromRow (a,b) where fromRow = (,) <$> field <*> field instance (FromField a, FromField b) => FromRow (Maybe (a,b)) where fromRow = (null *> null *> pure Nothing) <|> (Just <$> fromRow) instance (FromField a, FromField b, FromField c) => FromRow (a,b,c) where fromRow = (,,) <$> field <*> field <*> field instance (FromField a, FromField b, FromField c) => FromRow (Maybe (a,b,c)) where fromRow = (null *> null *> null *> pure Nothing) <|> (Just <$> fromRow) instance (FromField a, FromField b, FromField c, FromField d) => FromRow (a,b,c,d) where fromRow = (,,,) <$> field <*> field <*> field <*> field instance (FromField a, FromField b, FromField c, FromField d) => FromRow (Maybe (a,b,c,d)) where fromRow = (null *> null *> null *> null *> pure Nothing) <|> (Just <$> fromRow) instance (FromField a, FromField b, FromField c, FromField d, FromField e) => FromRow (a,b,c,d,e) where fromRow = (,,,,) <$> field <*> field <*> field <*> field <*> field instance (FromField a, FromField b, FromField c, FromField d, FromField e) => FromRow (Maybe (a,b,c,d,e)) where fromRow = (null *> null *> null *> null *> null *> pure Nothing) <|> (Just <$> fromRow) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f) => FromRow (a,b,c,d,e,f) where fromRow = (,,,,,) <$> field <*> field <*> field <*> field <*> field <*> field instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f) => FromRow (Maybe (a,b,c,d,e,f)) where fromRow = (null *> null *> null *> null *> null *> null *> pure Nothing) <|> (Just <$> fromRow) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g) => FromRow (a,b,c,d,e,f,g) where fromRow = (,,,,,,) <$> field <*> field <*> field <*> field <*> field <*> field <*> field instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g) => FromRow (Maybe (a,b,c,d,e,f,g)) where fromRow = (null *> null *> null *> null *> null *> null *> null *> pure Nothing) <|> (Just <$> fromRow) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h) => FromRow (a,b,c,d,e,f,g,h) where fromRow = (,,,,,,,) <$> field <*> field <*> field <*> field <*> field <*> field <*> field <*> field instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h) => FromRow (Maybe (a,b,c,d,e,f,g,h)) where fromRow = (null *> null *> null *> null *> null *> null *> null *> null *> pure Nothing) <|> (Just <$> fromRow) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h, FromField i) => FromRow (a,b,c,d,e,f,g,h,i) where fromRow = (,,,,,,,,) <$> field <*> field <*> field <*> field <*> field <*> field <*> field <*> field <*> field instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h, FromField i) => FromRow (Maybe (a,b,c,d,e,f,g,h,i)) where fromRow = (null *> null *> null *> null *> null *> null *> null *> null *> null *> pure Nothing) <|> (Just <$> fromRow) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h, FromField i, FromField j) => FromRow (a,b,c,d,e,f,g,h,i,j) where fromRow = (,,,,,,,,,) <$> field <*> field <*> field <*> field <*> field <*> field <*> field <*> field <*> field <*> field instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h, FromField i, FromField j) => FromRow (Maybe (a,b,c,d,e,f,g,h,i,j)) where fromRow = (null *> null *> null *> null *> null *> null *> null *> null *> null *> null *> pure Nothing) <|> (Just <$> fromRow) instance FromField a => FromRow [a] where fromRow = do n <- numFieldsRemaining replicateM n field instance FromField a => FromRow (Maybe [a]) where fromRow = do n <- numFieldsRemaining (replicateM_ n null *> pure Nothing) <|> (Just <$> replicateM n field) instance FromField a => FromRow (Vector a) where fromRow = do n <- numFieldsRemaining V.replicateM n field instance FromField a => FromRow (Maybe (Vector a)) where fromRow = do n <- numFieldsRemaining (replicateM_ n null *> pure Nothing) <|> (Just <$> V.replicateM n field) instance (FromRow a, FromRow b) => FromRow (a :. b) where fromRow = (:.) <$> fromRow <*> fromRow -- Type class for default implementation of FromRow using generics class GFromRow f where gfromRow :: RowParser (f p) instance GFromRow f => GFromRow (M1 c i f) where gfromRow = M1 <$> gfromRow instance (GFromRow f, GFromRow g) => GFromRow (f :*: g) where gfromRow = liftA2 (:*:) gfromRow gfromRow instance (FromField a) => GFromRow (K1 R a) where gfromRow = K1 <$> field instance GFromRow U1 where gfromRow = pure U1
tolysz/postgresql-simple
src/Database/PostgreSQL/Simple/FromRow.hs
bsd-3-clause
10,594
0
22
2,630
3,476
1,891
1,585
-1
-1
----------------------------------------------------------------------------- -- | -- Module : System.Taffybar.Pager -- Copyright : (c) José A. Romero L. -- License : BSD3-style (see LICENSE) -- -- Maintainer : José A. Romero L. <escherdragon@gmail.com> -- Stability : unstable -- Portability : unportable -- -- Common support for pager widgets. This module does not provide itself -- any widgets, but implements an event dispatcher on which widgets can -- subscribe the desktop events they're interested in, as well as common -- configuration facilities. -- -- N.B. If you're just looking for a drop-in replacement for the -- "System.Taffybar.XMonadLog" widget that is clickable and doesn't require -- DBus, you may want to see first "System.Taffybar.TaffyPager". -- -- You need only one Pager component to instantiate any number of pager -- widgets: -- -- > pager <- pagerNew defaultPagerConfig -- > -- > let wss = wspaceSwitcherNew pager -- Workspace Switcher widget -- > los = layoutSwitcherNew pager -- Layout Switcher widget -- > wnd = windowSwitcherNew pager -- Window Switcher widget -- ----------------------------------------------------------------------------- module System.Taffybar.Pager ( Pager (config) , PagerConfig (..) , defaultPagerConfig , pagerNew , subscribe , colorize , shorten , wrap , escape ) where import Control.Concurrent (forkIO) import Control.Exception import Control.Exception.Enclosed (catchAny) import Control.Monad.Reader import Data.IORef import Graphics.UI.Gtk (escapeMarkup) import Graphics.X11.Types import Graphics.X11.Xlib.Extras import Text.Printf (printf) import System.Information.X11DesktopInfo type Listener = Event -> IO () type Filter = Atom type SubscriptionList = IORef [(Listener, Filter)] -- | Structure contanining functions to customize the pretty printing of -- different widget elements. data PagerConfig = PagerConfig { activeWindow :: String -> String -- ^ the name of the active window. , activeLayout :: String -> String -- ^ the currently active layout. , activeWorkspace :: String -> String -- ^ the currently active workspace. , hiddenWorkspace :: String -> String -- ^ inactive workspace with windows. , emptyWorkspace :: String -> String -- ^ inactive workspace with no windows. , visibleWorkspace :: String -> String -- ^ all other visible workspaces (Xinerama or XRandR). , urgentWorkspace :: String -> String -- ^ workspaces containing windows with the urgency hint set. , widgetSep :: String -- ^ separator to use between desktop widgets in 'TaffyPager'. } -- | Structure containing the state of the Pager. data Pager = Pager { config :: PagerConfig -- ^ the configuration settings. , clients :: SubscriptionList -- ^ functions to apply on incoming events depending on their types. } -- | Default pretty printing options. defaultPagerConfig :: PagerConfig defaultPagerConfig = PagerConfig { activeWindow = escape . shorten 40 , activeLayout = escape , activeWorkspace = colorize "yellow" "" . wrap "[" "]" . escape , hiddenWorkspace = escape , emptyWorkspace = escape , visibleWorkspace = wrap "(" ")" . escape , urgentWorkspace = colorize "red" "yellow" . escape , widgetSep = " : " } -- | Creates a new Pager component (wrapped in the IO Monad) that can be -- used by widgets for subscribing X11 events. pagerNew :: PagerConfig -> IO Pager pagerNew cfg = do ref <- newIORef [] let pager = Pager cfg ref _ <- forkIO $ withDefaultCtx $ eventLoop (handleEvent ref) return pager where handleEvent :: SubscriptionList -> Event -> IO () handleEvent ref event = do listeners <- readIORef ref mapM_ (notify event) listeners -- | Passes the given Event to the given Listener, but only if it was -- registered for that type of events via 'subscribe'. notify :: Event -> (Listener, Filter) -> IO () notify event (listener, eventFilter) = case event of PropertyEvent _ _ _ _ _ atom _ _ -> when (atom == eventFilter) $ catchAny (listener event) ignoreException _ -> return () -- | Registers the given Listener as a subscriber of events of the given -- type: whenever a new event of the type with the given name arrives to -- the Pager, it will execute Listener on it. subscribe :: Pager -> Listener -> String -> IO () subscribe pager listener filterName = do eventFilter <- withDefaultCtx $ getAtom filterName registered <- readIORef (clients pager) let next = (listener, eventFilter) writeIORef (clients pager) (next : registered) ignoreException :: SomeException -> IO () ignoreException _ = return () -- | Creates markup with the given foreground and background colors and the -- given contents. colorize :: String -- ^ Foreground color. -> String -- ^ Background color. -> String -- ^ Contents. -> String colorize fg bg = printf "<span%s%s>%s</span>" (attr "fg" fg) (attr "bg" bg) where attr name value | null value = "" | otherwise = printf " %scolor=\"%s\"" name value -- | Limit a string to a certain length, adding "..." if truncated. shorten :: Int -> String -> String shorten l s | length s <= l = s | l >= 3 = take (l - 3) s ++ "..." | otherwise = "..." -- | Wrap the given string in the given delimiters. wrap :: String -- ^ Left delimiter. -> String -- ^ Right delimiter. -> String -- ^ Output string. -> String wrap open close s = open ++ s ++ close -- | Escape strings so that they can be safely displayed by Pango in the -- bar widget escape :: String -> String escape = escapeMarkup
Undeterminant/taffybar
src/System/Taffybar/Pager.hs
bsd-3-clause
5,670
0
11
1,177
1,003
561
442
91
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} module Mistral.TypeCheck.Monad ( -- * Type Checking Monad TC() , runTC -- ** Unification Interface , applySubst, getSubst , unify -- ** Variables , freshTVar , freshTVarTemplate , freshName , withSkolems , getSkolems -- ** Schemas , instSchema, instVarType , freshType, freshVarType, freshVarTypeRewrite , generalize -- ** Constraints , Goal(..), GoalSource(..) , goalToAssump , userGoal, userGoals , subGoalOf , getGoals , addGoal, addGoals , collectGoals -- ** Instances , schemaAssumps , localAssumps , assume , getAssumps , getInsts -- ** Environment , withEnv , getEnv , lookupSchema, tryLookupSchema , lookupTSyn , srcLoc , withSource, withLoc -- ** Errors , tcErr , tcWarn ) where import Mistral.Driver import Mistral.ModuleSystem.Interface ( IfaceTrie ) import qualified Mistral.ModuleSystem.Name as M import Mistral.TypeCheck.AST import qualified Mistral.TypeCheck.Env as E import Mistral.TypeCheck.Unify import Mistral.Utils.PP import Mistral.Utils.Panic import Mistral.Utils.Source import Control.Applicative ( Applicative(..), Alternative ) import Control.Monad ( MonadPlus(..), unless ) import Control.Monad.Fix ( MonadFix ) import Data.List ( partition ) import Data.Monoid ( Monoid(..) ) import MonadLib ( runM, ReaderT, ask, local, StateT, get, set, BaseM(..) ) import qualified Data.Set as Set tcPanic :: [String] -> a tcPanic = panic "Mistral.TypeCheck.Monad" data RO = RO { roSource :: Source , roEnv :: E.Env , roSkolems :: Skolems } data RW = RW { rwSubst :: Subst , rwFreshTy :: Int , rwFreshNm :: Int , rwGoals :: [Goal] , rwAssumps :: [Inst] -- ^ Local assumptions, learned from the solver. } newtype TC a = TC { getTC :: ReaderT RO (StateT RW Driver) a } deriving (Functor,Applicative,Monad,MonadPlus,MonadFix,Alternative) instance BaseM TC Driver where {-# INLINE inBase #-} inBase m = TC (inBase m) -- | Run a TC action in the Driver monad. runTC :: IfaceTrie -> TC a -> Driver a runTC ifaces m = do (a,_) <- runM (getTC m) ro rw return a where ro = RO { roSource = Unknown , roEnv = mempty { E.envIfaces = ifaces } , roSkolems = Set.empty } rw = RW { rwSubst = mempty , rwFreshTy = 0 , rwFreshNm = 0 , rwGoals = [] , rwAssumps = [] } -- Fresh Variables ------------------------------------------------------------- -- | Generate a fresh type parameter with no specific name. freshTVar :: TC Type freshTVar = do p <- freshTVarTemplate TParam { tpUserName = Nothing, tpIndex = 0 } return (TVar (TVFree p)) -- | Generate a fresh type parameter, given a template to use. freshTVarTemplate :: TParam -> TC TParam freshTVarTemplate tp = TC $ do rw <- get set rw { rwFreshTy = rwFreshTy rw + 1 } return tp { tpIndex = rwFreshTy rw } -- | Generate a fresh name for the typechecking pass. freshName :: TC M.Name freshName = TC $ do rw <- get set $! rw { rwFreshNm = rwFreshNm rw + 1 } return (M.mkFresh M.TC (rwFreshNm rw)) -- Schemas --------------------------------------------------------------------- -- | Instantiate a schema, given a set of types for the parameters, adding any -- generated goals to the set to be proven. instSchema :: [Type] -> Schema -> TC Type instSchema tys s@(Forall ps props ty) = do unless (length tys == length ps) $ do tcErr (invalidSchemaInst tys s) mzero let iSubst = boundBinds (zip ps tys) (iprops,ity) = apply iSubst (props,ty) addGoals =<< applySubst =<< userGoals iprops applySubst ity invalidSchemaInst :: [Type] -> Schema -> PPDoc invalidSchemaInst ts s = hang (text "Not enough type parameters given to schema") 2 (vcat [ text "parameters:" <+> nest 11 (commas (map pp ts)) , text "schema:" <+> nest 11 (pp s) ]) -- | Instantiate a schema from the environment, provided that the right number -- of parameters are given. In the event that the schema is instantiated -- incorrectly, log an error and fail with mzero. instVarType :: [Type] -> Expr -> E.VarType -> TC (Type,Expr) instVarType tys e vt = do ty <- instSchema tys (E.vtSchema vt) let expr = case vt of E.Var _ -> tappE e tys E.Checking _ e' -> tappE e' tys E.Primitive _ e' -> tappE (EPrim e') tys return (ty,expr) -- | Generate a fresh instantiation of a Schema, adding any generated goals to -- the set to be proven. freshType :: Schema -> TC ([TParam],Type) freshType s = do ps <- mapM freshTVarTemplate (sParams s) ty <- instSchema [ TVar (TVFree p) | p <- ps ] s return (ps,ty) -- | Instantiate a VarType, automatically adding its goals to the set of things -- to prove. freshVarType :: E.VarType -> TC ([TParam],Type) freshVarType vt = freshType (E.vtSchema vt) -- | Generate a fresh instantiation of a VarType, with an expression to use if -- there is no body to rewrite with. freshVarTypeRewrite :: Expr -> E.VarType -> TC ([TParam], Type, Expr) freshVarTypeRewrite e vt = do ps <- mapM freshTVarTemplate (sParams (E.vtSchema vt)) let tys = map (TVar . TVFree) ps (ty,e') <- instVarType tys e vt return (ps,ty,e') -- | Generalize a type WRT a set of type variables. The result is the new -- schema, and any goals that couldn't be generalized. generalize :: Types body => [TParam] -> [Goal] -> Type -> body -> TC (Schema,[Goal],body) generalize ps gs ty body = do env <- getEnv let -- don't generalize anything that's in the environment fvs = typeVars env ps' = filter (`Set.notMember` fvs) ps -- partition out goals that mention the variables that will be -- generalized gs' <- applySubst gs let tvars = Set.fromList ps' mentions_ps g = not (Set.null (tvars `Set.intersection` typeVars g)) (cxt,other) = partition mentions_ps gs' -- produce a set of new bound variables... bs = zipWith step [0 ..] ps' step i p = p { tpIndex = i } -- ...and the types they correspond to tys = [ TVar (TVBound p) | p <- bs ] -- generate a substitution to the bound variables u = freeBinds (zip ps' tys) props <- applySubst (map gProp cxt) body' <- applySubst body return (Forall bs (apply u props) (apply u ty), other, apply u body') -- | Extend the skolem environment locally. withSkolems :: Skolems -> TC a -> TC a withSkolems skolems body = TC $ do ro <- ask local ro { roSkolems = skolems `Set.union` roSkolems ro } (getTC body) getSkolems :: TC Skolems getSkolems = TC (roSkolems `fmap` ask) -- Constraints ----------------------------------------------------------------- data Goal = Goal { gSource :: GoalSource , gProp :: Prop } deriving (Show,Eq,Ord) instance PP Goal where ppr g = hang (backquotes (pp (gProp g))) 2 (pp (gSource g)) instance Types Goal where typeVars g = typeVars (gProp g, gSource g) applyBndrs b u g = g { gSource = applyBndrs b u (gSource g) , gProp = applyBndrs b u (gProp g) } instance HasSource Goal where getSource g = getSource (gSource g) data GoalSource = GSUser Source -- ^ Goals generated directly from user programs | GSGoal Prop GoalSource -- ^ Goals generated by other goals. deriving (Show,Eq,Ord) instance PP GoalSource where ppr gs = vcat (map (text "from" <+>) (ppGoalSource gs)) ppGoalSource :: GoalSource -> [PPDoc] ppGoalSource gs = case gs of GSUser Unknown -> [] GSUser src -> [pp src] GSGoal g gs' -> backquotes (pp g) : ppGoalSource gs' instance Types GoalSource where typeVars gs = case gs of GSUser _ -> Set.empty GSGoal g gs' -> typeVars (g,gs') applyBndrs b u gs = case gs of GSUser _ -> gs GSGoal g gs' -> GSGoal (applyBndrs b u g) (applyBndrs b u gs') instance HasSource GoalSource where getSource gs = case gs of GSUser src -> src GSGoal _ gs' -> getSource gs' goalToAssump :: Goal -> Inst goalToAssump g = Inst { iProp = mkSchema (gProp g) } -- | Construct a goal whose origin is the current source location. userGoal :: Prop -> TC Goal userGoal p = do src <- srcLoc return Goal { gSource = GSUser src, gProp = p } userGoals :: [Prop] -> TC [Goal] userGoals = mapM userGoal subGoalSource :: Goal -> GoalSource subGoalSource g = GSGoal (gProp g) (gSource g) -- | Make p a subgoal of q. subGoalOf :: Goal -> Goal -> Goal subGoalOf q p = p { gSource = subGoalSource q } addGoal :: Goal -> TC () addGoal g = addGoals [g] addGoals :: [Goal] -> TC () addGoals gs = TC $ do rw <- get set rw { rwGoals = gs ++ rwGoals rw } getGoals :: TC [Goal] getGoals = applySubst =<< TC body where body = do rw <- get set rw { rwGoals = [] } return (rwGoals rw) collectGoals :: TC a -> TC (a,[Goal]) collectGoals m = do orig <- getGoals a <- m ags <- getGoals addGoals orig return (a,ags) -- Instance DB Interaction ----------------------------------------------------- -- | Extract constraints from a schema. -- -- XXX this isn't quite right, as it adds all variables to every generated -- assumption. as a result, this type: -- -- forall a b. (Eq a, Eq b) => ... -- -- generates these assumptions -- -- forall a b. Eq a -- forall a b. Eq b schemaAssumps :: Schema -> [Inst] schemaAssumps schema = map toInst (sProps schema) where toInst prop = Inst { iProp = Forall (sParams schema) [] prop } -- | Clean out any assumptions introduced during this computation. localAssumps :: TC a -> TC a localAssumps m = do assumps <- getAssumps a <- m TC $ do rw' <- get set rw' { rwAssumps = assumps } return a -- | Add an assumption to the instance db. assume :: Inst -> TC () assume i = TC $ do traceMsg (text "assuming:" <+> pp i) rw <- get set rw { rwAssumps = i : rwAssumps rw } getAssumps :: TC [Inst] getAssumps = TC (rwAssumps `fmap` get) getInsts :: TC [Inst] getInsts = TC $ do ro <- ask return (E.getInsts (roEnv ro)) -- Unification ----------------------------------------------------------------- -- | Apply the current substitution to a type. applySubst :: Types a => a -> TC a applySubst a = do u <- getSubst return (apply u a) getSubst :: TC Subst getSubst = TC (rwSubst `fmap` get) -- | Unify two types, logging errors and using mzero on a failure. The -- left-hand side is the user-expected type, the right-hand-side is the inferred -- type. NOTE: the arguments are somewhat backwards from the way they work in -- `mgu`, this is just an accident. unify :: Type -> Type -> TC () unify l r = do skolems <- getSkolems u <- getSubst case mgu skolems (apply u r) (apply u l) of Right u' -> TC $ do rw <- get set $! rw { rwSubst = u' `mappend` u } Left err -> do tcErr (pp err) mzero -- Environment Interaction ----------------------------------------------------- -- | Run an action with an extended environment. withEnv :: E.Env -> TC a -> TC a withEnv env m = do env' <- applySubst env TC $ do ro <- ask local ro { roEnv = env' `mappend` roEnv ro } (getTC m) getEnv :: TC E.Env getEnv = applySubst =<< TC (roEnv `fmap` ask) -- | Lookup a schema in the environment. If the schema doesn't exist in the -- environment, this will report an error at the current location, and fail with -- mzero. lookupSchema :: Name -> TC E.VarType lookupSchema qn = do ro <- TC ask case E.lookupEnv qn (roEnv ro) of Just res -> return res Nothing -> tcPanic [ "no type for: " ++ show qn , "bug in the renamer? " , E.showEnv (roEnv ro) ] tryLookupSchema :: Name -> TC (Maybe E.VarType) tryLookupSchema qn = TC $ do ro <- ask return (E.lookupEnv qn (roEnv ro)) -- | Lookup a type synonym lookupTSyn :: Name -> TC (Maybe TySyn) lookupTSyn qn = TC $ do ro <- ask return (E.lookupTSyn qn (roEnv ro)) -- | The current source location. srcLoc :: TC Source srcLoc = TC (roSource `fmap` ask) -- | Run a TC action with source location information. withSource :: HasSource src => src -> TC a -> TC a withSource src m | real == Unknown = m | otherwise = TC $ do ro <- ask local ro { roSource = real } (getTC m) where real = getSource src -- | Run a TC action with the location and value of a located thing. withLoc :: (a -> TC b) -> Located a -> TC b withLoc f loc = withSource (getSource loc) (f (locThing loc)) -- Error Reporting ------------------------------------------------------------- -- | Report an error at the current location. tcErr :: PPDoc -> TC () tcErr msg = TC $ do ro <- ask inBase (addErrAt msg (roSource ro)) -- | Report a warning at the current location. tcWarn :: PPDoc -> TC () tcWarn msg = TC $ do ro <- ask inBase (addWarnAt msg (roSource ro))
GaloisInc/mistral
src/Mistral/TypeCheck/Monad.hs
bsd-3-clause
13,520
0
16
3,696
3,985
2,081
1,904
294
3
{-# LANGUAGE PackageImports #-} module GHC.IO.Handle.Text (module M) where import "base" GHC.IO.Handle.Text as M
silkapp/base-noprelude
src/GHC/IO/Handle/Text.hs
bsd-3-clause
118
0
4
18
25
19
6
3
0
-- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings where import Prelude import Text.Shakespeare.Text (st) import Language.Haskell.TH.Syntax import Database.Persist.Postgresql (PostgresConf) import Yesod.Default.Config import Yesod.Default.Util import Data.Text (Text) import Data.Yaml import Control.Applicative import Settings.Development import Data.Default (def) import Text.Hamlet import Text.Coffee -- | Which Persistent backend this site is using. type PersistConf = PostgresConf -- Static setting below. Changing these requires a recompile -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticDir :: FilePath staticDir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in Foundation.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in Foundation.hs staticRoot :: AppConfig DefaultEnv x -> Text staticRoot conf = [st|#{appRoot conf}/static|] -- | Settings for 'widgetFile', such as which template languages to support and -- default Hamlet settings. widgetFileSettings :: WidgetFileSettings widgetFileSettings = def { wfsHamletSettings = defaultHamletSettings { hamletNewlines = AlwaysNewlines } , wfsLanguages = \hset -> defaultTemplateLanguages hset ++ [TemplateLanguage True "coffee" coffeeFile coffeeFileReload] } -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = (if development then widgetFileReload else widgetFileNoReload) widgetFileSettings data Extra = Extra { extraCopyright :: Text , extraApproot :: Text , extraServeroot :: Text , extraAnalytics :: Maybe Text -- ^ Google Analytics , extraDirDyn :: FilePath -- , extraSections :: Map SectionId MediaConf , extraHaikuFile :: FilePath } deriving Show parseExtra :: DefaultEnv -> Object -> Parser Extra parseExtra _ o = Extra <$> o .: "copyright" <*> o .: "approot" <*> o .: "serveroot" <*> o .:? "analytics" <*> o .: "dyndir" <*> o .: "haikufile" -- <*> o .: "mediasections"
SimSaladin/rnfssp
Settings.hs
bsd-3-clause
3,067
0
16
582
376
231
145
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-| Redis DB snaplet. -} module Snap.Snaplet.RedisDB (RedisDB , runRedisDB , redisDBInit) where import Prelude hiding ((.)) import Control.Category ((.)) import Control.Monad.State import Data.Lens.Common import Data.Lens.Template import Database.Redis import Snap.Snaplet ------------------------------------------------------------------------------ -- | Snaplet's state data type data RedisDB = RedisDB { _connection :: Connection -- ^ DB connection pool. } makeLens ''RedisDB ------------------------------------------------------------------------------ -- | Perform action using Redis connection from RedisDB snaplet pool -- (wrapper for 'Database.Redis.runRedis'). -- -- > runRedisDB database $ do -- > set "hello" "world" runRedisDB :: (MonadIO m, MonadState app m) => Lens app (Snaplet RedisDB) -> Redis a -> m a runRedisDB snaplet action = do c <- gets $ getL (connection . snapletValue . snaplet) liftIO $ runRedis c action ------------------------------------------------------------------------------ -- | Make RedisDB snaplet and initialize database connection. -- -- > appInit :: SnapletInit MyApp MyApp -- > appInit = makeSnaplet "app" "App with Redis child snaplet" Nothing $ -- > do -- > d <- nestSnaplet "" database $ -- > redisDBInit defaultConnectInfo -- > return $ MyApp d redisDBInit :: ConnectInfo -- ^ Information for connnecting to a Redis server. -> SnapletInit b RedisDB redisDBInit connInfo = makeSnaplet "snaplet-redis" "Redis snaplet." Nothing $ do conn <- liftIO $ connect connInfo return $ RedisDB conn
lostbean/snaplet-neo4j
src/Snap/Snaplet/RedisDB.hs
bsd-3-clause
1,755
0
12
366
265
151
114
27
1
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 709 {-# LANGUAGE AutoDeriveTypeable #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Trans.Writer.Lazy -- Copyright : (c) Andy Gill 2001, -- (c) Oregon Graduate Institute of Science and Technology, 2001 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : ross@soi.city.ac.uk -- Stability : experimental -- Portability : portable -- -- The lazy 'WriterT' monad transformer, which adds collection of -- outputs (such as a count or string output) to a given monad. -- -- This monad transformer provides only limited access to the output -- during the computation. For more general access, use -- "Control.Monad.Trans.State" instead. -- -- This version builds its output lazily; for a strict version with -- the same interface, see "Control.Monad.Trans.Writer.Strict". ----------------------------------------------------------------------------- module Control.Monad.Trans.Writer.Lazy ( -- * The Writer monad Writer, writer, runWriter, execWriter, mapWriter, -- * The WriterT monad transformer WriterT(..), execWriterT, mapWriterT, -- * Writer operations tell, listen, listens, pass, censor, -- * Lifting other operations liftCallCC, liftCatch, ) where import Control.Monad.IO.Class import Control.Monad.Trans.Class import Data.Functor.Classes import Data.Functor.Identity import Control.Applicative import Control.Monad import Control.Monad.Fix import Control.Monad.Signatures import Data.Foldable (Foldable(foldMap)) import Data.Monoid import Data.Traversable (Traversable(traverse)) -- --------------------------------------------------------------------------- -- | A writer monad parameterized by the type @w@ of output to accumulate. -- -- The 'return' function produces the output 'mempty', while @>>=@ -- combines the outputs of the subcomputations using 'mappend'. type Writer w = WriterT w Identity -- | Construct a writer computation from a (result, output) pair. -- (The inverse of 'runWriter'.) writer :: (Monad m) => (a, w) -> WriterT w m a writer = WriterT . return -- | Unwrap a writer computation as a (result, output) pair. -- (The inverse of 'writer'.) runWriter :: Writer w a -> (a, w) runWriter = runIdentity . runWriterT -- | Extract the output from a writer computation. -- -- * @'execWriter' m = 'snd' ('runWriter' m)@ execWriter :: Writer w a -> w execWriter m = snd (runWriter m) -- | Map both the return value and output of a computation using -- the given function. -- -- * @'runWriter' ('mapWriter' f m) = f ('runWriter' m)@ mapWriter :: ((a, w) -> (b, w')) -> Writer w a -> Writer w' b mapWriter f = mapWriterT (Identity . f . runIdentity) -- --------------------------------------------------------------------------- -- | A writer monad parameterized by: -- -- * @w@ - the output to accumulate. -- -- * @m@ - The inner monad. -- -- The 'return' function produces the output 'mempty', while @>>=@ -- combines the outputs of the subcomputations using 'mappend'. newtype WriterT w m a = WriterT { runWriterT :: m (a, w) } instance (Eq w, Eq1 m, Eq a) => Eq (WriterT w m a) where WriterT x == WriterT y = eq1 x y instance (Ord w, Ord1 m, Ord a) => Ord (WriterT w m a) where compare (WriterT x) (WriterT y) = compare1 x y instance (Read w, Read1 m, Read a) => Read (WriterT w m a) where readsPrec = readsData $ readsUnary1 "WriterT" WriterT instance (Show w, Show1 m, Show a) => Show (WriterT w m a) where showsPrec d (WriterT m) = showsUnary1 "WriterT" d m instance (Eq w, Eq1 m) => Eq1 (WriterT w m) where eq1 = (==) instance (Ord w, Ord1 m) => Ord1 (WriterT w m) where compare1 = compare instance (Read w, Read1 m) => Read1 (WriterT w m) where readsPrec1 = readsPrec instance (Show w, Show1 m) => Show1 (WriterT w m) where showsPrec1 = showsPrec -- | Extract the output from a writer computation. -- -- * @'execWriterT' m = 'liftM' 'snd' ('runWriterT' m)@ execWriterT :: (Monad m) => WriterT w m a -> m w execWriterT m = do ~(_, w) <- runWriterT m return w -- | Map both the return value and output of a computation using -- the given function. -- -- * @'runWriterT' ('mapWriterT' f m) = f ('runWriterT' m)@ mapWriterT :: (m (a, w) -> n (b, w')) -> WriterT w m a -> WriterT w' n b mapWriterT f m = WriterT $ f (runWriterT m) instance (Functor m) => Functor (WriterT w m) where fmap f = mapWriterT $ fmap $ \ ~(a, w) -> (f a, w) instance (Foldable f) => Foldable (WriterT w f) where foldMap f = foldMap (f . fst) . runWriterT instance (Traversable f) => Traversable (WriterT w f) where traverse f = fmap WriterT . traverse f' . runWriterT where f' (a, b) = fmap (\ c -> (c, b)) (f a) instance (Monoid w, Applicative m) => Applicative (WriterT w m) where pure a = WriterT $ pure (a, mempty) f <*> v = WriterT $ liftA2 k (runWriterT f) (runWriterT v) where k ~(a, w) ~(b, w') = (a b, w `mappend` w') instance (Monoid w, Alternative m) => Alternative (WriterT w m) where empty = WriterT empty m <|> n = WriterT $ runWriterT m <|> runWriterT n instance (Monoid w, Monad m) => Monad (WriterT w m) where return a = writer (a, mempty) m >>= k = WriterT $ do ~(a, w) <- runWriterT m ~(b, w') <- runWriterT (k a) return (b, w `mappend` w') fail msg = WriterT $ fail msg instance (Monoid w, MonadPlus m) => MonadPlus (WriterT w m) where mzero = WriterT mzero m `mplus` n = WriterT $ runWriterT m `mplus` runWriterT n instance (Monoid w, MonadFix m) => MonadFix (WriterT w m) where mfix m = WriterT $ mfix $ \ ~(a, _) -> runWriterT (m a) instance (Monoid w) => MonadTrans (WriterT w) where lift m = WriterT $ do a <- m return (a, mempty) instance (Monoid w, MonadIO m) => MonadIO (WriterT w m) where liftIO = lift . liftIO -- | @'tell' w@ is an action that produces the output @w@. tell :: (Monoid w, Monad m) => w -> WriterT w m () tell w = writer ((), w) -- | @'listen' m@ is an action that executes the action @m@ and adds its -- output to the value of the computation. -- -- * @'runWriterT' ('listen' m) = 'liftM' (\\ (a, w) -> ((a, w), w)) ('runWriterT' m)@ listen :: (Monoid w, Monad m) => WriterT w m a -> WriterT w m (a, w) listen m = WriterT $ do ~(a, w) <- runWriterT m return ((a, w), w) -- | @'listens' f m@ is an action that executes the action @m@ and adds -- the result of applying @f@ to the output to the value of the computation. -- -- * @'listens' f m = 'liftM' (id *** f) ('listen' m)@ -- -- * @'runWriterT' ('listens' f m) = 'liftM' (\\ (a, w) -> ((a, f w), w)) ('runWriterT' m)@ listens :: (Monoid w, Monad m) => (w -> b) -> WriterT w m a -> WriterT w m (a, b) listens f m = WriterT $ do ~(a, w) <- runWriterT m return ((a, f w), w) -- | @'pass' m@ is an action that executes the action @m@, which returns -- a value and a function, and returns the value, applying the function -- to the output. -- -- * @'runWriterT' ('pass' m) = 'liftM' (\\ ((a, f), w) -> (a, f w)) ('runWriterT' m)@ pass :: (Monoid w, Monad m) => WriterT w m (a, w -> w) -> WriterT w m a pass m = WriterT $ do ~((a, f), w) <- runWriterT m return (a, f w) -- | @'censor' f m@ is an action that executes the action @m@ and -- applies the function @f@ to its output, leaving the return value -- unchanged. -- -- * @'censor' f m = 'pass' ('liftM' (\\ x -> (x,f)) m)@ -- -- * @'runWriterT' ('censor' f m) = 'liftM' (\\ (a, w) -> (a, f w)) ('runWriterT' m)@ censor :: (Monoid w, Monad m) => (w -> w) -> WriterT w m a -> WriterT w m a censor f m = WriterT $ do ~(a, w) <- runWriterT m return (a, f w) -- | Lift a @callCC@ operation to the new monad. liftCallCC :: (Monoid w) => CallCC m (a,w) (b,w) -> CallCC (WriterT w m) a b liftCallCC callCC f = WriterT $ callCC $ \ c -> runWriterT (f (\ a -> WriterT $ c (a, mempty))) -- | Lift a @catchE@ operation to the new monad. liftCatch :: Catch e m (a,w) -> Catch e (WriterT w m) a liftCatch catchE m h = WriterT $ runWriterT m `catchE` \ e -> runWriterT (h e)
DavidAlphaFox/ghc
libraries/transformers/Control/Monad/Trans/Writer/Lazy.hs
bsd-3-clause
8,182
0
14
1,770
2,329
1,263
1,066
113
1
{-# LANGUAGE DeriveFunctor #-} module Language.CFG(parse, CFG(CFG), Parse(Lit, Prod)) where import Data.Function import Data.Map as M (Map, findWithDefault, fromList, alter, lookup, empty, insert) import Data.Maybe import Debug.Trace import Data.Foldable import Prelude hiding (foldl,foldr, concatMap) -- | A context free grammar in Chomsky normal form. Contains the list of literal -- mappings, a list of all the productions and the dedicated 'stop' symbol. data CFG a b = CFG [(a,b)] [(a, (a, a))] a deriving (Show, Eq) -- | A possible parse of a string data Parse a b = -- | A literal node that includes the original symbol and position in the input. Lit Int b a -- | A production | Prod a (Parse a b) (Parse a b) deriving (Show, Eq, Functor) sym :: Parse a b -> a sym (Lit _ b val) = val sym (Prod val _ _) = val type Board a b = Map (Int, Int) [Parse a b] cell :: (Int, Int) -> Board a b -> [Parse a b] cell = findWithDefault [] makeEdge :: (Foldable f, Eq b) => [(a, b)] -> f b -> (Int, Board a b) makeEdge rules = foldl go (0,empty) where go (i, accum) x= (i+1, (insert (i,0) (matchLiteral rules (i,x)) accum)) -- | Given a context free grammer and a string returns all the valid parses using -- the CYK algorithm. parse :: (Eq a, Eq b, Foldable f) => CFG a b -> f b -> [Parse a b] parse cfg@(CFG _ _ s) input = filter isTerminated . cell (0,n-1) $ board where (n, board) = buildBoard cfg input isTerminated = (==s) . sym buildBoard :: (Eq a, Eq b, Foldable f) => CFG a b -> f b -> (Int, Board a b) buildBoard (CFG lit comp stop) input = (n, foldl (updateCell comp) edge [(i,j,k) | i <- [1 .. n-1], j <- [0 .. n-i], k <- [0 .. i-1]]) where (n, edge) = makeEdge lit input updateCell :: (Eq a) => [(a, (a, a))] -> Board a b -> (Int, Int, Int) -> Board a b updateCell rules board (i,j,k) = alter go (j, i) board where go (Just old) = Just $ old ++ productCell rules left right go Nothing = Just $ productCell rules left right left = cell (j,k) board right = cell (j+k+1, i-k-1) board matchLiteral :: Eq b => [(a, b)] -> (Int, b) -> [Parse a b] matchLiteral rules (i,lit) = map (Lit i lit . fst) . filter ((==lit) . snd) $ rules productCell :: Eq a => [(a, (a, a))] -> [Parse a b] -> [Parse a b] -> [Parse a b] productCell rules left right = concatMap (match rules) [(l,r)| l <- left, r <- right] match :: Eq a => [(a, (a, a))] -> (Parse a b, Parse a b) -> [Parse a b] match rules (p1, p2) = catMaybes $ map f rules where f (v, (l, r)) | sym p1 == l && sym p2 == r = Just $ Prod v p1 p2 | otherwise = Nothing
andreyLevushkin/CFG
Language/CFG.hs
bsd-3-clause
2,846
0
13
847
1,307
717
590
51
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecordWildCards #-} module Heisenberg ( -- * Setup newExperiment , runExperiment -- * Reporters , nullReporter , sequenceReporters , parallelReporters -- * Types , ExperimentName(..) , experimentName , Experiment , eName , _eName , eReporter , _eReporter , Outcome , _oControlObservation , _oCandidateObservation , oControlObservation , oCandidateObservation , Observation(..) , _FailedObservation , _Observation , SuccessfulObservation , _oResult , _oDuration , oResult , oDuration , NanoSeconds(..) , nanoSeconds ) where ------------------------------------------------------------------------------- import Control.Concurrent import Control.Concurrent.Async import Control.Exception import Control.Exception.Enclosed import Control.Monad import Control.Monad.Trans.Control import System.Clock import System.Random.MWC ------------------------------------------------------------------------------- import Heisenberg.Internal.Types ------------------------------------------------------------------------------- newExperiment :: ExperimentName -> ExperimentReporter m a -> IO (Experiment m a) newExperiment n reporter = do rng <- createSystemRandom return (Experiment n rng reporter) ------------------------------------------------------------------------------- -- TODO: list of named candidates? runExperiment :: ( MonadBaseControl IO m ) => Experiment m a -> m a -- ^ Control -> m a -- ^ Candidate -> m a runExperiment Experiment {..} ctrl cand = do controlFirst <- liftIO' (uniform _eRNG) if controlFirst then do ctrlRes <- runAction ctrl candRes <- runAction cand _ <- report ctrlRes candRes result ctrlRes else do candRes <- runAction cand ctrlRes <- runAction ctrl _ <- report ctrlRes candRes result ctrlRes where result (FailedObservation e) = liftIO' (throw e) result (Observation (SuccessfulObservation { _oResult = r})) = return r report ctrlRes candRes = liftBaseWith $ \runInIO -> forkIO (void (runInIO (_eReporter (Outcome ctrlRes candRes)))) ------------------------------------------------------------------------------- runAction :: ( MonadBaseControl IO m ) => m a -> m (Observation a) runAction f = do res <- tryAny go return $ case res of Left e -> FailedObservation e Right so -> Observation so where go = do t1 <- liftIO' getTime' res <- f t2 <- liftIO' getTime' let tDelta = NanoSeconds (timeSpecAsNanoSecs (diffTimeSpec t2 t1)) return (SuccessfulObservation res tDelta) getTime' = getTime Monotonic ------------------------------------------------------------------------------- -- | I don't actually know if this is right liftIO' :: MonadBaseControl IO m => IO a -> m a liftIO' f = liftBaseWith (const f) ------------------------------------------------------------------------------- nullReporter :: Monad m => ExperimentReporter m a nullReporter = const (return ()) ------------------------------------------------------------------------------- -- | Combine 2 experiment reporters to run in sequence. Eats synchronous exceptions for each reporter sequenceReporters :: (MonadBaseControl IO m) => ExperimentReporter m a -> ExperimentReporter m a -> ExperimentReporter m a sequenceReporters a b o = eatExceptions (a o) >> eatExceptions (b o) ------------------------------------------------------------------------------- parallelReporters :: (MonadBaseControl IO m) => ExperimentReporter m a -> ExperimentReporter m a -> ExperimentReporter m a parallelReporters a b o = restoreM =<< liftBaseWith (\runInIO -> let doConc = Concurrently . runInIO . eatExceptions in runConcurrently (doConc (a o) *> doConc (b o))) ------------------------------------------------------------------------------- eatExceptions :: (MonadBaseControl IO m) => m () -> m () eatExceptions = void . tryAny
MichaelXavier/heisenberg
src/Heisenberg.hs
bsd-3-clause
4,385
0
17
1,049
964
494
470
101
3
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} module Types where import Graphics.GL.Pal import Graphics.GL.Freetype import Control.Lens import Data.Map.Strict (Map) roomHeight :: GLfloat roomHeight = 10 roomWidth :: GLfloat roomWidth = 10 roomDepth :: GLfloat roomDepth = 10 sculptureSize :: GLfloat sculptureSize = 0.7 sculptureHeight :: GLfloat sculptureHeight = 1.0 pedestalHeight :: GLfloat pedestalHeight = sculptureHeight - (sculptureSize / 2) startHeight :: GLfloat startHeight = 1.5 -- Offset of pedestal beneath sculpture pedestalOffset :: V3 GLfloat pedestalOffset = V3 0 ((pedestalHeight/2) - 0.001) 0 -- Position of sculpture ( relative ) sculptureOffset :: V3 GLfloat sculptureOffset = V3 0 sculptureHeight 0 -- Offset of frame behind painting roomOffset :: V3 GLfloat roomOffset = V3 0 (roomHeight/2) 0 {- Uniforms: A Big list of uniforms we use across our programs -} data Uniforms = Uniforms { uModelViewProjection :: UniformLocation (M44 GLfloat) , uViewProjection :: UniformLocation (M44 GLfloat) , uNormalMatrix :: UniformLocation (M44 GLfloat) , uInverseModel :: UniformLocation (M44 GLfloat) , uModel :: UniformLocation (M44 GLfloat) , uEye :: UniformLocation (V3 GLfloat) , uHand1 :: UniformLocation (V3 GLfloat) , uHand2 :: UniformLocation (V3 GLfloat) , uLight :: UniformLocation (V3 GLfloat) , uTime :: UniformLocation GLfloat , uDimensions :: UniformLocation (V3 GLfloat) , uPoints :: UniformLocation [V3 GLfloat] } deriving (Data) {- Shapes: Keeping all the different shapes in a single structure, so we can pass them to the render function as a package, instead of one by one -} data Shapes u = Shapes { _shpPedestal :: Shape u , _shpRoom :: Shape u , _shpLight :: Shape u , _shpCodeHolder :: Shape u } makeLenses ''Shapes {- Sculpture: A sculpture is a 3D Cube in the middle of the room. Should have a 'pedestal' , a 'title' , a 'description' ( all coming later ) -} data Sculpture = Sculpture { _scpPose :: !(Pose GLfloat) , _scpGetShape :: !(IO (Shape Uniforms, String)) , _scpTextRenderer :: !TextRenderer , _scpScroll :: !GLfloat } makeLenses ''Sculpture {- Room: The thing that is rendered around the entire scene. Seperated into own data structure, because eventually we will want to use the APIs provided by Vive to dynamically scale room based on playable area -} data Room = Room { _romPose :: !(Pose GLfloat) } makeLenses ''Room {- World: This is where we keep the majority of our data. If we pass the same world into our render function, We should get the same visual result *every* time! -} type SculptureID = Int data World = World { _wldSculptures :: !(Map SculptureID Sculpture) , _wldPlayer :: !(Pose GLfloat) , _wldRoom :: !Room , _wldTime :: !Float , _wldLight :: !(Pose GLfloat) , _wldObjects :: ![(Pose GLfloat)] , _wldFocusedSculptureID :: !SculptureID } makeLenses ''World
vrtree/pedestal
app/Types.hs
bsd-3-clause
3,319
0
13
860
647
359
288
92
1
{-# LANGUAGE DeriveDataTypeable #-} module Main where import Browse import CabalDev (modifyOptions) import Check import Control.Applicative import Control.Exception import Data.Typeable import Data.Version import Info import Lang import Flag import Lint import List import Paths_ghc_mod import Prelude import System.Console.GetOpt import System.Directory import System.Environment (getArgs) import System.IO (hPutStr, hPutStrLn, stderr) import Types ---------------------------------------------------------------- ghcOptHelp :: String ghcOptHelp = " [-g GHC_opt1 -g GHC_opt2 ...] " usage :: String usage = "ghc-mod version " ++ showVersion version ++ "\n" ++ "Usage:\n" ++ "\t ghc-mod list" ++ ghcOptHelp ++ "[-l]\n" ++ "\t ghc-mod lang [-l]\n" ++ "\t ghc-mod flag [-l]\n" ++ "\t ghc-mod browse" ++ ghcOptHelp ++ "[-l] [-o] <module> [<module> ...]\n" ++ "\t ghc-mod check" ++ ghcOptHelp ++ "<HaskellFile>\n" ++ "\t ghc-mod info" ++ ghcOptHelp ++ "<HaskellFile> <module> <expression>\n" ++ "\t ghc-mod type" ++ ghcOptHelp ++ "<HaskellFile> <module> <line-no> <column-no>\n" ++ "\t ghc-mod lint [-h opt] <HaskellFile>\n" ++ "\t ghc-mod boot\n" ++ "\t ghc-mod help\n" ---------------------------------------------------------------- defaultOptions :: Options defaultOptions = Options { outputStyle = PlainStyle , hlintOpts = [] , ghcOpts = [] , operators = False } argspec :: [OptDescr (Options -> Options)] argspec = [ Option "l" ["tolisp"] (NoArg (\opts -> opts { outputStyle = LispStyle })) "print as a list of Lisp" , Option "h" ["hlintOpt"] (ReqArg (\h opts -> opts { hlintOpts = h : hlintOpts opts }) "hlintOpt") "hlint options" , Option "g" ["ghcOpt"] (ReqArg (\g opts -> opts { ghcOpts = g : ghcOpts opts }) "ghcOpt") "GHC options" , Option "o" ["operators"] (NoArg (\opts -> opts { operators = True })) "print operators, too" ] parseArgs :: [OptDescr (Options -> Options)] -> [String] -> (Options, [String]) parseArgs spec argv = case getOpt Permute spec argv of (o,n,[] ) -> (foldl (flip id) defaultOptions o, n) (_,_,errs) -> throw (CmdArg errs) ---------------------------------------------------------------- data GHCModError = SafeList | NoSuchCommand String | CmdArg [String] | FileNotExist String deriving (Show, Typeable) instance Exception GHCModError ---------------------------------------------------------------- main :: IO () main = flip catches handlers $ do args <- getArgs let (opt',cmdArg) = parseArgs argspec args res <- modifyOptions opt' >>= \opt -> case safelist cmdArg 0 of "browse" -> concat <$> mapM (browseModule opt) (tail cmdArg) "list" -> listModules opt "check" -> withFile (checkSyntax opt) (safelist cmdArg 1) "type" -> withFile (typeExpr opt (safelist cmdArg 2) (read $ safelist cmdArg 3) (read $ safelist cmdArg 4)) (safelist cmdArg 1) "info" -> withFile (infoExpr opt (safelist cmdArg 2) (safelist cmdArg 3)) (safelist cmdArg 1) "lint" -> withFile (lintSyntax opt) (safelist cmdArg 1) "lang" -> listLanguages opt "flag" -> listFlags opt "boot" -> do mods <- listModules opt langs <- listLanguages opt flags <- listFlags opt pre <- concat <$> mapM (browseModule opt) preBrowsedModules return $ mods ++ langs ++ flags ++ pre cmd -> throw (NoSuchCommand cmd) putStr res where handlers = [Handler handler1, Handler handler2] handler1 :: ErrorCall -> IO () handler1 = print -- for debug handler2 :: GHCModError -> IO () handler2 SafeList = printUsage handler2 (NoSuchCommand cmd) = do hPutStrLn stderr $ "\"" ++ cmd ++ "\" not supported" printUsage handler2 (CmdArg errs) = do mapM_ (hPutStr stderr) errs printUsage handler2 (FileNotExist file) = do hPutStrLn stderr $ "\"" ++ file ++ "\" not found" printUsage printUsage = hPutStrLn stderr $ '\n' : usageInfo usage argspec withFile cmd file = do exist <- doesFileExist file if exist then cmd file else throw (FileNotExist file) safelist xs idx | length xs <= idx = throw SafeList | otherwise = xs !! idx ---------------------------------------------------------------- preBrowsedModules :: [String] preBrowsedModules = [ "Prelude" , "Control.Applicative" , "Control.Monad" , "Control.Exception" , "Data.Char" , "Data.List" , "Data.Maybe" , "System.IO" ]
himura/ghc-mod
GHCMod.hs
bsd-3-clause
4,779
0
28
1,235
1,307
681
626
119
14
module DB where import Database.PostgreSQL.Simple cardDBInfo :: ConnectInfo cardDBInfo = defaultConnectInfo { connectUser = "flashbuild" , connectPassword = "justtouchitalready" , connectDatabase = "flashbuild" }
ppseafield/backend-flashcard
src/DB.hs
bsd-3-clause
280
0
6
91
40
26
14
7
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} {- | Module : Data.Random.Show.Unsafe Copyright : 2010 Aristid Breitkreuz License : BSD3 Stability : experimental Portability : portable Unsafely 'show' a 'RVar' by taking a random sample. Uses 'unsafePerformIO'. Contains an instance of 'Show' for 'RVar'. -} module Data.Random.Show.Unsafe () where import Data.Random.RVar import Data.Random.Source.DevRandom import System.IO.Unsafe instance (Show a) => Show (RVar a) where show rv = show . unsafePerformIO $ runRVar rv DevURandom
aristidb/random-extras
Data/Random/Show/Unsafe.hs
bsd-3-clause
565
0
7
98
76
45
31
8
0
{-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} module Main where import Data.Default.Class import UULayout import Data.Char import Data.List import System.Environment import Text.Read import Data.Maybe import Data.List.Split import Test.Hspec import Language.Haskell.TH.Ppr (Ppr(ppr)) import Language.Haskell.TH.PprLib (Doc) import Language.Haskell.TH.Syntax (Type(..), Dec(..), Exp(..), Pat(..), Name(..), OccName(..), NameFlavour(..), ModName(..), NameSpace(..), PkgName(..), TyVarBndr(..), Cxt(..), Pred(..), Kind, TyLit(..), Con(..), StrictType(..), Strict(..), FieldExp(..), Match(..), Lit(..), Guard(..), Stmt(..), Range(..), Body(..), Clause(..), FieldPat(..), ) defHP = def :: HParser runP :: Show t => (HParser -> HP t) -> String -> String runP p str = case runParser "p" (fixP (\d -> amb . p d) defHP) str of [e] -> show e es -> error $ "str:" ++ str ++ " parses as " ++ show (map show es) runPp :: Ppr t => (HParser -> HP t) -> String -> String runPp p str = case runParser "p" (fixP (\d -> amb . p d) defHP) str of [e] -> show (ppr e) es -> error $ "str:" ++ str ++ " parses as " ++ show (map ppr es) runPpAmb :: Ppr t => (HParser -> HP t) -> String -> Doc runPpAmb p str = ppr $ runParser "p" (fixP (\d -> amb . p d) defHP) str runPAmb :: Show t => (HParser -> HP t) -> String -> String runPAmb p str = show $ runParser "p" (fixP (\d -> amb . p d) defHP) str main = hspec $ do let sid f str = f str `shouldBe` str it "AppT" $ do runP pType "Ab B" `shouldBe` "AppT (ConT Ab) (ConT B)" runP pType "A B C" `shouldBe` "AppT (AppT (ConT A) (ConT B)) (ConT C)" runP pType "A B C D" `shouldBe` "AppT (AppT (AppT (ConT A) (ConT B)) (ConT C)) (ConT D)" it "AppE" $ do runP pExp "A B" `shouldBe` "AppE (ConE A) (ConE B)" runP pExp "A B C" `shouldBe` "AppE (AppE (ConE A) (ConE B)) (ConE C)" it "UInfix" $ do runP pExp "A + B + C D" `shouldBe` "UInfixE (UInfixE (ConE A) (VarE +) (ConE B)) (VarE +) (AppE (ConE C) (ConE D))" runPp pExp `sid` "A `b` C" runPp pExp "A b`b`C" `shouldBe` "A b `b` C" it "PromotedT" $ do runPp pExp `sid` "Proxy :: Proxy 'True" runPp pExp `sid` "Proxy :: Proxy ('True :: Bool)" runPp pExp "Proxy :: Proxy '(Int,String)" `shouldBe` "Proxy :: Proxy ('(Int, String))" runPp pExp "undefined :: HList [Int,String,Double]" `shouldBe` "undefined :: HList ((':) Int ((':) String ((':) Double '[])))" runPp pExp "x :: '[Int]" `shouldBe` "x :: (':) Int '[]" runP pExp "Proxy :: Proxy '(x,y)" `shouldBe` "SigE (ConE Proxy) (AppT (ConT Proxy) (AppT (AppT (PromotedTupleT 2) (VarT x)) (VarT y)))" it "ConT Infix" $ do runP pType "A :+: B" `shouldBe` "AppT (AppT (ConT :+:) (ConT A)) (ConT B)" it "ForallT" $ do runP pType "Show a => a" `shouldBe` "ForallT [] [ClassP Show [VarT a]] (VarT a)" runP pType "(a ~ b) => a" `shouldBe` "ForallT [] [EqualP (VarT a) (VarT b)] (VarT a)" runP pType "(Show a) => a" `shouldBe` "ForallT [] [ClassP Show [VarT a]] (VarT a)" runP pType "forall a. (Show a) => a" `shouldBe` "ForallT [PlainTV a] [ClassP Show [VarT a]] (VarT a)" it "SigT" $ do -- ghc bug #10050 runP pExp "x :: (x :: Constraint)" `shouldBe` "SigE (VarE x) (SigT (VarT x) ConstraintT)" runP pExp "x :: (x :: Constrainty)" `shouldBe` "SigE (VarE x) (SigT (VarT x) (ConT Constrainty))" runP pExp "x :: (x :: *)" `shouldBe` "SigE (VarE x) (SigT (VarT x) StarT)" runP pExp "x :: (x ::* )" `shouldBe` "SigE (VarE x) (SigT (VarT x) StarT)" it "TupleT" $ do runPp pExp `sid` "(a, b) :: (Int, String)" runPp pExp `sid` "(# a, b #) :: (# , #) Int String" runP pExp "(#a,b#)" `shouldBe` "UnboxedTupE [VarE a,VarE b]" it "CompE" $ do runP pExp "[ x | x <- xs ]" `shouldBe` "CompE [BindS (VarP x) (VarE xs),NoBindS (VarE x)]" it "LitT" $ do runPp pType `sid` show "1" runPp pExp `sid` "A :: 3" it "sections" $ do runPp pExp "(`f` x) y" `shouldBe` "((`f` x)) y" runPp pExp "(x `f`) y" `shouldBe` "((x `f`)) y" runPp pExp "(x `f` y) y" `shouldBe` "(x `f` y) y" it "ArithSeqE" $ do runPp pExp `sid` "[a..m] :: [Int]" runPp pExp "[a..] :: [] Int" `shouldBe` "[a..] :: [Int]" runPp pExp `sid` "[b,a..n]" runPp pExp `sid` "[c,c..]" runPp pExp `sid` "[A.c,A.B.c..]" it "LitE" $ do runPp pExp `sid` show "any random string" runPp pExp "12.3" `shouldBe` "3462142213541069 / 281474976710656" runPp pExp `sid` "12" it "qual" $ do runPp pExp `sid` "A.x b" runPp pExp `sid` "A.x . y b" runPp pExp "A.x.y b" `shouldBe` "A.x . y b" it "IfE" $ do runPp pExp `sid` "if a then b else c" it "MultiIfE" $ do runPp pExp "if | a -> b | c -> d" `shouldBe` "if | a -> b\n | c -> d" runPp pExp "if | f a -> b | c -> d" `shouldBe` "if | f a -> b\n | c -> d" runPp pExp "if | Just 1 <- f, f a -> b | c -> d" `shouldBe` "if | Just 1 <- f,\n f a\n -> b\n | c -> d" it "LamE" $ do runPp pExp `sid` "\\x (Just y) -> y" it "RecConE" $ do runP pExp "C { z = z g}" `shouldBe` "RecConE C [(z,AppE (VarE z) (VarE g))]" runP pExp "c { z = z g}" `shouldBe` "RecUpdE (VarE c) [(z,AppE (VarE z) (VarE g))]" runP pExp "f c { z = z g}" `shouldBe` "AppE (VarE f) (RecUpdE (VarE c) [(z,AppE (VarE z) (VarE g))])" runP pExp "C { z = z g }" `shouldBe` "RecConE C [(z,AppE (VarE z) (VarE g))]" it "SigE" $ do runP pSigE "A::B" `shouldBe` "SigE (ConE A) (ConT B)" it "ParensE / TupE" $ do runPp pExp `sid` "a (b c)" runPp pExp `sid` "a (b, c)" it "Type" $ do runPp pType `sid` "A -> B -> C" runPp pType `sid` "A a x y -> B -> C" runPp pType "a ': b" `shouldBe` "(':) a b" runPp pType "a ': b ': c" `shouldBe` "(':) a ((':) b c)" runPp pType "a ': b ': c ': '[]" `shouldBe` "(':) a ((':) b ((':) c '[]))" runPp pType `sid` "(A -> B) -> C" runPp pType `sid` "'(,,) -> C" it "ValD" $ do runPp pDec "Just x = b where b = c" `shouldBe` "Just x = b\n where b = c" runPp pDec `sid` "(a, b, Just c) = a" runP pDec "a@(a, b, Just c) = a" `shouldBe` "ValD (AsP a (TupP [VarP a,VarP b,ConP Just [VarP c]])) (NormalB (VarE a)) []" runP pDec "a@(!a, ~b, Just c) = a" `shouldBe` "ValD (AsP a (TupP [BangP (VarP a),TildeP (VarP b),ConP Just [VarP c]])) (NormalB (VarE a)) []" runP pDec "[a,b,c] = a" `shouldBe` "ValD (ListP [VarP a,VarP b,VarP c]) (NormalB (VarE a)) []" it "RecP/ViewP" $ do runP pPat "R { a = (f -> Just 3) }" `shouldBe` "RecP R [(a,ViewP (VarE f) (ConP Just [LitP (IntegerL 3)]))]" it "UInfixP" $ do runP pPat "f `HCons` x" `shouldBe` "UInfixP (VarP f) HCons (VarP x)" it "FunD" $ do runP pDec "f (Just 1) = 4 where _ = 2" `shouldBe` "FunD f [Clause [ParensP (ConP Just [LitP (IntegerL 1)])] (NormalB (LitE (IntegerL 4))) [ValD WildP (NormalB (LitE (IntegerL 2))) []]]" it "LetE" $ do runP pExp "let x = 1 in y" `shouldBe` "LetE [ValD (VarP x) (NormalB (LitE (IntegerL 1))) []] (VarE y)" let xyz = "LetE [ValD (VarP x) (NormalB (LitE (IntegerL 1))) [],ValD (VarP y) (NormalB (LitE (IntegerL 2))) []] (VarE z)" runP pExp "let { x = 1; y = 2 } in z" `shouldBe` xyz runP pExp "let x = 1; y = 2 in z" `shouldBe` xyz runP pExp "let x = let y = 1 in y in x" `shouldBe` "LetE [ValD (VarP x) (NormalB (LetE [ValD (VarP y) (NormalB (LitE (IntegerL 1))) []] (VarE y))) []] (VarE x)" it "CaseE" $ do runP pExp "case x of A -> B" `shouldBe` "CaseE (VarE x) [Match (ConP A []) (NormalB (ConE B)) []]" runP pExp "case x of A -> B; C -> D" `shouldBe` "CaseE (VarE x) [Match (ConP A []) (NormalB (ConE B)) []\ \,Match (ConP C []) (NormalB (ConE D)) []]" runP pExp "case x of a -> B; C -> D" `shouldBe` "CaseE (VarE x) [Match (VarP a) (NormalB (ConE B)) []\ \,Match (ConP C []) (NormalB (ConE D)) []]" runP pExp "case x of a | x <- b -> c" `shouldBe` "CaseE (VarE x) [Match (VarP a) (GuardedB [(PatG [BindS (VarP x) (VarE b)],VarE c)]) []]" runP pExp "case x of (f -> a) | x <- b -> c" `shouldBe` "CaseE (VarE x) [Match (ViewP (VarE f) (VarP a))\ \ (GuardedB [(PatG [BindS (VarP x) (VarE b)],VarE c)]) []]" it "infix decs" $ runP pDecs "x `f` y = (x,y)" `shouldBe` "[FunD f [Clause [VarP x,VarP y] (NormalB (TupE [VarE x,VarE y])) []]]" it "SigD" $ do runP pDecs "x :: Int -> Int" `shouldBe` "[SigD x (AppT (AppT ArrowT (ConT Int)) (ConT Int))]" runP pDecs "(+) :: Int -> Int" `shouldBe` "[SigD + (AppT (AppT ArrowT (ConT Int)) (ConT Int))]" it "DataD" $ do runPp pDecs `sid` "data X = X | Y | Z W" runPp pDecs `sid` "data X a = X a | Y | Z W" runP pDecs "data X a = X { a :: a }" `shouldBe` "[DataD [] X [PlainTV a] [RecC X [(a,NotStrict,VarT a)]] []]" runP pDecs "data X a = X { a, y :: a B, c :: TT T }" `shouldBe` "[DataD [] X [PlainTV a] [RecC X [(a,NotStrict,AppT (VarT a) (ConT B)),(y,NotStrict,AppT (VarT a) (ConT B)),(c,NotStrict,AppT (ConT TT) (ConT T))]] []]" runP pDecs "data X a = X deriving Foo" `shouldBe` "[DataD [] X [PlainTV a] [NormalC X []] [Foo]]" runP pDecs "data C a => X a = X deriving Foo" `shouldBe` "[DataD [ClassP C [VarT a]] X [PlainTV a] [NormalC X []] [Foo]]" runP pDecs "data X a = Y | forall f. (C f) => X a" `shouldBe` "[DataD [] X [PlainTV a] [NormalC Y [],ForallC [PlainTV f] [ClassP C [VarT f]] (NormalC X [(NotStrict,VarT a)])] []]" runP pDecs "data X a = forall f. (C f) => X | Y deriving Enum" `shouldBe` "[DataD [] X [PlainTV a] [ForallC [PlainTV f] [ClassP C [VarT f]] (NormalC X []),NormalC Y []] [Enum]]" runP pDecs "f x = x\nf x = x" `shouldBe` "[FunD f [Clause [VarP x] (NormalB (VarE x)) [],Clause [VarP x] (NormalB (VarE x)) []]]" it "InfixC" $ do runP pConstructor "A := Int" `shouldBe` "InfixC (NotStrict,ConT A) := (NotStrict,ConT Int)" it "pType" $ do runP pType "(:=)" `shouldBe` "ConT :=" failing = hspec $ do let sid f str = f str `shouldBe` str it "layout" $ runP pExp "1\n + 2" `shouldBe` "UInfixE (LitE (IntegerL 1)) (VarE +) (LitE (IntegerL 2))" it "DataD" $ do runPp pDecs `sid` "data a ::: b = X a" runPp pDecs `sid` "data a ::: b = a :+: b" runPp pDecs `sid` "newtype X = X { a = T }" runPp pDecs `sid` "data X a = forall f. (C f) => X a | Y" let xyz = "LetE [ValD (VarP x) (NormalB (LitE (IntegerL 1))) [],ValD (VarP y) (NormalB (LitE (IntegerL 2))) []] (VarE z)" it "letE" $ do runP pExp "let x = 1\n\ \ y = 2\n\ \ in z" `shouldBe` xyz type HP t = S -> P (Str Char String LineColPos) t newtype S = S (forall r. (HParser -> S -> r) -> r) data HParser = HParser {pType :: HP Type ,pDecs :: HP [Dec] ,pExp :: HP Exp ,pPat :: HP Pat ,pPat' :: HP Pat ,pSigP, pUInfixP ,pLitP, pVarP, pParensP, pUnboxedTupP, pConP, pAsP, pTildeP, pBangP, pWildP, pListP, pRecP, pViewP :: HP Pat ,pDec -- all the constructors for Dec ,pFunD ,pValD ,pFunDInfix -- ^ p1 `f` p2 = ... ,pDataD ,pNewtypeD ,pTySynD ,pClassD ,pInstanceD ,pSigD ,pForeignD ,pInfixD ,pPragmaD ,pFamilyD ,pDataInstD ,pNewtypeInstD ,pTySynInstD ,pClosedTypeFamilyD ,pRoleAnnotD :: HP Dec ,pConstructor :: HP Con ,pBody :: HP Body ,pWhere :: HP [Dec] ,pType' :: HP Type -- ^ a subset of Type that must consume -- input to produce a constructor (no leading spaces) ,pExp' :: HP Exp -- ^ a subset of Exp that must consume -- input to produce a constructor (no leading spaces) ,pVarE -- ^ @{ x }@ ,pConE -- ^ @data T1 = C1 t1 t2; p = {C1} e1 e2 @ ,pLitE -- ^ @{ 5 or 'c'}@ ,pSpaceSep {- ^ AppE @{ f x }@ RecConE @{ T { x = y, z = w } }@ RecUpdE @{ (f x) { z = w } }@ UInfixE @{x + y}@ using classifySpaceSep -} ,pInfixE -- ^ @{x + y} or {(x+)} or {(+ x)} or {(+)}@ ,pLamE -- ^ @{ \ p1 p2 -> e }@ ,pLamCaseE -- ^ @{ \case m1; m2 }@ ,pTupE -- ^ @{ (e1,e2) } @ -- or ParensE @{ (e) }@ ,pUnboxedTupE -- @{ (# e1,e2 #) } @ ,pCondE -- ^ @{ if e1 then e2 else e3 }@ ,pMultiIfE -- ^ @{ if | g1 -> e1 | g2 -> e2 }@ ,pLetE -- ^ @{ let x=e1; y=e2 in e3 }@ ,pCaseE -- ^ @{ case e of m1; m2 }@ ,pDoE -- ^ @{ do { p <- e1; e2 } }@ ,pCompE -- ^ @{ [ (x,y) | x <- xs, y <- ys ] }@ ,pArithSeqE -- ^ @{ [ 1 ,2 .. 10 ] }@ ,pListE -- ^ @{ [1,2,3] }@ ,pSigE -- ^ @{ e :: t }@ :: HP Exp -- helpers for Exp ,pMatch :: HP Match ,pGuard :: HP Guard ,pStmt :: HP Stmt ,pFieldExps :: HP [FieldExp] ,pForallT -- ^ @forall \<vars\>. \<ctxt\> -> \<type\>@ ,pSpaceSepT ,pSigT -- ^ @t :: k@ ,pVarT -- ^ @a@ ,pConAlphaT -- ^ @T@ or @Constraint@ ,pConSymT ,pPromotedT -- ^ @'T@ ,pTupleT -- ^ @(,), (,,), etc.@ or @(#,#), (#,,#), etc.@ ,pArrowT -- ^ @->@ ,pListT -- ^ @[]@ ,pPromotedTupleT -- ^ @'(), '(,), '(,,), etc.@ ,pStarT -- ^ @*@ ,pLitT :: HP Type -- ^ @0,1,2, etc.@ -- helpers for Type ,pKind :: HP Kind ,pCxt :: HP Cxt ,pPred :: HP Pred ,pLit :: HP Lit ,pQual :: (HParser -> HP Name) -> HP Name ,pVar ,pVarAlpha ,pVarSym ,pConSym ,pConAlpha ,pCon :: HP Name ,pAlpha :: HP Char ,pSy :: HP Char ,pCharLit :: HP Char ,pTyVarBndr :: HP TyVarBndr ,pForall :: HP () -- ^ @forall@ ,pLam :: HP () -- ^ @\\@ ,pRArrow :: HP () -- ^ @->@ ,pLArrow :: HP () -- ^ @<-@ ,pDColon :: HP () -- ^ @::@ ,pDotDot :: HP () -- ^ @..@ -- layout-related ,pSemi :: HP () ,pLBrace :: HP () ,pRBrace :: HP () ,pLaidout_ :: (forall row. (HParser -> HP row) -> HP [row]) ,isSy :: S -> Char -> Bool ,classifySpaceSep :: S -> [Either Exp [FieldExp]] -> Exp ,classifySpaceSepT :: S -> [Type] -> Type } -- fixP :: (HParser -> HP t) -> HParser -> Parser t fixP getP p = getP p s where s :: S s = S $ \f -> f p s instance Default HParser where def = HParser {pType = \(S s) -> (pSpaces *> s pSpaceSepT <* pSpaces) <|> s pSigT <|> pParens (s pConSymT) ,pType' = \(S s) -> s pConAlphaT -- so a::* is SigT _ StarT <|> s pStarT <|> s pForallT <|> s pLitT <|> s pVarT <|> s pPromotedT <|> s pTupleT <|> s pArrowT <|> s pListT <|> s pPromotedTupleT ,pExp = \(S s) -> (pSpaces *> s pSpaceSep <* pSpaces) <|> s pSigE ,pExp' = \(S s) -> s pVarE <|> s pConE <|> s pLitE <|> s pInfixE <|> s pTupE <|> s pLamE <|> s pLamCaseE <|> s pUnboxedTupE <|> s pCondE <|> s pMultiIfE <|> s pLetE <|> s pCaseE <|> s pDoE <|> s pCompE <|> s pArithSeqE <|> s pListE ,pPat = \(S s) -> pSpaces *> (s pPat' <|> s pSigP <|> s pUInfixP) <* pSpaces ,pSigP = \(S s) -> SigP <$> s pPat' <*> (s pDColon *> s pType) ,pUInfixP = \(S s) -> let infixCon = pSym '`' *> s pConAlpha <* pSym '`' in UInfixP <$> s pPat' <*> infixCon <*> s pPat ,pPat' = \(S s) -> s pLitP <|> s pVarP <|> s pParensP <|> s pUnboxedTupP <|> s pConP <|> s pAsP <|> s pTildeP <|> s pBangP <|> s pWildP <|> s pListP <|> s pRecP <|> s pViewP ,pLitP = \(S s) -> LitP <$> s pLit ,pVarP = \(S s) -> VarP <$> s pVarAlpha ,pParensP = \(S s) -> let tupP [x] = ParensP x tupP xs = TupP xs in pParens $ tupP <$> pList1Sep pComma (s pPat) ,pUnboxedTupP = \(S s) -> pToken "(#" *> (UnboxedTupP <$> ((:) <$> s pPat <*> (pList1 (pComma *> s pPat)))) <* pToken "#)" ,pConP = \(S s) -> ConP <$> s pCon <*> pListSep_ng pSpaces (s pPat) ,pAsP = \(S s) -> AsP <$> (s pVarAlpha <* pToken "@") <*> s pPat ,pTildeP = \(S s) -> TildeP <$> (pToken "~" *> s pPat) ,pBangP = \(S s) -> BangP <$> (pToken "!" *> s pPat) ,pWildP = \(S s) -> WildP <$ pToken "_" ,pListP = \(S s) -> ListP <$> listParser (s pPat) ,pRecP = \(S s) -> let con = s pConAlpha <* pSpaces fieldPats = pListSep pComma fieldPat fieldPat = (,) <$> s pVarAlpha <*> (pToken "=" *> s pPat) in RecP <$> con <*> pBraces fieldPats ,pViewP = \(S s) -> pParens $ ViewP <$> s pExp <*> (s pRArrow *> s pPat) ,pVar = \(S s) -> micro (s pVarAlpha <|> s pVarSym) 1 -- micro adds a penalty to choosing a variable name, -- so if/then/else are consumed by pToken, A.B.c does not -- use . as variable ,pVarE = \(S s) -> VarE <$> s (optQual pVar) <?> "VarE" ,pConE = \(S s) -> ConE <$> s (optQual pCon) <?> "ConE" ,pLitE = \(S s) -> LitE <$> s pLit ,pSpaceSepT = \(S s) -> (\ x xs -> s classifySpaceSepT (x : xs)) <$> s pType' <*> (pSpaces *> pListSep_ng pSpaces (s pType' <|> micro (s pConSymT) 1 -- so that T::* parses as SigT T * not -- a (ConT ::*) )) ,pSpaceSep = \ (S s) -> let e = Left <$> s pExp' <|> Right <$> s pFieldExps in s classifySpaceSep <$> pList1Sep_ng pSpaces e ,classifySpaceSepT = \ (S s) xs -> let isOp (VarT (Name (OccName (n:_)) _)) = s isSy n isOp (ConT (Name (OccName (':':_)) _)) = True isOp ArrowT = True isOp PromotedConsT = True isOp _ = False -- this is not really as general as it could be toCxt (AppT (ConT n) t) = [ClassP n (unapp t)] toCxt (ConT n) = [ClassP n []] toCxt (VarT n) = [ClassP n []] toCxt (VarT (Name (OccName "~") NameS) `AppT` x `AppT` y) = [EqualP x y] toCxt a = concatMap toCxt (reverse (fromTuple 0 a)) fromTuple n (AppT a b) = b : fromTuple (n+1) a fromTuple n (TupleT m) | n == m = [] | otherwise = error "QQParse.fromTuple" fromTuple _ x = error ("QQParse.fromTuple: don't know how to handle " ++ show x) unapp (AppT a b) = a : unapp b unapp x = [x] infixF (Right a : Left (VarT (Name (OccName "=>") _)) : cs) = ForallT [] (toCxt a) (infixF cs) infixF (Right a : Left b : cs) = infixF (Right (AppT b a) : cs) infixF (Left a : b : cs) = AppT a (infixF (b:cs)) infixF (Right a : b : cs) = AppT a (infixF (b:cs)) infixF [a] = either id id a in infixF $ mapMaybe (\x -> case x of [a] | isOp a -> Just (Left a) (a:b) -> Just (Right (foldl AppT a b)) _ -> Nothing) $ split (whenElt isOp) xs ,classifySpaceSep = \ (S s) xs -> let isOp (VarE (Name (OccName (n:_)) _)) = s isSy n isOp (ConE (Name (OccName (':':_)) _)) = True isOp (InfixE Nothing v Nothing) = not (isOp v) isOp _ = False minfix (Right a : Left op : Right b : xs) | InfixE Nothing op' Nothing <- op = minfix (Right (UInfixE a op' b) : xs) | otherwise = minfix (Right (UInfixE a op b) : xs) minfix (Right y : Left (InfixE Nothing x Nothing) : xs) = minfix (Left (InfixE (Just y) x Nothing) : xs) minfix (Left (InfixE Nothing x Nothing) : Right y : xs) = minfix (Left (InfixE Nothing x (Just y)) : xs) minfix (Left x : xs) = x : minfix xs minfix (Right x : xs) = x : minfix xs minfix [] = [] applyFieldExps (Left (ConE n) : Right fexp : as) = applyFieldExps (Left (RecConE n fexp) : as) applyFieldExps (Left e : Right fexp : as) = applyFieldExps (Left (RecUpdE e fexp) : as) applyFieldExps (Left e : es) = e : applyFieldExps es applyFieldExps [] = [] in foldl1 AppE $ minfix $ mapMaybe (\x -> case x of [a] | isOp a -> Just (Left a) a:b -> Just (Right (foldl AppE a b)) _ -> Nothing ) $ split (whenElt isOp) $ applyFieldExps xs ,pInfixE = \(S s) -> InfixE Nothing <$> (pSym '`' *> (VarE <$> s pVarAlpha <|> s pConE) <* pSym '`') <*> pure Nothing ,pLamE = \(S s) -> LamE <$> (pSym '\\' *> some (s pPat) <* s pRArrow) <*> s pExp ,pLamCaseE = \(S s) -> LamCaseE <$> (s pLam *> pSymbol "case" *> pList1Sep (s pSemi) (s pMatch)) -- XXX layout ,pTupE = \(S s) -> (\x -> case x of [e] -> ParensE e _ -> TupE x) <$> (pLParen *> (pList1Sep pComma (s pExp)) <* pSym ')') ,pUnboxedTupE = \(S s) -> pToken "(#" *> (UnboxedTupE <$> pList1Sep pComma (s pExp)) <* pSymbol "#)" ,pCondE = \(S s) -> CondE <$> (pSymbol "if" *> s pExp) <*> (pSymbol "then" *> s pExp) <*> (pSymbol "else" *> s pExp) ,pMultiIfE = \(S s) -> let guardE = (,) <$> s pGuard <*> (s pRArrow *> s pExp) in MultiIfE <$> (pSymbol "if" *> pSome guardE) -- ^ @{ if | g1 -> e1 | g2 -> e2 }@ ,pGuard = \(S s) -> let patG [NoBindS e] = NormalG e patG stmts = PatG stmts in pToken "|" *> ( patG <$> pList1Sep pComma (s pStmt) ) ,pMatch = \(S s) -> let normalB = s pRArrow *> (NormalB <$> s pExp) guardedB = GuardedB <$> pList1 ((,) <$> s pGuard <*> (s pRArrow *> s pExp)) in Match <$> s pPat <*> (normalB <|> guardedB) <*> s pWhere ,pLetE = \(S s) -> let decs = pToken "let" *> s (pLaidout pDec) in LetE <$> decs <*> (pSpaces *> pToken "in" *> s pExp) ,pCaseE = \(S s) -> CaseE <$> (pToken "case" *> s pExp <* pToken "of") <*> s (pLaidout pMatch) -- ^ @{ case e of m1; m2 }@ ,pDoE = \(S s) -> let stmts = pToken "do" *> s (pLaidout pStmt) in DoE <$> stmts ,pArithSeqE = \(S s) -> let toRange a (Just b) (Just c) = FromThenToR a b c toRange a Nothing Nothing = FromR a toRange a (Just b) Nothing = FromThenR a b toRange a Nothing (Just c) = FromToR a c addCon a b c = ArithSeqE (toRange a b c) in addCon <$> (pSym '[' *> s pExp) <*> optional (pComma *> s pExp) <*> (s pDotDot *> optional (s pExp) <* pSpaces) <* pSym ']' ,pCompE = \(S s) -> let toComp e stmts = CompE (stmts ++ [NoBindS e]) in toComp <$> (pSym '[' *> s pExp) <*> (pSym '|' *> pList1Sep pComma (s pStmt) <* pSym ']') -- ^ @{ [ (x,y) | x <- xs, y <- ys ] }@ ,pFieldExps = \(S s) -> pBraces (pList1Sep_ng pComma ((,) <$> (s pVarAlpha <* pToken "=") <*> s pExp)) ,pListE = \(S s) -> ListE <$> listParser (s pExp) ,pSigE = \(S s) -> SigE <$> s pExp' <*> (pSpaces *> s pDColon *> s pType) ,pDecs = \(S s) -> let mergeFunDs (FunD x a : FunD y b : xs) | x == y = mergeFunDs (FunD x (a ++ b) : xs) mergeFunDs (x : xs) = x : mergeFunDs xs mergeFunDs [] = [] in mergeFunDs <$> s (pLaidout pDec) ,pDec = \(S s) -> s pValD <|> micro (s pFunD) 1 -- data X = X <|> s pFunDInfix <|> s pSigD <|> s pDataD ,pValD = \(S s) -> ValD <$> s pPat <*> s pBody <*> s pWhere ,pWhere = \(S s) -> pToken "where" *> s pDecs <|> pure [] ,pBody = \(S s) -> let normalB = NormalB <$> (pToken "=" *> s pExp) guardedB = GuardedB <$> pList1 ((,) <$> (pToken "|" *> s pGuard) <*> (pToken "=" *> s pExp)) in normalB <|> guardedB ,pFunD = \(S s) -> let pClause = Clause <$> pList1 (s pPat) <*> s pBody <*> s pWhere in FunD <$> s pVarAlpha <* pSpaces <*> ((:[]) <$> pClause) ,pFunDInfix = \(S s) -> let infixV = (pSym '`' *> s pVarAlpha <* pSym '`') <|> s pVarSym f p1 n p2 b w = FunD n [Clause [p1,p2] b w] in f <$> s pPat <*> infixV <*> s pPat <*> s pBody <*> s pWhere ,pDataD = \(S s) -> let cxt = s pCxt <* pToken "=>" <|> pure [] derivingList = pParens (pListSep_ng pComma (s pCon)) <|> ((:[]) <$> s pCon) constructors = pList1Sep (pSpaces *> pSymbol "|") (s pConstructor) in DataD <$ pSymbol "data" <*> cxt <*> (pSpaces *> s pConAlpha <* pSpaces) <*> pListSep pSpaces (s pTyVarBndr) <* pSpaces <* pSymbol "=" <*> constructors <*> (pSymbol "deriving" *> derivingList <|> pure []) ,pConstructor = \(S s) -> let pUnpack = pToken "{-#" *> pToken "UNPACK" *> pToken "#-}" *> pToken "!" pStrict = IsStrict <$ pToken "!" <|> Unpacked <$ pUnpack <|> pure NotStrict pStrictType = ((,) <$ pSpaces <*> pStrict <*> s pType') pN = s pConAlpha <* pSpaces pNormalC = NormalC <$> pN <*> pList_ng (micro pStrictType 1) -- "deriving" is otherwise a valid type pRecC = RecC <$> pN <*> pBraces (concat <$> pList1Sep_ng pComma pVarStrictType) pVarStrictType = spread <$> (pList1Sep pComma (s pVarAlpha) <* s pDColon) <*> pStrict <*> s pType spread :: [n] -> s -> t -> [(n,s,t)] spread ns s t = map (\n -> (n,s,t)) ns pInfixC = InfixC <$> pStrictType <*> (pSpaces *> s pConSym <* pSpaces) <*> pStrictType pForallC = ForallC <$ (s pForall <* pSpaces) <*> (pList1Sep pSpaces (s pTyVarBndr) <* pSymbol ".") <*> (s pCxt <* pSymbol "=>") <*> s pConstructor in pInfixC <|> pNormalC <|> pRecC <|> pForallC {- | ForallC [TyVarBndr] Cxt Con -} ,pSigD = \(S s) -> SigD <$> (s pVarAlpha <|> pParens (s pVarSym)) <*> (s pDColon *> s pType) ,pStmt = \(S s) -> NoBindS <$> s pExp <|> BindS <$> s pPat <*> (s pLArrow *> s pExp) <|> LetS <$> (pToken "let" *> s pDecs) -- ParS XXX ,pSigT = \(S s) -> SigT <$> s pType' <*> (pSpaces *> s pDColon *> s pKind) ,pVarT = \(S s) -> VarT <$> (s pVarAlpha <|> micro (s pVarSym) 2) ,pConAlphaT = \(S s) -> let f (Name (OccName "Constraint") _) = ConstraintT f x = ConT x in f <$> s pConAlpha ,pConSymT = \(S s) -> ConT <$> s pConSym ,pForallT = \(S s) -> let tyVarBndrs = s pForall *> pSpaces *> some (s pTyVarBndr) <* pSymbol "." in ForallT <$> tyVarBndrs <*> (s pCxt <* pToken "=>") <*> s pType ,pTupleT = \ (S s) -> let appliedTupT c = f <$> pList1Sep pComma (s pType) where f [x] = x f xs = foldl AppT (c (length xs)) xs unappliedTupT c = c . (+1) . length <$> some pComma tt con = appliedTupT con <|> unappliedTupT con in pSymbol "(#" *> tt UnboxedTupleT <* pSymbol "#)" <|> pParens (tt TupleT) ,pArrowT = \ (S s) -> ArrowT <$ s pRArrow ,pLitT = \ _ -> fmap LitT $ NumTyLit <$> pInteger <|> StrTyLit <$> pQuotedString ,pPromotedT = \ (S s) -> let alph = s (optQual $ \_ _ -> s pCon <|> s pVarAlpha) sym = pParens (s (optQual pVarSym)) alphSym = alph <|> sym promotedT (Name (OccName ":") _) = PromotedConsT promotedT x = PromotedT x in pSym '\'' *> (promotedT <$> alphSym) ,pPromotedTupleT = \ (S s) -> let pList2Sep_ng sep p = (:) <$> p <*> (sep *> pList1Sep_ng sep p) notApp = PromotedTupleT . (+1) . length <$> some pComma app = f <$> pList2Sep_ng pComma (s pType) f xs = foldl AppT (PromotedTupleT (length xs)) xs in pSym '\'' *> pParens (notApp <|> app) ,pStarT = \_ -> StarT <$ pSymbol "*" ,pListT = \(S s) -> let f Nothing [] = ListT f Nothing [x] = ListT `AppT` x f _ xs = foldr (\a b -> PromotedConsT `AppT` a `AppT` b) PromotedNilT xs in f <$> optional (pSym '\'') <*> pBrackets (pListSep pComma (s pType)) ,pCxt = \(S s) -> (:[]) <$> s pPred <|> pParens (some (s pPred)) ,pPred = \(S s) -> ClassP <$> (s pCon <* pSpaces) <*> many (s pType) <|> EqualP <$> s pType' <*> (pSymbol "~" *> s pType) ,pKind = \(S s) -> s pType ,pTyVarBndr = \(S s) -> (PlainTV <$> s pVarAlpha) <|> pParens (KindedTV <$> s pVarAlpha <*> (s pDColon *> s pKind)) ,pQual = \next (S s) -> addQual <$> (pList1 (s pConAlpha <* pSym '.') <?> "module name") <*> s next ,pLit = \ (S s) -> let toLit x | Just n <- readMaybe x = IntegerL n | otherwise = RationalL (toRational (read x :: Double)) in StringL <$> pQuotedString <|> CharL <$> s pCharLit <|> toLit <$> micro pDoubleStr 1 {- <|> IntPrimL <$> pInteger <|> WordPrimL <$> pInteger | FloatPrimL Rational | DoublePrimL Rational | StringPrimL [GHC.Word.Word8] -} ,pCharLit = \ _ -> pSym '\'' <* (pSatisfy (/= '\\') (Insertion "\\" '\\' 100) <<|> ('\'' <$ pToken "\\'")) <* pSym '\'' ,pVarSym = \(S s) -> toName [] <$> pList1 (s pSy) ,pVarAlpha = \ (S s) -> toName [] <$> ((:) <$> pLower <*> pList (s pAlpha)) <* pSpaces ,pCon = \ (S s) -> (s pConAlpha <|> s pConSym) <* pSpaces ,pConAlpha = \ (S s) -> (\ x xs -> toName [] (x:xs)) <$> pUpper <*> pList (s pAlpha) ,pConSym = \ (S s) -> let sndSy = (:) <$> s pSy <*> pList (s pSy <|> pSym ':') sndColon = (:) <$> pSym ':' <*> pList1 (s pSy <|> pSym ':') in fmap (toName []) $ (:) <$> pSym ':' <*> (sndSy <|> sndColon <<|> pure []) ,pAlpha = \ _s -> pSatisfy (\x -> isAlpha x || x `elem` "'_") (Insertion "a" 'a' 100) ,pSy = \ (S s) -> pSatisfy (s isSy) (Insertion "+" '+' 100) ,isSy = \ _ x -> (isSymbol x || x `elem` "-!#$%^&*.?<>~") && x /= '`' ,pLam = \ _ -> () <$ pToken "\\" ,pRArrow = \ _ -> () <$ pToken "->" ,pLArrow = \ _ -> () <$ pToken "<-" ,pDColon = \ _ -> () <$ pToken "::" ,pForall = \ _ -> () <$ pToken "forall" ,pDotDot = \_ -> () <$ pToken ".." ,pSemi = \ _ -> () <$ pSym ';' -- or do layout here? ,pLBrace = \_ -> () <$ pSym '{' ,pRBrace = \_ -> () <$ pSym '}' ,pLaidout_ = \ e (S s) -> do pSpaces lbrace <- optional (s pLBrace) LineColPos _ c' _ <- pPos pList_ng (do munched <- pMunch (`elem` " \t\n;") LineColPos _ c _ <- pPos guard (isJust lbrace || ';' `elem` munched || c == c') s e) <* if isJust lbrace then s pRBrace else pure () } pLaidout :: (HParser -> HP a) -> t -> HP [a] pLaidout x _ (S s) = s $ \hp _ -> pLaidout_ hp x (S s) -- | s (qual pVar) qual :: (HParser -> HP Name) -> t -> HP Name qual x _ (S s) = s $ \hp _ -> pQual hp x (S s) optQual :: (HParser -> HP Name) -> t -> HP Name optQual x _ (S s) = s $ \hp _ -> pQual hp x (S s) <|> x hp (S s) toName :: [String] -> String -> Name toName [] var = Name (OccName var) NameS toName mn var = Name (OccName var) (NameQ (ModName (intercalate "." mn))) addQual :: [Name] -> Name -> Name addQual ms (Name (OccName var) NameS) = toName [ m | ~(Name (OccName m) NameS) <- ms ] var
aavogt/qqParse
QQParse.hs
bsd-3-clause
32,455
0
24
10,979
10,917
5,613
5,304
692
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TypeApplications #-} module Test.Spec.Wallets ( spec , genNewWalletRq ) where import Universum import Test.Hspec (Spec, describe, shouldBe, shouldSatisfy) import Test.Hspec.QuickCheck (prop) import Test.QuickCheck (arbitrary, suchThat, vectorOf, withMaxSuccess) import Test.QuickCheck.Monadic (PropertyM, monadicIO, pick) import Data.Coerce (coerce) import Formatting (build, formatToString) import Pos.Core (decodeTextAddress) import Pos.Core.NetworkMagic (makeNetworkMagic) import Pos.Crypto (ProtocolMagic, emptyPassphrase, hash) import Pos.Crypto.HD (firstHardened) import qualified Cardano.Mnemonic as Mnemonic import Cardano.Wallet.Kernel.DB.HdWallet (AssuranceLevel (..), HdRootId (..), UnknownHdRoot (..), WalletName (..), hdRootId) import qualified Cardano.Wallet.Kernel.DB.HdWallet as HD import Cardano.Wallet.Kernel.DB.HdWallet.Create (CreateHdRootError (..)) import Cardano.Wallet.Kernel.DB.InDb (InDb (..)) import qualified Cardano.Wallet.Kernel.DB.Util.IxSet as IxSet import qualified Cardano.Wallet.Kernel.Internal as Internal import qualified Cardano.Wallet.Kernel.Keystore as Keystore import Cardano.Wallet.Kernel.Types (WalletId (..)) import Cardano.Wallet.Kernel.Wallets (CreateWalletError (..)) import qualified Cardano.Wallet.Kernel.Wallets as Kernel import qualified Cardano.Wallet.WalletLayer as WalletLayer import qualified Cardano.Wallet.WalletLayer.Kernel.Wallets as Wallets import qualified Cardano.Wallet.API.Request as API import qualified Cardano.Wallet.API.Request.Pagination as API import qualified Cardano.Wallet.API.Response as V1 import Cardano.Wallet.API.V1.Handlers.Accounts as Handlers import Cardano.Wallet.API.V1.Handlers.Wallets as Handlers import Cardano.Wallet.API.V1.Types (V1 (..), unV1) import qualified Cardano.Wallet.API.V1.Types as V1 import Control.Monad.Except (runExceptT) import Servant.Server import Test.Spec.Fixture (GenPassiveWalletFixture, genSpendingPassword, withLayer, withPassiveWalletFixture) import Util.Buildable (ShowThroughBuild (..)) {-# ANN module ("HLint: ignore Reduce duplication" :: Text) #-} data Fixture = Fixture { fixtureSpendingPassword :: V1.SpendingPassword , fixtureV1Wallet :: V1.Wallet , fixtureHdRootId :: HdRootId } oppositeLevel :: V1.AssuranceLevel -> V1.AssuranceLevel oppositeLevel V1.StrictAssurance = V1.NormalAssurance oppositeLevel V1.NormalAssurance = V1.StrictAssurance genNewWalletRq :: Maybe V1.SpendingPassword -> PropertyM IO V1.NewWallet genNewWalletRq spendingPassword = do assuranceLevel <- pick arbitrary walletName <- pick arbitrary mnemonic <- Mnemonic.entropyToMnemonic <$> liftIO (Mnemonic.genEntropy @(Mnemonic.EntropySize 12)) return $ V1.NewWallet (V1.BackupPhrase mnemonic) spendingPassword assuranceLevel walletName V1.CreateWallet prepareFixtures :: GenPassiveWalletFixture Fixture prepareFixtures = do spendingPassword <- pick (arbitrary `suchThat` ((/=) mempty)) newWalletRq <- WalletLayer.CreateWallet <$> genNewWalletRq (Just spendingPassword) return $ \pw -> do res <- Wallets.createWallet pw newWalletRq case res of Left e -> error (show e) Right v1Wallet -> do let (V1.WalletId wId) = V1.walId v1Wallet case decodeTextAddress wId of Left e -> error $ "Error decoding the input Address " <> show wId <> ": " <> show e Right rootAddr -> do let rootId = HdRootId . InDb $ rootAddr return (Fixture spendingPassword v1Wallet rootId) -- | A 'Fixture' where we already have a new 'Wallet' in scope. withNewWalletFixture :: ProtocolMagic -> ( Keystore.Keystore -> WalletLayer.PassiveWalletLayer IO -> Internal.PassiveWallet -> Fixture -> IO a ) -> PropertyM IO a withNewWalletFixture pm cc = withPassiveWalletFixture pm prepareFixtures cc spec :: Spec spec = describe "Wallets" $ do describe "CreateWallet" $ do describe "Wallet creation (wallet layer)" $ do prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $ do monadicIO $ do pwd <- genSpendingPassword request <- WalletLayer.CreateWallet <$> genNewWalletRq pwd pm <- pick arbitrary withLayer pm $ \layer _ -> do liftIO $ do res <- WalletLayer.createWallet layer request (bimap STB STB res) `shouldSatisfy` isRight prop "fails if the wallet already exists" $ withMaxSuccess 5 $ do monadicIO $ do pwd <- genSpendingPassword request <- WalletLayer.CreateWallet <$> genNewWalletRq pwd pm <- pick arbitrary withLayer pm $ \layer _ -> do liftIO $ do -- The first time it must succeed. res1 <- WalletLayer.createWallet layer request (bimap STB STB res1) `shouldSatisfy` isRight -- The second time it must not. res2 <- WalletLayer.createWallet layer request case res2 of Left (WalletLayer.CreateWalletError (CreateWalletFailed (CreateHdRootExists _))) -> return () Left unexpectedErr -> fail $ "expecting different failure than " <> show unexpectedErr Right _ -> fail "expecting wallet not to be created, but it was." prop "supports Unicode characters" $ withMaxSuccess 5 $ do monadicIO $ do pwd <- genSpendingPassword request <- genNewWalletRq pwd pm <- pick arbitrary withLayer pm $ \layer _ -> do let w' = WalletLayer.CreateWallet $ request { V1.newwalName = "İıÀļƒȑĕďŏŨƞįťŢęșťıİ 日本" } liftIO $ do res <- WalletLayer.createWallet layer w' (bimap STB STB res) `shouldSatisfy` isRight describe "Wallet creation (kernel)" $ do prop "correctly persists the ESK in the keystore" $ withMaxSuccess 5 $ monadicIO $ do pwd <- genSpendingPassword V1.NewWallet{..} <- genNewWalletRq pwd pm <- pick arbitrary withLayer @IO pm $ \_ wallet -> do liftIO $ do let hdAssuranceLevel = case newwalAssuranceLevel of V1.NormalAssurance -> AssuranceLevelNormal V1.StrictAssurance -> AssuranceLevelStrict res <- Kernel.createHdWallet wallet (V1.unBackupPhrase newwalBackupPhrase) (maybe emptyPassphrase coerce newwalSpendingPassword) hdAssuranceLevel (WalletName newwalName) case res of Left e -> fail (show e) Right hdRoot -> do -- Check that the key is in the keystore let nm = makeNetworkMagic pm wid = WalletIdHdRnd (hdRoot ^. hdRootId) mbEsk <- Keystore.lookup nm wid (wallet ^. Internal.walletKeystore) mbEsk `shouldSatisfy` isJust describe "Wallet creation (Servant)" $ do prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $ do monadicIO $ do pwd <- genSpendingPassword rq <- genNewWalletRq pwd pm <- pick arbitrary withLayer pm $ \layer _ -> do liftIO $ do res <- runExceptT . runHandler' $ Handlers.newWallet layer rq (bimap identity STB res) `shouldSatisfy` isRight prop "comes by default with 1 account at a predictable index" $ withMaxSuccess 5 $ do monadicIO $ do pwd <- genSpendingPassword rq <- genNewWalletRq pwd pm <- pick arbitrary withLayer pm $ \layer _ -> do liftIO $ do let fetchAccount wId = Handlers.getAccount layer wId (V1.unsafeMkAccountIndex firstHardened) res <- runExceptT . runHandler' $ do V1.APIResponse{..} <- Handlers.newWallet layer rq fetchAccount (V1.walId wrData) (bimap identity STB res) `shouldSatisfy` isRight prop "comes by default with 1 address at the default account" $ withMaxSuccess 5 $ do monadicIO $ do pwd <- genSpendingPassword rq <- genNewWalletRq pwd pm <- pick arbitrary withLayer pm $ \layer _ -> do liftIO $ do let fetchAccount wId = Handlers.getAccount layer wId (V1.unsafeMkAccountIndex firstHardened) res <- runExceptT . runHandler' $ do V1.APIResponse{..} <- Handlers.newWallet layer rq fetchAccount (V1.walId wrData) case res of Left e -> throwM e Right V1.APIResponse{..} -> length (V1.accAddresses wrData) `shouldBe` 1 describe "DeleteWallet" $ do describe "Wallet deletion (wallet layer)" $ do prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $ do monadicIO $ do pm <- pick arbitrary withNewWalletFixture pm $ \_ layer _ Fixture{..} -> do let wId = V1.walId fixtureV1Wallet liftIO $ do res1 <- WalletLayer.deleteWallet layer wId (bimap STB STB res1) `shouldSatisfy` isRight -- Check that the wallet is not there anymore res2 <- WalletLayer.getWallet layer wId (bimap STB STB res2) `shouldSatisfy` isLeft prop "cascade-deletes all the associated accounts" $ withMaxSuccess 5 $ do monadicIO $ do pm <- pick arbitrary withNewWalletFixture pm $ \_ layer _ Fixture{..} -> do let wId = V1.walId fixtureV1Wallet liftIO $ do let check predicate _ V1.Account{..} = do acc <- WalletLayer.getAccount layer wId accIndex (bimap STB STB acc) `shouldSatisfy` predicate Right allAccounts <- WalletLayer.getAccounts layer wId -- We should have 1 account, and fetching it must -- succeed. IxSet.size allAccounts `shouldBe` 1 foldM_ (check isRight) () allAccounts -- Deletion should still return 'Right'. res <- WalletLayer.deleteWallet layer wId (bimap STB STB res) `shouldSatisfy` isRight -- Fetching the old, not-existing-anymore accounts -- should fail. foldM_ (check isLeft) () allAccounts prop "fails if the wallet doesn't exists" $ withMaxSuccess 5 $ do monadicIO $ do wId <- pick arbitrary pm <- pick arbitrary withLayer pm $ \layer _ -> do liftIO $ do res <- WalletLayer.deleteWallet layer wId case res of Left (WalletLayer.DeleteWalletError (UnknownHdRoot _)) -> return () Left unexpectedErr -> fail $ "expecting different failure than " <> show unexpectedErr Right _ -> fail "expecting wallet not to be created, but it was." describe "Wallet deletion (kernel)" $ do prop "correctly deletes the ESK in the keystore" $ withMaxSuccess 5 $ monadicIO $ do pm <- pick arbitrary withNewWalletFixture pm $ \ks _ wallet Fixture{..} -> do liftIO $ do let nm = makeNetworkMagic pm wId = WalletIdHdRnd fixtureHdRootId mbKey <- Keystore.lookup nm wId ks mbKey `shouldSatisfy` isJust res <- Kernel.deleteHdWallet nm wallet fixtureHdRootId case res of Left e -> fail (formatToString build e) Right () -> do -- Check that the key is not in the keystore anymore mbKey' <- Keystore.lookup nm wId ks mbKey' `shouldSatisfy` isNothing describe "UpdateWalletPassword" $ do describe "Wallet update password (wallet layer)" $ do prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $ do monadicIO $ do newPwd <- pick arbitrary pm <- pick arbitrary withNewWalletFixture pm $ \ _ layer _ Fixture{..} -> do let request = V1.PasswordUpdate fixtureSpendingPassword newPwd let wId = V1.walId fixtureV1Wallet res <- WalletLayer.updateWalletPassword layer wId request (bimap STB STB res) `shouldSatisfy` isRight prop "fails if the old password doesn't match" $ withMaxSuccess 5 $ do monadicIO $ do wrongPwd <- pick (arbitrary `suchThat` ((/=) mempty)) newPwd <- pick arbitrary pm <- pick arbitrary withNewWalletFixture pm $ \ _ layer _ Fixture{..} -> do let request = V1.PasswordUpdate wrongPwd newPwd let wId = V1.walId fixtureV1Wallet res <- WalletLayer.updateWalletPassword layer wId request case res of Left (WalletLayer.UpdateWalletPasswordError (Kernel.UpdateWalletPasswordOldPasswordMismatch _)) -> return () Left unexpectedErr -> fail $ "expecting different failure than " <> show unexpectedErr Right _ -> fail "expecting password not to be updated, but it was." describe "Wallet update password (kernel)" $ do prop "correctly replaces the ESK in the keystore" $ withMaxSuccess 5 $ monadicIO $ do newPwd <- pick arbitrary pm <- pick arbitrary withNewWalletFixture pm $ \ keystore _ wallet Fixture{..} -> do let nm = makeNetworkMagic pm wid = WalletIdHdRnd fixtureHdRootId oldKey <- Keystore.lookup nm wid keystore res <- Kernel.updatePassword wallet fixtureHdRootId (unV1 fixtureSpendingPassword) newPwd case res of Left e -> fail (show e) Right (_db, _newRoot) -> do -- Check that the key was replaced in the keystore correctly. newKey <- Keystore.lookup nm wid keystore newKey `shouldSatisfy` isJust (fmap hash newKey) `shouldSatisfy` (not . (==) (fmap hash oldKey)) prop "correctly updates hdRootHasPassword" $ withMaxSuccess 5 $ do monadicIO $ do newPwd <- pick arbitrary pm <- pick arbitrary withNewWalletFixture pm $ \ _ _ wallet Fixture{..} -> do res <- Kernel.updatePassword wallet fixtureHdRootId (unV1 fixtureSpendingPassword) newPwd let passphraseIsEmpty = newPwd == emptyPassphrase let satisfied = \case HD.NoSpendingPassword -> passphraseIsEmpty HD.HasSpendingPassword _ -> not passphraseIsEmpty case res of Left e -> fail (show e) Right (_, newRoot) -> do (newRoot ^. HD.hdRootHasPassword) `shouldSatisfy` satisfied describe "Wallet update password (Servant)" $ do prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $ do monadicIO $ do newPwd <- pick arbitrary pm <- pick arbitrary withNewWalletFixture pm $ \ _ layer _ Fixture{..} -> do liftIO $ do let wId = V1.walId fixtureV1Wallet let rq = V1.PasswordUpdate fixtureSpendingPassword newPwd res <- runExceptT . runHandler' $ Handlers.updatePassword layer wId rq (bimap identity STB res) `shouldSatisfy` isRight describe "GetWallet" $ do -- There is no formal \"kernel function\" for this one, so we are -- testing only the WalletLayer and the Servant handler. describe "Get a specific wallet (wallet layer)" $ do prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $ do monadicIO $ do pm <- pick arbitrary withNewWalletFixture pm $ \ _ layer _ Fixture{..} -> do let wId = V1.walId fixtureV1Wallet res <- WalletLayer.getWallet layer wId (bimap STB STB res) `shouldBe` (Right (STB fixtureV1Wallet)) prop "fails if the wallet doesn't exist" $ withMaxSuccess 5 $ do monadicIO $ do wId <- pick arbitrary pm <- pick arbitrary withLayer pm $ \ layer _ -> do res <- WalletLayer.getWallet layer wId case res of Left (WalletLayer.GetWalletError (UnknownHdRoot _)) -> return () Left unexpectedErr -> fail $ "expecting different failure than " <> show unexpectedErr Right _ -> fail "expecting wallet not to be fetched, but it was." describe "Get a specific wallet (Servant)" $ do prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $ do monadicIO $ do pm <- pick arbitrary withNewWalletFixture pm $ \ _ layer _ Fixture{..} -> do liftIO $ do let wId = V1.walId fixtureV1Wallet res <- runExceptT . runHandler' $ Handlers.getWallet layer wId (bimap identity STB res) `shouldSatisfy` isRight prop "fails if the wallet doesn't exist" $ withMaxSuccess 5 $ do monadicIO $ do wId <- pick arbitrary pm <- pick arbitrary withLayer pm $ \layer _ -> do let getW = Handlers.getWallet layer wId res <- try . runExceptT . runHandler' $ getW case res of Left (_e :: WalletLayer.GetWalletError) -> return () Right (Left e) -> throwM e -- Unexpected Failure Right (Right _) -> fail "Expecting a failure, but the handler succeeded." describe "UpdateWallet" $ do -- There is no formal \"kernel function\" for this one, so we are -- testing only the WalletLayer and the Servant handler. describe "Update a wallet (wallet layer)" $ do prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $ do monadicIO $ do pm <- pick arbitrary withNewWalletFixture pm $ \ _ layer _ Fixture{..} -> do let wId = V1.walId fixtureV1Wallet let newLevel = oppositeLevel (V1.walAssuranceLevel fixtureV1Wallet) res <- WalletLayer.updateWallet layer wId (V1.WalletUpdate newLevel "FooBar") case res of Left e -> fail (formatToString build e) Right w -> do V1.walAssuranceLevel w `shouldBe` newLevel V1.walName w `shouldBe` "FooBar" prop "fails if the wallet doesn't exist" $ withMaxSuccess 5 $ do monadicIO $ do wId <- pick arbitrary lvl <- pick arbitrary name <- pick arbitrary pm <- pick arbitrary withLayer pm $ \ layer _ -> do res <- WalletLayer.updateWallet layer wId (V1.WalletUpdate lvl name) case res of Left (WalletLayer.UpdateWalletError (UnknownHdRoot _)) -> return () Left unexpectedErr -> fail $ "expecting different failure than " <> show unexpectedErr Right _ -> fail "expecting wallet not to be updated, but it was." describe "Update a wallet (Servant)" $ do prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $ do monadicIO $ do pm <- pick arbitrary withNewWalletFixture pm $ \ _ layer _ Fixture{..} -> do liftIO $ do let wId = V1.walId fixtureV1Wallet let newLevel = oppositeLevel (V1.walAssuranceLevel fixtureV1Wallet) let updt = V1.WalletUpdate newLevel "FooBar" res <- runExceptT . runHandler' $ Handlers.updateWallet layer wId updt case res of Left e -> fail (show e) Right (V1.APIResponse{..}) -> do V1.walAssuranceLevel wrData `shouldBe` newLevel V1.walName wrData `shouldBe` "FooBar" prop "fails if the wallet doesn't exist" $ withMaxSuccess 5 $ do monadicIO $ do wId <- pick arbitrary lvl <- pick arbitrary name <- pick arbitrary pm <- pick arbitrary withLayer pm $ \layer _ -> do let updateW = Handlers.updateWallet layer wId res <- try . runExceptT . runHandler' $ updateW (V1.WalletUpdate lvl name) case res of Left (_e :: WalletLayer.UpdateWalletError) -> return () Right (Left e) -> throwM e -- Unexpected Failure Right (Right _) -> fail "Expecting a failure, but the handler succeeded." describe "GetWallets" $ do -- There is no formal \"kernel function\" for this one, so we are -- testing only the WalletLayer and the Servant handler. describe "Gets a list of wallets (wallet layer)" $ do prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $ do monadicIO $ do rqs <- map (\rq -> WalletLayer.CreateWallet $ rq { V1.newwalOperation = V1.CreateWallet }) <$> pick (vectorOf 5 arbitrary) pm <- pick arbitrary withLayer pm $ \layer _ -> do forM_ rqs (WalletLayer.createWallet layer) res <- WalletLayer.getWallets layer (IxSet.size res) `shouldBe` 5 describe "Gets a list of wallets (Servant)" $ do prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $ do monadicIO $ do rqs <- map (\rq -> rq { V1.newwalOperation = V1.CreateWallet }) <$> pick (vectorOf 5 arbitrary) pm <- pick arbitrary withLayer pm $ \ layer _ -> do liftIO $ do forM_ rqs (runExceptT . runHandler' . Handlers.newWallet layer) let params = API.RequestParams (API.PaginationParams (API.Page 1) (API.PerPage 10)) res <- runExceptT . runHandler' $ Handlers.listWallets layer params API.NoFilters API.NoSorts case res of Left e -> throwM e Right (V1.APIResponse{..}) -> do length wrData `shouldBe` 5
input-output-hk/pos-haskell-prototype
wallet/test/unit/Test/Spec/Wallets.hs
mit
28,124
0
36
12,820
5,767
2,748
3,019
-1
-1
-- ALGOSPOT - 콘서트 -- http://algospot.com/judge/problem/read/CONCERT module Main where import Control.Monad concert :: Int -> Int -> Int -> [Int] -> Int concert n vs vm vl = mf n vs vm vl (n,vm) mf :: Int -> Int -> Int -> [Int] -> (Int,Int) -> Int mf = undefined --mf n vs vm vl (x,y) = (map f [(a,b)|a<-[0..n], b<-[0..vm]] !!) -- where f (n,vm) = main :: IO () main = do line <- getLine let caseNum = read line :: Int subMain caseNum subMain :: Int -> IO() subMain caseNum = unless (0 == caseNum) $ do line1 <- getLine line2 <- getLine let (n:vs:[vm]) = [read x :: Int|x<-words line1] vl = [read x :: Int|x<-words line2] print (concert n vs vm vl) subMain (caseNum-1)
everyevery/programming_study
algospot/concert/concert.hs
mit
765
0
14
220
300
154
146
20
1
class X where foo :: Int <ESC>a-- ----------- -- The Y class class Y where bar :: Int
itchyny/vim-haskell-indent
test/comment/splitter.in.hs
mit
87
2
5
19
33
18
15
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.DataPipeline.Types.Sum -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.AWS.DataPipeline.Types.Sum where import Network.AWS.Prelude data OperatorType = OperatorBetween | OperatorEQ' | OperatorGE | OperatorLE | OperatorRefEQ deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic) instance FromText OperatorType where parser = takeLowerText >>= \case "between" -> pure OperatorBetween "eq" -> pure OperatorEQ' "ge" -> pure OperatorGE "le" -> pure OperatorLE "ref_eq" -> pure OperatorRefEQ e -> fromTextError $ "Failure parsing OperatorType from value: '" <> e <> "'. Accepted values: BETWEEN, EQ, GE, LE, REF_EQ" instance ToText OperatorType where toText = \case OperatorBetween -> "BETWEEN" OperatorEQ' -> "EQ" OperatorGE -> "GE" OperatorLE -> "LE" OperatorRefEQ -> "REF_EQ" instance Hashable OperatorType instance ToByteString OperatorType instance ToQuery OperatorType instance ToHeader OperatorType instance ToJSON OperatorType where toJSON = toJSONText data TaskStatus = Failed | False' | Finished deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic) instance FromText TaskStatus where parser = takeLowerText >>= \case "failed" -> pure Failed "false" -> pure False' "finished" -> pure Finished e -> fromTextError $ "Failure parsing TaskStatus from value: '" <> e <> "'. Accepted values: FAILED, FALSE, FINISHED" instance ToText TaskStatus where toText = \case Failed -> "FAILED" False' -> "FALSE" Finished -> "FINISHED" instance Hashable TaskStatus instance ToByteString TaskStatus instance ToQuery TaskStatus instance ToHeader TaskStatus instance ToJSON TaskStatus where toJSON = toJSONText
fmapfmapfmap/amazonka
amazonka-datapipeline/gen/Network/AWS/DataPipeline/Types/Sum.hs
mpl-2.0
2,364
0
12
571
437
229
208
59
0
{-# LANGUAGE CPP#-} module Paths (getStaticDir, samplesURL) where import Control.Monad import System.FilePath #if CABAL -- using cabal import qualified Paths_threepenny_gui (getDataDir) getStaticDir :: IO FilePath getStaticDir = (</> "wwwroot") `liftM` Paths_threepenny_gui.getDataDir #else -- using GHCi getStaticDir :: IO FilePath getStaticDir = return "../wwwroot/" #endif -- | Base URL for the example source code. samplesURL :: String samplesURL = "https://github.com/HeinrichApfelmus/threepenny-gui/blob/master/samples/"
yuvallanger/threepenny-gui
samples/Paths.hs
bsd-3-clause
534
0
6
66
72
47
25
8
1
-- | -- Module : Basement.Compat.Typeable -- License : BSD-style -- Maintainer : Nicolas Di Prima <nicolas@primetype.co.uk> -- Stability : statble -- Portability : portable -- -- conveniently provide support for legacy and modern base -- {-# LANGUAGE CPP #-} module Basement.Compat.Typeable ( #if MIN_VERSION_base(4,7,0) Typeable #else Typeable(..) , typeRep #endif ) where #if !MIN_VERSION_base(4,7,0) import Data.Proxy (Proxy(..)) import qualified Prelude (undefined) #endif import Data.Typeable #if !MIN_VERSION_base(4,7,0) -- this function does not exist prior base 4.7 typeRep :: Typeable a => Proxy a -> TypeRep typeRep = typeRep' Prelude.undefined where typeRep' :: Typeable a => a -> Proxy a -> TypeRep typeRep' a _ = typeOf a {-# INLINE typeRep' #-} #endif
vincenthz/hs-foundation
basement/Basement/Compat/Typeable.hs
bsd-3-clause
820
0
10
166
126
77
49
13
1
{-# LANGUAGE CPP #-} module Main where import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Codec.Compression.GZip as GZip (compress, decompress) import qualified Codec.Compression.BZip as BZip (compress, decompress) import Control.Exception (throwIO) import qualified Data.ByteString.Lazy as BS import Data.ByteString.Lazy (ByteString) import Data.Bits (testBit) import Data.Char (toUpper) import System.Console.GetOpt (OptDescr(..), ArgDescr(..), ArgOrder(..), getOpt', usageInfo) import System.Environment (getArgs) import System.Exit (exitFailure) import System.IO (hPutStrLn, stderr) import Data.Time (formatTime) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) #if MIN_VERSION_time(1,5,0) import Data.Time (defaultTimeLocale) #else import System.Locale (defaultTimeLocale) #endif main :: IO () main = do (opts, files) <- parseOptions =<< getArgs main' opts files main' :: Options -> [FilePath] -> IO () main' (Options { optFile = file, optDir = dir, optAction = action, optCompression = compression, optVerbosity = verbosity }) files = case action of NoAction -> die ["No action given. Specify one of -c, -t or -x."] Help -> printUsage Create -> output . compress compression . Tar.write =<< Tar.pack dir files Extract -> Tar.unpack dir . Tar.read . decompress compression =<< input List -> printEntries . Tar.read . decompress compression =<< input Append | compression /= None -> die ["Append cannot be used together with compression."] | file == "-" -> die ["Append must be used on a file, not stdin/stdout."] | otherwise -> Tar.append file dir files where input = if file == "-" then BS.getContents else BS.readFile file output = if file == "-" then BS.putStr else BS.writeFile file printEntries = Tar.foldEntries (\entry rest -> printEntry entry >> rest) (return ()) throwIO printEntry = putStrLn . entryInfo verbosity data Compression = None | GZip | BZip deriving (Show, Eq) compress :: Compression -> ByteString -> ByteString compress None = id compress GZip = GZip.compress compress BZip = BZip.compress decompress :: Compression -> ByteString -> ByteString decompress None = id decompress GZip = GZip.decompress decompress BZip = BZip.decompress data Verbosity = Verbose | Concise ------------------------ -- List archive contents entryInfo :: Verbosity -> Tar.Entry -> String entryInfo Verbose = detailedInfo entryInfo Concise = Tar.entryPath detailedInfo :: Tar.Entry -> String detailedInfo entry = unwords [ typeCode : permissions , justify 19 (owner ++ '/' : group) size , time , name ++ link ] where typeCode = case Tar.entryContent entry of Tar.HardLink _ -> 'h' Tar.SymbolicLink _ -> 'l' Tar.CharacterDevice _ _ -> 'c' Tar.BlockDevice _ _ -> 'b' Tar.Directory -> 'd' Tar.NamedPipe -> 'p' _ -> '-' permissions = concat [userPerms, groupPerms, otherPerms] where userPerms = formatPerms 8 7 6 11 's' groupPerms = formatPerms 5 4 3 10 's' otherPerms = formatPerms 2 1 0 9 't' formatPerms r w x s c = [if testBit m r then 'r' else '-' ,if testBit m w then 'w' else '-' ,if testBit m s then if testBit m x then c else toUpper c else if testBit m x then 'x' else '-'] m = Tar.entryPermissions entry owner = nameOrID ownerName ownerId group = nameOrID groupName groupId (Tar.Ownership ownerName groupName ownerId groupId) = Tar.entryOwnership entry nameOrID n i = if null n then show i else n size = case Tar.entryContent entry of Tar.NormalFile _ fileSize -> show fileSize _ -> "0" time = formatEpochTime "%Y-%m-%d %H:%M" (Tar.entryTime entry) name = Tar.entryPath entry link = case Tar.entryContent entry of Tar.HardLink l -> " link to " ++ Tar.fromLinkTarget l Tar.SymbolicLink l -> " -> " ++ Tar.fromLinkTarget l _ -> "" justify :: Int -> String -> String -> String justify width left right = left ++ padding ++ right where padding = replicate padWidth ' ' padWidth = max 1 (width - length left - length right) formatEpochTime :: String -> Tar.EpochTime -> String formatEpochTime f = formatTime defaultTimeLocale f . posixSecondsToUTCTime . fromIntegral ------------------------ -- Command line handling data Options = Options { optFile :: FilePath, -- "-" means stdin/stdout optDir :: FilePath, optAction :: Action, optCompression :: Compression, optVerbosity :: Verbosity } defaultOptions :: Options defaultOptions = Options { optFile = "-", optDir = "", optAction = NoAction, optCompression = None, optVerbosity = Concise } data Action = NoAction | Help | Create | Extract | List | Append deriving Show optDescr :: [OptDescr (Options -> Options)] optDescr = [ Option ['c'] ["create"] (action Create) "Create a new archive." , Option ['x'] ["extract", "get"] (action Extract) "Extract files from an archive." , Option ['t'] ["list"] (action List) "List the contents of an archive." , Option ['r'] ["append"] (action Append) "Append files to the end of an archive." , Option ['f'] ["file"] (ReqArg (\f o -> o { optFile = f}) "ARCHIVE") "Use archive file ARCHIVE." , Option ['C'] ["directory"] (ReqArg (\d o -> o { optDir = d }) "DIR") "Create or extract relative to DIR." , Option ['z'] ["gzip", "gunzip", "ungzip"] (compression GZip) "Use gzip compression." , Option ['j'] ["bzip2"] (compression BZip) "Use bzip2 compression." , Option ['v'] ["verbose"] (NoArg (\o -> o { optVerbosity = Verbose })) "Verbosely list files processed." , Option ['h', '?'] ["help"] (action Help) "Print this help output." ] where action a = NoArg (\o -> o { optAction = a }) compression c = NoArg (\o -> o { optCompression = c }) printUsage :: IO () printUsage = putStrLn (usageInfo headder optDescr) where headder = unlines ["htar creates and extracts TAR archives.", "", "Usage: htar [OPTION ...] [FILE ...]"] parseOptions :: [String] -> IO (Options, [FilePath]) parseOptions args = let (fs, files, nonopts, errors) = getOpt' Permute optDescr args in case (nonopts, errors) of ([], []) -> return $ (foldl (flip ($)) defaultOptions fs, files) (_ , (_:_)) -> die errors (_ , _) -> die (map (("unrecognized option "++).show) nonopts) die :: [String] -> IO a die errs = do mapM_ (\e -> hPutStrLn stderr $ "htar: " ++ e) $ errs hPutStrLn stderr "Try `htar --help' for more information." exitFailure
hvr/tar
htar/htar.hs
bsd-3-clause
7,382
0
15
2,187
2,125
1,157
968
178
16
{-# LANGUAGE OverloadedStrings #-} -- Module : Test.AWS.Types -- Copyright : (c) 2013-2015 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) module Test.AWS.Types where import Data.Aeson import Network.AWS.Data import Network.AWS.Prelude import Test.Tasty.HUnit newtype Entries a = Entries a deriving (Eq, Show) instance FromXML a => FromXML (Entries a) where parseXML x = Entries <$> x .@ "Entries" assertXML :: (FromXML a, Show a, Eq a) => LazyByteString -> a -> Assertion assertXML s x = (decodeXML s >>= parseXML) @?= Right x assertJSON :: (FromJSON a, Show a, Eq a) => LazyByteString -> a -> Assertion assertJSON s x = eitherDecode' s @?= Right x
kim/amazonka
core/test/Test/AWS/Types.hs
mpl-2.0
1,051
0
8
228
212
118
94
14
1
module Verify.Graphics.Vty.Prelude ( module Verify.Graphics.Vty.Prelude , MockWindow(..) ) where import Graphics.Vty.Debug import Verify data EmptyWindow = EmptyWindow MockWindow instance Arbitrary EmptyWindow where arbitrary = return $ EmptyWindow (MockWindow (0 :: Int) (0 :: Int)) instance Show EmptyWindow where show (EmptyWindow _) = "EmptyWindow" instance Arbitrary MockWindow where arbitrary = do w <- choose (1,1024) h <- choose (1,1024) return $ MockWindow w h
jtdaugherty/vty
test/Verify/Graphics/Vty/Prelude.hs
bsd-3-clause
519
0
10
112
162
90
72
15
0
{-# Language BangPatterns #-} {- | Here are the serialization and deserialization functions. This module cooperates with the generated code to implement the Wire instances. The encoding is mostly documented at <http://code.google.com/apis/protocolbuffers/docs/encoding.html>. The user API functions are grouped into sections and documented. The rest are for internal use. The main functions are 'messageGet' and 'messagePut' (and 'messageSize'). There are then several 'message*' variants which allow for finer control and for making delimited messages. -} module Text.ProtocolBuffers.WireMessage ( -- * User API functions -- ** Main encoding and decoding operations (non-delimited message encoding) messageSize,messagePut,messageGet,messagePutM,messageGetM -- ** These should agree with the length delimited message format of protobuf-2.10, where the message size preceeds the data. , messageWithLengthSize,messageWithLengthPut,messageWithLengthGet,messageWithLengthPutM,messageWithLengthGetM -- ** Encoding to write or read a single message field (good for delimited messages or incremental use) , messageAsFieldSize,messageAsFieldPutM,messageAsFieldGetM -- ** The Put monad from the binary package, and a custom binary Get monad ("Text.ProtocolBuffers.Get") , Put,Get,runPut,runGet,runGetOnLazy,getFromBS -- * The Wire monad itself. Users should beware that passing an incompatible 'FieldType' is a runtime error or fail , Wire(..) -- * The internal exports, for use by generated code and the "Text.ProtcolBuffer.Extensions" module , size'WireTag,toWireType,toWireTag,toPackedWireTag,mkWireTag , prependMessageSize,putSize,putVarUInt,getVarInt,putLazyByteString,splitWireTag,fieldIdOf , wireSizeReq,wireSizeOpt,wireSizeRep,wireSizePacked , wirePutReq,wirePutOpt,wirePutRep,wirePutPacked , wireSizeErr,wirePutErr,wireGetErr , getMessageWith,getBareMessageWith,wireGetEnum,wireGetPackedEnum , unknownField,unknown,wireGetFromWire , castWord64ToDouble,castWord32ToFloat,castDoubleToWord64,castFloatToWord32 , zzEncode64,zzEncode32,zzDecode64,zzDecode32 ) where import Control.Monad(when) import Control.Monad.Error.Class(throwError) import Control.Monad.ST import Data.Array.ST(newArray,readArray) import Data.Array.Unsafe(castSTUArray) import Data.Bits (Bits(..)) --import qualified Data.ByteString as S(last) --import qualified Data.ByteString.Unsafe as S(unsafeIndex) import qualified Data.ByteString.Lazy as BS (length) import qualified Data.Foldable as F(foldl',forM_) --import Data.List (genericLength) import Data.Maybe(fromMaybe) import Data.Sequence ((|>)) import qualified Data.Sequence as Seq(length,empty) import qualified Data.Set as Set(delete,null) import Data.Typeable (Typeable,typeOf) -- GHC internals for getting at Double and Float representation as Word64 and Word32 -- This has been superceded by the ST array trick (ugly, but promised to work) --import GHC.Exts (Double(D#),Float(F#),unsafeCoerce#) --import GHC.Word (Word64(W64#)) -- ,Word32(W32#)) -- binary package import Data.Binary.Put (Put,runPut,putWord8,putWord32le,putWord64le,putLazyByteString) import Text.ProtocolBuffers.Basic import Text.ProtocolBuffers.Get as Get (Result(..),Get,runGet,runGetAll,bytesRead,isReallyEmpty,decode7unrolled ,spanOf,skip,lookAhead,highBitRun -- ,getByteString,getWord8,decode7 ,getWord32le,getWord64le,getLazyByteString) import Text.ProtocolBuffers.Reflections(ReflectDescriptor(reflectDescriptorInfo,getMessageInfo) ,DescriptorInfo(..),GetMessageInfo(..)) -- import Debug.Trace(trace) trace :: a -> b -> b trace _ = id -- External user API for writing and reading messages -- | This computes the size of the message's fields with tags on the -- wire with no initial tag or length (in bytes). This is also the -- length of the message as placed between group start and stop tags. messageSize :: (ReflectDescriptor msg,Wire msg) => msg -> WireSize messageSize msg = wireSize 10 msg -- | This computes the size of the message fields as in 'messageSize' -- and add the length of the encoded size to the total. Thus this is -- the the length of the message including the encoded length header, -- but without any leading tag. messageWithLengthSize :: (ReflectDescriptor msg,Wire msg) => msg -> WireSize messageWithLengthSize msg = wireSize 11 msg -- | This computes the size of the 'messageWithLengthSize' and then -- adds the length an initial tag with the given 'FieldId'. messageAsFieldSize :: (ReflectDescriptor msg,Wire msg) => FieldId -> msg -> WireSize messageAsFieldSize fi msg = let headerSize = size'WireTag (toWireTag fi 11) in headerSize + messageWithLengthSize msg -- | This is 'runPut' applied to 'messagePutM'. It result in a -- 'ByteString' with a length of 'messageSize' bytes. messagePut :: (ReflectDescriptor msg, Wire msg) => msg -> ByteString messagePut msg = runPut (messagePutM msg) -- | This is 'runPut' applied to 'messageWithLengthPutM'. It results -- in a 'ByteString' with a length of 'messageWithLengthSize' bytes. messageWithLengthPut :: (ReflectDescriptor msg, Wire msg) => msg -> ByteString messageWithLengthPut msg = runPut (messageWithLengthPutM msg) -- | This writes just the message's fields with tags to the wire. This -- 'Put' monad can be composed and eventually executed with 'runPut'. -- -- This is actually @ wirePut 10 msg @ messagePutM :: (ReflectDescriptor msg, Wire msg) => msg -> Put messagePutM msg = wirePut 10 msg -- | This writes the encoded length of the message's fields and then -- the message's fields with tags to the wire. This 'Put' monad can -- be composed and eventually executed with 'runPut'. -- -- This is actually @ wirePut 11 msg @ messageWithLengthPutM :: (ReflectDescriptor msg, Wire msg) => msg -> Put messageWithLengthPutM msg = wirePut 11 msg -- | This writes an encoded wire tag with the given 'FieldId' and then -- the encoded length of the message's fields and then the message's -- fields with tags to the wire. This 'Put' monad can be composed -- and eventually executed with 'runPut'. messageAsFieldPutM :: (ReflectDescriptor msg, Wire msg) => FieldId -> msg -> Put messageAsFieldPutM fi msg = let wireTag = toWireTag fi 11 in wirePutReq wireTag 11 msg -- | This consumes the 'ByteString' to decode a message. It assumes -- the 'ByteString' is merely a sequence of the tagged fields of the -- message, and consumes until a group stop tag is detected or the -- entire input is consumed. Any 'ByteString' past the end of the -- stop tag is returned as well. -- -- This is 'runGetOnLazy' applied to 'messageGetM'. messageGet :: (ReflectDescriptor msg, Wire msg) => ByteString -> Either String (msg,ByteString) messageGet bs = runGetOnLazy messageGetM bs -- | This 'runGetOnLazy' applied to 'messageWithLengthGetM'. -- -- This first reads the encoded length of the message and will then -- succeed when it has consumed precisely this many additional bytes. -- The 'ByteString' after this point will be returned. messageWithLengthGet :: (ReflectDescriptor msg, Wire msg) => ByteString -> Either String (msg,ByteString) messageWithLengthGet bs = runGetOnLazy messageWithLengthGetM bs -- | This reads the tagged message fields until the stop tag or the -- end of input is reached. -- -- This is actually @ wireGet 10 msg @ messageGetM :: (ReflectDescriptor msg, Wire msg) => Get msg messageGetM = wireGet 10 -- | This reads the encoded message length and then the message. -- -- This is actually @ wireGet 11 msg @ messageWithLengthGetM :: (ReflectDescriptor msg, Wire msg) => Get msg messageWithLengthGetM = wireGet 11 -- | This reads a wire tag (must be of type '2') to get the 'FieldId'. -- Then the encoded message length is read, followed by the message -- itself. Both the 'FieldId' and the message are returned. -- -- This allows for incremental reading and processing. messageAsFieldGetM :: (ReflectDescriptor msg, Wire msg) => Get (FieldId,msg) messageAsFieldGetM = do wireTag <- fmap WireTag getVarInt let (fieldId,wireType) = splitWireTag wireTag when (wireType /= 2) (throwError $ "messageAsFieldGetM: wireType was not 2 "++show (fieldId,wireType)) msg <- wireGet 11 return (fieldId,msg) -- more functions -- | This is 'runGetOnLazy' with the 'Left' results converted to -- 'error' calls and the trailing 'ByteString' discarded. This use of -- runtime errors is discouraged, but may be convenient. getFromBS :: Get r -> ByteString -> r getFromBS parser bs = case runGetOnLazy parser bs of Left msg -> error msg Right (r,_) -> r -- This is like 'runGet', without the ability to pass in more input -- beyond the initial ByteString. Thus the 'ByteString' argument is -- taken to be the entire input. To be able to incrementally feed in -- more input you should use 'runGet' and respond to 'Partial' -- differently. runGetOnLazy :: Get r -> ByteString -> Either String (r,ByteString) runGetOnLazy parser bs = resolve (runGetAll parser bs) where resolve :: Result r -> Either String (r,ByteString) resolve (Failed i s) = Left ("Failed at "++show i++" : "++s) resolve (Finished bsOut _i r) = Right (r,bsOut) resolve (Partial op) = resolve (op Nothing) -- should be impossible -- | Used in generated code. prependMessageSize :: WireSize -> WireSize prependMessageSize n = n + size'WireSize n {-# INLINE wirePutReq #-} -- | Used in generated code. wirePutReq :: Wire v => WireTag -> FieldType -> v -> Put wirePutReq wireTag 10 v = let startTag = getWireTag wireTag endTag = succ startTag in putVarUInt startTag >> wirePut 10 v >> putVarUInt endTag wirePutReq wireTag fieldType v = putVarUInt (getWireTag wireTag) >> wirePut fieldType v {-# INLINE wirePutOpt #-} -- | Used in generated code. wirePutOpt :: Wire v => WireTag -> FieldType -> Maybe v -> Put wirePutOpt _wireTag _fieldType Nothing = return () wirePutOpt wireTag fieldType (Just v) = wirePutReq wireTag fieldType v {-# INLINE wirePutRep #-} -- | Used in generated code. wirePutRep :: Wire v => WireTag -> FieldType -> Seq v -> Put wirePutRep wireTag fieldType vs = F.forM_ vs (\v -> wirePutReq wireTag fieldType v) {-# INLINE wirePutPacked #-} -- | Used in generated code. wirePutPacked :: Wire v => WireTag -> FieldType -> Seq v -> Put wirePutPacked wireTag fieldType vs = do putVarUInt (getWireTag wireTag) let size = F.foldl' (\n v -> n + wireSize fieldType v) 0 vs putSize size F.forM_ vs (\v -> wirePut fieldType v) {-# INLINE wireSizeReq #-} -- | Used in generated code. wireSizeReq :: Wire v => Int64 -> FieldType -> v -> Int64 wireSizeReq tagSize 10 v = tagSize + wireSize 10 v + tagSize wireSizeReq tagSize fieldType v = tagSize + wireSize fieldType v {-# INLINE wireSizeOpt #-} -- | Used in generated code. wireSizeOpt :: Wire v => Int64 -> FieldType -> Maybe v -> Int64 wireSizeOpt _tagSize _i Nothing = 0 wireSizeOpt tagSize i (Just v) = wireSizeReq tagSize i v {-# INLINE wireSizeRep #-} -- | Used in generated code. wireSizeRep :: Wire v => Int64 -> FieldType -> Seq v -> Int64 wireSizeRep tagSize i vs = F.foldl' (\n v -> n + wireSizeReq tagSize i v) 0 vs {-# INLINE wireSizePacked #-} -- | Used in generated code. wireSizePacked :: Wire v => Int64 -> FieldType -> Seq v -> Int64 wireSizePacked tagSize i vs = tagSize + prependMessageSize (F.foldl' (\n v -> n + wireSize i v) 0 vs) {-# INLINE putSize #-} -- | Used in generated code. putSize :: WireSize -> Put putSize = putVarUInt toPackedWireTag :: FieldId -> WireTag toPackedWireTag fieldId = mkWireTag fieldId 2 {- packed always uses Length delimited and has wire type of 2 -} toWireTag :: FieldId -> FieldType -> WireTag toWireTag fieldId fieldType = mkWireTag fieldId (toWireType fieldType) mkWireTag :: FieldId -> WireType -> WireTag mkWireTag fieldId wireType = ((fromIntegral . getFieldId $ fieldId) `shiftL` 3) .|. (fromIntegral . getWireType $ wireType) splitWireTag :: WireTag -> (FieldId,WireType) splitWireTag (WireTag wireTag) = ( FieldId . fromIntegral $ wireTag `shiftR` 3 , WireType . fromIntegral $ wireTag .&. 7 ) fieldIdOf :: WireTag -> FieldId fieldIdOf = fst . splitWireTag {-# INLINE wireGetPackedEnum #-} wireGetPackedEnum :: (Typeable e,Enum e) => (Int -> Maybe e) -> Get (Seq e) wireGetPackedEnum toMaybe'Enum = do packedLength <- getVarInt start <- bytesRead let stop = packedLength+start next !soFar = do here <- bytesRead case compare stop here of EQ -> return soFar LT -> tooMuchData packedLength soFar start here GT -> do value <- wireGetEnum toMaybe'Enum seq value $ next (soFar |> value) next Seq.empty where Just e = undefined `asTypeOf` (toMaybe'Enum undefined) tooMuchData packedLength soFar start here = throwError ("Text.ProtocolBuffers.WireMessage.wireGetPackedEnum: overran expected length." ++ "\n The type and count of values so far is " ++ show (typeOf (undefined `asTypeOf` e),Seq.length soFar) ++ "\n at (packedLength,start,here) == " ++ show (packedLength,start,here)) {-# INLINE genericPacked #-} genericPacked :: Wire a => FieldType -> Get (Seq a) genericPacked ft = do packedLength <- getVarInt start <- bytesRead let stop = packedLength+start next !soFar = do here <- bytesRead case compare stop here of EQ -> return soFar LT -> tooMuchData packedLength soFar start here GT -> do value <- wireGet ft seq value $! next $! soFar |> value next Seq.empty where tooMuchData packedLength soFar start here = throwError ("Text.ProtocolBuffers.WireMessage.genericPacked: overran expected length." ++ "\n The FieldType and count of values so far are " ++ show (ft,Seq.length soFar) ++ "\n at (packedLength,start,here) == " ++ show (packedLength,start,here)) -- getMessageWith assumes the wireTag for the message, if it existed, has already been read. -- getMessageWith assumes that it still needs to read the Varint encoded length of the message. getMessageWith :: (Default message, ReflectDescriptor message) -- => (WireTag -> FieldId -> WireType -> message -> Get message) => (WireTag -> message -> Get message) -> Get message {- manyTAT.bin testing INLINE getMessageWith but made slower -} getMessageWith updater = do messageLength <- getVarInt start <- bytesRead let stop = messageLength+start -- switch from go to go' once all the required fields have been found go reqs !message | Set.null reqs = go' message | otherwise = do here <- bytesRead case compare stop here of EQ -> notEnoughData messageLength start LT -> tooMuchData messageLength start here GT -> do wireTag <- fmap WireTag getVarInt -- get tag off wire let -- (fieldId,wireType) = splitWireTag wireTag reqs' = Set.delete wireTag reqs updater wireTag {- fieldId wireType -} message >>= go reqs' go' !message = do here <- bytesRead case compare stop here of EQ -> return message LT -> tooMuchData messageLength start here GT -> do wireTag <- fmap WireTag getVarInt -- get tag off wire -- let (fieldId,wireType) = splitWireTag wireTag updater wireTag {- fieldId wireType -} message >>= go' go required initialMessage where initialMessage = defaultValue (GetMessageInfo {requiredTags=required}) = getMessageInfo initialMessage notEnoughData messageLength start = throwError ("Text.ProtocolBuffers.WireMessage.getMessageWith: Required fields missing when processing " ++ (show . descName . reflectDescriptorInfo $ initialMessage) ++ "\n at (messageLength,start) == " ++ show (messageLength,start)) tooMuchData messageLength start here = throwError ("Text.ProtocolBuffers.WireMessage.getMessageWith: overran expected length when processing" ++ (show . descName . reflectDescriptorInfo $ initialMessage) ++ "\n at (messageLength,start,here) == " ++ show (messageLength,start,here)) -- | Used by generated code -- getBareMessageWith assumes the wireTag for the message, if it existed, has already been read. -- getBareMessageWith assumes that it does needs to read the Varint encoded length of the message. -- getBareMessageWith will consume the entire ByteString it is operating on, or until it -- finds any STOP_GROUP tag (wireType == 4) getBareMessageWith :: (Default message, ReflectDescriptor message) -- => (WireTag -> FieldId -> WireType -> message -> Get message) -- handle wireTags that are unknown or produce errors => (WireTag -> message -> Get message) -- handle wireTags that are unknown or produce errors -> Get message {- manyTAT.bin testing INLINE getBareMessageWith but made slower -} getBareMessageWith updater = go required initialMessage where go reqs !message | Set.null reqs = go' message | otherwise = do done <- isReallyEmpty if done then notEnoughData else do wireTag <- fmap WireTag getVarInt -- get tag off wire let (_fieldId,wireType) = splitWireTag wireTag if wireType == 4 then notEnoughData -- END_GROUP too soon else let reqs' = Set.delete wireTag reqs in updater wireTag {- fieldId wireType -} message >>= go reqs' go' !message = do done <- isReallyEmpty if done then return message else do wireTag <- fmap WireTag getVarInt -- get tag off wire let (_fieldId,wireType) = splitWireTag wireTag if wireType == 4 then return message else updater wireTag {- fieldId wireType -} message >>= go' initialMessage = defaultValue (GetMessageInfo {requiredTags=required}) = getMessageInfo initialMessage notEnoughData = throwError ("Text.ProtocolBuffers.WireMessage.getBareMessageWith: Required fields missing when processing " ++ (show . descName . reflectDescriptorInfo $ initialMessage)) unknownField :: Typeable a => a -> FieldId -> Get a unknownField msg fieldId = do here <- bytesRead throwError ("Impossible? Text.ProtocolBuffers.WireMessage.unknownField" ++"\n Updater for "++show (typeOf msg)++" claims there is an unknown field id on wire: "++show fieldId ++"\n at a position just before byte location "++show here) unknown :: (Typeable a,ReflectDescriptor a) => FieldId -> WireType -> a -> Get a unknown fieldId wireType initialMessage = do here <- bytesRead throwError ("Text.ProtocolBuffers.WireMessage.unknown: Unknown field found or failure parsing field (e.g. unexpected Enum value):" ++ "\n (message type name,field id number,wire type code,bytes read) == " ++ show (typeOf initialMessage,fieldId,wireType,here) ++ "\n when processing " ++ (show . descName . reflectDescriptorInfo $ initialMessage)) {-# INLINE castWord32ToFloat #-} castWord32ToFloat :: Word32 -> Float --castWord32ToFloat (W32# w) = F# (unsafeCoerce# w) --castWord32ToFloat x = unsafePerformIO $ alloca $ \p -> poke p x >> peek (castPtr p) castWord32ToFloat x = runST (newArray (0::Int,0) x >>= castSTUArray >>= flip readArray 0) {-# INLINE castFloatToWord32 #-} castFloatToWord32 :: Float -> Word32 --castFloatToWord32 (F# f) = W32# (unsafeCoerce# f) castFloatToWord32 x = runST (newArray (0::Int,0) x >>= castSTUArray >>= flip readArray 0) {-# INLINE castWord64ToDouble #-} castWord64ToDouble :: Word64 -> Double -- castWord64ToDouble (W64# w) = D# (unsafeCoerce# w) castWord64ToDouble x = runST (newArray (0::Int,0) x >>= castSTUArray >>= flip readArray 0) {-# INLINE castDoubleToWord64 #-} castDoubleToWord64 :: Double -> Word64 -- castDoubleToWord64 (D# d) = W64# (unsafeCoerce# d) castDoubleToWord64 x = runST (newArray (0::Int,0) x >>= castSTUArray >>= flip readArray 0) -- These error handlers are exported to the generated code wireSizeErr :: Typeable a => FieldType -> a -> WireSize wireSizeErr ft x = error $ concat [ "Impossible? wireSize field type mismatch error: Field type number ", show ft , " does not match internal type ", show (typeOf x) ] wirePutErr :: Typeable a => FieldType -> a -> Put wirePutErr ft x = fail $ concat [ "Impossible? wirePut field type mismatch error: Field type number ", show ft , " does not match internal type ", show (typeOf x) ] wireGetErr :: Typeable a => FieldType -> Get a wireGetErr ft = answer where answer = throwError $ concat [ "Impossible? wireGet field type mismatch error: Field type number ", show ft , " does not match internal type ", show (typeOf (undefined `asTypeOf` typeHack answer)) ] typeHack :: Get a -> a typeHack = undefined -- | The 'Wire' class is for internal use, and may change. If there -- is a mis-match between the 'FieldType' and the type of @b@ then you -- will get a failure at runtime. -- -- Users should stick to the message functions defined in -- "Text.ProtocolBuffers.WireMessage" and exported to use user by -- "Text.ProtocolBuffers". These are less likely to change. class Wire b where wireSize :: FieldType -> b -> WireSize wirePut :: FieldType -> b -> Put wireGet :: FieldType -> Get b {-# INLINE wireGetPacked #-} wireGetPacked :: FieldType -> Get (Seq b) wireGetPacked ft = throwError ("Text.ProtocolBuffers.ProtoCompile.Basic: wireGetPacked default:" ++ "\n There is no way to get a packed FieldType of "++show ft ++ ".\n Either there is a bug in this library or the wire format is has been updated.") instance Wire Double where {-# INLINE wireSize #-} wireSize {- TYPE_DOUBLE -} 1 _ = 8 wireSize ft x = wireSizeErr ft x {-# INLINE wirePut #-} wirePut {- TYPE_DOUBLE -} 1 x = putWord64le (castDoubleToWord64 x) wirePut ft x = wirePutErr ft x {-# INLINE wireGet #-} wireGet {- TYPE_DOUBLE -} 1 = fmap castWord64ToDouble getWord64le wireGet ft = wireGetErr ft {-# INLINE wireGetPacked #-} wireGetPacked 1 = genericPacked 1 wireGetPacked ft = wireGetErr ft instance Wire Float where {-# INLINE wireSize #-} wireSize {- TYPE_FLOAT -} 2 _ = 4 wireSize ft x = wireSizeErr ft x {-# INLINE wirePut #-} wirePut {- TYPE_FLOAT -} 2 x = putWord32le (castFloatToWord32 x) wirePut ft x = wirePutErr ft x {-# INLINE wireGet #-} wireGet {- TYPE_FLOAT -} 2 = fmap castWord32ToFloat getWord32le wireGet ft = wireGetErr ft {-# INLINE wireGetPacked #-} wireGetPacked 2 = genericPacked 2 wireGetPacked ft = wireGetErr ft instance Wire Int64 where {-# INLINE wireSize #-} wireSize {- TYPE_INT64 -} 3 x = size'Int64 x wireSize {- TYPE_SINT64 -} 18 x = size'Word64 (zzEncode64 x) wireSize {- TYPE_SFIXED64 -} 16 _ = 8 wireSize ft x = wireSizeErr ft x {-# INLINE wirePut #-} wirePut {- TYPE_INT64 -} 3 x = putVarSInt x wirePut {- TYPE_SINT64 -} 18 x = putVarUInt (zzEncode64 x) wirePut {- TYPE_SFIXED64 -} 16 x = putWord64le (fromIntegral x) wirePut ft x = wirePutErr ft x {-# INLINE wireGet #-} wireGet {- TYPE_INT64 -} 3 = getVarInt wireGet {- TYPE_SINT64 -} 18 = fmap zzDecode64 getVarInt wireGet {- TYPE_SFIXED64 -} 16 = fmap fromIntegral getWord64le wireGet ft = wireGetErr ft {-# INLINE wireGetPacked #-} wireGetPacked 3 = genericPacked 3 wireGetPacked 18 = genericPacked 18 wireGetPacked 16 = genericPacked 16 wireGetPacked ft = wireGetErr ft instance Wire Int32 where {-# INLINE wireSize #-} wireSize {- TYPE_INT32 -} 5 x = size'Int32 x wireSize {- TYPE_SINT32 -} 17 x = size'Word32 (zzEncode32 x) wireSize {- TYPE_SFIXED32 -} 15 _ = 4 wireSize ft x = wireSizeErr ft x {-# INLINE wirePut #-} wirePut {- TYPE_INT32 -} 5 x = putVarSInt x wirePut {- TYPE_SINT32 -} 17 x = putVarUInt (zzEncode32 x) wirePut {- TYPE_SFIXED32 -} 15 x = putWord32le (fromIntegral x) wirePut ft x = wirePutErr ft x {-# INLINE wireGet #-} wireGet {- TYPE_INT32 -} 5 = getVarInt wireGet {- TYPE_SINT32 -} 17 = fmap zzDecode32 getVarInt wireGet {- TYPE_SFIXED32 -} 15 = fmap fromIntegral getWord32le wireGet ft = wireGetErr ft {-# INLINE wireGetPacked #-} wireGetPacked 5 = genericPacked 5 wireGetPacked 17 = genericPacked 17 wireGetPacked 15 = genericPacked 15 wireGetPacked ft = wireGetErr ft instance Wire Word64 where {-# INLINE wireSize #-} wireSize {- TYPE_UINT64 -} 4 x = size'Word64 x wireSize {- TYPE_FIXED64 -} 6 _ = 8 wireSize ft x = wireSizeErr ft x {-# INLINE wirePut #-} wirePut {- TYPE_UINT64 -} 4 x = putVarUInt x wirePut {- TYPE_FIXED64 -} 6 x = putWord64le x wirePut ft x = wirePutErr ft x {-# INLINE wireGet #-} wireGet {- TYPE_FIXED64 -} 6 = getWord64le wireGet {- TYPE_UINT64 -} 4 = getVarInt wireGet ft = wireGetErr ft {-# INLINE wireGetPacked #-} wireGetPacked 6 = genericPacked 6 wireGetPacked 4 = genericPacked 4 wireGetPacked ft = wireGetErr ft instance Wire Word32 where {-# INLINE wireSize #-} wireSize {- TYPE_UINT32 -} 13 x = size'Word32 x wireSize {- TYPE_FIXED32 -} 7 _ = 4 wireSize ft x = wireSizeErr ft x {-# INLINE wirePut #-} wirePut {- TYPE_UINT32 -} 13 x = putVarUInt x wirePut {- TYPE_FIXED32 -} 7 x = putWord32le x wirePut ft x = wirePutErr ft x {-# INLINE wireGet #-} wireGet {- TYPE_UINT32 -} 13 = getVarInt wireGet {- TYPE_FIXED32 -} 7 = getWord32le wireGet ft = wireGetErr ft {-# INLINE wireGetPacked #-} wireGetPacked 13 = genericPacked 13 wireGetPacked 7 = genericPacked 7 wireGetPacked ft = wireGetErr ft instance Wire Bool where {-# INLINE wireSize #-} wireSize {- TYPE_BOOL -} 8 _ = 1 wireSize ft x = wireSizeErr ft x {-# INLINE wirePut #-} wirePut {- TYPE_BOOL -} 8 False = putWord8 0 wirePut {- TYPE_BOOL -} 8 True = putWord8 1 -- google's wire_format_lite_inl.h wirePut ft x = wirePutErr ft x {-# INLINE wireGet #-} wireGet {- TYPE_BOOL -} 8 = do x <- getVarInt :: Get Int32 -- google's wire_format_lit_inl.h line 155 case x of 0 -> return False _ -> return True -- x' | x' < 128 -> return True -- _ -> throwError ("TYPE_BOOL read failure : " ++ show x) wireGet ft = wireGetErr ft {-# INLINE wireGetPacked #-} wireGetPacked 8 = genericPacked 8 wireGetPacked ft = wireGetErr ft instance Wire Utf8 where -- items of TYPE_STRING is already in a UTF8 encoded Data.ByteString.Lazy {-# INLINE wireSize #-} wireSize {- TYPE_STRING -} 9 x = prependMessageSize $ BS.length (utf8 x) wireSize ft x = wireSizeErr ft x {-# INLINE wirePut #-} wirePut {- TYPE_STRING -} 9 x = putVarUInt (BS.length (utf8 x)) >> putLazyByteString (utf8 x) wirePut ft x = wirePutErr ft x {-# INLINE wireGet #-} wireGet {- TYPE_STRING -} 9 = getVarInt >>= getLazyByteString >>= verifyUtf8 wireGet ft = wireGetErr ft instance Wire ByteString where -- items of TYPE_BYTES is an untyped binary Data.ByteString.Lazy {-# INLINE wireSize #-} wireSize {- TYPE_BYTES -} 12 x = prependMessageSize $ BS.length x wireSize ft x = wireSizeErr ft x {-# INLINE wirePut #-} wirePut {- TYPE_BYTES -} 12 x = putVarUInt (BS.length x) >> putLazyByteString x wirePut ft x = wirePutErr ft x {-# INLINE wireGet #-} wireGet {- TYPE_BYTES -} 12 = getVarInt >>= getLazyByteString wireGet ft = wireGetErr ft -- Wrap a protocol-buffer Enum in fromEnum or toEnum and serialize the Int: instance Wire Int where {-# INLINE wireSize #-} wireSize {- TYPE_ENUM -} 14 x = size'Int x wireSize ft x = wireSizeErr ft x {-# INLINE wirePut #-} wirePut {- TYPE_ENUM -} 14 x = putVarSInt x wirePut ft x = wirePutErr ft x {-# INLINE wireGet #-} wireGet {- TYPE_ENUM -} 14 = getVarInt wireGet ft = wireGetErr ft {-# INLINE wireGetPacked #-} wireGetPacked 14 = genericPacked 14 -- Should not actually be used, see wireGetPackedEnum, though this ought to work if it were used (e.g. genericPacked) wireGetPacked ft = wireGetErr ft {-# INLINE verifyUtf8 #-} verifyUtf8 :: ByteString -> Get Utf8 verifyUtf8 bs = case isValidUTF8 bs of Nothing -> return (Utf8 bs) Just i -> throwError $ "Text.ProtocolBuffers.WireMessage.verifyUtf8: ByteString is not valid utf8 at position "++show i {-# INLINE wireGetEnum #-} wireGetEnum :: (Typeable e, Enum e) => (Int -> Maybe e) -> Get e wireGetEnum toMaybe'Enum = do int <- wireGet 14 -- uses the "instance Wire Int" defined above case toMaybe'Enum int of Just !v -> return v Nothing -> throwError (msg ++ show int) where msg = "Bad wireGet of Enum "++show (typeOf (undefined `asTypeOf` typeHack toMaybe'Enum))++", unrecognized Int value is " typeHack :: (Int -> Maybe e) -> e typeHack f = fromMaybe undefined (f undefined) -- This will have to examine the value of positive numbers to get the size size'WireTag :: WireTag -> Int64 size'WireTag = size'Word32 . getWireTag size'Word32 :: Word32 -> Int64 size'Word32 b | b <= 0x7F = 1 | b <= 0x3FFF = 2 | b <= 0x1FFFFF = 3 | b <= 0xFFFFFFF = 4 | otherwise = 5 size'Int32 :: Int32 -> Int64 size'Int32 b | b < 0 = 10 | b <= 0x7F = 1 | b <= 0x3FFF = 2 | b <= 0x1FFFFF = 3 | b <= 0xFFFFFFF = 4 | otherwise = 5 size'Word64 :: Word64 -> Int64 size'Word64 b | b <= 0x7F = 1 | b <= 0x3FFF = 2 | b <= 0x1FFFFF = 3 | b <= 0xFFFFFFF = 4 | b <= 0X7FFFFFFFF = 5 | b <= 0x3FFFFFFFFFF = 6 | b <= 0x1FFFFFFFFFFFF = 7 | b <= 0xFFFFFFFFFFFFFF = 8 | b <= 0x7FFFFFFFFFFFFFFF = 9 | otherwise = 10 -- Should work for Int of 32 and 64 bits size'Int :: Int -> Int64 size'Int b | b < 0 = 10 | b <= 0x7F = 1 | b <= 0x3FFF = 2 | b <= 0x1FFFFF = 3 | b <= 0xFFFFFFF = 4 | b <= 0x7FFFFFFF = 5 -- maxBound :: Int32 | b <= 0x7FFFFFFFF = 5 | b <= 0x3FFFFFFFFFF = 6 | b <= 0x1FFFFFFFFFFFF = 7 | b <= 0xFFFFFFFFFFFFFF = 8 | otherwise = 9 size'Int64,size'WireSize :: Int64 -> Int64 size'WireSize = size'Int64 size'Int64 b | b < 0 = 10 | b <= 0x7F = 1 | b <= 0x3FFF = 2 | b <= 0x1FFFFF = 3 | b <= 0xFFFFFFF = 4 | b <= 0x7FFFFFFFF = 5 | b <= 0x3FFFFFFFFFF = 6 | b <= 0x1FFFFFFFFFFFF = 7 | b <= 0xFFFFFFFFFFFFFF = 8 | otherwise = 9 {- size'Varint :: (Integral b, Bits b) => b -> Int64 {-# INLINE size'Varint #-} size'Varint b = case compare b 0 of LT -> 10 -- fromIntegral (divBy (bitSize b) 7) EQ -> 1 GT -> genericLength . takeWhile (0<) . iterate (`shiftR` 7) $ b -} -- Taken from google's code, but I had to explcitly add fromIntegral in the right places: zzEncode32 :: Int32 -> Word32 zzEncode32 x = fromIntegral ((x `shiftL` 1) `xor` (x `shiftR` 31)) zzEncode64 :: Int64 -> Word64 zzEncode64 x = fromIntegral ((x `shiftL` 1) `xor` (x `shiftR` 63)) zzDecode32 :: Word32 -> Int32 zzDecode32 w = (fromIntegral (w `shiftR` 1)) `xor` (negate (fromIntegral (w .&. 1))) zzDecode64 :: Word64 -> Int64 zzDecode64 w = (fromIntegral (w `shiftR` 1)) `xor` (negate (fromIntegral (w .&. 1))) {- -- The above is tricky, so the testing roundtrips and versus examples is needed: testZZ :: Bool testZZ = and (concat testsZZ) where testsZZ = [ map (\v -> v ==zzEncode64 (zzDecode64 v)) values , map (\v -> v ==zzEncode32 (zzDecode32 v)) values , map (\v -> v ==zzDecode64 (zzEncode64 v)) values , map (\v -> v ==zzDecode32 (zzEncode32 v)) values , [ zzEncode32 minBound == maxBound , zzEncode32 maxBound == pred maxBound , zzEncode64 minBound == maxBound , zzEncode64 maxBound == pred maxBound , zzEncode64 0 == 0, zzEncode32 0 == 0 , zzEncode64 (-1) == 1, zzEncode32 (-1) == 1 , zzEncode64 1 == 2, zzEncode32 1 == 2 ] ] let values :: (Bounded a,Integral a) => [a]; values = [minBound,div minBound 2 - 1,div minBound 2, div minBound 2 + 1,-257,-256,-255,-129,-128,-127,-3,-2,-1,0,1,2,3,127,128,129,255,256,257,div maxBound 2 - 1, div maxBound 2, div maxBound 2 + 1, maxBound] -} getVarInt :: (Show a, Integral a, Bits a) => Get a {-# INLINE getVarInt #-} --getVarInt = decode7unrolled -- decode7 -- getVarInt below getVarInt = do a <- decode7unrolled trace ("getVarInt: "++show a) $ return a {- getVarInt = do -- optimize first read instead of calling (go 0 0) b <- getWord8 if testBit b 7 then go 7 (fromIntegral (b .&. 0x7F)) else return (fromIntegral b) where go n val = do b <- getWord8 if testBit b 7 then go (n+7) (val .|. ((fromIntegral (b .&. 0x7F)) `shiftL` n)) else return (val .|. ((fromIntegral b) `shiftL` n)) -} -- This can be used on any Integral type and is needed for signed types; unsigned can use putVarUInt below. -- This has been changed to handle only up to 64 bit integral values (to match documentation). {-# INLINE putVarSInt #-} putVarSInt :: (Integral a, Bits a) => a -> Put putVarSInt bIn = case compare bIn 0 of LT -> let b :: Int64 -- upcast to 64 bit to match documentation of 10 bytes for all negative values b = fromIntegral bIn len :: Int len = 10 -- (pred 10)*7 < 64 <= 10*7 last'Mask = 1 -- pred (1 `shiftL` 1) go !i 1 = putWord8 (fromIntegral (i .&. last'Mask)) go !i n = putWord8 (fromIntegral (i .&. 0x7F) .|. 0x80) >> go (i `shiftR` 7) (pred n) in go b len EQ -> putWord8 0 GT -> putVarUInt bIn -- This should be used on unsigned Integral types only (not checked) {-# INLINE putVarUInt #-} putVarUInt :: (Integral a, Bits a) => a -> Put putVarUInt i | i < 0x80 = putWord8 (fromIntegral i) | otherwise = putWord8 (fromIntegral (i .&. 0x7F) .|. 0x80) >> putVarUInt (i `shiftR` 7) -- | This reads in the raw bytestring corresponding to an field known -- only through the wiretag's 'FieldId' and 'WireType'. wireGetFromWire :: FieldId -> WireType -> Get ByteString wireGetFromWire fi wt = getLazyByteString =<< calcLen where calcLen = case wt of 0 -> highBitRun -- lenOf (spanOf (>=128) >> skip 1) 1 -> return 8 2 -> lookAhead $ do here <- bytesRead len <- getVarInt there <- bytesRead return ((there-here)+len) 3 -> lenOf (skipGroup fi) 4 -> throwError $ "Cannot wireGetFromWire with wireType of STOP_GROUP: "++show (fi,wt) 5 -> return 4 wtf -> throwError $ "Invalid wire type (expected 0,1,2,3,or 5) found: "++show (fi,wtf) lenOf g = do here <- bytesRead there <- lookAhead (g >> bytesRead) trace (":wireGetFromWire.lenOf: "++show ((fi,wt),(here,there,there-here))) $ return (there-here) -- | After a group start tag with the given 'FieldId' this will skip -- ahead in the stream past the end tag of that group. Used by -- 'wireGetFromWire' to help compule the length of an unknown field -- when loading an extension. skipGroup :: FieldId -> Get () skipGroup start_fi = go where go = do (fieldId,wireType) <- fmap (splitWireTag . WireTag) getVarInt case wireType of 0 -> spanOf (>=128) >> skip 1 >> go 1 -> skip 8 >> go 2 -> getVarInt >>= skip >> go 3 -> skipGroup fieldId >> go 4 | start_fi /= fieldId -> throwError $ "skipGroup failed, fieldId mismatch bewteen START_GROUP and STOP_GROUP: "++show (start_fi,(fieldId,wireType)) | otherwise -> return () 5 -> skip 4 >> go wtf -> throwError $ "Invalid wire type (expected 0,1,2,3,4,or 5) found: "++show (fieldId,wtf) {- enum WireType { WIRETYPE_VARINT = 0, WIRETYPE_FIXED64 = 1, WIRETYPE_LENGTH_DELIMITED = 2, WIRETYPE_START_GROUP = 3, WIRETYPE_END_GROUP = 4, WIRETYPE_FIXED32 = 5, }; FieldType is TYPE_DOUBLE = 1; TYPE_FLOAT = 2; TYPE_INT64 = 3; TYPE_UINT64 = 4; TYPE_INT32 = 5; TYPE_FIXED64 = 6; TYPE_FIXED32 = 7; TYPE_BOOL = 8; TYPE_STRING = 9; TYPE_GROUP = 10; // Tag-delimited aggregate. TYPE_MESSAGE = 11; TYPE_BYTES = 12; TYPE_UINT32 = 13; TYPE_ENUM = 14; TYPE_SFIXED32 = 15; TYPE_SFIXED64 = 16; TYPE_SINT32 = 17; TYPE_SINT64 = 18; -} -- http://code.google.com/apis/protocolbuffers/docs/encoding.html toWireType :: FieldType -> WireType toWireType 1 = 1 toWireType 2 = 5 toWireType 3 = 0 toWireType 4 = 0 toWireType 5 = 0 toWireType 6 = 1 toWireType 7 = 5 toWireType 8 = 0 toWireType 9 = 2 toWireType 10 = 3 -- START_GROUP toWireType 11 = 2 toWireType 12 = 2 toWireType 13 = 0 toWireType 14 = 0 toWireType 15 = 5 toWireType 16 = 1 toWireType 17 = 0 toWireType 18 = 0 toWireType x = error $ "Text.ProcolBuffers.Basic.toWireType: Bad FieldType: "++show x {- -- OPTIMIZE attempt: -- Used in bench-003-highBitrun-and-new-getVarInt and much slower -- This is a much slower variant than supplied by default in version 1.8.4 getVarInt :: (Integral a, Bits a) => Get a getVarInt = do n <- highBitRun -- n is at least 0, or an error is thrown by highBitRun s <- getByteString (succ n) -- length of s is at least 1 let go 0 val = return val go m val = let m' = pred m -- m' will be [(n-2) .. 0] val' = (val `shiftL` 7) .|. (fromIntegral (0x7F .&. S.unsafeIndex s m')) in go m' $! val' go n (fromIntegral (S.last s)) -} -- OPTIMIZE try inlinining getMessageWith and getBareMessageWith: bench-005, slower -- OPTIMIZE try NO-inlining getMessageWith and getBareMessageWith
timjb/protocol-buffers
Text/ProtocolBuffers/WireMessage.hs
apache-2.0
39,093
0
22
9,714
7,956
4,114
3,842
582
7
{-# LANGUAGE RankNTypes, TypeFamilies, PolyKinds, FunctionalDependencies #-} module T16946 where import Data.Kind class CatMonad (c :: k -> k -> Type) (m :: forall (x :: k) (y :: k). c x y -> Type -> Type) | c -> m where type Id c :: c x x xpure :: a -> m (Id c) a boom :: forall k (c :: k -> k -> Type) (m :: forall (x :: k) (y :: k). c x y -> Type -> Type) a. CatMonad c m => a -> m (Id c) a boom = xpure
sdiehl/ghc
testsuite/tests/typecheck/should_fail/T16946.hs
bsd-3-clause
415
0
10
106
203
116
87
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Bag: an unordered collection with duplicates -} {-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables #-} module Bag ( Bag, -- abstract type emptyBag, unitBag, unionBags, unionManyBags, mapBag, elemBag, lengthBag, filterBag, partitionBag, partitionBagWith, concatBag, foldBag, foldrBag, foldlBag, isEmptyBag, isSingletonBag, consBag, snocBag, anyBag, listToBag, bagToList, foldrBagM, foldlBagM, mapBagM, mapBagM_, flatMapBagM, flatMapBagPairM, mapAndUnzipBagM, mapAccumBagLM ) where import Outputable import Util import MonadUtils import Data.Data import Data.List ( partition ) infixr 3 `consBag` infixl 3 `snocBag` data Bag a = EmptyBag | UnitBag a | TwoBags (Bag a) (Bag a) -- INVARIANT: neither branch is empty | ListBag [a] -- INVARIANT: the list is non-empty deriving Typeable emptyBag :: Bag a emptyBag = EmptyBag unitBag :: a -> Bag a unitBag = UnitBag lengthBag :: Bag a -> Int lengthBag EmptyBag = 0 lengthBag (UnitBag {}) = 1 lengthBag (TwoBags b1 b2) = lengthBag b1 + lengthBag b2 lengthBag (ListBag xs) = length xs elemBag :: Eq a => a -> Bag a -> Bool elemBag _ EmptyBag = False elemBag x (UnitBag y) = x == y elemBag x (TwoBags b1 b2) = x `elemBag` b1 || x `elemBag` b2 elemBag x (ListBag ys) = any (x ==) ys unionManyBags :: [Bag a] -> Bag a unionManyBags xs = foldr unionBags EmptyBag xs -- This one is a bit stricter! The bag will get completely evaluated. unionBags :: Bag a -> Bag a -> Bag a unionBags EmptyBag b = b unionBags b EmptyBag = b unionBags b1 b2 = TwoBags b1 b2 consBag :: a -> Bag a -> Bag a snocBag :: Bag a -> a -> Bag a consBag elt bag = (unitBag elt) `unionBags` bag snocBag bag elt = bag `unionBags` (unitBag elt) isEmptyBag :: Bag a -> Bool isEmptyBag EmptyBag = True isEmptyBag _ = False -- NB invariants isSingletonBag :: Bag a -> Bool isSingletonBag EmptyBag = False isSingletonBag (UnitBag _) = True isSingletonBag (TwoBags _ _) = False -- Neither is empty isSingletonBag (ListBag xs) = isSingleton xs filterBag :: (a -> Bool) -> Bag a -> Bag a filterBag _ EmptyBag = EmptyBag filterBag pred b@(UnitBag val) = if pred val then b else EmptyBag filterBag pred (TwoBags b1 b2) = sat1 `unionBags` sat2 where sat1 = filterBag pred b1 sat2 = filterBag pred b2 filterBag pred (ListBag vs) = listToBag (filter pred vs) anyBag :: (a -> Bool) -> Bag a -> Bool anyBag _ EmptyBag = False anyBag p (UnitBag v) = p v anyBag p (TwoBags b1 b2) = anyBag p b1 || anyBag p b2 anyBag p (ListBag xs) = any p xs concatBag :: Bag (Bag a) -> Bag a concatBag EmptyBag = EmptyBag concatBag (UnitBag b) = b concatBag (TwoBags b1 b2) = concatBag b1 `unionBags` concatBag b2 concatBag (ListBag bs) = unionManyBags bs partitionBag :: (a -> Bool) -> Bag a -> (Bag a {- Satisfy predictate -}, Bag a {- Don't -}) partitionBag _ EmptyBag = (EmptyBag, EmptyBag) partitionBag pred b@(UnitBag val) = if pred val then (b, EmptyBag) else (EmptyBag, b) partitionBag pred (TwoBags b1 b2) = (sat1 `unionBags` sat2, fail1 `unionBags` fail2) where (sat1, fail1) = partitionBag pred b1 (sat2, fail2) = partitionBag pred b2 partitionBag pred (ListBag vs) = (listToBag sats, listToBag fails) where (sats, fails) = partition pred vs partitionBagWith :: (a -> Either b c) -> Bag a -> (Bag b {- Left -}, Bag c {- Right -}) partitionBagWith _ EmptyBag = (EmptyBag, EmptyBag) partitionBagWith pred (UnitBag val) = case pred val of Left a -> (UnitBag a, EmptyBag) Right b -> (EmptyBag, UnitBag b) partitionBagWith pred (TwoBags b1 b2) = (sat1 `unionBags` sat2, fail1 `unionBags` fail2) where (sat1, fail1) = partitionBagWith pred b1 (sat2, fail2) = partitionBagWith pred b2 partitionBagWith pred (ListBag vs) = (listToBag sats, listToBag fails) where (sats, fails) = partitionWith pred vs foldBag :: (r -> r -> r) -- Replace TwoBags with this; should be associative -> (a -> r) -- Replace UnitBag with this -> r -- Replace EmptyBag with this -> Bag a -> r {- Standard definition foldBag t u e EmptyBag = e foldBag t u e (UnitBag x) = u x foldBag t u e (TwoBags b1 b2) = (foldBag t u e b1) `t` (foldBag t u e b2) foldBag t u e (ListBag xs) = foldr (t.u) e xs -} -- More tail-recursive definition, exploiting associativity of "t" foldBag _ _ e EmptyBag = e foldBag t u e (UnitBag x) = u x `t` e foldBag t u e (TwoBags b1 b2) = foldBag t u (foldBag t u e b2) b1 foldBag t u e (ListBag xs) = foldr (t.u) e xs foldrBag :: (a -> r -> r) -> r -> Bag a -> r foldrBag _ z EmptyBag = z foldrBag k z (UnitBag x) = k x z foldrBag k z (TwoBags b1 b2) = foldrBag k (foldrBag k z b2) b1 foldrBag k z (ListBag xs) = foldr k z xs foldlBag :: (r -> a -> r) -> r -> Bag a -> r foldlBag _ z EmptyBag = z foldlBag k z (UnitBag x) = k z x foldlBag k z (TwoBags b1 b2) = foldlBag k (foldlBag k z b1) b2 foldlBag k z (ListBag xs) = foldl k z xs foldrBagM :: (Monad m) => (a -> b -> m b) -> b -> Bag a -> m b foldrBagM _ z EmptyBag = return z foldrBagM k z (UnitBag x) = k x z foldrBagM k z (TwoBags b1 b2) = do { z' <- foldrBagM k z b2; foldrBagM k z' b1 } foldrBagM k z (ListBag xs) = foldrM k z xs foldlBagM :: (Monad m) => (b -> a -> m b) -> b -> Bag a -> m b foldlBagM _ z EmptyBag = return z foldlBagM k z (UnitBag x) = k z x foldlBagM k z (TwoBags b1 b2) = do { z' <- foldlBagM k z b1; foldlBagM k z' b2 } foldlBagM k z (ListBag xs) = foldlM k z xs mapBag :: (a -> b) -> Bag a -> Bag b mapBag _ EmptyBag = EmptyBag mapBag f (UnitBag x) = UnitBag (f x) mapBag f (TwoBags b1 b2) = TwoBags (mapBag f b1) (mapBag f b2) mapBag f (ListBag xs) = ListBag (map f xs) mapBagM :: Monad m => (a -> m b) -> Bag a -> m (Bag b) mapBagM _ EmptyBag = return EmptyBag mapBagM f (UnitBag x) = do r <- f x return (UnitBag r) mapBagM f (TwoBags b1 b2) = do r1 <- mapBagM f b1 r2 <- mapBagM f b2 return (TwoBags r1 r2) mapBagM f (ListBag xs) = do rs <- mapM f xs return (ListBag rs) mapBagM_ :: Monad m => (a -> m b) -> Bag a -> m () mapBagM_ _ EmptyBag = return () mapBagM_ f (UnitBag x) = f x >> return () mapBagM_ f (TwoBags b1 b2) = mapBagM_ f b1 >> mapBagM_ f b2 mapBagM_ f (ListBag xs) = mapM_ f xs flatMapBagM :: Monad m => (a -> m (Bag b)) -> Bag a -> m (Bag b) flatMapBagM _ EmptyBag = return EmptyBag flatMapBagM f (UnitBag x) = f x flatMapBagM f (TwoBags b1 b2) = do r1 <- flatMapBagM f b1 r2 <- flatMapBagM f b2 return (r1 `unionBags` r2) flatMapBagM f (ListBag xs) = foldrM k EmptyBag xs where k x b2 = do { b1 <- f x; return (b1 `unionBags` b2) } flatMapBagPairM :: Monad m => (a -> m (Bag b, Bag c)) -> Bag a -> m (Bag b, Bag c) flatMapBagPairM _ EmptyBag = return (EmptyBag, EmptyBag) flatMapBagPairM f (UnitBag x) = f x flatMapBagPairM f (TwoBags b1 b2) = do (r1,s1) <- flatMapBagPairM f b1 (r2,s2) <- flatMapBagPairM f b2 return (r1 `unionBags` r2, s1 `unionBags` s2) flatMapBagPairM f (ListBag xs) = foldrM k (EmptyBag, EmptyBag) xs where k x (r2,s2) = do { (r1,s1) <- f x ; return (r1 `unionBags` r2, s1 `unionBags` s2) } mapAndUnzipBagM :: Monad m => (a -> m (b,c)) -> Bag a -> m (Bag b, Bag c) mapAndUnzipBagM _ EmptyBag = return (EmptyBag, EmptyBag) mapAndUnzipBagM f (UnitBag x) = do (r,s) <- f x return (UnitBag r, UnitBag s) mapAndUnzipBagM f (TwoBags b1 b2) = do (r1,s1) <- mapAndUnzipBagM f b1 (r2,s2) <- mapAndUnzipBagM f b2 return (TwoBags r1 r2, TwoBags s1 s2) mapAndUnzipBagM f (ListBag xs) = do ts <- mapM f xs let (rs,ss) = unzip ts return (ListBag rs, ListBag ss) mapAccumBagLM :: Monad m => (acc -> x -> m (acc, y)) -- ^ combining funcction -> acc -- ^ initial state -> Bag x -- ^ inputs -> m (acc, Bag y) -- ^ final state, outputs mapAccumBagLM _ s EmptyBag = return (s, EmptyBag) mapAccumBagLM f s (UnitBag x) = do { (s1, x1) <- f s x; return (s1, UnitBag x1) } mapAccumBagLM f s (TwoBags b1 b2) = do { (s1, b1') <- mapAccumBagLM f s b1 ; (s2, b2') <- mapAccumBagLM f s1 b2 ; return (s2, TwoBags b1' b2') } mapAccumBagLM f s (ListBag xs) = do { (s', xs') <- mapAccumLM f s xs ; return (s', ListBag xs') } listToBag :: [a] -> Bag a listToBag [] = EmptyBag listToBag vs = ListBag vs bagToList :: Bag a -> [a] bagToList b = foldrBag (:) [] b instance (Outputable a) => Outputable (Bag a) where ppr bag = braces (pprWithCommas ppr (bagToList bag)) instance Data a => Data (Bag a) where gfoldl k z b = z listToBag `k` bagToList b -- traverse abstract type abstractly toConstr _ = abstractConstr $ "Bag("++show (typeOf (undefined::a))++")" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "Bag" dataCast1 x = gcast1 x
forked-upstream-packages-for-ghcjs/ghc
compiler/utils/Bag.hs
bsd-3-clause
9,822
0
11
3,067
3,876
1,972
1,904
204
2
module Tests.Writers.Native (tests) where import Test.Framework import Text.Pandoc.Builder import Text.Pandoc import Tests.Helpers import Tests.Arbitrary() p_write_rt :: Pandoc -> Bool p_write_rt d = read (writeNative defaultWriterOptions{ writerStandalone = True } d) == d p_write_blocks_rt :: [Block] -> Bool p_write_blocks_rt bs = length bs > 20 || read (writeNative defaultWriterOptions (Pandoc (Meta [] [] []) bs)) == bs tests :: [Test] tests = [ property "p_write_rt" p_write_rt , property "p_write_blocks_rt" p_write_blocks_rt ]
beni55/pandoc
src/Tests/Writers/Native.hs
gpl-2.0
562
0
14
96
180
98
82
16
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Network.HTTP.ReverseProxy.Rewrite ( ReverseProxyConfig (..) , RewriteRule (..) , RPEntry (..) , simpleReverseProxy ) where import Control.Applicative import Control.Exception (bracket) import Data.Function (fix) import Data.Monoid ((<>)) import qualified Data.Set as Set import Data.Set (Set) import qualified Data.Map as Map import Data.Map ( Map ) import Data.Array ((!)) import Data.Aeson import Control.Monad (unless) import qualified Data.ByteString as S import qualified Data.Text as T import Data.Text (Text) import Data.Text.Encoding (encodeUtf8, decodeUtf8) import qualified Data.CaseInsensitive as CI import Blaze.ByteString.Builder (fromByteString) -- Configuration files import Data.Default -- Regular expression parsing, replacement, matching import Data.Attoparsec.Text (string, takeWhile1, endOfInput, parseOnly, Parser) import Text.Regex.TDFA (makeRegex, matchOnceText, MatchText) import Text.Regex.TDFA.String (Regex) import Data.Char (isDigit) -- Reverse proxy apparatus import qualified Network.Wai as Wai import Network.HTTP.Client.Conduit import qualified Network.HTTP.Client as NHC import Network.HTTP.Types data RPEntry = RPEntry { config :: ReverseProxyConfig , httpManager :: Manager } instance Show RPEntry where show x = "RPEntry { config = " ++ (show $ config x) ++ " }" getGroup :: MatchText String -> Int -> String getGroup matches i = fst $ matches ! i rewrite :: (String, MatchText String, String) -> String -> String -> Text rewrite (before, match, after) input replacement = case parseOnly parseSubstitute (T.pack replacement) of Left _ -> T.pack input Right result -> T.pack before <> result <> T.pack after where parseSubstitute :: Parser Text parseSubstitute = (endOfInput >> "") <|> do { _ <- string "\\\\" ; rest <- parseSubstitute ; return $ "\\" <> rest } <|> do { _ <- string "\\" ; n <- (fmap (read . T.unpack) $ takeWhile1 isDigit) :: Parser Int ; rest <- parseSubstitute ; return $ T.pack (getGroup match n) <> rest } <|> do { text <- takeWhile1 (/= '\\') ; rest <- parseSubstitute ; return $ text <> rest } rewriteHeader :: Map HeaderName RewriteRule -> Header -> Header rewriteHeader rules header@(name, value) = case Map.lookup name rules of Nothing -> header Just r -> (name, regexRewrite r value) rewriteHeaders :: Map HeaderName RewriteRule -> [Header] -> [Header] rewriteHeaders ruleMap = map (rewriteHeader ruleMap) regexRewrite :: RewriteRule -> S.ByteString -> S.ByteString regexRewrite (RewriteRule _ regex' replacement) input = case matchOnceText regex strInput of Just match -> encodeUtf8 $ rewrite match strInput strReplacement Nothing -> input where strRegex = T.unpack regex' regex :: Regex regex = makeRegex strRegex strInput = T.unpack . decodeUtf8 $ input strReplacement = T.unpack replacement filterHeaders :: [Header] -> [Header] filterHeaders = filter useHeader where useHeader ("Transfer-Encoding", _) = False useHeader ("Content-Length", _) = False useHeader ("Host", _) = False useHeader _ = True mkRuleMap :: Set RewriteRule -> Map HeaderName RewriteRule mkRuleMap = Map.fromList . map (\k -> (CI.mk . encodeUtf8 $ ruleHeader k, k)) . Set.toList mkRequest :: ReverseProxyConfig -> Wai.Request -> Request mkRequest rpConfig request = def { method = Wai.requestMethod request , secure = reverseUseSSL rpConfig , host = encodeUtf8 $ reversedHost rpConfig , port = reversedPort rpConfig , path = Wai.rawPathInfo request , queryString = Wai.rawQueryString request , requestHeaders = filterHeaders $ rewriteHeaders reqRuleMap (Wai.requestHeaders request) , requestBody = case Wai.requestBodyLength request of Wai.ChunkedBody -> RequestBodyStreamChunked ($ Wai.requestBody request) Wai.KnownLength n -> RequestBodyStream (fromIntegral n) ($ Wai.requestBody request) , decompress = const False , redirectCount = 0 , checkStatus = \_ _ _ -> Nothing , responseTimeout = reverseTimeout rpConfig , cookieJar = Nothing } where reqRuleMap = mkRuleMap $ rewriteRequestRules rpConfig simpleReverseProxy :: Manager -> ReverseProxyConfig -> Wai.Application simpleReverseProxy mgr rpConfig request sendResponse = bracket (NHC.responseOpen proxiedRequest mgr) responseClose $ \res -> sendResponse $ Wai.responseStream (responseStatus res) (rewriteHeaders respRuleMap $ responseHeaders res) (sendBody $ responseBody res) where proxiedRequest = mkRequest rpConfig request respRuleMap = mkRuleMap $ rewriteResponseRules rpConfig sendBody body send _flush = fix $ \loop -> do bs <- body unless (S.null bs) $ do () <- send $ fromByteString bs loop data ReverseProxyConfig = ReverseProxyConfig { reversedHost :: Text , reversedPort :: Int , reversingHost :: Text , reverseUseSSL :: Bool , reverseTimeout :: Maybe Int , rewriteResponseRules :: Set RewriteRule , rewriteRequestRules :: Set RewriteRule } deriving (Eq, Ord, Show) instance FromJSON ReverseProxyConfig where parseJSON (Object o) = ReverseProxyConfig <$> o .: "reversed-host" <*> o .: "reversed-port" <*> o .: "reversing-host" <*> o .:? "ssl" .!= False <*> o .:? "timeout" .!= Nothing <*> o .:? "rewrite-response" .!= Set.empty <*> o .:? "rewrite-request" .!= Set.empty parseJSON _ = fail "Wanted an object" instance ToJSON ReverseProxyConfig where toJSON ReverseProxyConfig {..} = object [ "reversed-host" .= reversedHost , "reversed-port" .= reversedPort , "reversing-host" .= reversingHost , "ssl" .= reverseUseSSL , "timeout" .= reverseTimeout , "rewrite-response" .= rewriteResponseRules , "rewrite-request" .= rewriteRequestRules ] instance Default ReverseProxyConfig where def = ReverseProxyConfig { reversedHost = "" , reversedPort = 80 , reversingHost = "" , reverseUseSSL = False , reverseTimeout = Nothing , rewriteResponseRules = Set.empty , rewriteRequestRules = Set.empty } data RewriteRule = RewriteRule { ruleHeader :: Text , ruleRegex :: Text , ruleReplacement :: Text } deriving (Eq, Ord, Show) instance FromJSON RewriteRule where parseJSON (Object o) = RewriteRule <$> o .: "header" <*> o .: "from" <*> o .: "to" parseJSON _ = fail "Wanted an object" instance ToJSON RewriteRule where toJSON RewriteRule {..} = object [ "header" .= ruleHeader , "from" .= ruleRegex , "to" .= ruleReplacement ]
telser/keter
Network/HTTP/ReverseProxy/Rewrite.hs
mit
7,061
0
23
1,740
1,938
1,057
881
173
4
module Simple2 where f3 :: Num t => t -> t -> (t, t) f3 x y = (x + y, y - x) -- f1 :: Int -> Int -> Int f1 x y = x + y f2 x y = y - x
kmate/HaRe
old/testing/merging/Simple2_TokOut.hs
bsd-3-clause
143
0
8
55
83
45
38
5
1
-- -- The Computer Language Shootout -- http://shootout.alioth.debian.org/ -- -- compile with : ghc fastest.hs -o fastest -- -- contributed by Greg Buchholz -- Modified by Mirko Rahn, Don Stewart, Chris Kuklewicz and Lemmih -- import Data.Char main = print . new 0 =<< getContents new i [] = i new i ('-':xs) = neg 0 xs where neg n ('\n':xs) = new (i - n) xs neg n (x :xs) = neg (parse x + (10 * n)) xs new i (x:xs) = pos (parse x) xs where pos n ('\n':xs) = new (i + n) xs pos n (x :xs) = pos (parse x + (10 * n)) xs parse c = ord c - ord '0'
hvr/jhc
regress/tests/8_shootout/SumFile.hs
mit
585
0
11
160
251
131
120
10
3
{-# Language PartialTypeSignatures, RankNTypes #-} module Foo where f xs = let ys = reverse xs in ys `seq` let w = length xs in w + length (reverse (case ys of { a:as -> as; [] -> [] }))
sdiehl/ghc
testsuite/tests/simplCore/should_compile/T15631.hs
bsd-3-clause
219
0
18
72
90
47
43
6
2
module Typed.Manual (benchmarks) where import Control.Applicative import Criterion import Data.Aeson hiding (Result) import Data.ByteString.Builder as B import Data.ByteString.Lazy as L import Twitter.Manual import Typed.Common encodeDirect :: Result -> L.ByteString encodeDirect = encode encodeViaValue :: Result -> L.ByteString encodeViaValue = encode . toJSON benchmarks :: Benchmark benchmarks = env ((,) <$> load "json-data/twitter100.json" <*> load "json-data/jp100.json") $ \ ~(twitter100, jp100) -> bgroup "manual" [ bgroup "direct" [ bench "twitter100" $ nf encodeDirect twitter100 , bench "jp100" $ nf encodeDirect jp100 ] , bgroup "viaValue" [ bench "twitter100" $ nf encodeViaValue twitter100 , bench "jp100" $ nf encodeViaValue jp100 ] ]
23Skidoo/aeson
benchmarks/Typed/Manual.hs
bsd-3-clause
813
0
12
161
222
121
101
22
1
import StackTest import System.Directory main :: IO () main = do isAlpine <- getIsAlpine if isAlpine || isARM then logInfo "Disabled on Alpine Linux and ARM since it cannot yet install its own GHC." else do run "cabal" ["sandbox", "init"] stack ["unpack", "acme-dont-1.1"] run "cabal" ["install", "./acme-dont-1.1"] removeDirectoryRecursive "acme-dont-1.1" stack ["--install-ghc", "init", "--solver"] stack ["build"]
AndreasPK/stack
test/integration/tests/cabal-solver/Main.hs
bsd-3-clause
466
0
11
104
119
59
60
14
2
foreign import ccall "foo" c_foo :: IO Int main = c_foo >>= print
ezyang/ghc
testsuite/tests/ghci/linking/dyn/big-obj.hs
bsd-3-clause
67
0
6
14
25
13
12
2
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , NoImplicitPrelude , ExistentialQuantification #-} {-# OPTIONS_GHC -funbox-strict-fields #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Handle.Types -- Copyright : (c) The University of Glasgow, 1994-2009 -- License : see libraries/base/LICENSE -- -- Maintainer : libraries@haskell.org -- Stability : internal -- Portability : non-portable -- -- Basic types for the implementation of IO Handles. -- ----------------------------------------------------------------------------- module GHC.IO.Handle.Types ( Handle(..), Handle__(..), showHandle, checkHandleInvariants, BufferList(..), HandleType(..), isReadableHandleType, isWritableHandleType, isReadWriteHandleType, BufferMode(..), BufferCodec(..), NewlineMode(..), Newline(..), nativeNewline, universalNewlineMode, noNewlineTranslation, nativeNewlineMode ) where #undef DEBUG import GHC.Base import GHC.MVar import GHC.IO import GHC.IO.Buffer import GHC.IO.BufferedIO import GHC.IO.Encoding.Types import GHC.IORef import GHC.Show import GHC.Read import GHC.Word import GHC.IO.Device import Data.Typeable #ifdef DEBUG import Control.Monad #endif -- --------------------------------------------------------------------------- -- Handle type -- A Handle is represented by (a reference to) a record -- containing the state of the I/O port/device. We record -- the following pieces of info: -- * type (read,write,closed etc.) -- * the underlying file descriptor -- * buffering mode -- * buffer, and spare buffers -- * user-friendly name (usually the -- FilePath used when IO.openFile was called) -- Note: when a Handle is garbage collected, we want to flush its buffer -- and close the OS file handle, so as to free up a (precious) resource. -- | Haskell defines operations to read and write characters from and to files, -- represented by values of type @Handle@. Each value of this type is a -- /handle/: a record used by the Haskell run-time system to /manage/ I\/O -- with file system objects. A handle has at least the following properties: -- -- * whether it manages input or output or both; -- -- * whether it is /open/, /closed/ or /semi-closed/; -- -- * whether the object is seekable; -- -- * whether buffering is disabled, or enabled on a line or block basis; -- -- * a buffer (whose length may be zero). -- -- Most handles will also have a current I\/O position indicating where the next -- input or output operation will occur. A handle is /readable/ if it -- manages only input or both input and output; likewise, it is /writable/ if -- it manages only output or both input and output. A handle is /open/ when -- first allocated. -- Once it is closed it can no longer be used for either input or output, -- though an implementation cannot re-use its storage while references -- remain to it. Handles are in the 'Show' and 'Eq' classes. The string -- produced by showing a handle is system dependent; it should include -- enough information to identify the handle for debugging. A handle is -- equal according to '==' only to itself; no attempt -- is made to compare the internal state of different handles for equality. data Handle = FileHandle -- A normal handle to a file FilePath -- the file (used for error messages -- only) !(MVar Handle__) | DuplexHandle -- A handle to a read/write stream FilePath -- file for a FIFO, otherwise some -- descriptive string (used for error -- messages only) !(MVar Handle__) -- The read side !(MVar Handle__) -- The write side -- NOTES: -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be -- seekable. instance Eq Handle where (FileHandle _ h1) == (FileHandle _ h2) = h1 == h2 (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2 _ == _ = False data Handle__ = forall dev enc_state dec_state . (IODevice dev, BufferedIO dev, Typeable dev) => Handle__ { haDevice :: !dev, haType :: HandleType, -- type (read/write/append etc.) haByteBuffer :: !(IORef (Buffer Word8)), haBufferMode :: BufferMode, haLastDecode :: !(IORef (dec_state, Buffer Word8)), haCharBuffer :: !(IORef (Buffer CharBufElem)), -- the current buffer haBuffers :: !(IORef (BufferList CharBufElem)), -- spare buffers haEncoder :: Maybe (TextEncoder enc_state), haDecoder :: Maybe (TextDecoder dec_state), haCodec :: Maybe TextEncoding, haInputNL :: Newline, haOutputNL :: Newline, haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a -- duplex handle. } -- we keep a few spare buffers around in a handle to avoid allocating -- a new one for each hPutStr. These buffers are *guaranteed* to be the -- same size as the main buffer. data BufferList e = BufferListNil | BufferListCons (RawBuffer e) (BufferList e) -- Internally, we classify handles as being one -- of the following: data HandleType = ClosedHandle | SemiClosedHandle | ReadHandle | WriteHandle | AppendHandle | ReadWriteHandle isReadableHandleType :: HandleType -> Bool isReadableHandleType ReadHandle = True isReadableHandleType ReadWriteHandle = True isReadableHandleType _ = False isWritableHandleType :: HandleType -> Bool isWritableHandleType AppendHandle = True isWritableHandleType WriteHandle = True isWritableHandleType ReadWriteHandle = True isWritableHandleType _ = False isReadWriteHandleType :: HandleType -> Bool isReadWriteHandleType ReadWriteHandle{} = True isReadWriteHandleType _ = False -- INVARIANTS on Handles: -- -- * A handle *always* has a buffer, even if it is only 1 character long -- (an unbuffered handle needs a 1 character buffer in order to support -- hLookAhead and hIsEOF). -- * In a read Handle, the byte buffer is always empty (we decode when reading) -- * In a wriite Handle, the Char buffer is always empty (we encode when writing) -- checkHandleInvariants :: Handle__ -> IO () #ifdef DEBUG checkHandleInvariants h_ = do bbuf <- readIORef (haByteBuffer h_) checkBuffer bbuf cbuf <- readIORef (haCharBuffer h_) checkBuffer cbuf when (isWriteBuffer cbuf && not (isEmptyBuffer cbuf)) $ error ("checkHandleInvariants: char write buffer non-empty: " ++ summaryBuffer bbuf ++ ", " ++ summaryBuffer cbuf) when (isWriteBuffer bbuf /= isWriteBuffer cbuf) $ error ("checkHandleInvariants: buffer modes differ: " ++ summaryBuffer bbuf ++ ", " ++ summaryBuffer cbuf) #else checkHandleInvariants _ = return () #endif -- --------------------------------------------------------------------------- -- Buffering modes -- | Three kinds of buffering are supported: line-buffering, -- block-buffering or no-buffering. These modes have the following -- effects. For output, items are written out, or /flushed/, -- from the internal buffer according to the buffer mode: -- -- * /line-buffering/: the entire output buffer is flushed -- whenever a newline is output, the buffer overflows, -- a 'System.IO.hFlush' is issued, or the handle is closed. -- -- * /block-buffering/: the entire buffer is written out whenever it -- overflows, a 'System.IO.hFlush' is issued, or the handle is closed. -- -- * /no-buffering/: output is written immediately, and never stored -- in the buffer. -- -- An implementation is free to flush the buffer more frequently, -- but not less frequently, than specified above. -- The output buffer is emptied as soon as it has been written out. -- -- Similarly, input occurs according to the buffer mode for the handle: -- -- * /line-buffering/: when the buffer for the handle is not empty, -- the next item is obtained from the buffer; otherwise, when the -- buffer is empty, characters up to and including the next newline -- character are read into the buffer. No characters are available -- until the newline character is available or the buffer is full. -- -- * /block-buffering/: when the buffer for the handle becomes empty, -- the next block of data is read into the buffer. -- -- * /no-buffering/: the next input item is read and returned. -- The 'System.IO.hLookAhead' operation implies that even a no-buffered -- handle may require a one-character buffer. -- -- The default buffering mode when a handle is opened is -- implementation-dependent and may depend on the file system object -- which is attached to that handle. -- For most implementations, physical files will normally be block-buffered -- and terminals will normally be line-buffered. data BufferMode = NoBuffering -- ^ buffering is disabled if possible. | LineBuffering -- ^ line-buffering should be enabled if possible. | BlockBuffering (Maybe Int) -- ^ block-buffering should be enabled if possible. -- The size of the buffer is @n@ items if the argument -- is 'Just' @n@ and is otherwise implementation-dependent. deriving (Eq, Ord, Read, Show) {- [note Buffering Implementation] Each Handle has two buffers: a byte buffer (haByteBuffer) and a Char buffer (haCharBuffer). [note Buffered Reading] For read Handles, bytes are read into the byte buffer, and immediately decoded into the Char buffer (see GHC.IO.Handle.Internals.readTextDevice). The only way there might be some data left in the byte buffer is if there is a partial multi-byte character sequence that cannot be decoded into a full character. Note that the buffering mode (haBufferMode) makes no difference when reading data into a Handle. When reading, we can always just read all the data there is available without blocking, decode it into the Char buffer, and then provide it immediately to the caller. [note Buffered Writing] Characters are written into the Char buffer by e.g. hPutStr. At the end of the operation, or when the char buffer is full, the buffer is decoded to the byte buffer (see writeCharBuffer). This is so that we can detect encoding errors at the right point. Hence, the Char buffer is always empty between Handle operations. [note Buffer Sizing] The char buffer is always a default size (dEFAULT_CHAR_BUFFER_SIZE). The byte buffer size is chosen by the underlying device (via its IODevice.newBuffer). Hence the size of these buffers is not under user control. There are certain minimum sizes for these buffers imposed by the library (but not checked): - we must be able to buffer at least one character, so that hLookAhead can work - the byte buffer must be able to store at least one encoded character in the current encoding (6 bytes?) - when reading, the char buffer must have room for two characters, so that we can spot the \r\n sequence. How do we implement hSetBuffering? For reading, we have never used the user-supplied buffer size, because there's no point: we always pass all available data to the reader immediately. Buffering would imply waiting until a certain amount of data is available, which has no advantages. So hSetBuffering is essentially a no-op for read handles, except that it turns on/off raw mode for the underlying device if necessary. For writing, the buffering mode is handled by the write operations themselves (hPutChar and hPutStr). Every write ends with writeCharBuffer, which checks whether the buffer should be flushed according to the current buffering mode. Additionally, we look for newlines and flush if the mode is LineBuffering. [note Buffer Flushing] ** Flushing the Char buffer We must be able to flush the Char buffer, in order to implement hSetEncoding, and things like hGetBuf which want to read raw bytes. Flushing the Char buffer on a write Handle is easy: it is always empty. Flushing the Char buffer on a read Handle involves rewinding the byte buffer to the point representing the next Char in the Char buffer. This is done by - remembering the state of the byte buffer *before* the last decode - re-decoding the bytes that represent the chars already read from the Char buffer. This gives us the point in the byte buffer that represents the *next* Char to be read. In order for this to work, after readTextHandle we must NOT MODIFY THE CONTENTS OF THE BYTE OR CHAR BUFFERS, except to remove characters from the Char buffer. ** Flushing the byte buffer The byte buffer can be flushed if the Char buffer has already been flushed (see above). For a read Handle, flushing the byte buffer means seeking the device back by the number of bytes in the buffer, and hence it is only possible on a seekable Handle. -} -- --------------------------------------------------------------------------- -- Newline translation -- | The representation of a newline in the external file or stream. data Newline = LF -- ^ '\n' | CRLF -- ^ '\r\n' deriving (Eq, Ord, Read, Show) -- | Specifies the translation, if any, of newline characters between -- internal Strings and the external file or stream. Haskell Strings -- are assumed to represent newlines with the '\n' character; the -- newline mode specifies how to translate '\n' on output, and what to -- translate into '\n' on input. data NewlineMode = NewlineMode { inputNL :: Newline, -- ^ the representation of newlines on input outputNL :: Newline -- ^ the representation of newlines on output } deriving (Eq, Ord, Read, Show) -- | The native newline representation for the current platform: 'LF' -- on Unix systems, 'CRLF' on Windows. nativeNewline :: Newline #ifdef mingw32_HOST_OS nativeNewline = CRLF #else nativeNewline = LF #endif -- | Map '\r\n' into '\n' on input, and '\n' to the native newline -- represetnation on output. This mode can be used on any platform, and -- works with text files using any newline convention. The downside is -- that @readFile >>= writeFile@ might yield a different file. -- -- > universalNewlineMode = NewlineMode { inputNL = CRLF, -- > outputNL = nativeNewline } -- universalNewlineMode :: NewlineMode universalNewlineMode = NewlineMode { inputNL = CRLF, outputNL = nativeNewline } -- | Use the native newline representation on both input and output -- -- > nativeNewlineMode = NewlineMode { inputNL = nativeNewline -- > outputNL = nativeNewline } -- nativeNewlineMode :: NewlineMode nativeNewlineMode = NewlineMode { inputNL = nativeNewline, outputNL = nativeNewline } -- | Do no newline translation at all. -- -- > noNewlineTranslation = NewlineMode { inputNL = LF, outputNL = LF } -- noNewlineTranslation :: NewlineMode noNewlineTranslation = NewlineMode { inputNL = LF, outputNL = LF } -- --------------------------------------------------------------------------- -- Show instance for Handles -- handle types are 'show'n when printing error msgs, so -- we provide a more user-friendly Show instance for it -- than the derived one. instance Show HandleType where showsPrec _ t = case t of ClosedHandle -> showString "closed" SemiClosedHandle -> showString "semi-closed" ReadHandle -> showString "readable" WriteHandle -> showString "writable" AppendHandle -> showString "writable (append)" ReadWriteHandle -> showString "read-writable" instance Show Handle where showsPrec _ (FileHandle file _) = showHandle file showsPrec _ (DuplexHandle file _ _) = showHandle file showHandle :: FilePath -> String -> String showHandle file = showString "{handle: " . showString file . showString "}"
urbanslug/ghc
libraries/base/GHC/IO/Handle/Types.hs
bsd-3-clause
16,247
0
13
3,664
1,344
807
537
132
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Documentation.Haddock.Doc (docParagraph, docAppend, docConcat, metaDocConcat, metaDocAppend, emptyMetaDoc, metaAppend, metaConcat) where import Control.Applicative ((<|>), empty) import Documentation.Haddock.Types import Data.Char (isSpace) docConcat :: [DocH mod id] -> DocH mod id docConcat = foldr docAppend DocEmpty -- | Concat using 'metaAppend'. metaConcat :: [Meta] -> Meta metaConcat = foldr metaAppend emptyMeta -- | Like 'docConcat' but also joins the 'Meta' info. metaDocConcat :: [MetaDoc mod id] -> MetaDoc mod id metaDocConcat = foldr metaDocAppend emptyMetaDoc -- | We do something perhaps unexpected here and join the meta info -- in ‘reverse’: this results in the metadata from the ‘latest’ -- paragraphs taking precedence. metaDocAppend :: MetaDoc mod id -> MetaDoc mod id -> MetaDoc mod id metaDocAppend (MetaDoc { _meta = m, _doc = d }) (MetaDoc { _meta = m', _doc = d' }) = MetaDoc { _meta = m' `metaAppend` m, _doc = d `docAppend` d' } -- | This is not a monoidal append, it uses '<|>' for the '_version'. metaAppend :: Meta -> Meta -> Meta metaAppend (Meta { _version = v }) (Meta { _version = v' }) = Meta { _version = v <|> v' } emptyMetaDoc :: MetaDoc mod id emptyMetaDoc = MetaDoc { _meta = emptyMeta, _doc = DocEmpty } emptyMeta :: Meta emptyMeta = Meta { _version = empty } docAppend :: DocH mod id -> DocH mod id -> DocH mod id docAppend (DocDefList ds1) (DocDefList ds2) = DocDefList (ds1++ds2) docAppend (DocDefList ds1) (DocAppend (DocDefList ds2) d) = DocAppend (DocDefList (ds1++ds2)) d docAppend (DocOrderedList ds1) (DocOrderedList ds2) = DocOrderedList (ds1 ++ ds2) docAppend (DocOrderedList ds1) (DocAppend (DocOrderedList ds2) d) = DocAppend (DocOrderedList (ds1++ds2)) d docAppend (DocUnorderedList ds1) (DocUnorderedList ds2) = DocUnorderedList (ds1 ++ ds2) docAppend (DocUnorderedList ds1) (DocAppend (DocUnorderedList ds2) d) = DocAppend (DocUnorderedList (ds1++ds2)) d docAppend DocEmpty d = d docAppend d DocEmpty = d docAppend (DocString s1) (DocString s2) = DocString (s1 ++ s2) docAppend (DocAppend d (DocString s1)) (DocString s2) = DocAppend d (DocString (s1 ++ s2)) docAppend (DocString s1) (DocAppend (DocString s2) d) = DocAppend (DocString (s1 ++ s2)) d docAppend d1 d2 = DocAppend d1 d2 -- again to make parsing easier - we spot a paragraph whose only item -- is a DocMonospaced and make it into a DocCodeBlock docParagraph :: DocH mod id -> DocH mod id docParagraph (DocMonospaced p) = DocCodeBlock (docCodeBlock p) docParagraph (DocAppend (DocString s1) (DocMonospaced p)) | all isSpace s1 = DocCodeBlock (docCodeBlock p) docParagraph (DocAppend (DocString s1) (DocAppend (DocMonospaced p) (DocString s2))) | all isSpace s1 && all isSpace s2 = DocCodeBlock (docCodeBlock p) docParagraph (DocAppend (DocMonospaced p) (DocString s2)) | all isSpace s2 = DocCodeBlock (docCodeBlock p) docParagraph p = DocParagraph p -- Drop trailing whitespace from @..@ code blocks. Otherwise this: -- -- -- @ -- -- foo -- -- @ -- -- turns into (DocCodeBlock "\nfoo\n ") which when rendered in HTML -- gives an extra vertical space after the code block. The single space -- on the final line seems to trigger the extra vertical space. -- docCodeBlock :: DocH mod id -> DocH mod id docCodeBlock (DocString s) = DocString (reverse $ dropWhile (`elem` " \t") $ reverse s) docCodeBlock (DocAppend l r) = DocAppend l (docCodeBlock r) docCodeBlock d = d
DavidAlphaFox/ghc
utils/haddock/haddock-library/src/Documentation/Haddock/Doc.hs
bsd-3-clause
3,607
0
11
708
1,120
586
534
59
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE BangPatterns, NoImplicitPrelude #-} -- Copyright (c) 2008, Ralf Hinze -- 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. -- -- * The names of the contributors may not be used to endorse or -- promote products derived from this software without specific -- prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -- COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED -- OF THE POSSIBILITY OF SUCH DAMAGE. -- | A /priority search queue/ (henceforth /queue/) efficiently -- supports the operations of both a search tree and a priority queue. -- An 'Elem'ent is a product of a key, a priority, and a -- value. Elements can be inserted, deleted, modified and queried in -- logarithmic time, and the element with the least priority can be -- retrieved in constant time. A queue can be built from a list of -- elements, sorted by keys, in linear time. -- -- This implementation is due to Ralf Hinze with some modifications by -- Scott Dillard and Johan Tibell. -- -- * Hinze, R., /A Simple Implementation Technique for Priority Search -- Queues/, ICFP 2001, pp. 110-121 -- -- <http://citeseer.ist.psu.edu/hinze01simple.html> module GHC.Event.PSQ ( -- * Binding Type Elem(..) , Key , Prio -- * Priority Search Queue Type , PSQ -- * Query , size , null , lookup -- * Construction , empty , singleton -- * Insertion , insert -- * Delete/Update , delete , adjust -- * Conversion , toList , toAscList , toDescList , fromList -- * Min , findMin , deleteMin , minView , atMost ) where import Data.Maybe (Maybe(..)) import GHC.Base import GHC.Num (Num(..)) import GHC.Show (Show(showsPrec)) import GHC.Event.Unique (Unique) -- | @E k p@ binds the key @k@ with the priority @p@. data Elem a = E { key :: {-# UNPACK #-} !Key , prio :: {-# UNPACK #-} !Prio , value :: a } deriving (Eq, Show) ------------------------------------------------------------------------ -- | A mapping from keys @k@ to priorites @p@. type Prio = Double type Key = Unique data PSQ a = Void | Winner {-# UNPACK #-} !(Elem a) !(LTree a) {-# UNPACK #-} !Key -- max key deriving (Eq, Show) -- | /O(1)/ The number of elements in a queue. size :: PSQ a -> Int size Void = 0 size (Winner _ lt _) = 1 + size' lt -- | /O(1)/ True if the queue is empty. null :: PSQ a -> Bool null Void = True null (Winner _ _ _) = False -- | /O(log n)/ The priority and value of a given key, or Nothing if -- the key is not bound. lookup :: Key -> PSQ a -> Maybe (Prio, a) lookup k q = case tourView q of Null -> Nothing Single (E k' p v) | k == k' -> Just (p, v) | otherwise -> Nothing tl `Play` tr | k <= maxKey tl -> lookup k tl | otherwise -> lookup k tr ------------------------------------------------------------------------ -- Construction empty :: PSQ a empty = Void -- | /O(1)/ Build a queue with one element. singleton :: Key -> Prio -> a -> PSQ a singleton k p v = Winner (E k p v) Start k ------------------------------------------------------------------------ -- Insertion -- | /O(log n)/ Insert a new key, priority and value in the queue. If -- the key is already present in the queue, the associated priority -- and value are replaced with the supplied priority and value. insert :: Key -> Prio -> a -> PSQ a -> PSQ a insert k p v q = case q of Void -> singleton k p v Winner (E k' p' v') Start _ -> case compare k k' of LT -> singleton k p v `play` singleton k' p' v' EQ -> singleton k p v GT -> singleton k' p' v' `play` singleton k p v Winner e (RLoser _ e' tl m tr) m' | k <= m -> insert k p v (Winner e tl m) `play` (Winner e' tr m') | otherwise -> (Winner e tl m) `play` insert k p v (Winner e' tr m') Winner e (LLoser _ e' tl m tr) m' | k <= m -> insert k p v (Winner e' tl m) `play` (Winner e tr m') | otherwise -> (Winner e' tl m) `play` insert k p v (Winner e tr m') ------------------------------------------------------------------------ -- Delete/Update -- | /O(log n)/ Delete a key and its priority and value from the -- queue. When the key is not a member of the queue, the original -- queue is returned. delete :: Key -> PSQ a -> PSQ a delete k q = case q of Void -> empty Winner (E k' p v) Start _ | k == k' -> empty | otherwise -> singleton k' p v Winner e (RLoser _ e' tl m tr) m' | k <= m -> delete k (Winner e tl m) `play` (Winner e' tr m') | otherwise -> (Winner e tl m) `play` delete k (Winner e' tr m') Winner e (LLoser _ e' tl m tr) m' | k <= m -> delete k (Winner e' tl m) `play` (Winner e tr m') | otherwise -> (Winner e' tl m) `play` delete k (Winner e tr m') -- | /O(log n)/ Update a priority at a specific key with the result -- of the provided function. When the key is not a member of the -- queue, the original queue is returned. adjust :: (Prio -> Prio) -> Key -> PSQ a -> PSQ a adjust f k q0 = go q0 where go q = case q of Void -> empty Winner (E k' p v) Start _ | k == k' -> singleton k' (f p) v | otherwise -> singleton k' p v Winner e (RLoser _ e' tl m tr) m' | k <= m -> go (Winner e tl m) `unsafePlay` (Winner e' tr m') | otherwise -> (Winner e tl m) `unsafePlay` go (Winner e' tr m') Winner e (LLoser _ e' tl m tr) m' | k <= m -> go (Winner e' tl m) `unsafePlay` (Winner e tr m') | otherwise -> (Winner e' tl m) `unsafePlay` go (Winner e tr m') {-# INLINE adjust #-} ------------------------------------------------------------------------ -- Conversion -- | /O(n*log n)/ Build a queue from a list of key/priority/value -- tuples. If the list contains more than one priority and value for -- the same key, the last priority and value for the key is retained. fromList :: [Elem a] -> PSQ a fromList = foldr (\(E k p v) q -> insert k p v q) empty -- | /O(n)/ Convert to a list of key/priority/value tuples. toList :: PSQ a -> [Elem a] toList = toAscList -- | /O(n)/ Convert to an ascending list. toAscList :: PSQ a -> [Elem a] toAscList q = seqToList (toAscLists q) toAscLists :: PSQ a -> Sequ (Elem a) toAscLists q = case tourView q of Null -> emptySequ Single e -> singleSequ e tl `Play` tr -> toAscLists tl <> toAscLists tr -- | /O(n)/ Convert to a descending list. toDescList :: PSQ a -> [ Elem a ] toDescList q = seqToList (toDescLists q) toDescLists :: PSQ a -> Sequ (Elem a) toDescLists q = case tourView q of Null -> emptySequ Single e -> singleSequ e tl `Play` tr -> toDescLists tr <> toDescLists tl ------------------------------------------------------------------------ -- Min -- | /O(1)/ The element with the lowest priority. findMin :: PSQ a -> Maybe (Elem a) findMin Void = Nothing findMin (Winner e _ _) = Just e -- | /O(log n)/ Delete the element with the lowest priority. Returns -- an empty queue if the queue is empty. deleteMin :: PSQ a -> PSQ a deleteMin Void = Void deleteMin (Winner _ t m) = secondBest t m -- | /O(log n)/ Retrieve the binding with the least priority, and the -- rest of the queue stripped of that binding. minView :: PSQ a -> Maybe (Elem a, PSQ a) minView Void = Nothing minView (Winner e t m) = Just (e, secondBest t m) secondBest :: LTree a -> Key -> PSQ a secondBest Start _ = Void secondBest (LLoser _ e tl m tr) m' = Winner e tl m `play` secondBest tr m' secondBest (RLoser _ e tl m tr) m' = secondBest tl m `play` Winner e tr m' -- | /O(r*(log n - log r))/ Return a list of elements ordered by -- key whose priorities are at most @pt@. atMost :: Prio -> PSQ a -> ([Elem a], PSQ a) atMost pt q = let (sequ, q') = atMosts pt q in (seqToList sequ, q') atMosts :: Prio -> PSQ a -> (Sequ (Elem a), PSQ a) atMosts !pt q = case q of (Winner e _ _) | prio e > pt -> (emptySequ, q) Void -> (emptySequ, Void) Winner e Start _ -> (singleSequ e, Void) Winner e (RLoser _ e' tl m tr) m' -> let (sequ, q') = atMosts pt (Winner e tl m) (sequ', q'') = atMosts pt (Winner e' tr m') in (sequ <> sequ', q' `play` q'') Winner e (LLoser _ e' tl m tr) m' -> let (sequ, q') = atMosts pt (Winner e' tl m) (sequ', q'') = atMosts pt (Winner e tr m') in (sequ <> sequ', q' `play` q'') ------------------------------------------------------------------------ -- Loser tree type Size = Int data LTree a = Start | LLoser {-# UNPACK #-} !Size {-# UNPACK #-} !(Elem a) !(LTree a) {-# UNPACK #-} !Key -- split key !(LTree a) | RLoser {-# UNPACK #-} !Size {-# UNPACK #-} !(Elem a) !(LTree a) {-# UNPACK #-} !Key -- split key !(LTree a) deriving (Eq, Show) size' :: LTree a -> Size size' Start = 0 size' (LLoser s _ _ _ _) = s size' (RLoser s _ _ _ _) = s left, right :: LTree a -> LTree a left Start = moduleError "left" "empty loser tree" left (LLoser _ _ tl _ _ ) = tl left (RLoser _ _ tl _ _ ) = tl right Start = moduleError "right" "empty loser tree" right (LLoser _ _ _ _ tr) = tr right (RLoser _ _ _ _ tr) = tr maxKey :: PSQ a -> Key maxKey Void = moduleError "maxKey" "empty queue" maxKey (Winner _ _ m) = m lloser, rloser :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lloser k p v tl m tr = LLoser (1 + size' tl + size' tr) (E k p v) tl m tr rloser k p v tl m tr = RLoser (1 + size' tl + size' tr) (E k p v) tl m tr ------------------------------------------------------------------------ -- Balancing -- | Balance factor omega :: Int omega = 4 lbalance, rbalance :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lbalance k p v l m r | size' l + size' r < 2 = lloser k p v l m r | size' r > omega * size' l = lbalanceLeft k p v l m r | size' l > omega * size' r = lbalanceRight k p v l m r | otherwise = lloser k p v l m r rbalance k p v l m r | size' l + size' r < 2 = rloser k p v l m r | size' r > omega * size' l = rbalanceLeft k p v l m r | size' l > omega * size' r = rbalanceRight k p v l m r | otherwise = rloser k p v l m r lbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lbalanceLeft k p v l m r | size' (left r) < size' (right r) = lsingleLeft k p v l m r | otherwise = ldoubleLeft k p v l m r lbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lbalanceRight k p v l m r | size' (left l) > size' (right l) = lsingleRight k p v l m r | otherwise = ldoubleRight k p v l m r rbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rbalanceLeft k p v l m r | size' (left r) < size' (right r) = rsingleLeft k p v l m r | otherwise = rdoubleLeft k p v l m r rbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rbalanceRight k p v l m r | size' (left l) > size' (right l) = rsingleRight k p v l m r | otherwise = rdoubleRight k p v l m r lsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) | p1 <= p2 = lloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3 | otherwise = lloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3 lsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) = rloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3 lsingleLeft _ _ _ _ _ _ = moduleError "lsingleLeft" "malformed tree" rsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) = rloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3 rsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) = rloser k2 p2 v2 (rloser k1 p1 v1 t1 m1 t2) m2 t3 rsingleLeft _ _ _ _ _ _ = moduleError "rsingleLeft" "malformed tree" lsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = lloser k2 p2 v2 t1 m1 (lloser k1 p1 v1 t2 m2 t3) lsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = lloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3) lsingleRight _ _ _ _ _ _ = moduleError "lsingleRight" "malformed tree" rsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = lloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3) rsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 | p1 <= p2 = rloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3) | otherwise = rloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3) rsingleRight _ _ _ _ _ _ = moduleError "rsingleRight" "malformed tree" ldoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a ldoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) = lsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3) ldoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) = lsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3) ldoubleLeft _ _ _ _ _ _ = moduleError "ldoubleLeft" "malformed tree" ldoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a ldoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = lsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3 ldoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = lsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3 ldoubleRight _ _ _ _ _ _ = moduleError "ldoubleRight" "malformed tree" rdoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rdoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) = rsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3) rdoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) = rsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3) rdoubleLeft _ _ _ _ _ _ = moduleError "rdoubleLeft" "malformed tree" rdoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rdoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = rsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3 rdoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = rsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3 rdoubleRight _ _ _ _ _ _ = moduleError "rdoubleRight" "malformed tree" -- | Take two pennants and returns a new pennant that is the union of -- the two with the precondition that the keys in the first tree are -- strictly smaller than the keys in the second tree. play :: PSQ a -> PSQ a -> PSQ a Void `play` t' = t' t `play` Void = t Winner e@(E k p v) t m `play` Winner e'@(E k' p' v') t' m' | p <= p' = Winner e (rbalance k' p' v' t m t') m' | otherwise = Winner e' (lbalance k p v t m t') m' {-# INLINE play #-} -- | A version of 'play' that can be used if the shape of the tree has -- not changed or if the tree is known to be balanced. unsafePlay :: PSQ a -> PSQ a -> PSQ a Void `unsafePlay` t' = t' t `unsafePlay` Void = t Winner e@(E k p v) t m `unsafePlay` Winner e'@(E k' p' v') t' m' | p <= p' = Winner e (rloser k' p' v' t m t') m' | otherwise = Winner e' (lloser k p v t m t') m' {-# INLINE unsafePlay #-} data TourView a = Null | Single {-# UNPACK #-} !(Elem a) | (PSQ a) `Play` (PSQ a) tourView :: PSQ a -> TourView a tourView Void = Null tourView (Winner e Start _) = Single e tourView (Winner e (RLoser _ e' tl m tr) m') = Winner e tl m `Play` Winner e' tr m' tourView (Winner e (LLoser _ e' tl m tr) m') = Winner e' tl m `Play` Winner e tr m' ------------------------------------------------------------------------ -- Utility functions moduleError :: String -> String -> a moduleError fun msg = error ("GHC.Event.PSQ." ++ fun ++ ':' : ' ' : msg) {-# NOINLINE moduleError #-} ------------------------------------------------------------------------ -- Hughes's efficient sequence type newtype Sequ a = Sequ ([a] -> [a]) emptySequ :: Sequ a emptySequ = Sequ (\as -> as) singleSequ :: a -> Sequ a singleSequ a = Sequ (\as -> a : as) (<>) :: Sequ a -> Sequ a -> Sequ a Sequ x1 <> Sequ x2 = Sequ (\as -> x1 (x2 as)) infixr 5 <> seqToList :: Sequ a -> [a] seqToList (Sequ x) = x [] instance Show a => Show (Sequ a) where showsPrec d a = showsPrec d (seqToList a)
beni55/haste-compiler
libraries/ghc-7.8/base/GHC/Event/PSQ.hs
bsd-3-clause
18,091
0
14
5,065
6,453
3,235
3,218
305
6
{-# LANGUAGE Arrows #-} import Control.Arrow import Control.Applicative import Debug.Trace -- i tried to build an identity arrow which traces an argument arrow -- it doen't work, i guess the left side of (*>) isn't evaluated to the -- needed depth to run the traceIO (guess²: only to the needed Applicative) traceArr :: (Arrow a, Show b) => a c b -> a c c traceArr a = unwrapArrow $ (flip traceShow) id <$> WrapArrow a <*> WrapArrow (arr id) twelveArr :: Arrow f => f p Int twelveArr = arr (const 12) fortyTwoArr :: Arrow f => f p Int fortyTwoArr = arr (const 42) incArr :: (Arrow f, Num a) => f a a incArr = arr (+1) exampleUse1 :: (Arrow f) => f p Int exampleUse1 = traceArr fortyTwoArr <<< incArr <<< twelveArr -- expected a "42" trace exampleUse2 :: (Arrow f) => f p Int exampleUse2 = proc _ -> do twelve <- twelveArr -< () thirty <- traceArr fortyTwoArr <<< incArr -< twelve -- expected a "42" trace returnA -< thirty main :: IO () main = do e1 <- runKleisli exampleUse1 id print e1 e2 <- runKleisli exampleUse2 id print e2
MaxDaten/netwire-examples
TracingArrow.hs
mit
1,056
1
11
223
351
174
177
25
1
{-| Module : Faker.Lorem Description : Module for generating fake words, sentences and paragraphs Copyright : (c) Alexey Gaziev, 2014-2018 License : MIT Maintainer : alex.gaziev@gmail.com Stability : experimental Portability : POSIX Fake data -} module Faker.Lorem ( -- * Functions for generate fake words, sentences and paragraphs word , words , character , characters , sentence , sentences , paragraph , paragraphs ) where import Data.Char import Faker.Utils import Prelude hiding (words) -- | Returns random word, i.e. "recusandae" word :: Faker String word = randomLoremWord "words" -- | Returns random word or supplemental word, i.e. "benevolentia" wordOrSupplemental :: Faker String wordOrSupplemental = do ind <- randomInt (0,1) case ind of 0 -> word _ -> randomLoremWord "supplemental" -- | Returns list of random words with size of provided num, -- i.e. ["alveus","ademptio","arcus","autem","nihil"] words :: Int -> Faker [String] words num = sequence $ replicate num wordOrSupplemental -- | Returns random character, i.e. 'a' character :: Faker Char character = do w <- word ind <- randomInt (0, length w - 1) return $ w !! ind -- | Returns random characters with size of provided num, i.e. "afasde" characters :: Int -> Faker [Char] characters num = sequence $ replicate num character -- | Returns random sentence, i.e. "Ultio et solus uter nisi." sentence :: Faker String sentence = do ws <- randomInt (3,12) >>= words let ss = unwords ws result = (toUpper $ head ss) : tail ss ++ "." return result -- | Returns list of random sentences with size of provided num, -- i.e. ["Optio ago aliquid magnam bestia dolores unde.","Villa recusandae velociter assumenda."] sentences :: Int -> Faker [String] sentences num = sequence $ replicate num sentence -- | Returns paragraph, of random sentences (from 3 to 6), -- i.e. "Cupressus atque civis perferendis viduo dolorem conor appositus tempore cunae. Veritatis ut tot est. Valde temperantia necessitatibus sint celo uterque sequi aduro itaque officiis quam. Statim cribro et subvenio." paragraph :: Faker String paragraph = randomInt (3,6) >>= sentences >>= return . unwords -- | Returns list of random paragraphs with size of provided num paragraphs :: Int -> Faker [String] paragraphs num = sequence $ replicate num paragraph randomLoremWord :: String -> Faker String randomLoremWord = randomValue "lorem"
gazay/faker
src/Faker/Lorem.hs
mit
2,492
0
14
504
445
235
210
44
2
module Y2016.M08.D05.Solution where import Control.Arrow ((&&&)) import Control.Monad import Data.Map (Map) import qualified Data.Map as Map import Y2016.M08.D04.Solution type Idx = Int type Pos = Int type Total = Int type Row = (Total, Schema) type CrossingPoint = ((Idx, Pos), (Idx, Pos)) {-- CrossingPoint says, e.g. from above Row 1, Position 0 crosses at Row 3, Position 0 (That is if row 1 is idx 1, row 2, idx 2, col a, idx 3, col b, idx 4, ... etc) So with that we can have a grid type: --} data Grid = Grd (Map Idx Row) [CrossingPoint] deriving Show -- and our materialized grid is: unc :: Int -> Schema unc = (`replicate` Unconstrained) con :: [Int] -> Schema con = uncurry replicate . (length &&& ConstrainedTo) four :: Row four = (4, con [1,3]) kakuro :: Grid kakuro = Grd (Map.fromList [(1, (13, unc 3)), (2, (20, unc 3)), -- rows 1 and 2 (3, (16, con [7,9])), (4, four), (5, (25, unc 4)), -- columns a,b,c (6, (13, unc 3)), (7, (20, unc 3)), -- rows 3 and 4 (8, (17, con [8,9])), (9, four)]) -- columns d,e [((1,0),(3,0)), ((1,1),(4,0)), ((1,2),(5,0)), -- row 1 xings ((2,0),(3,1)), ((2,1),(4,1)), ((2,2),(5,1)), -- row 2 xings ((6,0),(5,2)), ((6,1),(8,0)), ((6,2),(9,0)), -- row 3 xings ((7,0),(5,3)), ((7,1),(8,1)), ((7,2),(9,1))] -- row 4 xings -- Note that I added the lightest of constraints. Do you want to constrain -- the grid further by redeclaring it? kakuroSolver :: Grid -> [Map Idx Schema] kakuroSolver (Grd rows xing) = mapM (uncurry (flip solver)) (Map.elems rows) >>= \schemata -> let solvedmap = Map.fromList (zip [1..] schemata) in guardEach xing solvedmap >> return solvedmap guardEach :: MonadPlus m => [CrossingPoint] -> Map Idx Schema -> m () guardEach [] _ = return () guardEach ((a,b):rest) m = guard (idx m a == idx m b) >> guardEach rest m idx :: Map Idx Schema -> (Idx, Int) -> Cell idx m (x,y) = m Map.! x !! y -- ugh, does it solve the problem eventually? Maybe. I got bored waiting for -- the answer and solved it myself first, and still the solution hasn't returned -- Solution: -- 7 1 5 -- 9 3 8 -- 3 9 1 -- 9 8 3 -- What are faster/better ways to approach this solution? -- INTERESTING EXERCISE FOR THE READER ... OR: http://lpaste.net/113394
geophf/1HaskellADay
exercises/HAD/Y2016/M08/D05/Solution.hs
mit
2,634
0
14
837
915
556
359
38
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Hpack.UtilSpec (main, spec) where import Data.Aeson import Data.Aeson.QQ import Data.Aeson.Types import Helper import System.Directory import Hpack.Config import Hpack.Util main :: IO () main = hspec spec spec :: Spec spec = do describe "sort" $ do it "sorts lexicographically" $ do sort ["foo", "Foo"] `shouldBe` ["Foo", "foo" :: String] describe "parseMain" $ do it "accepts source file" $ do parseMain "Main.hs" `shouldBe` ("Main.hs", []) it "accepts literate source file" $ do parseMain "Main.lhs" `shouldBe` ("Main.lhs", []) it "accepts module" $ do parseMain "Foo" `shouldBe` ("Foo.hs", ["-main-is Foo"]) it "accepts hierarchical module" $ do parseMain "Foo.Bar.Baz" `shouldBe` ("Foo/Bar/Baz.hs", ["-main-is Foo.Bar.Baz"]) it "accepts qualified identifier" $ do parseMain "Foo.bar" `shouldBe` ("Foo.hs", ["-main-is Foo.bar"]) describe "toModule" $ do it "maps .hs paths to module names" $ do toModule ["Foo", "Bar", "Baz.hs"] `shouldBe` Just "Foo.Bar.Baz" it "maps .lhs paths to module names" $ do toModule ["Foo", "Bar", "Baz.lhs"] `shouldBe` Just "Foo.Bar.Baz" it "maps .hsc paths to module names" $ do toModule ["Foo", "Bar", "Baz.hsc"] `shouldBe` Just "Foo.Bar.Baz" it "rejects invalid module names" $ do toModule ["resources", "hello.hs"] `shouldBe` Nothing describe "getModuleFilesRecursive" $ do it "gets all files from given directory" $ do inTempDirectory $ do touch "foo/bar" touch "foo/baz" actual <- getModuleFilesRecursive "foo" actual `shouldMatchList` [ ["bar"] , ["baz"] ] it "descends into subdirectories" $ do inTempDirectory $ do touch "foo/Bar/baz" getModuleFilesRecursive "foo" `shouldReturn` [["Bar", "baz"]] context "when a subdirectory is not a valid module name" $ do it "does not descend" $ do inTempDirectory $ do touch "foo/bar/baz" getModuleFilesRecursive "foo" `shouldReturn` empty describe "List" $ do let invalid = [aesonQQ|{ name: "hpack", gi: "sol/hpack", ref: "master" }|] parseError :: String -> Either String (List Dependency) parseError prefix = Left (prefix ++ ": neither key \"git\" nor key \"github\" present") context "when parsing single values" $ do it "returns the value in a singleton list" $ do fromJSON (toJSON $ Number 23) `shouldBe` Success (List [23 :: Int]) it "returns error messages from element parsing" $ do parseEither parseJSON invalid `shouldBe` parseError "Error in $" context "when parsing a list of values" $ do it "returns the list" $ do fromJSON (toJSON [Number 23, Number 42]) `shouldBe` Success (List [23, 42 :: Int]) it "propagates parse error messages of invalid elements" $ do parseEither parseJSON (toJSON [String "foo", invalid]) `shouldBe` parseError "Error in $[1]" describe "tryReadFile" $ do it "reads file" $ do inTempDirectory $ do writeFile "foo" "bar" tryReadFile "foo" `shouldReturn` Just "bar" it "returns Nothing if file does not exist" $ do inTempDirectory $ do tryReadFile "foo" `shouldReturn` Nothing describe "expandGlobs" $ around withTempDirectory $ do it "accepts simple files" $ \dir -> do touch (dir </> "foo.js") expandGlobs "field-name" dir ["foo.js"] `shouldReturn` ([], ["foo.js"]) it "removes duplicates" $ \dir -> do touch (dir </> "foo.js") expandGlobs "field-name" dir ["foo.js", "*.js"] `shouldReturn` ([], ["foo.js"]) it "rejects directories" $ \dir -> do touch (dir </> "foo") createDirectory (dir </> "bar") expandGlobs "field-name" dir ["*"] `shouldReturn` ([], ["foo"]) it "rejects character ranges" $ \dir -> do touch (dir </> "foo1") touch (dir </> "foo2") touch (dir </> "foo[1,2]") expandGlobs "field-name" dir ["foo[1,2]"] `shouldReturn` ([], ["foo[1,2]"]) context "when expanding *" $ do it "expands by extension" $ \dir -> do let files = [ "files/foo.js" , "files/bar.js" , "files/baz.js"] mapM_ (touch . (dir </>)) files touch (dir </> "files/foo.hs") expandGlobs "field-name" dir ["files/*.js"] `shouldReturn` ([], sort files) it "rejects dot-files" $ \dir -> do touch (dir </> "foo/bar") touch (dir </> "foo/.baz") expandGlobs "field-name" dir ["foo/*"] `shouldReturn` ([], ["foo/bar"]) it "accepts dot-files when explicitly asked to" $ \dir -> do touch (dir </> "foo/bar") touch (dir </> "foo/.baz") expandGlobs "field-name" dir ["foo/.*"] `shouldReturn` ([], ["foo/.baz"]) it "matches at most one directory component" $ \dir -> do touch (dir </> "foo/bar/baz.js") touch (dir </> "foo/bar.js") expandGlobs "field-name" dir ["*/*.js"] `shouldReturn` ([], ["foo/bar.js"]) context "when expanding **" $ do it "matches arbitrary many directory components" $ \dir -> do let file = "foo/bar/baz.js" touch (dir </> file) expandGlobs "field-name" dir ["**/*.js"] `shouldReturn` ([], [file]) context "when a pattern does not match anything" $ do it "warns" $ \dir -> do expandGlobs "field-name" dir ["foo"] `shouldReturn` (["Specified pattern \"foo\" for field-name does not match any files"], []) context "when a pattern only matches a directory" $ do it "warns" $ \dir -> do createDirectory (dir </> "foo") expandGlobs "field-name" dir ["foo"] `shouldReturn` (["Specified pattern \"foo\" for field-name does not match any files"], [])
mitchellwrosen/hpack
test/Hpack/UtilSpec.hs
mit
6,003
0
21
1,616
1,731
860
871
128
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.HTMLButtonElement (js_checkValidity, checkValidity, js_setCustomValidity, setCustomValidity, js_setAutofocus, setAutofocus, js_getAutofocus, getAutofocus, js_setDisabled, setDisabled, js_getDisabled, getDisabled, js_getForm, getForm, js_setFormAction, setFormAction, js_getFormAction, getFormAction, js_setFormEnctype, setFormEnctype, js_getFormEnctype, getFormEnctype, js_setFormMethod, setFormMethod, js_getFormMethod, getFormMethod, js_setFormNoValidate, setFormNoValidate, js_getFormNoValidate, getFormNoValidate, js_setFormTarget, setFormTarget, js_getFormTarget, getFormTarget, js_setName, setName, js_getName, getName, js_setType, setType, js_getType, getType, js_setValue, setValue, js_getValue, getValue, js_getWillValidate, getWillValidate, js_getValidity, getValidity, js_getValidationMessage, getValidationMessage, js_getLabels, getLabels, HTMLButtonElement, castToHTMLButtonElement, gTypeHTMLButtonElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "($1[\"checkValidity\"]() ? 1 : 0)" js_checkValidity :: JSRef HTMLButtonElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.checkValidity Mozilla HTMLButtonElement.checkValidity documentation> checkValidity :: (MonadIO m) => HTMLButtonElement -> m Bool checkValidity self = liftIO (js_checkValidity (unHTMLButtonElement self)) foreign import javascript unsafe "$1[\"setCustomValidity\"]($2)" js_setCustomValidity :: JSRef HTMLButtonElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.setCustomValidity Mozilla HTMLButtonElement.setCustomValidity documentation> setCustomValidity :: (MonadIO m, ToJSString error) => HTMLButtonElement -> Maybe error -> m () setCustomValidity self error = liftIO (js_setCustomValidity (unHTMLButtonElement self) (toMaybeJSString error)) foreign import javascript unsafe "$1[\"autofocus\"] = $2;" js_setAutofocus :: JSRef HTMLButtonElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.autofocus Mozilla HTMLButtonElement.autofocus documentation> setAutofocus :: (MonadIO m) => HTMLButtonElement -> Bool -> m () setAutofocus self val = liftIO (js_setAutofocus (unHTMLButtonElement self) val) foreign import javascript unsafe "($1[\"autofocus\"] ? 1 : 0)" js_getAutofocus :: JSRef HTMLButtonElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.autofocus Mozilla HTMLButtonElement.autofocus documentation> getAutofocus :: (MonadIO m) => HTMLButtonElement -> m Bool getAutofocus self = liftIO (js_getAutofocus (unHTMLButtonElement self)) foreign import javascript unsafe "$1[\"disabled\"] = $2;" js_setDisabled :: JSRef HTMLButtonElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.disabled Mozilla HTMLButtonElement.disabled documentation> setDisabled :: (MonadIO m) => HTMLButtonElement -> Bool -> m () setDisabled self val = liftIO (js_setDisabled (unHTMLButtonElement self) val) foreign import javascript unsafe "($1[\"disabled\"] ? 1 : 0)" js_getDisabled :: JSRef HTMLButtonElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.disabled Mozilla HTMLButtonElement.disabled documentation> getDisabled :: (MonadIO m) => HTMLButtonElement -> m Bool getDisabled self = liftIO (js_getDisabled (unHTMLButtonElement self)) foreign import javascript unsafe "$1[\"form\"]" js_getForm :: JSRef HTMLButtonElement -> IO (JSRef HTMLFormElement) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.form Mozilla HTMLButtonElement.form documentation> getForm :: (MonadIO m) => HTMLButtonElement -> m (Maybe HTMLFormElement) getForm self = liftIO ((js_getForm (unHTMLButtonElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"formAction\"] = $2;" js_setFormAction :: JSRef HTMLButtonElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.formAction Mozilla HTMLButtonElement.formAction documentation> setFormAction :: (MonadIO m, ToJSString val) => HTMLButtonElement -> val -> m () setFormAction self val = liftIO (js_setFormAction (unHTMLButtonElement self) (toJSString val)) foreign import javascript unsafe "$1[\"formAction\"]" js_getFormAction :: JSRef HTMLButtonElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.formAction Mozilla HTMLButtonElement.formAction documentation> getFormAction :: (MonadIO m, FromJSString result) => HTMLButtonElement -> m result getFormAction self = liftIO (fromJSString <$> (js_getFormAction (unHTMLButtonElement self))) foreign import javascript unsafe "$1[\"formEnctype\"] = $2;" js_setFormEnctype :: JSRef HTMLButtonElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.formEnctype Mozilla HTMLButtonElement.formEnctype documentation> setFormEnctype :: (MonadIO m, ToJSString val) => HTMLButtonElement -> Maybe val -> m () setFormEnctype self val = liftIO (js_setFormEnctype (unHTMLButtonElement self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"formEnctype\"]" js_getFormEnctype :: JSRef HTMLButtonElement -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.formEnctype Mozilla HTMLButtonElement.formEnctype documentation> getFormEnctype :: (MonadIO m, FromJSString result) => HTMLButtonElement -> m (Maybe result) getFormEnctype self = liftIO (fromMaybeJSString <$> (js_getFormEnctype (unHTMLButtonElement self))) foreign import javascript unsafe "$1[\"formMethod\"] = $2;" js_setFormMethod :: JSRef HTMLButtonElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.formMethod Mozilla HTMLButtonElement.formMethod documentation> setFormMethod :: (MonadIO m, ToJSString val) => HTMLButtonElement -> Maybe val -> m () setFormMethod self val = liftIO (js_setFormMethod (unHTMLButtonElement self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"formMethod\"]" js_getFormMethod :: JSRef HTMLButtonElement -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.formMethod Mozilla HTMLButtonElement.formMethod documentation> getFormMethod :: (MonadIO m, FromJSString result) => HTMLButtonElement -> m (Maybe result) getFormMethod self = liftIO (fromMaybeJSString <$> (js_getFormMethod (unHTMLButtonElement self))) foreign import javascript unsafe "$1[\"formNoValidate\"] = $2;" js_setFormNoValidate :: JSRef HTMLButtonElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.formNoValidate Mozilla HTMLButtonElement.formNoValidate documentation> setFormNoValidate :: (MonadIO m) => HTMLButtonElement -> Bool -> m () setFormNoValidate self val = liftIO (js_setFormNoValidate (unHTMLButtonElement self) val) foreign import javascript unsafe "($1[\"formNoValidate\"] ? 1 : 0)" js_getFormNoValidate :: JSRef HTMLButtonElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.formNoValidate Mozilla HTMLButtonElement.formNoValidate documentation> getFormNoValidate :: (MonadIO m) => HTMLButtonElement -> m Bool getFormNoValidate self = liftIO (js_getFormNoValidate (unHTMLButtonElement self)) foreign import javascript unsafe "$1[\"formTarget\"] = $2;" js_setFormTarget :: JSRef HTMLButtonElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.formTarget Mozilla HTMLButtonElement.formTarget documentation> setFormTarget :: (MonadIO m, ToJSString val) => HTMLButtonElement -> val -> m () setFormTarget self val = liftIO (js_setFormTarget (unHTMLButtonElement self) (toJSString val)) foreign import javascript unsafe "$1[\"formTarget\"]" js_getFormTarget :: JSRef HTMLButtonElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.formTarget Mozilla HTMLButtonElement.formTarget documentation> getFormTarget :: (MonadIO m, FromJSString result) => HTMLButtonElement -> m result getFormTarget self = liftIO (fromJSString <$> (js_getFormTarget (unHTMLButtonElement self))) foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName :: JSRef HTMLButtonElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.name Mozilla HTMLButtonElement.name documentation> setName :: (MonadIO m, ToJSString val) => HTMLButtonElement -> val -> m () setName self val = liftIO (js_setName (unHTMLButtonElement self) (toJSString val)) foreign import javascript unsafe "$1[\"name\"]" js_getName :: JSRef HTMLButtonElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.name Mozilla HTMLButtonElement.name documentation> getName :: (MonadIO m, FromJSString result) => HTMLButtonElement -> m result getName self = liftIO (fromJSString <$> (js_getName (unHTMLButtonElement self))) foreign import javascript unsafe "$1[\"type\"] = $2;" js_setType :: JSRef HTMLButtonElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.type Mozilla HTMLButtonElement.type documentation> setType :: (MonadIO m, ToJSString val) => HTMLButtonElement -> Maybe val -> m () setType self val = liftIO (js_setType (unHTMLButtonElement self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"type\"]" js_getType :: JSRef HTMLButtonElement -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.type Mozilla HTMLButtonElement.type documentation> getType :: (MonadIO m, FromJSString result) => HTMLButtonElement -> m (Maybe result) getType self = liftIO (fromMaybeJSString <$> (js_getType (unHTMLButtonElement self))) foreign import javascript unsafe "$1[\"value\"] = $2;" js_setValue :: JSRef HTMLButtonElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.value Mozilla HTMLButtonElement.value documentation> setValue :: (MonadIO m, ToJSString val) => HTMLButtonElement -> val -> m () setValue self val = liftIO (js_setValue (unHTMLButtonElement self) (toJSString val)) foreign import javascript unsafe "$1[\"value\"]" js_getValue :: JSRef HTMLButtonElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.value Mozilla HTMLButtonElement.value documentation> getValue :: (MonadIO m, FromJSString result) => HTMLButtonElement -> m result getValue self = liftIO (fromJSString <$> (js_getValue (unHTMLButtonElement self))) foreign import javascript unsafe "($1[\"willValidate\"] ? 1 : 0)" js_getWillValidate :: JSRef HTMLButtonElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.willValidate Mozilla HTMLButtonElement.willValidate documentation> getWillValidate :: (MonadIO m) => HTMLButtonElement -> m Bool getWillValidate self = liftIO (js_getWillValidate (unHTMLButtonElement self)) foreign import javascript unsafe "$1[\"validity\"]" js_getValidity :: JSRef HTMLButtonElement -> IO (JSRef ValidityState) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.validity Mozilla HTMLButtonElement.validity documentation> getValidity :: (MonadIO m) => HTMLButtonElement -> m (Maybe ValidityState) getValidity self = liftIO ((js_getValidity (unHTMLButtonElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"validationMessage\"]" js_getValidationMessage :: JSRef HTMLButtonElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.validationMessage Mozilla HTMLButtonElement.validationMessage documentation> getValidationMessage :: (MonadIO m, FromJSString result) => HTMLButtonElement -> m result getValidationMessage self = liftIO (fromJSString <$> (js_getValidationMessage (unHTMLButtonElement self))) foreign import javascript unsafe "$1[\"labels\"]" js_getLabels :: JSRef HTMLButtonElement -> IO (JSRef NodeList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement.labels Mozilla HTMLButtonElement.labels documentation> getLabels :: (MonadIO m) => HTMLButtonElement -> m (Maybe NodeList) getLabels self = liftIO ((js_getLabels (unHTMLButtonElement self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/HTMLButtonElement.hs
mit
14,148
184
11
2,275
2,835
1,511
1,324
217
1
{-# LANGUAGE OverloadedStrings #-} module Player.Style where import Player.Building.Style import Player.Resources.Style import Common.CssClass import Common.CommonClasses import Clay import Clay.Flexbox as F import Data.Monoid playerClass :: CssClass playerClass = CssClass "player" selectedPlayerClass :: CssClass selectedPlayerClass = CssClass "selected-player" playerContainerClass :: CssClass playerContainerClass = CssClass "player-container" selectionClass :: CssClass selectionClass = CssClass "selection" playerDataContainerClass :: CssClass playerDataContainerClass = CssClass "player-data-container" hiddenPlayerData :: CssClass hiddenPlayerData = CssClass "hidden-player-data" freeWorkersClass :: CssClass freeWorkersClass = CssClass "free-workers" playerInfoClass :: CssClass playerInfoClass = CssClass "player-info" currentPlayerIconClassInternal :: CssClass currentPlayerIconClassInternal = CssClass "current-player-icon" armingClass :: CssClass armingClass = CssClass "arming" currentPlayerIconClass :: CssClass currentPlayerIconClass = currentPlayerIconClassInternal <> faClass <> faPlayClass playerStyle :: Css playerStyle = do buildingStyle resourcesStyle star # classSelector playerDataContainerClass ? do display Clay.flex flexFlow row F.wrap margin nil nil nil nil padding nil nil nil nil star # classSelector hiddenPlayerData ? do display none star # classSelector freeWorkersClass ? do position fixed bottom (em 2) right (em 2) padding (em 1) (em 1) (em 1) (em 1) width (pct 45) height (pct 55) boxSizing borderBox star # classSelector playerClass ? do display inlineBlock margin nil (em 0.3) (em 0.3) (em 0.3) padding (em 0.7) (em 0.7) (em 0.7) (em 0.7) backgroundColor "#8f765f" borderBottomLeftRadius (px 10) (px 10) borderBottomRightRadius (px 10) (px 10) cursor pointer width (em 10) star # classSelector playerClass # firstChild ? marginLeft (em 3) star # classSelector playerClass # classSelector selectedPlayerClass ? do backgroundColor "#27201a" color white fontWeight bold star # classSelector playerContainerClass ? do order 1 F.flex 1 1 (pct 85) minWidth (em 35) star # classSelector playerInfoClass ? do order 3 F.flex 1 1 (pct 10) minWidth (em 10) padding (em 2) (em 2) (em 2) (em 2) margin (em 2) (em 2) (em 2) (em 2) fontWeight bold star # classSelector playerInfoClass |> button ? do marginTop (em 1) display block star # classSelector armingClass ? do marginTop (em 1) star # classSelector armingClass Clay.** input ? do marginRight (em 0.5) width (em 4) star # classSelector currentPlayerIconClassInternal ? float floatRight star # classSelector selectionClass ? do position fixed display Clay.flex F.justifyContent center F.alignItems center left (pct 30) top (pct 40) width (pct 30) height(em 10) minWidth (em 25) backgroundColor "#8f765f" zIndex 10000 borderRadius (em 2) (em 2) (em 2) (em 2) star # classSelector selectionClass Clay.** button ? do margin (em 2) (em 2) (em 2) (em 2) width (em 10) height (em 3)
martin-kolinek/some-board-game
src/Player/Style.hs
mit
3,207
0
12
647
1,143
517
626
102
1
{-# LANGUAGE OverloadedStrings #-} module System.Directory.Watchman.FileType ( FileType(..) , fileTypeChar , fileTypeFromChar ) where import Data.ByteString (ByteString) data FileType = TBlockSpecialFile | TCharacterSpecialFile | TDirectory | TRegularFile | TNamedPipe | TSymbolicLink | TSocket | TSolarisDoor | TUnknown deriving (Show, Eq, Ord) fileTypeChar :: FileType -> ByteString fileTypeChar TBlockSpecialFile = "b" fileTypeChar TCharacterSpecialFile = "c" fileTypeChar TDirectory = "d" fileTypeChar TRegularFile = "f" fileTypeChar TNamedPipe = "p" fileTypeChar TSymbolicLink = "l" fileTypeChar TSocket = "s" fileTypeChar TSolarisDoor = "D" fileTypeFromChar :: ByteString -> FileType fileTypeFromChar "b" = TBlockSpecialFile fileTypeFromChar "c" = TCharacterSpecialFile fileTypeFromChar "d" = TDirectory fileTypeFromChar "f" = TRegularFile fileTypeFromChar "p" = TNamedPipe fileTypeFromChar "l" = TSymbolicLink fileTypeFromChar "s" = TSocket fileTypeFromChar "D" = TSolarisDoor fileTypeFromChar _ = TUnknown
bitc/hs-watchman
src/System/Directory/Watchman/FileType.hs
mit
1,075
0
6
180
234
129
105
36
1
{-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE BangPatterns #-} {-| Module : Statistics.FastBayes.Linear Description : Bayesian linear regression via maximum marginal likelihood. Copyright : (c) Melinae, 2014 Chad Scherrer, 2014 License : MIT Maintainer : chad.scherrer@gmail.com Stability : experimental Portability : POSIX This module gives an implementation of Bayesian linear regression, with the scale of the prior chosen by marginal likelihood. The inputs for a Bayesian linear model are identical to those of a classical linear model, except that in addition to a design matrix and response, we must also specify a prior distribution on the weights and the noise. This leaves us with an open question of how these should be specified. In his book /Pattern Recognition and Machine Learning/, Christopher Bishop provides details for an approach that simplifies the situation significantly, and allows for much faster inference. The structure of the linear model allows us to integrate the posterior over the weights, resulting in the /marginal likelihood/, expressed as a function of the prior precision and noise precision. This, in turn, can be easily optimized. -} module Statistics.FastBayes.Linear ( test , Fit , fit0 , fit1 , priorPrecision , noisePrecision , effectiveNumParameters , logEvidence , mapWeights , intercept , hessian , features , Predict , predict , studentize , studentizeM , inputs , fitted , fittedSD ) where import qualified Data.Vector.Storable as V import Data.Packed.Matrix import Numeric.LinearAlgebra data Fit a = Fit { priorPrecision :: Double -- ^The precision (inverse variance) of the prior distribution, determined by maximizing the marginal likelihood , noisePrecision :: Double -- ^The precision (inverse variance) of the noise , effectiveNumParameters :: Double -- ^The effective number of parameters in the model , logEvidence :: Double -- ^The log of the evidence, which is useful for model comparison (different features, same response) , mapWeights :: Vector Double -- ^The MAP (maximum a posteriori) values for the parameter weights , intercept :: Double -- ^The y-intercept , hessian :: Matrix Double -- ^The Hessian (matrix of second derivatives) for the posterior distribution , features :: a → Vector Double -- ^Extract features from a data point } -- instance Show (Fit a) where -- |@fit0 lim x y@ fits a Bayesian linear model to a design matrix @x@ and response vector @y@. This is an iterative algorithm, resulting in a sequence (list) of (α,β) values. Here α is the prior precision, and β is the noise precision. The @lim@ function passed in is used to specify how the limit of this sequence should be computed. fit0 :: ([(Double, Double)] → (Double, Double)) -- ^How to take the limit of the (α,β) sequence. A simple approach is, /e.g./, @fit (!! 1000) x y@ → Bool -- ^Whether to studentize (translate and re-scale) the features → (a → Vector Double) -- ^The features → [a] -- ^The input data → Vector Double -- ^The response vector → Fit a fit0 lim student f xs y = Fit α β γ logEv m 0 h f' where (x, f') | not student = (fromRows $ map f xs, f) | student = ( x0, fs . f) where (x0, fs) = studentizeM . fromRows . map f $ xs n = rows x p = cols x α0 = 1.0 β0 = 1.0 -- A vector of the eigenvalues of xtx (_,sqrtEigs,_) = compactSVD x eigs = V.map square sqrtEigs xtx = trans x <> x xty = trans x <> y getHessian a b = diag (V.replicate p a) + scale b xtx m = scale β $ h <\> xty go :: Double → Double → [(Double, Double)] go a0 b0 = (a0, b0) : go a b where h0 = getHessian a0 b0 m0 = scale b0 $ h0 <\> xty c = V.sum $ V.map (\x' → x' / (a0 + x')) eigs a = c / (m0 <.> m0) b = recip $ (normSq $ y - x <> m0) / (fromIntegral n - c) γ = V.sum $ V.map (\x' → x' / (α + x')) eigs h = getHessian α β logEv = 0.5 * ( fromIntegral p * log α + fromIntegral n * log β - (β * normSq (y - x <> m) + α * (m <.> m)) - logDetH - fromIntegral n * log (2*pi) ) where (_,(logDetH, _)) = invlndet h (α, β) = lim $ go α0 β0 fit1 :: ([(Double, Double)] → (Double, Double)) -- ^How to take the limit of the (α,β) sequence. A simple approach is, /e.g./, @fit (!! 1000) x y@ → Bool -- ^Whether to studentize (translate and re-scale) the features → (a → Vector Double) -- ^The features → [a] -- ^The input data → Vector Double -- ^The response vector → Fit a fit1 lim student f xs y = f0 {intercept = μ} where μ = mean y n = V.length y f0 = fit0 lim student f xs (y - konst μ n) square :: Double → Double square x = x * x normSq :: Vector Double → Double normSq x = x <.> x mean :: Vector Double -> Double mean v = V.sum v / fromIntegral (V.length v) studentizeM :: Matrix Double -> (Matrix Double, Vector Double → Vector Double) studentizeM m = (x, f) where (xs, fs) = unzip . map studentize . toColumns $ m x = fromColumns xs f = fromList . zipWith ($) fs . toList studentize :: Vector Double -> (Vector Double, Double → Double) studentize v = (scale (1/σ) v0, f) where n = V.length v μ = mean v v0 = v - konst μ n σ = sqrt $ normSq v0 / fromIntegral n f x = (x - μ) / σ test = myFit 11 where x = [1,1.1..pi] y = fromList $ map sin x f n x = fromList . map (x **) $ [1..n] myFit n = fit1 (!!100) True (f n) x y data Predict a = Predict { inputs :: [a] , fitted :: [Double] , fittedSD :: [Double] } predict :: Fit a -> [a] -> Predict a predict myFit xs = Predict xs ys (toList . V.map sqrt $ konst (1/β) n + takeDiag cov) where n = rows x α = priorPrecision myFit β = noisePrecision myFit w = mapWeights myFit y0 = intercept myFit h = hessian myFit f = features myFit x = fromRows $ map f xs cov = x <> (h <\> trans x) y = x <> w + konst y0 n ys = toList y
cscherrer/fastbayes
src/Statistics/FastBayes/Linear.hs
mit
6,584
0
20
2,008
1,624
875
749
123
1
{-# LANGUAGE Arrows #-} {-# LANGUAGE TupleSections #-} module Yage.Wire.Input where import Yage.Lens import Yage.Math import Yage.Prelude import Yage.UI import Control.Wire import Yage.Wire.Event import Yage.Wire.Types import FRP.Netwire as Netwire ------------------------------------------------------------------------------- -- State Events mouseVelocity :: (Real t, RealFloat a) => YageWire t b (V2 a) mouseVelocity = overA _x derivative <<< overA _y derivative <<< currentMousePosition mouseAcceleration :: (Real t, RealFloat a) => YageWire t b (V2 a) mouseAcceleration = overA _y derivative . overA _x derivative . mouseVelocity keyboardEvent :: (Num t) => YageWire t a (Netwire.Event KeyEvent) keyboardEvent = go [] where go evQueue = mkSF $ \(Timed _ inputSt) _ -> (maybeToEvent $ listToMaybe evQueue, go (drop 1 evQueue ++ inputSt^.keyboardEvents )) mouseEvent :: (Num t) => YageWire t a (Netwire.Event MouseEvent) mouseEvent = go [] where go evQueue = mkSF $ \(Timed _ inputSt) _ -> (maybeToEvent $ listToMaybe evQueue, go (drop 1 evQueue ++ inputSt^.mouseEvents )) -- | fires ONCE everytime a `key` is pressed keyJustPressed :: (Num t) => Key -> YageWire t a (Netwire.Event KeyEvent) keyJustPressed !key = filterE (keyStateIs key KeyState'Pressed) . keyboardEvent keyJustReleased :: (Num t) => Key -> YageWire t a (Netwire.Event KeyEvent) keyJustReleased !key = filterE (\(KeyEvent k _int s _mod) -> key == k && s == KeyState'Released) . keyboardEvent -- | acts like `id` while `key` is down, inhibits while `key` is up whileKeyDown :: (Num t) => Key -> YageWire t a a whileKeyDown !key = proc x -> do pressed <- keyJustPressed key -< () released <- keyJustReleased key -< () between -< (x, pressed, released) -- | a signal wire with the stream of the mouse position currentMousePosition :: (Real t, Fractional a) => YageWire t b (V2 a) currentMousePosition = ( pos <$> hold . filterE isMouseMoveEvent . mouseEvent ) <|> 0 where pos (MouseMoveEvent p) = realToFrac <$> p pos _ = error "impossible" currentInputState :: (Num t) => YageWire t a InputState currentInputState = mkSF $ \(Timed _ inputState) _ -> (inputState, currentInputState) -- | a wire for switching between two values 'a' & 'b', starting with 'a'. -- 'trigger' is the event source. toggle :: Monad m => Wire s e m a (Event d) -> b -> b -> Wire s e m a b toggle trigger a b = dSwitch $ pure a &&& (fmap (fmap . const $ toggle trigger b a) trigger) {-# INLINE toggle #-}
MaxDaten/yage
src/Yage/Wire/Input.hs
mit
2,631
1
14
583
843
436
407
43
2
module Main where import Graphics.Gloss import Graphics.Gloss.Data.Point import Graphics.Gloss.Interface.Pure.Game import System.Random -- Main main :: IO () main = do sg <- getStdGen let world = World (Player (0,0) 0 50 D D) (redApple (15,15)) [] sg play (InWindow "Mine Runner" (width,height) (10,10)) white 60 world draw event step -- Model width :: Num a => a width = 600 height :: Num a => a height = 400 appleSize :: Num a => a appleSize = 10 playerSize :: Num a => a playerSize = 10 mineSize :: Num a => a mineSize = playerSize data World = World { player :: Player , apple :: Apple , mines :: [Point] , stdgen :: StdGen } data Direction = U | D | L | R deriving (Eq) data Player = Player { pPos :: Point , score :: Int , speed :: Float , oldDir :: Direction , newDir :: Direction } data Apple = Apple { aPos :: Point , fun :: Player -> Player , aColor :: Color } -- Display draw :: World -> Picture draw (World { player = (Player { pPos = (px,py), newDir = dir, score = sco }) , apple = (Apple { aPos = (a,b), aColor = c }) , mines = m }) = pictures [ translate (-50 * (fromIntegral . length $ show sco)) (-30) . text $ show sco , pictures $ zipWith (\n (x,y) -> color (greyN n) $ rect x y mineSize mineSize) ([1, 0.67, 0.5] ++ repeat 0) m -- colour the first mine white, the next two grey , translate a b $ drawApple c , translate px py $ drawPlayer dir ] drawPlayer :: Direction -> Picture drawPlayer dir = pictures [circleSolid (playerSize/2), eyes] where s = playerSize/5 base = pictures [ translate (-s) s . color white $ circle 1.75 , translate s s . color white $ circle 1.75 ] eyes = (flip rotate) base $ case dir of U -> 0; D -> 180; L -> 270; R -> 90 drawApple :: Color -> Picture drawApple c = pictures [ color c $ circleSolid (appleSize/2) , translate 1 (appleSize/3) . color green $ circleSolid 2.5 ] rect :: Float -> Float -> Float -> Float -> Picture rect x y w h = translate x y $ rectangleSolid w h -- Update event :: Event -> World -> World event (EventKey (SpecialKey x) Down _ _) w = w { player = (player w) { newDir = d } } where d = case x of KeyUp -> U KeyDown -> D KeyLeft -> L KeyRight -> R _ -> oldDir $ player w event _ w = w step :: Float -> World -> World step dt = hit . eat . move dt hit :: World -> World hit w@(World { player = p@(Player { pPos = pos }) , mines = m }) = if any (\mp -> pointInCircle mp pos playerSize) $ drop 3 m then w { player = p { score = 0, speed = 50 } , mines = [] } else w eat :: World -> World eat w@(World { apple = (Apple { aPos = ap, fun = f }) , player = p@(Player { pPos = pp }) , stdgen = sg }) = if pointInCircle ap pp playerSize then let (a,sg') = randomApple sg (mines w) in w { apple = a, stdgen = sg', player = f p } else w move :: Float -> World -> World move dt w@(World { player = p@(Player { pPos = pos, oldDir = od, newDir = nd, speed = v }) , mines = m }) = let newMines = if nd /= od then pos : m else m np = (wrapScreen $ pos `add` dirToPoint nd (v*dt)) in w { player = p { pPos = np, oldDir = nd } , mines = newMines } -- Utility -- apples redApple :: Point -> Apple redApple p = Apple p (\s -> s { score = succ $ score s, speed = 2 + speed s }) red greenApple :: Point -> Apple greenApple p = Apple p (\s -> s { score = 3 + score s, speed = 2 + speed s }) $ dark green randomApple :: StdGen -> [Point] -> (Apple, StdGen) randomApple sg mins = let (x,sg') = randomR (-width/2 + appleSize/2, width/2 - appleSize/2) sg :: (Float,StdGen) (y,sg'') = randomR (-height/2 + appleSize/2 ,height/2 - appleSize/2) sg' :: (Float,StdGen) (which,sg''') = randomR (0,10) sg'' :: (Float,StdGen) in if any (\m -> pInBox (x,y) (boxAround m mineSize)) mins then randomApple sg''' mins else (if which >= 7 then greenApple (x,y) else redApple (x,y), sg''') -- points add :: Point -> Point -> Point add (a,b) (x,y) = (a+x,b+y) wrap :: (Num a, Ord a) => a -> a -> a -> a wrap mi ma n | n > ma = mi | n < mi = ma | otherwise = n wrapScreen :: Point -> Point wrapScreen (x,y) = ((wrap (-width /2) (width /2) x), (wrap (-height/2) (height/2) y)) dirToPoint :: Direction -> Float -> Point dirToPoint d x = case d of U -> (0,x) D -> (0,-x) L -> (-x,0) R -> (x,0) -- collision dist :: Point -> Point -> Float dist (x,y) (a,b) = sqrt $ (x-a)**2 + (y-b)**2 pointInCircle :: Point -> Point -> Float -> Bool pointInCircle p c r = dist p c <= r boxAround :: Point -> Float -> (Point,Point) boxAround (x,y) w = ((x-w, y-w), (x+w, y+w)) pInBox :: Point -> (Point,Point) -> Bool pInBox p (u,l) = pointInBox p u l
andreasfrom/minerunner
main.hs
mit
5,095
0
15
1,582
2,351
1,295
1,056
119
5
import Data.Digits import Data.List import Data.Maybe -- When we search numbers of i digits, if the maximum sum that you can -- generate (i*9^5) doesn't even have i digits [>10^(i-1)], that is out of bounds upperBound = (fromMaybe 7 $ find (\i -> 9^5 * i < 10^(i-1)) [1..]) -1 isTarget n = ((sum $ map (^5) $ digits 10 n) == n) searchSpace = [2..10^upperBound] targets = filter isTarget searchSpace answer = sum targets main = print answer
gumgl/project-euler
30/30.hs
mit
445
0
14
84
154
83
71
9
1
{-# LANGUAGE OverloadedStrings #-} module Web.Slack.PagerSpec (spec) where -- base import Control.Exception (throwIO) import Data.Maybe (fromJust) -- fakepull import Test.Pull.Fake.IO (FakeStream, pull, newFakeStream) -- hspec import Test.Hspec -- slack-web import Web.Slack.Pager import Web.Slack.Common ( mkSlackTimestamp , Cursor (..) , Message (..) , MessageType (..) , SlackMessageText (..) ) import Web.Slack.Conversation ( ConversationId (ConversationId) , mkHistoryReq , mkRepliesReq , HistoryReq (..) , HistoryRsp (..) , RepliesReq (..) , ResponseMetadata (..) ) import Web.Slack.Types (UserId (..)) -- text import qualified Data.Text as Text -- time import Data.Time.Clock (getCurrentTime, nominalDay, addUTCTime) stubbedSendRequest :: FakeStream (Response HistoryRsp) -> a -> IO (Response HistoryRsp) stubbedSendRequest stream _request = fromJust <$> pull stream spec :: Spec spec = do let prepare = do nowUtc <- getCurrentTime let now = mkSlackTimestamp nowUtc oldest = mkSlackTimestamp $ addUTCTime (nominalDay * negate 20) nowUtc messagesPerPage = 3 allResponses :: [Response HistoryRsp] allResponses = do -- According to https://api.slack.com/docs/pagination, -- The last page's cursor can be either an empty string, null, or non-exisitent in the object. (pageN, cursor) <- zip [1..3] ["cursor1=", "cursor2=", ""] let pageNT = Text.pack (show pageN) pure . Right $ HistoryRsp { historyRspMessages = do messageN <- [1..messagesPerPage] let messagesPerPageNDT = fromIntegral messagesPerPage messageNDT = fromIntegral messageN messageNT = Text.pack (show messageN) createdBefore = negate $ nominalDay * ((pageN - 1) * messagesPerPageNDT + messageNDT) pure $ Message MessageTypeMessage (Just . UserId $ "U" <> pageNT <> messageNT) (SlackMessageText $ "message " <> pageNT <> "-" <> messageNT) (mkSlackTimestamp $ addUTCTime createdBefore nowUtc) , historyRspResponseMetadata = Just . ResponseMetadata . Just $ Cursor cursor } responsesToReturn <- newFakeStream allResponses return (now, oldest, messagesPerPage, allResponses, responsesToReturn) describe "conversationsHistoryAllBy" $ it "collect all results by sending requests" $ do (now, oldest, messagesPerPage, allResponses, responsesToReturn) <- prepare let initialRequest = (mkHistoryReq (ConversationId "C01234567")) { historyReqCount = messagesPerPage , historyReqLatest = Just now , historyReqOldest = Just oldest , historyReqInclusive = False } loadPage <- conversationsHistoryAllBy (stubbedSendRequest responsesToReturn) initialRequest let actual = unfoldPageM $ either throwIO return =<< loadPage expected <- fmap (map historyRspMessages) . either throwIO return $ sequenceA allResponses actual `shouldReturn` expected describe "repliesFetchAllBy" $ it "collect all results by sending requests" $ do (now, oldest, messagesPerPage, allResponses, responsesToReturn) <- prepare let initialRequest = (mkRepliesReq (ConversationId "C98765432") oldest) { repliesReqLimit = messagesPerPage , repliesReqLatest = Just now , repliesReqOldest = Just oldest , repliesReqInclusive = False } loadPage <- repliesFetchAllBy (stubbedSendRequest responsesToReturn) initialRequest let actual = unfoldPageM $ either throwIO return =<< loadPage expected <- fmap (map historyRspMessages) . either throwIO return $ sequenceA allResponses actual `shouldReturn` expected -- | Runs the given action repeatedly until it returns an empty list. unfoldPageM :: Monad m => m [a] -> m [[a]] unfoldPageM act = reverse <$> go [] where go accum = do x <- act case x of [] -> return accum xs -> go $! xs : accum
jpvillaisaza/slack-web
tests/Web/Slack/PagerSpec.hs
mit
4,251
0
30
1,174
1,043
559
484
83
2
module Batch.Transformer ( from , to ) where import Batch.Definitions import qualified Common as C import Control.Exception (assert) import Debug.Trace (trace) data Subroutine = Subroutine { unLabel :: String, unBody :: [Command] } from :: Command -> C.Project from (Program commands) = C.Project [makeModule commands] from _ = assert False undefined to :: C.Project -> Command to = assert False undefined makeModule :: [Command] -> C.Module makeModule = C.Module "Script" . subroutinesToFunctions . groupSubroutines subroutinesToFunctions :: [Subroutine] -> [C.Definition] subroutinesToFunctions = map (\sub -> C.Function (unLabel sub) (body $ unBody sub)) groupSubroutines :: [Command] -> [Subroutine] groupSubroutines = go where go [] = [] go (Label l:cs) = let (statements, cs') = consume cs following = go cs' in Subroutine l (statements ++ callNext following) : following go cs = go (Label "":cs) consume = consume' [] consume' :: [Command] -> [Command] -> ([Command], [Command]) consume' xs [] = (xs, []) consume' xs ys@(Label _:_) = (xs, ys) consume' xs (y:ys) = consume' (xs++[y]) ys callNext xs = [Call (unLabel $ head xs) | not (null xs)] body :: [Command] -> [C.Statement] body = map statement statement :: Command -> C.Statement statement (Quieted c) = C.FunctionCall quietFunc [C.ExprArg $ expressionable c] statement (Call label) = C.FunctionCall (userFunc label) [] statement (Goto label) = C.FunctionCall (userFunc label) [] statement (Comment msg) = C.Comment msg statement (If expr consequent alternative) = C.If (expression expr) (body consequent) (body alternative) statement (Noop) = C.Noop statement c = C.FunctionCall printFunc [C.ExprArg $ expressionable c] expressionable :: Command -> C.Expression expressionable (EchoEnabled b) = C.FunctionCallExpr echoEnableFunc [C.BoolArg b] expressionable (EchoMessage msg) = C.FunctionCallExpr echoFunc [C.StringArg msg] expressionable (PipeCommand c1 c2) = piped (expressionable c1) c2 expressionable (Redirection c path) = C.FunctionCallExpr writeFunc [C.ExprArg (expressionable c), C.StringArg path] expressionable (Ver) = C.FunctionCallExpr verFunc [] expressionable c = trace (show c) $ assert False undefined expressionWithInput :: Command -> C.Expression -> C.Expression expressionWithInput (Find str []) e = C.FunctionCallExpr findFunc [C.StringArg str, C.ExprArg e] expressionWithInput (Redirection c path) e = C.FunctionCallExpr writeFunc [C.ExprArg (expressionWithInput c e), C.StringArg path] expressionWithInput c e = trace ("On: " ++ show e ++ ", " ++ show c) $ assert False undefined piped :: C.Expression -> Command -> C.Expression piped e c = expressionWithInput c e expression :: Expression -> C.Expression expression (EqualsExpr (StringExpr l) (StringExpr r)) = C.StringEqualsExpr l r expression (ErrorLevelExpr n) = C.FunctionCallExpr errorLevelFunc [C.IntegerArg n] expression e = trace (show e) $ assert False undefined echoEnableFunc, echoFunc, printFunc, quietFunc :: C.FuncRef echoEnableFunc = C.FuncRef internalNS "EchoEnable" verFunc = C.FuncRef internalNS "Ver" errorLevelFunc = C.FuncRef internalNS "ErrorLevel" findFunc = C.FuncRef internalNS "Find" echoFunc = C.FuncRef internalNS "Echo" printFunc = C.FuncRef internalNS "Print" quietFunc = C.FuncRef internalNS "Quiet" writeFunc = C.FuncRef internalNS "Redirect" userFunc :: String -> C.FuncRef userFunc = C.FuncRef userNS userNS :: C.ModuleRef userNS = C.ModuleRef ["Script"] internalNS :: C.ModuleRef internalNS = C.ModuleRef []
danstiner/transpiler
src/Batch/Transformer.hs
mit
3,626
0
13
623
1,379
708
671
73
5
{-| Module : Test.Make.Config.Class Description : Tests the Make Class file Copyright : (c) Andrew Burnett 2014-2015 Maintainer : andyburnett88@gmail.com Stability : experimental Portability : Unknown Contains the test hierarchy for the Class modules -} module Test.Make.Config.Class ( tests -- TestTree ) where import HSat.Make.Config.Class import Test.Make.Instances.CNF.Internal (genCNFConfig) import HSat.Make.Instances.CNF () import TestUtils name :: String name = "Class" tests :: TestTree tests = testGroup name [ testGroup "mkConfig" [ mkConfigTest1 ] ] mkConfigTest1 :: TestTree mkConfigTest1 = testProperty ("mkConfig a " `equiv` " Config a Nothing") $ forAll (sized genCNFConfig) (\cnfConfig -> Config cnfConfig Nothing === mkConfig cnfConfig ) instance Arbitrary Config where arbitrary = oneof [ mkConfig <$> sized genCNFConfig ] shrink _ = []
aburnett88/HSat
tests-src/Test/Make/Config/Class.hs
mit
936
0
10
197
177
102
75
24
1
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} module Fun.Quiz.Type2 where import Fun.Type import Autolib.Reader import Autolib.ToDoc import Data.Typeable data Param = Param { expression_size :: Int , table_size :: Int , properties :: [ Property ] } deriving ( Typeable ) example :: Param example = Param { expression_size = 10 , table_size = 10 , properties = [ Builtins [] ] } $(derives [makeReader, makeToDoc] [''Param]) -- local variables: -- mode: haskell -- end:
Erdwolf/autotool-bonn
src/Fun/Quiz/Type2.hs
gpl-2.0
510
6
9
108
135
82
53
16
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Yesod.Auth.Autotool.Widget (authAutotoolWidget, createAccountWidget, errorWidget, invalidEmailWidget, mailSentWidget, resetPasswordWidget) where import Yesod.Auth.Autotool.Type import qualified Yesod.Auth.Autotool.Message as Msg import Yesod.Auth import Yesod.Core import Control.Monad.Catch import qualified Data.List as L import Data.Function import Data.Maybe import qualified Data.Text as T import System.IO import qualified Control.Schule.Typ as Schule import Control.Student.Type as Stud import Control.Types authAutotoolWidget :: (PathPiece AuthSchool, PathPiece AuthStudent, YesodAuthAutotool site, RenderMessage site YesodAuthAutotoolMessage) => Maybe AuthSchool -> Maybe AuthSchool -> Maybe AuthStudent -> Maybe Student -> (AuthRoute -> Route site) -> WidgetT site IO () authAutotoolWidget u mschool mstud s tm = do schools <- getSchools theSchool <- getSchool u setTitleI Msg.LoginTitle let login = case u of Nothing -> tm signinR Just u' -> tm $ signinSchoolR u' [whamlet| $newline never <div .container> $if L.null schools <p>_{Msg.ErrorNoSchool} $else <form method="post" action=@{login} .form-signin role=form> <h2 .form-signin-heading>_{Msg.LoginTitle} $maybe u' <- theSchool <input type="hidden" name="school" value=#{toString $ Schule.unr u'}> $nothing <select .form-control name="school"> $forall school <- schools <option value=#{toString $ Schule.unr school}> #{toString $ Schule.name school} $maybe s' <- s <input type="text" name="matriculationnumber" .form-control placeholder=_{Msg.MatriculationNumber} required autofocus spellcheck="false" value=#{toString $ mnr s'}> $nothing <input type="text" name="matriculationnumber" .form-control placeholder=_{Msg.MatriculationNumber} required autofocus spellcheck="false"> <input type="password" name="password" .form-control placeholder=_{Msg.Password} required> $maybe s' <- mstud $maybe u' <- mschool <p><a href=@{tm $ resetPasswordR u' s'}>_{Msg.ForgotPassword} <button type=submit .btn .btn-lg .btn-primary .btn-block>_{Msg.Login} |] createAccountWidget :: (YesodAuthAutotool site, PathPiece AuthSchool, RenderMessage site YesodAuthAutotoolMessage) => Maybe AuthSchool -> (AuthRoute -> Route site) -> WidgetT site IO () createAccountWidget u tp = do schools <- getSchools theSchool <- getSchool u let create = case u of Nothing -> tp createAccountR Just u' -> tp $ createAccountSchoolR u' setTitleI Msg.RegisterTitle [whamlet| $newline never <div .container> $if L.null schools _{Msg.ErrorNoSchool} $else <form method="post" action=@{create} .form-signin role=form> <h2 .form-signin-heading>_{Msg.RegisterTitle} $maybe u' <- theSchool <input type="hidden" name="school" value=#{toString $ Schule.name u'}> $nothing <select .form-control name="school"> $forall school <- schools <option value=#{toString $ Schule.unr school}> #{toString $ Schule.name school} <input type="text" name="matriculationnumber" .form-control placeholder=_{Msg.MatriculationNumber} required autofocus> <input type="text" name="firstname" .form-control placeholder=_{Msg.FirstName} required> <input type="text" name="surname" .form-control placeholder=_{Msg.Surname} required> <input type="text" name="email" .form-control placeholder=_{Msg.EmailAddress} required> <button type=submit .btn .btn-lg .btn-primary .btn-block>_{Msg.Register} |] errorWidget :: (MonadBaseControl IO m, MonadIO m, MonadThrow m, RenderMessage site YesodAuthAutotoolMessage) => WidgetT site m () errorWidget = do setTitle "Error" [whamlet| $newline never <p>Error |] invalidEmailWidget :: (MonadBaseControl IO m, MonadIO m, MonadThrow m, RenderMessage site YesodAuthAutotoolMessage) => WidgetT site m () invalidEmailWidget = do setTitleI Msg.ErrorInvalidEmail [whamlet| $newline never <p>_{Msg.ErrorInvalidEmail} |] mailSentWidget :: (MonadBaseControl IO m, MonadIO m, MonadThrow m, RenderMessage site YesodAuthAutotoolMessage) => T.Text -> MNr -> WidgetT site m () mailSentWidget u m = do setTitleI Msg.ResetPasswordTitle [whamlet| $newline never <p>_{Msg.EmailSent u m} |] resetPasswordWidget :: (YesodAuthAutotool master, PathPiece AuthSchool, PathPiece AuthStudent, RenderMessage master YesodAuthAutotoolMessage) => AuthSchool -> AuthStudent -> (AuthRoute -> Route master) -> WidgetT master IO () resetPasswordWidget u m tp = do setTitleI Msg.ResetPasswordTitle [whamlet| $newline never <div .container> <form method="post" action=@{tp $ resetPasswordR u m} .form-signin role=form> <h2 .form-signin-heading>_{Msg.ResetPasswordTitle} <p>_{Msg.ResetPasswordDescription} <button type=submit .btn .btn-lg .btn-primary .btn-block autofocus>_{Msg.ResetPassword} |]
marcellussiegburg/autotool
yesod/Yesod/Auth/Autotool/Widget.hs
gpl-2.0
5,457
0
14
1,209
728
386
342
82
2
-- group same element of a list p9 :: Eq a => [a] -> [[a]] p9 [] = [] p9 (x:xs) = (x : takeWhile (==x) xs) : p9 (dropWhile (== x) xs)
yalpul/CENG242
H99/1-10/p9.hs
gpl-3.0
136
0
9
35
89
48
41
3
1
{-# LANGUAGE MultiParamTypeClasses #-} module Language.Verse.Transform.Chess where import Text.Blaze.Html5 ((!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Data.Monoid import Data.String import Language.Verse.Renderer import Language.Verse.Renderer.Html import System.IO import Control.Monad.IO.Class import Control.Monad.State import Control.Monad.Trans data ChessTC = ChessTC { chessCount :: Int, chessBoardPath :: String } deriving Show scriptInclude :: String -> Rendering HtmlRenderContext scriptInclude path = H.script ! A.src (fromString path) $ mempty instance Transform HtmlRenderContext ChessTC where renderTransform cc s = do lift . lift . put $ TransformContext (cc { chessCount = chessCount cc + 1 }) return $ chessInclude <> (H.script $ H.toHtml $ unwords [playFn, eventListener]) <> (H.canvas ! A.id (fromString bdName) $ mempty) where fnName = "play" ++ show (chessCount cc) bdName = "board" ++ show (chessCount cc) chessInclude = if chessCount cc < 1 then scriptInclude (chessBoardPath cc) else mempty moveList = if null s then "" else "game.move(\"" ++ s ++ "\");" gameDef = "game = Chessboard.newGame();" drawCmd = "game.draw(\"" ++ bdName ++ "\");" eventListener = "window.addEventListener('load', " ++ fnName ++ ", false);" playFn = "function " ++ fnName ++ "() {" ++ gameDef ++ "\n" ++ moveList ++ "\n" ++ drawCmd ++ "}" {- H.img ! A.src ( -} {- fromString $ "http://www.eddins.net/steve/chess/ChessImager/ChessImager.php?fen=" ++ s ++ "/" -} {- ) -}
sykora/verse
src/Language/Verse/Transform/Chess.hs
gpl-3.0
1,745
0
15
431
434
243
191
34
1
module Selectable where import Prelude hiding(id) import Data.IxSet as IS import Data.Unique import Data.Typeable import Foreign.C.Types import Graphics.UI.SDL(Rect(..), Renderer) import EasierSdl type Selected = IxSet SelectableId class Selectable a where id :: a -> Unique boundingBox :: a -> Rect newtype SelectableId = SelectableId Unique deriving (Eq, Ord, Typeable) instance Indexable SelectableId where empty = ixSet [ ixFun $ return ] getId :: Selectable a => a -> SelectableId getId = SelectableId . id borderColor :: RGB borderColor = (RGB 255 255 255) displaySelection :: Selectable a => Renderer -> Selected -> a -> IO () displaySelection renderer selected item = if isSelected then display else return () where isSelected = not . IS.null $ selected @= getId item display = displayBorder renderer borderColor 3 2 $ boundingBox item displayBorder :: Renderer -> RGB -> CInt -> CInt -> Rect -> IO () displayBorder renderer color bw bs (Rect x y w h) = mapM_ (fillRect renderer color) [up, right,bottom, left] where up = Rect (x-bw-bs) (y-bw-bs) (w+2*bw+2*bs) bw right = Rect (x+w+bs) (y-bs) bw (h+bw+2*bs) bottom = Rect (x-bw-bs) (y+h+bs) (w+bw+2*bs) bw left = Rect (x-bw-bs) (y-bs) bw (h+2*bs)
Tomsik/SpaceHegemony
src/Selectable.hs
gpl-3.0
1,292
0
12
277
564
303
261
30
2
module HackerRank.Utilities.Manager.Read where import Control.Applicative import Control.Monad import System.Process import HackerRank.Utilities.Manager.Haskell ( pushInMain ) copyStringToPasteboard :: String -> IO () copyStringToPasteboard = void . readCreateProcessWithExitCode (shell "pbcopy") copySource :: FilePath -> IO () copySource = rewriteSource >=> copyStringToPasteboard printSource :: FilePath -> IO () printSource = rewriteSource >=> putStrLn rewriteSource :: FilePath -> IO String rewriteSource = pushInMain
oopsno/hrank
src/HackerRank/Utilities/Manager/Read.hs
unlicense
530
0
8
65
130
72
58
13
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} module KMean where import Data.List import Data.Default import qualified Data.Map as M class (Default v, Ord v) => Vector v where distance :: v -> v -> Double centroid :: [v] -> v instance Vector (Double, Double) where distance (a, b) (c,d) = sqrt $ (a-c)^2 + (b-d)^2 centroid lst = let (u, v) = foldr (\(a,b) (c,d) -> (a+c,b+d)) (0.0, 0.0) lst n = fromIntegral $ length lst in (u / n, v / n) class Vector v => Vectorizable e v where toVector :: e -> v instance Vectorizable (Double, Double) (Double, Double) where toVector = id --yxfun p m = let chosenCentroid = minimumBy (\x y -> compare (distance x $ toVector p) (distance y $ toVector p) in M.adjust (p:) clusterAssignmentPhase :: (Vector v, Vectorizable e v) => [v] -> [e] -> M.Map v [e] clusterAssignmentPhase centroids points = let initialMap = M.fromList $ zip centroids (repeat []) in foldr (\p m -> let chosenCentroid = minimumBy (\x y -> compare ( distance x $ toVector p) ( distance y $ toVector p)) centroids in M.adjust (p:) chosenCentroid m) initialMap points newCentroidPhase :: (Vector v, Vectorizable e v) => M.Map v [e] -> [(v,v)] newCentroidPhase = M.toList . fmap (centroid . map toVector) initializeSimple :: Int -> [e] -> [(Double,Double)] initializeSimple 0 _ = [] initializeSimple n v = (fromIntegral n::Double, fromIntegral n::Double) : initializeSimple (n-1) v shouldStop :: (Vector v) => [(v,v)] -> Double -> Bool shouldStop centroids threshold = foldr (\(x,y) s -> s + distance x y) 0.0 centroids < threshold kMeans :: (Vector v, Vectorizable e v) => (Int -> [e] -> [v]) -- initialization function -> Int -- number of centroids -> [e] -- the information -> Double -- threshold -> [v] -- final centroids kMeans i k points = kMeans' (i k points) points kMeans' :: (Vector v, Vectorizable e v) => [v] -> [e] -> Double -> [v] kMeans' centroids points threshold = let assignments = clusterAssignmentPhase centroids points oldNewCentroids = newCentroidPhase assignments newCentroids = map snd oldNewCentroids in if shouldStop oldNewCentroids threshold then newCentroids else kMeans' newCentroids points threshold genCluster :: M.Map (Double,Double) [(Double,Double)] --genCluster :: (Vector v, Vectorizable e v) => [e] -> M.Map v [e] genCluster = let es = ([(1,2),(3,4),(5,6)]::[(Double,Double)]) f x = toVector x::(Double,Double) in M.fromList $ zip (map f es) (repeat [])
wangyixiang/beginninghaskell
chapter6/src/Chapter6/KMean.hs
unlicense
2,758
9
16
733
1,033
564
469
53
2
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs, FlexibleContexts, ScopedTypeVariables, MultiParamTypeClasses #-} import Database.Persist import Database.Persist.Sqlite import Database.Persist.TH import Control.Monad.IO.Class (liftIO) import Data.Time (UTCTime) import Data.Text (Text) import qualified Data.Text as T import Control.Monad.Logger import Control.Monad.Trans.Resource (runResourceT) import qualified Data.Octree as Octree import qualified Data.Map as Map import qualified Data.List as List import qualified Data.Function as F import qualified Data.Set as Set import qualified Math.Combinatorics.Multiset as MS import qualified Data.String as String import qualified Debug.Trace as Trace share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistUpperCase| System Id Int sqltype=int sql=SystemId name Text sqltype=text sql=SystemName x Double sqltype=double sql=SystemX y Double sqltype=double sql=SystemY z Double sqltype=double sql=SystemZ size Double Maybe sqltype=double sql=SystemSize deriving Show Commod Id Text sqltype=text sql=name -- name Text sql=Name type Text Maybe sql=Type avg Double Maybe sqltype=double sql=Avg deriving Show Station sql=SysStation Id Int sqltype=int sql=SysStationID systemName Text sqltype=text sql=SysStationSystem stationName Text sqltype=text sql=SysStationStation -- 'SysStationLookup' TEXT COLLATE NOCASE NOT NULL UNIQUE, dist Int sqltype=int sql=SysStationDist -- 'SysStationDist' INTEGER, -- 'SysStationBM' TEXT COLLATE NOCASE , maxPad Text Maybe sqltype=text sql=SysStationMaxPad -- 'SysStationMaxPad' TEXT COLLATE NOCASE , padSize Int Maybe sqltype=int sql=SysStationPadSize -- 'SysStationFaction' TEXT COLLATE NOCASE , -- 'SysStationGovernment' TEXT COLLATE NOCASE , -- 'SysStationLastUpdate' DATETIME deriving Show SC Id Int sqltype=int sql=SCid systemName Text sqltype=text sql=SCStationSystem stationName Text sqltype=text sql=SCStationName stationCommod Text sqltype=text sql=SCStationCommod sell Int sqltype=int sql=SCStationSell -- sell to station demand Double Maybe sql=SCStationDemand price Int sqltype=int sql=SCStationPrice stock Double sql=SCStationStock -- 'SCStationLocal' TEXT COLLATE NOCASE , -- 'SCStationCommodGroup' TEXT COLLATE NOCASE , -- 'SCStationCommodAvg' INTEGER, -- 'SCStationPrice' INTEGER, -- 'SCStationSell' INTEGER, -- 'SCStationFence' INTEGER, -- 'SCStationDemand' REAL, -- 'SCStationDemandCode' TEXT COLLATE NOCASE , -- unused? -- 'SCStationSupply' REAL, -- 'SCStationSupplyCode' TEXT COLLATE NOCASE , -- unused? -- 'SCStationStock' REAL, -- 'SCStationIllegal' TEXT COLLATE NOCASE DEFAULT 0, -- 'SCStationConsumer' TEXT COLLATE NOCASE , -- 'SCStationProducer' TEXT COLLATE NOCASE , -- 'SCStationLastUpdate' TEXT COLLATE NOCASE , -- 'SCStationForSale' TEXT DEFAULT 1, -- 'S1' TEXT COLLATE NOCASE , -- 'S2' TEXT COLLATE NOCASE , -- 'S3' TEXT COLLATE NOCASE , -- 'S4' TEXT COLLATE NOCASE , -- 'N1' DOUBLE, -- 'N2' DOUBLE, -- 'N3' DOUBLE, -- 'N4' DOUBLE, -- 'B1' Bit, -- 'B2' Bit, -- 'SCUNIQUE' TEXT COLLATE NOCASE NOT NULL, deriving Show |] connStr = "C:\\Program Files (x86)\\Slopeys ED BPC\\ED4.db" systemPosition:: System -> Octree.Vector3 systemPosition v = Octree.Vector3 (systemX v) (systemY v) (systemZ v) extractStations systemStations cur = case Map.lookup (T.toLower $ systemName cur) systemStations of Nothing -> [] Just stations -> stations scKey x = (T.toLower $ sCSystemName x, T.toLower $ sCStationName x) stationKey x = (T.toLower $ stationSystemName x, T.toLower $ stationStationName x) goodKey = T.toLower . sCStationCommod instance Eq Station where x == y = sys x == sys y && station x == station y where sys = T.toLower . stationSystemName station = T.toLower . stationStationName x /= y = sys x /= sys y || station x /= station y where sys = T.toLower . stationSystemName station = T.toLower . stationStationName extractGoods resSc nearStations = Map.fromList [(scKey $ head scs, Map.fromList [(goodKey g, g) | g <- scs]) | scs <- grouped] where grouped = List.groupBy ((==) `F.on` scKey) $ List.sortBy (compare `F.on` scKey) [v | Entity k v <- resSc] -- safeHead [] = [] -- safeHead (x:ys) = profit :: SC -> (Maybe SC) -> Int profit bg maybe_sg = -- Trace.trace (show bg ++ " " ++ show maybe_sg ++ show (effectiveSell maybe_sg - effectivePrice bg) ) if baseProfit > 10000 then 0 else if sCStationCommod bg == "Slaves" then 0 else baseProfit where baseProfit = effectiveSell maybe_sg - effectivePrice bg effectiveSell Nothing = 0 effectiveSell (Just sc) = sCSell sc effectivePrice sc = if sCStock sc < 1000 then 100000 else if sCPrice sc < 1 then 100000 else sCPrice sc -- buy at price, sell at sell, -- must have supply must have demand, > 1000... demand is blank in bpc's db. reverseSort :: (Ord a) => [(a, a1)] -> [(a, a1)] reverseSort = List.sortBy inversecompare where inversecompare (x, _) (y, _) = y `compare` x bestbuy stationGoods x y = case List.length profits of 0 -> (0, "Nothing") x -> sane (head profits) where sane (profit, item) = if profit > 0 then (profit, item) else (0, "Nothing") buys = l x sells = l y l s = case Map.lookup (stationKey s) stationGoods of Just b -> b Nothing -> Map.empty profits = reverseSort [ (profit bg $ Map.lookup k sells, k) | (k, bg) <- Map.toList buys] trades :: (String.IsString t, Ord t) => Map.Map (Text, Text) (Map.Map t SC) -> [Station] -> (Int, [((Int, t), (Text, Text))]) trades stationGoods route = ((foldr f 0 buys), buys) where pairs [] = [] pairs [x] = [] pairs (x:y:xz) = (x,y):pairs (y:xz) cycle = (List.last route):route buys = [(bestbuy stationGoods x y, stationKey x) | (x, y) <- pairs cycle] f ((p, _), _) acc = p + acc routes xs steps = List.concat [MS.cycles s | s <- MS.kSubsets steps stations] where stations = MS.fromDistinctList xs usableStation x = if stationDist x < 4000 then usablePad x else False where usablePad x = case stationPadSize x of Nothing -> True -- who knows Just 0 -> True -- in case 0 == any Just s -> if s < 3 then False else True showRoute (profit, xs) = ((fromIntegral profit) / (fromIntegral $ List.length xs), xs) lookupData = runStdoutLoggingT $ withSqlitePool connStr 10 $ \pool -> runResourceT $ flip runSqlPool pool $ do -- printMigration migrateAll res_system :: [Entity System] <- selectList [] [] --, OffsetBy 1] -- LimitTo 1, OffsetBy 1] res_commodities :: [Entity Commod] <- selectList [] [] resSc :: [Entity SC] <- selectList [ SCStationName !=. "ANY"] [] -- SCStationCommod ==. "Resonating Separators" -- , SCSystem ==. "Keiadabiko" -- , SCPrice ==. 5457 -- , SCStationName ==. "Maclean Vision" -- ] [LimitTo 1] resStations :: [Entity Station] <- selectList [StationStationName !=. "ANY"] [] return (res_system, res_commodities, resSc, resStations) -- res :: [Entity Commod] <- selectList [] [LimitTo 1, OffsetBy 1] --res :: [Entity SC] <- selectList [SCStationCommod ==. "Resonating Separators" -- , SCSystem ==. "Keiadabiko" -- , SCPrice ==. 5457 -- , SCStationName ==. "Maclean Vision" -- ] [LimitTo 1] -- liftIO $ print res -- TODOs -- we could calculate the best route between each station once, then for the path calculation avoid all the product work etc. main :: IO () main = do (res_system, res_commodities, resSc, resStations) <- lookupData let systems = [v | Entity k v <- res_system] -- [System] stations = List.groupBy ((==) `F.on` (T.toLower . stationSystemName)) $ List.sortBy (compare `F.on` (T.toLower . stationSystemName)) $ List.filter usableStation [v | Entity k v <- resStations] systemStations = Map.fromList [(T.toLower $ stationSystemName $ head v, v) | v <- stations] --groupBy (\(x _) (y _) -> (x == y)) systemNames = Map.fromList [(T.toLower $ systemName v, v) | v <- systems] --stationsByName = Map.fromList stations systemMap = Octree.fromList [(systemPosition v, v) | v <- systems] -- octree (pos -> system) keiadabiko = case Map.lookup "anlave" systemNames of Nothing -> error "wat" Just x -> x near = Octree.withinRange systemMap 25.0 (systemPosition keiadabiko) nearStations = List.concatMap (extractStations systemStations) [s | (_, s) <- near] stationGoods = extractGoods resSc nearStations route1 = routes nearStations 2 route2 = routes nearStations 3 route3 = routes nearStations 4 -- route4 = routes nearStations 5 liftIO $ print [systemName s | (_, s) <- near] -- liftIO $ print $ take 3 route1 -- liftIO $ print $ List.length route1 liftIO $ print $ showRoute $ List.maximum $ map (trades stationGoods) route1 liftIO $ print $ showRoute $ List.maximum $ map (trades stationGoods) route2 liftIO $ print $ showRoute $ List.maximum $ map (trades stationGoods) route3 -- liftIO $ print $ showRoute $ head $ reverseSort $ map (trades stationGoods) route4
rbtcollins/edtrades
src/Main.hs
apache-2.0
9,971
0
17
2,598
2,143
1,148
995
108
6
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE PolyKinds #-} module Data.Memorable.Theme.Metric where import Data.Memorable type UnitsPlural = ToTree '[ "meters" , "seconds" , "grams" , "liters" , "volts" , "ohms" , "amps" , "henries" ] type Units = ToTree '[ "meter" , "second" , "gram" , "liter" , "volt" , "ohm" , "amp" , "henry" ] type SIPrefix = ToTree '[ "atto" , "femto" , "pico" , "nano" , "micro" , "milli" , "centi" , "deci" , "deca" , "hecto" , "kilo" , "mega" , "giga" , "tera" , "peta" , "exa" ] type Measurements = Number Dec 5 :- "." :- Number Dec 3 :- " " :- SIPrefix :- UnitsPlural :- " per " :- SIPrefix :- Units :- "^" :- NumberWithOffset Dec 2 2 measurements :: Proxy Measurements measurements = Proxy
luke-clifton/memorable-bits
src/Data/Memorable/Theme/Metric.hs
bsd-2-clause
968
0
15
359
221
132
89
54
1
module Circular where data Circular a = Circular [a] [a] toList (Circular xs ys) = xs ++ ys fromList = Circular [] instance Functor Circular where fmap f (Circular xs ys) = Circular (map f xs) (map f ys)
cullina/Extractor
src/Circular.hs
bsd-3-clause
209
0
8
44
99
52
47
6
1
primitive primAddInt "bluejelly.Int.add", primSubInt "bluejelly.Int.sub" :: Int -> Int -> Int
ppedemon/Bluejelly
bluejelly-bjc/src/test/resources/parser.tests/Prims.hs
bsd-3-clause
101
6
3
18
23
12
11
-1
-1
module Domains.Multiplicative where infixl 7 * class Multiplicative a where (*) :: a -> a -> a one :: a instance Multiplicative Int where (*) = (Prelude.*) one = 1 instance Multiplicative Integer where (*) = (Prelude.*) one = 1 instance Multiplicative Double where (*) = (Prelude.*) one = 1
pmilne/algebra
src/Domains/Multiplicative.hs
bsd-3-clause
312
0
8
71
112
68
44
14
0
module Matterhorn.Draw.Autocomplete ( autocompleteLayer ) where import Prelude () import Matterhorn.Prelude import Brick import Brick.Widgets.Border import Brick.Widgets.List ( renderList, listElementsL, listSelectedFocusedAttr , listSelectedElement ) import qualified Data.Text as T import Network.Mattermost.Types ( User(..), Channel(..) ) import Matterhorn.Constants ( normalChannelSigil ) import Matterhorn.Draw.Util import Matterhorn.Themes import Matterhorn.Types import Matterhorn.Types.Common ( sanitizeUserText ) autocompleteLayer :: ChatState -> Widget Name autocompleteLayer st = case st^.csCurrentTeam.tsEditState.cedAutocomplete of Nothing -> emptyWidget Just ac -> renderAutocompleteBox st ac userNotInChannelMarker :: T.Text userNotInChannelMarker = "*" elementTypeLabel :: AutocompletionType -> Text elementTypeLabel ACUsers = "Users" elementTypeLabel ACChannels = "Channels" elementTypeLabel ACCodeBlockLanguage = "Languages" elementTypeLabel ACEmoji = "Emoji" elementTypeLabel ACCommands = "Commands" renderAutocompleteBox :: ChatState -> AutocompleteState -> Widget Name renderAutocompleteBox st ac = let matchList = _acCompletionList ac maxListHeight = 5 visibleHeight = min maxListHeight numResults numResults = length elements elements = matchList^.listElementsL label = withDefAttr clientMessageAttr $ txt $ elementTypeLabel (ac^.acType) <> ": " <> (T.pack $ show numResults) <> " match" <> (if numResults == 1 then "" else "es") <> " (Tab/Shift-Tab to select)" selElem = snd <$> listSelectedElement matchList curChan = st^.csCurrentChannel footer = case renderAutocompleteFooterFor curChan =<< selElem of Just w -> hBorderWithLabel w _ -> hBorder curUser = myUsername st in if numResults == 0 then emptyWidget else Widget Greedy Greedy $ do ctx <- getContext let rowOffset = ctx^.availHeightL - 3 - editorOffset - visibleHeight editorOffset = if st^.csCurrentTeam.tsEditState.cedEphemeral.eesMultiline then multilineHeightLimit else 0 render $ translateBy (Location (0, rowOffset)) $ vBox [ hBorderWithLabel label , vLimit visibleHeight $ renderList (renderAutocompleteAlternative curUser) True matchList , footer ] renderAutocompleteFooterFor :: ClientChannel -> AutocompleteAlternative -> Maybe (Widget Name) renderAutocompleteFooterFor _ (SpecialMention MentionChannel) = Nothing renderAutocompleteFooterFor _ (SpecialMention MentionAll) = Nothing renderAutocompleteFooterFor ch (UserCompletion _ False) = Just $ hBox [ txt $ "(" , withDefAttr clientEmphAttr (txt userNotInChannelMarker) , txt ": not a member of " , withDefAttr channelNameAttr (txt $ normalChannelSigil <> ch^.ccInfo.cdName) , txt ")" ] renderAutocompleteFooterFor _ (ChannelCompletion False ch) = Just $ hBox [ txt $ "(" , withDefAttr clientEmphAttr (txt userNotInChannelMarker) , txt ": you are not a member of " , withDefAttr channelNameAttr (txt $ normalChannelSigil <> sanitizeUserText (channelName ch)) , txt ")" ] renderAutocompleteFooterFor _ (CommandCompletion src _ _ _) = case src of Server -> Just $ hBox [ txt $ "(" , withDefAttr clientEmphAttr (txt serverCommandMarker) , txt ": command provided by the server)" ] Client -> Nothing renderAutocompleteFooterFor _ _ = Nothing serverCommandMarker :: Text serverCommandMarker = "*" renderAutocompleteAlternative :: Text -> Bool -> AutocompleteAlternative -> Widget Name renderAutocompleteAlternative _ sel (EmojiCompletion e) = padRight Max $ renderEmojiCompletion sel e renderAutocompleteAlternative _ sel (SpecialMention m) = padRight Max $ renderSpecialMention m sel renderAutocompleteAlternative curUser sel (UserCompletion u inChan) = padRight Max $ renderUserCompletion curUser u inChan sel renderAutocompleteAlternative _ sel (ChannelCompletion inChan c) = padRight Max $ renderChannelCompletion c inChan sel renderAutocompleteAlternative _ _ (SyntaxCompletion t) = padRight Max $ txt t renderAutocompleteAlternative _ _ (CommandCompletion src n args desc) = padRight Max $ renderCommandCompletion src n args desc renderSpecialMention :: SpecialMention -> Bool -> Widget Name renderSpecialMention m sel = let usernameWidth = 18 padTo n a = hLimit n $ vLimit 1 (a <+> fill ' ') maybeForce = if sel then forceAttr listSelectedFocusedAttr else id t = autocompleteAlternativeReplacement $ SpecialMention m desc = case m of MentionChannel -> "Notifies all users in this channel" MentionAll -> "Mentions all users in this channel" in maybeForce $ hBox [ txt " " , padTo usernameWidth $ withDefAttr clientEmphAttr $ txt t , txt desc ] renderEmojiCompletion :: Bool -> T.Text -> Widget Name renderEmojiCompletion sel e = let maybeForce = if sel then forceAttr listSelectedFocusedAttr else id in maybeForce $ padLeft (Pad 2) $ withDefAttr emojiAttr $ txt $ autocompleteAlternativeReplacement $ EmojiCompletion e renderUserCompletion :: Text -> User -> Bool -> Bool -> Widget Name renderUserCompletion curUser u inChan selected = let usernameWidth = 18 fullNameWidth = 25 padTo n a = hLimit n $ vLimit 1 (a <+> fill ' ') username = userUsername u fullName = (sanitizeUserText $ userFirstName u) <> " " <> (sanitizeUserText $ userLastName u) nickname = sanitizeUserText $ userNickname u maybeForce = if selected then forceAttr listSelectedFocusedAttr else id memberDisplay = if inChan then txt " " else withDefAttr clientEmphAttr $ txt $ userNotInChannelMarker <> " " in maybeForce $ hBox [ memberDisplay , padTo usernameWidth $ colorUsername curUser username ("@" <> username) , padTo fullNameWidth $ txt fullName , txt nickname ] renderChannelCompletion :: Channel -> Bool -> Bool -> Widget Name renderChannelCompletion c inChan selected = let urlNameWidth = 30 displayNameWidth = 30 padTo n a = hLimit n $ vLimit 1 (a <+> fill ' ') maybeForce = if selected then forceAttr listSelectedFocusedAttr else id memberDisplay = if inChan then txt " " else withDefAttr clientEmphAttr $ txt $ userNotInChannelMarker <> " " in maybeForce $ hBox [ memberDisplay , padTo urlNameWidth $ withDefAttr channelNameAttr $ txt $ normalChannelSigil <> (sanitizeUserText $ channelName c) , padTo displayNameWidth $ withDefAttr channelNameAttr $ txt $ sanitizeUserText $ channelDisplayName c , vLimit 1 $ txt $ sanitizeUserText $ channelPurpose c ] renderCommandCompletion :: CompletionSource -> Text -> Text -> Text -> Widget Name renderCommandCompletion src name args desc = (txt $ " " <> srcTxt <> " ") <+> withDefAttr clientMessageAttr (txt $ "/" <> name <> if T.null args then "" else " " <> args) <+> (txt $ " - " <> desc) where srcTxt = case src of Server -> serverCommandMarker Client -> " "
matterhorn-chat/matterhorn
src/Matterhorn/Draw/Autocomplete.hs
bsd-3-clause
8,303
0
18
2,683
1,944
986
958
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} module Protocol.ROC.PointTypes.PointType2 where import Data.Binary.Get (getByteString, getWord8, getWord16le, getWord32le, Get) import Data.ByteString (ByteString) import Data.Int (Int16) import Data.Word (Word8,Word16,Word32) import Prelude (($), return, Bool, Eq, Float, Read, Show) import Protocol.ROC.Float (getIeeeFloat32) import Protocol.ROC.Utils (anyButNull,getInt16) data PointType2 = PointType2 { pointType2PointTag :: !PointType2PointTag ,pointType2TimeOn :: !PointType2TimeOn ,pointType2Spare :: !PointType2Spare ,pointType2Status :: !PointType2Status ,pointType2BitfieldHigh :: !PointType2BitfieldHigh ,pointType2BitfieldLow :: !PointType2BitfieldLow ,pointType2AccumulatedValue :: !PointType2AccumulatedValue ,pointType2Units :: !PointType2Units ,pointType2CycleTime :: !PointType2CycleTime ,pointType2Count0 :: !PointType2Count0 ,pointType2Count100 :: !PointType2Count100 ,pointType2LowReading :: !PointType2LowReading ,pointType2HighReading :: !PointType2HighReading ,pointType2EuValue :: !PointType2EuValue ,pointType2AlarmMode :: !PointType2AlarmMode ,pointType2ScanningMode :: !PointType2ScanningMode ,pointType2ManualState :: !PointType2ManualState ,pointType2PhysicalState :: !PointType2PhysicalState } deriving (Read,Eq, Show) type PointType2PointTag = ByteString type PointType2TimeOn = Word16 type PointType2Spare = Word8 type PointType2Status = Bool type PointType2BitfieldHigh = Word8 type PointType2BitfieldLow = Word8 type PointType2AccumulatedValue = Word32 type PointType2Units = ByteString type PointType2CycleTime = Word16 type PointType2Count0 = Int16 type PointType2Count100 = Int16 type PointType2LowReading = Float type PointType2HighReading = Float type PointType2EuValue = Float type PointType2AlarmMode = Word8 type PointType2ScanningMode = Bool type PointType2ManualState = Word8 type PointType2PhysicalState = Word8 pointType2Parser :: Get PointType2 pointType2Parser = do pointId <- getByteString 10 timeon <- getWord16le spare <- getWord8 sts <- anyButNull cfg <- getWord8 alarmCode <- getWord8 accumulatedvalue <- getWord32le units <- getByteString 10 cycleTime <- getWord16le count0 <- getInt16 count100 <- getInt16 lowReading <- getIeeeFloat32 highReading <- getIeeeFloat32 euValue <- getIeeeFloat32 alarmMode <- getWord8 scanningMode <- anyButNull manualState <- getWord8 physicalState <- getWord8 return $ PointType2 pointId timeon spare sts cfg alarmCode accumulatedvalue units cycleTime count0 count100 lowReading highReading euValue alarmMode scanningMode manualState physicalState
plow-technologies/roc-translator
src/Protocol/ROC/PointTypes/PointType2.hs
bsd-3-clause
3,439
0
9
1,128
568
320
248
114
1
{-# LANGUAGE OverloadedStrings, GADTs #-} -- | A renderer that produces a lazy 'L.Text' value, using the Text Builder. -- module Text.Blaze.Renderer.Text ( renderMarkupBuilder , renderMarkupBuilderWith , renderMarkup , renderMarkupWith , renderHtmlBuilder , renderHtmlBuilderWith , renderHtml , renderHtmlWith ) where import Data.Monoid (mappend, mempty) import Data.List (isInfixOf) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) import qualified Data.Text.Lazy as L import Data.ByteString (ByteString) import qualified Data.ByteString as S (isInfixOf) import Text.Blaze.Internal import Data.Text.Lazy.Builder (Builder) import qualified Data.Text.Lazy.Builder as B -- | Escape predefined XML entities in a text value -- escapeMarkupEntities :: Text -- ^ Text to escape -> Builder -- ^ Resulting text builder escapeMarkupEntities = T.foldr escape mempty where escape :: Char -> Builder -> Builder escape '<' b = B.fromText "&lt;" `mappend` b escape '>' b = B.fromText "&gt;" `mappend` b escape '&' b = B.fromText "&amp;" `mappend` b escape '"' b = B.fromText "&quot;" `mappend` b escape '\'' b = B.fromText "&#39;" `mappend` b escape x b = B.singleton x `mappend` b -- | Render a 'ChoiceString'. TODO: Optimization possibility, apply static -- argument transformation. -- fromChoiceString :: (ByteString -> Text) -- ^ Decoder for bytestrings -> ChoiceString -- ^ String to render -> Builder -- ^ Resulting builder fromChoiceString _ (Static s) = B.fromText $ getText s fromChoiceString _ (String s) = escapeMarkupEntities $ T.pack s fromChoiceString _ (Text s) = escapeMarkupEntities s fromChoiceString d (ByteString s) = B.fromText $ d s fromChoiceString d (PreEscaped x) = case x of String s -> B.fromText $ T.pack s Text s -> B.fromText s s -> fromChoiceString d s fromChoiceString d (External x) = case x of -- Check that the sequence "</" is *not* in the external data. String s -> if "</" `isInfixOf` s then mempty else B.fromText (T.pack s) Text s -> if "</" `T.isInfixOf` s then mempty else B.fromText s ByteString s -> if "</" `S.isInfixOf` s then mempty else B.fromText (d s) s -> fromChoiceString d s fromChoiceString d (AppendChoiceString x y) = fromChoiceString d x `mappend` fromChoiceString d y fromChoiceString _ EmptyChoiceString = mempty {-# INLINE fromChoiceString #-} -- | Render markup to a text builder renderMarkupBuilder :: Markup -> Builder renderMarkupBuilder = renderMarkupBuilderWith decodeUtf8 {-# INLINE renderMarkupBuilder #-} renderHtmlBuilder :: Markup -> Builder renderHtmlBuilder = renderMarkupBuilder {-# INLINE renderHtmlBuilder #-} {-# DEPRECATED renderHtmlBuilder "Use renderHtmlBuilder from Text.Blaze.Html.Renderer.Text instead" #-} -- | Render some 'Markup' to a Text 'Builder'. -- renderMarkupBuilderWith :: (ByteString -> Text) -- ^ Decoder for bytestrings -> Markup -- ^ Markup to render -> Builder -- ^ Resulting builder renderMarkupBuilderWith d = go mempty where go :: Builder -> MarkupM b -> Builder go attrs (Parent _ open close content) = B.fromText (getText open) `mappend` attrs `mappend` B.singleton '>' `mappend` go mempty content `mappend` B.fromText (getText close) go attrs (CustomParent tag content) = B.singleton '<' `mappend` fromChoiceString d tag `mappend` attrs `mappend` B.singleton '>' `mappend` go mempty content `mappend` B.fromText "</" `mappend` fromChoiceString d tag `mappend` B.singleton '>' go attrs (Leaf _ begin end) = B.fromText (getText begin) `mappend` attrs `mappend` B.fromText (getText end) go attrs (CustomLeaf tag close) = B.singleton '<' `mappend` fromChoiceString d tag `mappend` attrs `mappend` (if close then B.fromText " />" else B.singleton '>') go attrs (AddAttribute _ key value h) = go (B.fromText (getText key) `mappend` fromChoiceString d value `mappend` B.singleton '"' `mappend` attrs) h go attrs (AddCustomAttribute key value h) = go (B.singleton ' ' `mappend` fromChoiceString d key `mappend` B.fromText "=\"" `mappend` fromChoiceString d value `mappend` B.singleton '"' `mappend` attrs) h go _ (Content content) = fromChoiceString d content go _ (Comment comment) = B.fromText "<!-- " `mappend` fromChoiceString d comment `mappend` " -->" go attrs (Append h1 h2) = go attrs h1 `mappend` go attrs h2 go _ (Empty _) = mempty {-# NOINLINE go #-} {-# INLINE renderMarkupBuilderWith #-} renderHtmlBuilderWith :: (ByteString -> Text) -- ^ Decoder for bytestrings -> Markup -- ^ Markup to render -> Builder -- ^ Resulting builder renderHtmlBuilderWith = renderMarkupBuilderWith {-# INLINE renderHtmlBuilderWith #-} {-# DEPRECATED renderHtmlBuilderWith "Use renderHtmlBuilderWith from Text.Blaze.Html.Renderer.Text instead" #-} -- | Render markup to a lazy Text value. If there are any ByteString's in the -- input markup, this function will consider them as UTF-8 encoded values and -- decode them that way. -- renderMarkup :: Markup -> L.Text renderMarkup = renderMarkupWith decodeUtf8 {-# INLINE renderMarkup #-} renderHtml :: Markup -> L.Text renderHtml = renderMarkup {-# INLINE renderHtml #-} {-# DEPRECATED renderHtml "Use renderHtml from Text.Blaze.Html.Renderer.Text instead" #-} -- | Render markup to a lazy Text value. This function allows you to specify what -- should happen with ByteString's in the input HTML. You can decode them or -- drop them, this depends on the application... -- renderMarkupWith :: (ByteString -> Text) -- ^ Decoder for ByteString's. -> Markup -- ^ Markup to render -> L.Text -- Resulting lazy text renderMarkupWith d = B.toLazyText . renderMarkupBuilderWith d renderHtmlWith :: (ByteString -> Text) -- ^ Decoder for ByteString's. -> Markup -- ^ Markup to render -> L.Text -- ^ Resulting lazy text renderHtmlWith = renderMarkupWith {-# DEPRECATED renderHtmlWith "Use renderHtmlWith from Text.Blaze.Html.Renderer.Text instead" #-}
dylex/blaze-markup
src/Text/Blaze/Renderer/Text.hs
bsd-3-clause
6,791
0
15
1,830
1,474
810
664
130
11
{-# LANGUAGE CPP, MagicHash #-} -- -- (c) The University of Glasgow 2002-2006 -- -- | ByteCodeGen: Generate bytecode from Core module ETA.Interactive.ByteCodeGen ( UnlinkedBCO, byteCodeGen, coreExprToBCOs ) where #include "HsVersions.h" import ETA.Interactive.ByteCodeInstr import ETA.Interactive.ByteCodeItbls import ETA.Interactive.ByteCodeAsm import ETA.Interactive.ByteCodeLink import ETA.Main.DynFlags import ETA.Utils.Outputable import ETA.Utils.Platform import ETA.BasicTypes.Name import ETA.BasicTypes.MkId import ETA.BasicTypes.Id import ETA.CodeGen.ArgRep import qualified ETA.BasicTypes.Id as Id import ETA.Prelude.ForeignCall import ETA.Main.HscTypes import ETA.Core.CoreUtils import ETA.Core.CoreSyn import ETA.Core.PprCore import ETA.BasicTypes.Literal import ETA.Prelude.PrimOp import ETA.Core.CoreFVs import ETA.Types.Type import ETA.BasicTypes.DataCon import ETA.Types.TyCon import ETA.Utils.Util import ETA.BasicTypes.Var import ETA.BasicTypes.VarSet import ETA.Prelude.TysPrim import ETA.Main.ErrUtils import ETA.BasicTypes.Unique import ETA.Utils.FastString import ETA.Utils.Panic import ETA.Utils.OrdList import ETA.BasicTypes.UniqSupply import ETA.Main.BreakArray import ETA.BasicTypes.Module import Foreign import Foreign.C import Control.Monad import Data.Char import Data.Maybe import Data.List import Data.Map (Map) import Data.Ord import qualified Data.ByteString as BS import qualified Data.ByteString.Unsafe as BS import qualified Data.Map as Map import qualified ETA.Utils.FiniteMap as Map byteCodeGen = undefined coreExprToBCOs = undefined -- -- ----------------------------------------------------------------------------- -- -- Generating byte code for a complete module -- byteCodeGen :: DynFlags -- -> Module -- -> CoreProgram -- -> [TyCon] -- -> ModBreaks -- -> IO CompiledByteCode -- byteCodeGen dflags this_mod binds tycs modBreaks -- = do showPass dflags "ByteCodeGen" -- let flatBinds = [ (bndr, freeVars rhs) -- | (bndr, rhs) <- flattenBinds binds] -- us <- mkSplitUniqSupply 'y' -- (BcM_State _dflags _us _this_mod _final_ctr mallocd _, proto_bcos) -- <- runBc dflags us this_mod modBreaks (mapM schemeTopBind flatBinds) -- when (notNull mallocd) -- (panic "ByteCodeGen.byteCodeGen: missing final emitBc?") -- dumpIfSet_dyn dflags Opt_D_dump_BCOs -- "Proto-BCOs" (vcat (intersperse (char ' ') (map ppr proto_bcos))) -- assembleBCOs dflags proto_bcos tycs -- -- ----------------------------------------------------------------------------- -- -- Generating byte code for an expression -- -- Returns: (the root BCO for this expression, -- -- a list of auxilary BCOs resulting from compiling closures) -- coreExprToBCOs :: DynFlags -- -> Module -- -> CoreExpr -- -> IO UnlinkedBCO -- coreExprToBCOs dflags this_mod expr -- = do showPass dflags "ByteCodeGen" -- -- create a totally bogus name for the top-level BCO; this -- -- should be harmless, since it's never used for anything -- let invented_name = mkSystemVarName (mkPseudoUniqueE 0) (fsLit "ExprTopLevel") -- invented_id = Id.mkLocalId invented_name (panic "invented_id's type") -- -- the uniques are needed to generate fresh variables when we introduce new -- -- let bindings for ticked expressions -- us <- mkSplitUniqSupply 'y' -- (BcM_State _dflags _us _this_mod _final_ctr mallocd _ , proto_bco) -- <- runBc dflags us this_mod emptyModBreaks $ -- schemeTopBind (invented_id, freeVars expr) -- when (notNull mallocd) -- (panic "ByteCodeGen.coreExprToBCOs: missing final emitBc?") -- dumpIfSet_dyn dflags Opt_D_dump_BCOs "Proto-BCOs" (ppr proto_bco) -- assembleBCO dflags proto_bco -- -- ----------------------------------------------------------------------------- -- -- Compilation schema for the bytecode generator -- type BCInstrList = OrdList BCInstr -- type Sequel = Word -- back off to this depth before ENTER -- -- Maps Ids to the offset from the stack _base_ so we don't have -- -- to mess with it after each push/pop. -- type BCEnv = Map Id Word -- To find vars on the stack -- {- -- ppBCEnv :: BCEnv -> SDoc -- ppBCEnv p -- = text "begin-env" -- $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (Map.toList p)))) -- $$ text "end-env" -- where -- pp_one (var, offset) = int offset <> colon <+> ppr var <+> ppr (bcIdArgRep var) -- cmp_snd x y = compare (snd x) (snd y) -- -} -- -- Create a BCO and do a spot of peephole optimisation on the insns -- -- at the same time. -- mkProtoBCO -- :: DynFlags -- -> name -- -> BCInstrList -- -> Either [AnnAlt Id VarSet] (AnnExpr Id VarSet) -- -> Int -- -> Word16 -- -> [StgWord] -- -> Bool -- True <=> is a return point, rather than a function -- -> [BcPtr] -- -> ProtoBCO name -- mkProtoBCO dflags nm instrs_ordlist origin arity bitmap_size bitmap is_ret mallocd_blocks -- = ProtoBCO { -- protoBCOName = nm, -- protoBCOInstrs = maybe_with_stack_check, -- protoBCOBitmap = bitmap, -- protoBCOBitmapSize = bitmap_size, -- protoBCOArity = arity, -- protoBCOExpr = origin, -- protoBCOPtrs = mallocd_blocks -- } -- where -- -- Overestimate the stack usage (in words) of this BCO, -- -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit -- -- stack check. (The interpreter always does a stack check -- -- for iNTERP_STACK_CHECK_THRESH words at the start of each -- -- BCO anyway, so we only need to add an explicit one in the -- -- (hopefully rare) cases when the (overestimated) stack use -- -- exceeds iNTERP_STACK_CHECK_THRESH. -- maybe_with_stack_check -- | is_ret && stack_usage < fromIntegral (aP_STACK_SPLIM dflags) = peep_d -- -- don't do stack checks at return points, -- -- everything is aggregated up to the top BCO -- -- (which must be a function). -- -- That is, unless the stack usage is >= AP_STACK_SPLIM, -- -- see bug #1466. -- | stack_usage >= fromIntegral iNTERP_STACK_CHECK_THRESH -- = STKCHECK stack_usage : peep_d -- | otherwise -- = peep_d -- the supposedly common case -- -- We assume that this sum doesn't wrap -- stack_usage = sum (map bciStackUse peep_d) -- -- Merge local pushes -- peep_d = peep (fromOL instrs_ordlist) -- peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest) -- = PUSH_LLL off1 (off2-1) (off3-2) : peep rest -- peep (PUSH_L off1 : PUSH_L off2 : rest) -- = PUSH_LL off1 (off2-1) : peep rest -- peep (i:rest) -- = i : peep rest -- peep [] -- = [] -- argBits :: DynFlags -> [ArgRep] -> [Bool] -- argBits _ [] = [] -- argBits dflags (rep : args) -- | isFollowableArg rep = False : argBits dflags args -- | otherwise = take (argRepSizeW dflags rep) (repeat True) ++ argBits dflags args -- -- ----------------------------------------------------------------------------- -- -- schemeTopBind -- -- Compile code for the right-hand side of a top-level binding -- schemeTopBind :: (Id, AnnExpr Id VarSet) -> BcM (ProtoBCO Name) -- schemeTopBind (id, rhs) -- | Just data_con <- isDataConWorkId_maybe id, -- isNullaryRepDataCon data_con = do -- dflags <- getDynFlags -- -- Special case for the worker of a nullary data con. -- -- It'll look like this: Nil = /\a -> Nil a -- -- If we feed it into schemeR, we'll get -- -- Nil = Nil -- -- because mkConAppCode treats nullary constructor applications -- -- by just re-using the single top-level definition. So -- -- for the worker itself, we must allocate it directly. -- -- ioToBc (putStrLn $ "top level BCO") -- emitBc (mkProtoBCO dflags (getName id) (toOL [PACK data_con 0, ENTER]) -- (Right rhs) 0 0 [{-no bitmap-}] False{-not alts-}) -- | otherwise -- = schemeR [{- No free variables -}] (id, rhs) -- -- ----------------------------------------------------------------------------- -- -- schemeR -- -- Compile code for a right-hand side, to give a BCO that, -- -- when executed with the free variables and arguments on top of the stack, -- -- will return with a pointer to the result on top of the stack, after -- -- removing the free variables and arguments. -- -- -- -- Park the resulting BCO in the monad. Also requires the -- -- variable to which this value was bound, so as to give the -- -- resulting BCO a name. -- schemeR :: [Id] -- Free vars of the RHS, ordered as they -- -- will appear in the thunk. Empty for -- -- top-level things, which have no free vars. -- -> (Id, AnnExpr Id VarSet) -- -> BcM (ProtoBCO Name) -- schemeR fvs (nm, rhs) -- {- -- | trace (showSDoc ( -- (char ' ' -- $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs -- $$ pprCoreExpr (deAnnotate rhs) -- $$ char ' ' -- ))) False -- = undefined -- | otherwise -- -} -- = schemeR_wrk fvs nm rhs (collect rhs) -- collect :: AnnExpr Id VarSet -> ([Var], AnnExpr' Id VarSet) -- collect (_, e) = go [] e -- where -- go xs e | Just e' <- bcView e = go xs e' -- go xs (AnnLam x (_,e)) -- | UbxTupleRep _ <- repType (idType x) -- = unboxedTupleException -- | otherwise -- = go (x:xs) e -- go xs not_lambda = (reverse xs, not_lambda) -- schemeR_wrk :: [Id] -> Id -> AnnExpr Id VarSet -> ([Var], AnnExpr' Var VarSet) -> BcM (ProtoBCO Name) -- schemeR_wrk fvs nm original_body (args, body) -- = do -- dflags <- getDynFlags -- let -- all_args = reverse args ++ fvs -- arity = length all_args -- -- all_args are the args in reverse order. We're compiling a function -- -- \fv1..fvn x1..xn -> e -- -- i.e. the fvs come first -- szsw_args = map (fromIntegral . idSizeW dflags) all_args -- szw_args = sum szsw_args -- p_init = Map.fromList (zip all_args (mkStackOffsets 0 szsw_args)) -- -- make the arg bitmap -- bits = argBits dflags (reverse (map bcIdArgRep all_args)) -- bitmap_size = genericLength bits -- bitmap = mkBitmap dflags bits -- body_code <- schemeER_wrk szw_args p_init body -- emitBc (mkProtoBCO dflags (getName nm) body_code (Right original_body) -- arity bitmap_size bitmap False{-not alts-}) -- -- introduce break instructions for ticked expressions -- schemeER_wrk :: Word -> BCEnv -> AnnExpr' Id VarSet -> BcM BCInstrList -- schemeER_wrk d p rhs -- | AnnTick (Breakpoint tick_no fvs) (_annot, newRhs) <- rhs -- = do code <- schemeE (fromIntegral d) 0 p newRhs -- arr <- getBreakArray -- this_mod <- getCurrentModule -- let idOffSets = getVarOffSets d p fvs -- let breakInfo = BreakInfo -- { breakInfo_module = this_mod -- , breakInfo_number = tick_no -- , breakInfo_vars = idOffSets -- , breakInfo_resty = exprType (deAnnotate' newRhs) -- } -- let breakInstr = case arr of -- BA arr# -> -- BRK_FUN arr# (fromIntegral tick_no) breakInfo -- return $ breakInstr `consOL` code -- | otherwise = schemeE (fromIntegral d) 0 p rhs -- getVarOffSets :: Word -> BCEnv -> [Id] -> [(Id, Word16)] -- getVarOffSets d p = catMaybes . map (getOffSet d p) -- getOffSet :: Word -> BCEnv -> Id -> Maybe (Id, Word16) -- getOffSet d env id -- = case lookupBCEnv_maybe id env of -- Nothing -> Nothing -- Just offset -> Just (id, trunc16 $ d - offset) -- trunc16 :: Word -> Word16 -- trunc16 w -- | w > fromIntegral (maxBound :: Word16) -- = panic "stack depth overflow" -- | otherwise -- = fromIntegral w -- fvsToEnv :: BCEnv -> VarSet -> [Id] -- -- Takes the free variables of a right-hand side, and -- -- delivers an ordered list of the local variables that will -- -- be captured in the thunk for the RHS -- -- The BCEnv argument tells which variables are in the local -- -- environment: these are the ones that should be captured -- -- -- -- The code that constructs the thunk, and the code that executes -- -- it, have to agree about this layout -- fvsToEnv p fvs = [v | v <- varSetElems fvs, -- isId v, -- Could be a type variable -- v `Map.member` p] -- -- ----------------------------------------------------------------------------- -- -- schemeE -- returnUnboxedAtom :: Word -> Sequel -> BCEnv -- -> AnnExpr' Id VarSet -> ArgRep -- -> BcM BCInstrList -- -- Returning an unlifted value. -- -- Heave it on the stack, SLIDE, and RETURN. -- returnUnboxedAtom d s p e e_rep -- = do (push, szw) <- pushAtom d p e -- return (push -- value onto stack -- `appOL` mkSLIDE szw (d-s) -- clear to sequel -- `snocOL` RETURN_UBX e_rep) -- go -- -- Compile code to apply the given expression to the remaining args -- -- on the stack, returning a HNF. -- schemeE :: Word -> Sequel -> BCEnv -> AnnExpr' Id VarSet -> BcM BCInstrList -- schemeE d s p e -- | Just e' <- bcView e -- = schemeE d s p e' -- -- Delegate tail-calls to schemeT. -- schemeE d s p e@(AnnApp _ _) = schemeT d s p e -- schemeE d s p e@(AnnLit lit) = returnUnboxedAtom d s p e (typeArgRep (literalType lit)) -- schemeE d s p e@(AnnCoercion {}) = returnUnboxedAtom d s p e V -- schemeE d s p e@(AnnVar v) -- | isUnLiftedType (idType v) = returnUnboxedAtom d s p e (bcIdArgRep v) -- | otherwise = schemeT d s p e -- schemeE d s p (AnnLet (AnnNonRec x (_,rhs)) (_,body)) -- | (AnnVar v, args_r_to_l) <- splitApp rhs, -- Just data_con <- isDataConWorkId_maybe v, -- dataConRepArity data_con == length args_r_to_l -- = do -- Special case for a non-recursive let whose RHS is a -- -- saturatred constructor application. -- -- Just allocate the constructor and carry on -- alloc_code <- mkConAppCode d s p data_con args_r_to_l -- body_code <- schemeE (d+1) s (Map.insert x d p) body -- return (alloc_code `appOL` body_code) -- -- General case for let. Generates correct, if inefficient, code in -- -- all situations. -- schemeE d s p (AnnLet binds (_,body)) = do -- dflags <- getDynFlags -- let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs]) -- AnnRec xs_n_rhss -> unzip xs_n_rhss -- n_binds = genericLength xs -- fvss = map (fvsToEnv p' . fst) rhss -- -- Sizes of free vars -- sizes = map (\rhs_fvs -> sum (map (fromIntegral . idSizeW dflags) rhs_fvs)) fvss -- -- the arity of each rhs -- arities = map (genericLength . fst . collect) rhss -- -- This p', d' defn is safe because all the items being pushed -- -- are ptrs, so all have size 1. d' and p' reflect the stack -- -- after the closures have been allocated in the heap (but not -- -- filled in), and pointers to them parked on the stack. -- p' = Map.insertList (zipE xs (mkStackOffsets d (genericReplicate n_binds 1))) p -- d' = d + fromIntegral n_binds -- zipE = zipEqual "schemeE" -- -- ToDo: don't build thunks for things with no free variables -- build_thunk _ [] size bco off arity -- = return (PUSH_BCO bco `consOL` unitOL (mkap (off+size) size)) -- where -- mkap | arity == 0 = MKAP -- | otherwise = MKPAP -- build_thunk dd (fv:fvs) size bco off arity = do -- (push_code, pushed_szw) <- pushAtom dd p' (AnnVar fv) -- more_push_code <- build_thunk (dd + fromIntegral pushed_szw) fvs size bco off arity -- return (push_code `appOL` more_push_code) -- alloc_code = toOL (zipWith mkAlloc sizes arities) -- where mkAlloc sz 0 -- | is_tick = ALLOC_AP_NOUPD sz -- | otherwise = ALLOC_AP sz -- mkAlloc sz arity = ALLOC_PAP arity sz -- is_tick = case binds of -- AnnNonRec id _ -> occNameFS (getOccName id) == tickFS -- _other -> False -- compile_bind d' fvs x rhs size arity off = do -- bco <- schemeR fvs (x,rhs) -- build_thunk d' fvs size bco off arity -- compile_binds = -- [ compile_bind d' fvs x rhs size arity n -- | (fvs, x, rhs, size, arity, n) <- -- zip6 fvss xs rhss sizes arities [n_binds, n_binds-1 .. 1] -- ] -- body_code <- schemeE d' s p' body -- thunk_codes <- sequence compile_binds -- return (alloc_code `appOL` concatOL thunk_codes `appOL` body_code) -- -- introduce a let binding for a ticked case expression. This rule -- -- *should* only fire when the expression was not already let-bound -- -- (the code gen for let bindings should take care of that). Todo: we -- -- call exprFreeVars on a deAnnotated expression, this may not be the -- -- best way to calculate the free vars but it seemed like the least -- -- intrusive thing to do -- schemeE d s p exp@(AnnTick (Breakpoint _id _fvs) _rhs) -- = if isUnLiftedType ty -- then do -- -- If the result type is unlifted, then we must generate -- -- let f = \s . tick<n> e -- -- in f realWorld# -- -- When we stop at the breakpoint, _result will have an unlifted -- -- type and hence won't be bound in the environment, but the -- -- breakpoint will otherwise work fine. -- id <- newId (mkFunTy realWorldStatePrimTy ty) -- st <- newId realWorldStatePrimTy -- let letExp = AnnLet (AnnNonRec id (fvs, AnnLam st (emptyVarSet, exp))) -- (emptyVarSet, (AnnApp (emptyVarSet, AnnVar id) -- (emptyVarSet, AnnVar realWorldPrimId))) -- schemeE d s p letExp -- else do -- id <- newId ty -- -- Todo: is emptyVarSet correct on the next line? -- let letExp = AnnLet (AnnNonRec id (fvs, exp)) (emptyVarSet, AnnVar id) -- schemeE d s p letExp -- where exp' = deAnnotate' exp -- fvs = exprFreeVars exp' -- ty = exprType exp' -- -- ignore other kinds of tick -- schemeE d s p (AnnTick _ (_, rhs)) = schemeE d s p rhs -- schemeE d s p (AnnCase (_,scrut) _ _ []) = schemeE d s p scrut -- -- no alts: scrut is guaranteed to diverge -- schemeE d s p (AnnCase scrut bndr _ [(DataAlt dc, [bind1, bind2], rhs)]) -- | isUnboxedTupleCon dc -- , UnaryRep rep_ty1 <- repType (idType bind1), UnaryRep rep_ty2 <- repType (idType bind2) -- -- Convert -- -- case .... of x { (# V'd-thing, a #) -> ... } -- -- to -- -- case .... of a { DEFAULT -> ... } -- -- becuse the return convention for both are identical. -- -- -- -- Note that it does not matter losing the void-rep thing from the -- -- envt (it won't be bound now) because we never look such things up. -- , Just res <- case () of -- _ | VoidRep <- typePrimRep rep_ty1 -- -> Just $ doCase d s p scrut bind2 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} -- | VoidRep <- typePrimRep rep_ty2 -- -> Just $ doCase d s p scrut bind1 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} -- | otherwise -- -> Nothing -- = res -- schemeE d s p (AnnCase scrut bndr _ [(DataAlt dc, [bind1], rhs)]) -- | isUnboxedTupleCon dc, UnaryRep _ <- repType (idType bind1) -- -- Similarly, convert -- -- case .... of x { (# a #) -> ... } -- -- to -- -- case .... of a { DEFAULT -> ... } -- = --trace "automagic mashing of case alts (# a #)" $ -- doCase d s p scrut bind1 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} -- schemeE d s p (AnnCase scrut bndr _ [(DEFAULT, [], rhs)]) -- | Just (tc, tys) <- splitTyConApp_maybe (idType bndr) -- , isUnboxedTupleTyCon tc -- , Just res <- case tys of -- [ty] | UnaryRep _ <- repType ty -- , let bind = bndr `setIdType` ty -- -> Just $ doCase d s p scrut bind [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} -- [ty1, ty2] | UnaryRep rep_ty1 <- repType ty1 -- , UnaryRep rep_ty2 <- repType ty2 -- -> case () of -- _ | VoidRep <- typePrimRep rep_ty1 -- , let bind2 = bndr `setIdType` ty2 -- -> Just $ doCase d s p scrut bind2 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} -- | VoidRep <- typePrimRep rep_ty2 -- , let bind1 = bndr `setIdType` ty1 -- -> Just $ doCase d s p scrut bind1 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} -- | otherwise -- -> Nothing -- _ -> Nothing -- = res -- schemeE d s p (AnnCase scrut bndr _ alts) -- = doCase d s p scrut bndr alts Nothing{-not an unboxed tuple-} -- schemeE _ _ _ expr -- = pprPanic "ByteCodeGen.schemeE: unhandled case" -- (pprCoreExpr (deAnnotate' expr)) -- {- -- Ticked Expressions -- ------------------ -- The idea is that the "breakpoint<n,fvs> E" is really just an annotation on -- the code. When we find such a thing, we pull out the useful information, -- and then compile the code as if it was just the expression E. -- -} -- -- Compile code to do a tail call. Specifically, push the fn, -- -- slide the on-stack app back down to the sequel depth, -- -- and enter. Four cases: -- -- -- -- 0. (Nasty hack). -- -- An application "GHC.Prim.tagToEnum# <type> unboxed-int". -- -- The int will be on the stack. Generate a code sequence -- -- to convert it to the relevant constructor, SLIDE and ENTER. -- -- -- -- 1. The fn denotes a ccall. Defer to generateCCall. -- -- -- -- 2. (Another nasty hack). Spot (# a::V, b #) and treat -- -- it simply as b -- since the representations are identical -- -- (the V takes up zero stack space). Also, spot -- -- (# b #) and treat it as b. -- -- -- -- 3. Application of a constructor, by defn saturated. -- -- Split the args into ptrs and non-ptrs, and push the nonptrs, -- -- then the ptrs, and then do PACK and RETURN. -- -- -- -- 4. Otherwise, it must be a function call. Push the args -- -- right to left, SLIDE and ENTER. -- schemeT :: Word -- Stack depth -- -> Sequel -- Sequel depth -- -> BCEnv -- stack env -- -> AnnExpr' Id VarSet -- -> BcM BCInstrList -- schemeT d s p app -- -- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False -- -- = panic "schemeT ?!?!" -- -- | trace ("\nschemeT\n" ++ showSDoc (pprCoreExpr (deAnnotate' app)) ++ "\n") False -- -- = error "?!?!" -- -- Case 0 -- | Just (arg, constr_names) <- maybe_is_tagToEnum_call app -- = implement_tagToId d s p arg constr_names -- -- Case 1 -- | Just (CCall ccall_spec) <- isFCallId_maybe fn -- = generateCCall d s p ccall_spec fn args_r_to_l -- -- Case 2: Constructor application -- | Just con <- maybe_saturated_dcon, -- isUnboxedTupleCon con -- = case args_r_to_l of -- [arg1,arg2] | isVAtom arg1 -> -- unboxedTupleReturn d s p arg2 -- [arg1,arg2] | isVAtom arg2 -> -- unboxedTupleReturn d s p arg1 -- _other -> unboxedTupleException -- -- Case 3: Ordinary data constructor -- | Just con <- maybe_saturated_dcon -- = do alloc_con <- mkConAppCode d s p con args_r_to_l -- return (alloc_con `appOL` -- mkSLIDE 1 (d - s) `snocOL` -- ENTER) -- -- Case 4: Tail call of function -- | otherwise -- = doTailCall d s p fn args_r_to_l -- where -- -- Extract the args (R->L) and fn -- -- The function will necessarily be a variable, -- -- because we are compiling a tail call -- (AnnVar fn, args_r_to_l) = splitApp app -- -- Only consider this to be a constructor application iff it is -- -- saturated. Otherwise, we'll call the constructor wrapper. -- n_args = length args_r_to_l -- maybe_saturated_dcon -- = case isDataConWorkId_maybe fn of -- Just con | dataConRepArity con == n_args -> Just con -- _ -> Nothing -- -- ----------------------------------------------------------------------------- -- -- Generate code to build a constructor application, -- -- leaving it on top of the stack -- mkConAppCode :: Word -> Sequel -> BCEnv -- -> DataCon -- The data constructor -- -> [AnnExpr' Id VarSet] -- Args, in *reverse* order -- -> BcM BCInstrList -- mkConAppCode _ _ _ con [] -- Nullary constructor -- = ASSERT( isNullaryRepDataCon con ) -- return (unitOL (PUSH_G (getName (dataConWorkId con)))) -- -- Instead of doing a PACK, which would allocate a fresh -- -- copy of this constructor, use the single shared version. -- mkConAppCode orig_d _ p con args_r_to_l -- = ASSERT( dataConRepArity con == length args_r_to_l ) -- do_pushery orig_d (non_ptr_args ++ ptr_args) -- where -- -- The args are already in reverse order, which is the way PACK -- -- expects them to be. We must push the non-ptrs after the ptrs. -- (ptr_args, non_ptr_args) = partition isPtrAtom args_r_to_l -- do_pushery d (arg:args) -- = do (push, arg_words) <- pushAtom d p arg -- more_push_code <- do_pushery (d + fromIntegral arg_words) args -- return (push `appOL` more_push_code) -- do_pushery d [] -- = return (unitOL (PACK con n_arg_words)) -- where -- n_arg_words = trunc16 $ d - orig_d -- -- ----------------------------------------------------------------------------- -- -- Returning an unboxed tuple with one non-void component (the only -- -- case we can handle). -- -- -- -- Remember, we don't want to *evaluate* the component that is being -- -- returned, even if it is a pointed type. We always just return. -- unboxedTupleReturn -- :: Word -> Sequel -> BCEnv -- -> AnnExpr' Id VarSet -> BcM BCInstrList -- unboxedTupleReturn d s p arg = returnUnboxedAtom d s p arg (atomRep arg) -- -- ----------------------------------------------------------------------------- -- -- Generate code for a tail-call -- doTailCall -- :: Word -> Sequel -> BCEnv -- -> Id -> [AnnExpr' Id VarSet] -- -> BcM BCInstrList -- doTailCall init_d s p fn args -- = do_pushes init_d args (map atomRep args) -- where -- do_pushes d [] reps = do -- ASSERT( null reps ) return () -- (push_fn, sz) <- pushAtom d p (AnnVar fn) -- ASSERT( sz == 1 ) return () -- return (push_fn `appOL` ( -- mkSLIDE (trunc16 $ d - init_d + 1) (init_d - s) `appOL` -- unitOL ENTER)) -- do_pushes d args reps = do -- let (push_apply, n, rest_of_reps) = findPushSeq reps -- (these_args, rest_of_args) = splitAt n args -- (next_d, push_code) <- push_seq d these_args -- instrs <- do_pushes (next_d + 1) rest_of_args rest_of_reps -- -- ^^^ for the PUSH_APPLY_ instruction -- return (push_code `appOL` (push_apply `consOL` instrs)) -- push_seq d [] = return (d, nilOL) -- push_seq d (arg:args) = do -- (push_code, sz) <- pushAtom d p arg -- (final_d, more_push_code) <- push_seq (d + fromIntegral sz) args -- return (final_d, push_code `appOL` more_push_code) -- -- v. similar to CgStackery.findMatch, ToDo: merge -- findPushSeq :: [ArgRep] -> (BCInstr, Int, [ArgRep]) -- findPushSeq (P: P: P: P: P: P: rest) -- = (PUSH_APPLY_PPPPPP, 6, rest) -- findPushSeq (P: P: P: P: P: rest) -- = (PUSH_APPLY_PPPPP, 5, rest) -- findPushSeq (P: P: P: P: rest) -- = (PUSH_APPLY_PPPP, 4, rest) -- findPushSeq (P: P: P: rest) -- = (PUSH_APPLY_PPP, 3, rest) -- findPushSeq (P: P: rest) -- = (PUSH_APPLY_PP, 2, rest) -- findPushSeq (P: rest) -- = (PUSH_APPLY_P, 1, rest) -- findPushSeq (V: rest) -- = (PUSH_APPLY_V, 1, rest) -- findPushSeq (N: rest) -- = (PUSH_APPLY_N, 1, rest) -- findPushSeq (F: rest) -- = (PUSH_APPLY_F, 1, rest) -- findPushSeq (D: rest) -- = (PUSH_APPLY_D, 1, rest) -- findPushSeq (L: rest) -- = (PUSH_APPLY_L, 1, rest) -- findPushSeq _ -- = panic "ByteCodeGen.findPushSeq" -- -- ----------------------------------------------------------------------------- -- -- Case expressions -- doCase :: Word -> Sequel -> BCEnv -- -> AnnExpr Id VarSet -> Id -> [AnnAlt Id VarSet] -- -> Maybe Id -- Just x <=> is an unboxed tuple case with scrut binder, don't enter the result -- -> BcM BCInstrList -- doCase d s p (_,scrut) bndr alts is_unboxed_tuple -- | UbxTupleRep _ <- repType (idType bndr) -- = unboxedTupleException -- | otherwise -- = do -- dflags <- getDynFlags -- let -- -- Top of stack is the return itbl, as usual. -- -- underneath it is the pointer to the alt_code BCO. -- -- When an alt is entered, it assumes the returned value is -- -- on top of the itbl. -- ret_frame_sizeW :: Word -- ret_frame_sizeW = 2 -- -- An unlifted value gets an extra info table pushed on top -- -- when it is returned. -- unlifted_itbl_sizeW :: Word -- unlifted_itbl_sizeW | isAlgCase = 0 -- | otherwise = 1 -- -- depth of stack after the return value has been pushed -- d_bndr = d + ret_frame_sizeW + fromIntegral (idSizeW dflags bndr) -- -- depth of stack after the extra info table for an unboxed return -- -- has been pushed, if any. This is the stack depth at the -- -- continuation. -- d_alts = d_bndr + unlifted_itbl_sizeW -- -- Env in which to compile the alts, not including -- -- any vars bound by the alts themselves -- d_bndr' = fromIntegral d_bndr - 1 -- p_alts0 = Map.insert bndr d_bndr' p -- p_alts = case is_unboxed_tuple of -- Just ubx_bndr -> Map.insert ubx_bndr d_bndr' p_alts0 -- Nothing -> p_alts0 -- bndr_ty = idType bndr -- isAlgCase = not (isUnLiftedType bndr_ty) && isNothing is_unboxed_tuple -- -- given an alt, return a discr and code for it. -- codeAlt (DEFAULT, _, (_,rhs)) -- = do rhs_code <- schemeE d_alts s p_alts rhs -- return (NoDiscr, rhs_code) -- codeAlt alt@(_, bndrs, (_,rhs)) -- -- primitive or nullary constructor alt: no need to UNPACK -- | null real_bndrs = do -- rhs_code <- schemeE d_alts s p_alts rhs -- return (my_discr alt, rhs_code) -- | any (\bndr -> case repType (idType bndr) of UbxTupleRep _ -> True; _ -> False) bndrs -- = unboxedTupleException -- -- algebraic alt with some binders -- | otherwise = -- let -- (ptrs,nptrs) = partition (isFollowableArg.bcIdArgRep) real_bndrs -- ptr_sizes = map (fromIntegral . idSizeW dflags) ptrs -- nptrs_sizes = map (fromIntegral . idSizeW dflags) nptrs -- bind_sizes = ptr_sizes ++ nptrs_sizes -- size = sum ptr_sizes + sum nptrs_sizes -- -- the UNPACK instruction unpacks in reverse order... -- p' = Map.insertList -- (zip (reverse (ptrs ++ nptrs)) -- (mkStackOffsets d_alts (reverse bind_sizes))) -- p_alts -- in do -- MASSERT(isAlgCase) -- rhs_code <- schemeE (d_alts + size) s p' rhs -- return (my_discr alt, unitOL (UNPACK (trunc16 size)) `appOL` rhs_code) -- where -- real_bndrs = filterOut isTyVar bndrs -- my_discr (DEFAULT, _, _) = NoDiscr {-shouldn't really happen-} -- my_discr (DataAlt dc, _, _) -- | isUnboxedTupleCon dc -- = unboxedTupleException -- | otherwise -- = DiscrP (fromIntegral (dataConTag dc - fIRST_TAG)) -- my_discr (LitAlt l, _, _) -- = case l of MachInt i -> DiscrI (fromInteger i) -- MachWord w -> DiscrW (fromInteger w) -- MachFloat r -> DiscrF (fromRational r) -- MachDouble r -> DiscrD (fromRational r) -- MachChar i -> DiscrI (ord i) -- _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l) -- maybe_ncons -- | not isAlgCase = Nothing -- | otherwise -- = case [dc | (DataAlt dc, _, _) <- alts] of -- [] -> Nothing -- (dc:_) -> Just (tyConFamilySize (dataConTyCon dc)) -- -- the bitmap is relative to stack depth d, i.e. before the -- -- BCO, info table and return value are pushed on. -- -- This bit of code is v. similar to buildLivenessMask in CgBindery, -- -- except that here we build the bitmap from the known bindings of -- -- things that are pointers, whereas in CgBindery the code builds the -- -- bitmap from the free slots and unboxed bindings. -- -- (ToDo: merge?) -- -- -- -- NOTE [7/12/2006] bug #1013, testcase ghci/should_run/ghci002. -- -- The bitmap must cover the portion of the stack up to the sequel only. -- -- Previously we were building a bitmap for the whole depth (d), but we -- -- really want a bitmap up to depth (d-s). This affects compilation of -- -- case-of-case expressions, which is the only time we can be compiling a -- -- case expression with s /= 0. -- bitmap_size = trunc16 $ d-s -- bitmap_size' :: Int -- bitmap_size' = fromIntegral bitmap_size -- bitmap = intsToReverseBitmap dflags bitmap_size'{-size-} -- (sort (filter (< bitmap_size') rel_slots)) -- where -- binds = Map.toList p -- -- NB: unboxed tuple cases bind the scrut binder to the same offset -- -- as one of the alt binders, so we have to remove any duplicates here: -- rel_slots = nub $ map fromIntegral $ concat (map spread binds) -- spread (id, offset) | isFollowableArg (bcIdArgRep id) = [ rel_offset ] -- | otherwise = [] -- where rel_offset = trunc16 $ d - fromIntegral offset - 1 -- alt_stuff <- mapM codeAlt alts -- alt_final <- mkMultiBranch maybe_ncons alt_stuff -- let -- alt_bco_name = getName bndr -- alt_bco = mkProtoBCO dflags alt_bco_name alt_final (Left alts) -- 0{-no arity-} bitmap_size bitmap True{-is alts-} -- -- trace ("case: bndr = " ++ showSDocDebug (ppr bndr) ++ "\ndepth = " ++ show d ++ "\nenv = \n" ++ showSDocDebug (ppBCEnv p) ++ -- -- "\n bitmap = " ++ show bitmap) $ do -- scrut_code <- schemeE (d + ret_frame_sizeW) -- (d + ret_frame_sizeW) -- p scrut -- alt_bco' <- emitBc alt_bco -- let push_alts -- | isAlgCase = PUSH_ALTS alt_bco' -- | otherwise = PUSH_ALTS_UNLIFTED alt_bco' (typeArgRep bndr_ty) -- return (push_alts `consOL` scrut_code) -- -- ----------------------------------------------------------------------------- -- -- Deal with a CCall. -- -- Taggedly push the args onto the stack R->L, -- -- deferencing ForeignObj#s and adjusting addrs to point to -- -- payloads in Ptr/Byte arrays. Then, generate the marshalling -- -- (machine) code for the ccall, and create bytecodes to call that and -- -- then return in the right way. -- generateCCall :: Word -> Sequel -- stack and sequel depths -- -> BCEnv -- -> CCallSpec -- where to call -- -> Id -- of target, for type info -- -> [AnnExpr' Id VarSet] -- args (atoms) -- -> BcM BCInstrList -- generateCCall d0 s p (CCallSpec target cconv safety) fn args_r_to_l -- = do -- dflags <- getDynFlags -- let -- -- useful constants -- addr_sizeW :: Word16 -- addr_sizeW = fromIntegral (argRepSizeW dflags N) -- -- Get the args on the stack, with tags and suitably -- -- dereferenced for the CCall. For each arg, return the -- -- depth to the first word of the bits for that arg, and the -- -- ArgRep of what was actually pushed. -- pargs _ [] = return [] -- pargs d (a:az) -- = let UnaryRep arg_ty = repType (exprType (deAnnotate' a)) -- in case tyConAppTyCon_maybe arg_ty of -- -- Don't push the FO; instead push the Addr# it -- -- contains. -- Just t -- | t == arrayPrimTyCon || t == mutableArrayPrimTyCon -- -> do rest <- pargs (d + fromIntegral addr_sizeW) az -- code <- parg_ArrayishRep (fromIntegral (arrPtrsHdrSize dflags)) d p a -- return ((code,AddrRep):rest) -- | t == smallArrayPrimTyCon || t == smallMutableArrayPrimTyCon -- -> do rest <- pargs (d + fromIntegral addr_sizeW) az -- code <- parg_ArrayishRep (fromIntegral (smallArrPtrsHdrSize dflags)) d p a -- return ((code,AddrRep):rest) -- | t == byteArrayPrimTyCon || t == mutableByteArrayPrimTyCon -- -> do rest <- pargs (d + fromIntegral addr_sizeW) az -- code <- parg_ArrayishRep (fromIntegral (arrWordsHdrSize dflags)) d p a -- return ((code,AddrRep):rest) -- -- Default case: push taggedly, but otherwise intact. -- _ -- -> do (code_a, sz_a) <- pushAtom d p a -- rest <- pargs (d + fromIntegral sz_a) az -- return ((code_a, atomPrimRep a) : rest) -- -- Do magic for Ptr/Byte arrays. Push a ptr to the array on -- -- the stack but then advance it over the headers, so as to -- -- point to the payload. -- parg_ArrayishRep :: Word16 -> Word -> BCEnv -> AnnExpr' Id VarSet -- -> BcM BCInstrList -- parg_ArrayishRep hdrSize d p a -- = do (push_fo, _) <- pushAtom d p a -- -- The ptr points at the header. Advance it over the -- -- header and then pretend this is an Addr#. -- return (push_fo `snocOL` SWIZZLE 0 hdrSize) -- code_n_reps <- pargs d0 args_r_to_l -- let -- (pushs_arg, a_reps_pushed_r_to_l) = unzip code_n_reps -- a_reps_sizeW = fromIntegral (sum (map (primRepSizeW dflags) a_reps_pushed_r_to_l)) -- push_args = concatOL pushs_arg -- d_after_args = d0 + a_reps_sizeW -- a_reps_pushed_RAW -- | null a_reps_pushed_r_to_l || head a_reps_pushed_r_to_l /= VoidRep -- = panic "ByteCodeGen.generateCCall: missing or invalid World token?" -- | otherwise -- = reverse (tail a_reps_pushed_r_to_l) -- -- Now: a_reps_pushed_RAW are the reps which are actually on the stack. -- -- push_args is the code to do that. -- -- d_after_args is the stack depth once the args are on. -- -- Get the result rep. -- (returns_void, r_rep) -- = case maybe_getCCallReturnRep (idType fn) of -- Nothing -> (True, VoidRep) -- Just rr -> (False, rr) -- {- -- Because the Haskell stack grows down, the a_reps refer to -- lowest to highest addresses in that order. The args for the call -- are on the stack. Now push an unboxed Addr# indicating -- the C function to call. Then push a dummy placeholder for the -- result. Finally, emit a CCALL insn with an offset pointing to the -- Addr# just pushed, and a literal field holding the mallocville -- address of the piece of marshalling code we generate. -- So, just prior to the CCALL insn, the stack looks like this -- (growing down, as usual): -- <arg_n> -- ... -- <arg_1> -- Addr# address_of_C_fn -- <placeholder-for-result#> (must be an unboxed type) -- The interpreter then calls the marshall code mentioned -- in the CCALL insn, passing it (& <placeholder-for-result#>), -- that is, the addr of the topmost word in the stack. -- When this returns, the placeholder will have been -- filled in. The placeholder is slid down to the sequel -- depth, and we RETURN. -- This arrangement makes it simple to do f-i-dynamic since the Addr# -- value is the first arg anyway. -- The marshalling code is generated specifically for this -- call site, and so knows exactly the (Haskell) stack -- offsets of the args, fn address and placeholder. It -- copies the args to the C stack, calls the stacked addr, -- and parks the result back in the placeholder. The interpreter -- calls it as a normal C call, assuming it has a signature -- void marshall_code ( StgWord* ptr_to_top_of_stack ) -- -} -- -- resolve static address -- get_target_info = do -- case target of -- DynamicTarget -- -> return (False, panic "ByteCodeGen.generateCCall(dyn)") -- StaticTarget _ _ False -> -- panic "generateCCall: unexpected FFI value import" -- StaticTarget target _ True -- -> do res <- ioToBc (lookupStaticPtr stdcall_adj_target) -- return (True, res) -- where -- stdcall_adj_target -- | OSMinGW32 <- platformOS (targetPlatform dflags) -- , StdCallConv <- cconv -- = let size = fromIntegral a_reps_sizeW * wORD_SIZE dflags in -- mkFastString (unpackFS target ++ '@':show size) -- | otherwise -- = target -- (is_static, static_target_addr) <- get_target_info -- let -- -- Get the arg reps, zapping the leading Addr# in the dynamic case -- a_reps -- | trace (showSDoc (ppr a_reps_pushed_RAW)) False = error "???" -- | is_static = a_reps_pushed_RAW -- | otherwise = if null a_reps_pushed_RAW -- then panic "ByteCodeGen.generateCCall: dyn with no args" -- else tail a_reps_pushed_RAW -- -- push the Addr# -- (push_Addr, d_after_Addr) -- | is_static -- = (toOL [PUSH_UBX (Right static_target_addr) addr_sizeW], -- d_after_args + fromIntegral addr_sizeW) -- | otherwise -- is already on the stack -- = (nilOL, d_after_args) -- -- Push the return placeholder. For a call returning nothing, -- -- this is a V (tag). -- r_sizeW = fromIntegral (primRepSizeW dflags r_rep) -- d_after_r = d_after_Addr + fromIntegral r_sizeW -- r_lit = mkDummyLiteral r_rep -- push_r = (if returns_void -- then nilOL -- else unitOL (PUSH_UBX (Left r_lit) r_sizeW)) -- -- generate the marshalling code we're going to call -- -- Offset of the next stack frame down the stack. The CCALL -- -- instruction needs to describe the chunk of stack containing -- -- the ccall args to the GC, so it needs to know how large it -- -- is. See comment in Interpreter.c with the CCALL instruction. -- stk_offset = trunc16 $ d_after_r - s -- -- the only difference in libffi mode is that we prepare a cif -- -- describing the call type by calling libffi, and we attach the -- -- address of this to the CCALL instruction. -- token <- ioToBc $ error "ByteCodeGen: unimplemented" --prepForeignCall dflags cconv a_reps r_rep -- let addr_of_marshaller = castPtrToFunPtr token -- recordItblMallocBc (ItblPtr (castFunPtrToPtr addr_of_marshaller)) -- let -- -- do the call -- do_call = unitOL (CCALL stk_offset (castFunPtrToPtr addr_of_marshaller) -- (fromIntegral (fromEnum (playInterruptible safety)))) -- -- slide and return -- wrapup = mkSLIDE r_sizeW (d_after_r - fromIntegral r_sizeW - s) -- `snocOL` RETURN_UBX (toArgRep r_rep) -- --trace (show (arg1_offW, args_offW , (map argRepSizeW a_reps) )) $ -- return ( -- push_args `appOL` -- push_Addr `appOL` push_r `appOL` do_call `appOL` wrapup -- ) -- -- Make a dummy literal, to be used as a placeholder for FFI return -- -- values on the stack. -- mkDummyLiteral :: PrimRep -> Literal -- mkDummyLiteral pr -- = case pr of -- IntRep -> MachInt 0 -- WordRep -> MachWord 0 -- AddrRep -> MachNullAddr -- DoubleRep -> MachDouble 0 -- FloatRep -> MachFloat 0 -- Int64Rep -> MachInt64 0 -- Word64Rep -> MachWord64 0 -- _ -> panic "mkDummyLiteral" -- -- Convert (eg) -- -- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld -- -- -> (# GHC.Prim.State# GHC.Prim.RealWorld, GHC.Prim.Int# #) -- -- -- -- to Just IntRep -- -- and check that an unboxed pair is returned wherein the first arg is V'd. -- -- -- -- Alternatively, for call-targets returning nothing, convert -- -- -- -- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld -- -- -> (# GHC.Prim.State# GHC.Prim.RealWorld #) -- -- -- -- to Nothing -- maybe_getCCallReturnRep :: Type -> Maybe PrimRep -- maybe_getCCallReturnRep fn_ty -- = let (_a_tys, r_ty) = splitFunTys (dropForAlls fn_ty) -- maybe_r_rep_to_go -- = if isSingleton r_reps then Nothing else Just (r_reps !! 1) -- r_reps = case repType r_ty of -- UbxTupleRep reps -> map typePrimRep reps -- UnaryRep _ -> blargh -- ok = ( ( r_reps `lengthIs` 2 && VoidRep == head r_reps) -- || r_reps == [VoidRep] ) -- && case maybe_r_rep_to_go of -- Nothing -> True -- Just r_rep -> r_rep /= PtrRep -- -- if it was, it would be impossible -- -- to create a valid return value -- -- placeholder on the stack -- blargh :: a -- Used at more than one type -- blargh = pprPanic "maybe_getCCallReturn: can't handle:" -- (pprType fn_ty) -- in -- --trace (showSDoc (ppr (a_reps, r_reps))) $ -- if ok then maybe_r_rep_to_go else blargh -- maybe_is_tagToEnum_call :: AnnExpr' Id VarSet -> Maybe (AnnExpr' Id VarSet, [Name]) -- -- Detect and extract relevant info for the tagToEnum kludge. -- maybe_is_tagToEnum_call app -- | AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType t)) arg <- app -- , Just TagToEnumOp <- isPrimOpId_maybe v -- = Just (snd arg, extract_constr_Names t) -- | otherwise -- = Nothing -- where -- extract_constr_Names ty -- | UnaryRep rep_ty <- repType ty -- , Just tyc <- tyConAppTyCon_maybe rep_ty, -- isDataTyCon tyc -- = map (getName . dataConWorkId) (tyConDataCons tyc) -- -- NOTE: use the worker name, not the source name of -- -- the DataCon. See DataCon.lhs for details. -- | otherwise -- = pprPanic "maybe_is_tagToEnum_call.extract_constr_Ids" (ppr ty) -- {- ----------------------------------------------------------------------------- -- Note [Implementing tagToEnum#] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- (implement_tagToId arg names) compiles code which takes an argument -- 'arg', (call it i), and enters the i'th closure in the supplied list -- as a consequence. The [Name] is a list of the constructors of this -- (enumeration) type. -- The code we generate is this: -- push arg -- push bogus-word -- TESTEQ_I 0 L1 -- PUSH_G <lbl for first data con> -- JMP L_Exit -- L1: TESTEQ_I 1 L2 -- PUSH_G <lbl for second data con> -- JMP L_Exit -- ...etc... -- Ln: TESTEQ_I n L_fail -- PUSH_G <lbl for last data con> -- JMP L_Exit -- L_fail: CASEFAIL -- L_exit: SLIDE 1 n -- ENTER -- The 'bogus-word' push is because TESTEQ_I expects the top of the stack -- to have an info-table, and the next word to have the value to be -- tested. This is very weird, but it's the way it is right now. See -- Interpreter.c. We don't acutally need an info-table here; we just -- need to have the argument to be one-from-top on the stack, hence pushing -- a 1-word null. See Trac #8383. -- -} -- implement_tagToId :: Word -> Sequel -> BCEnv -- -> AnnExpr' Id VarSet -> [Name] -> BcM BCInstrList -- -- See Note [Implementing tagToEnum#] -- implement_tagToId d s p arg names -- = ASSERT( notNull names ) -- do (push_arg, arg_words) <- pushAtom d p arg -- labels <- getLabelsBc (genericLength names) -- label_fail <- getLabelBc -- label_exit <- getLabelBc -- let infos = zip4 labels (tail labels ++ [label_fail]) -- [0 ..] names -- steps = map (mkStep label_exit) infos -- return (push_arg -- `appOL` unitOL (PUSH_UBX (Left MachNullAddr) 1) -- -- Push bogus word (see Note [Implementing tagToEnum#]) -- `appOL` concatOL steps -- `appOL` toOL [ LABEL label_fail, CASEFAIL, -- LABEL label_exit ] -- `appOL` mkSLIDE 1 (d - s + fromIntegral arg_words + 1) -- -- "+1" to account for bogus word -- -- (see Note [Implementing tagToEnum#]) -- `appOL` unitOL ENTER) -- where -- mkStep l_exit (my_label, next_label, n, name_for_n) -- = toOL [LABEL my_label, -- TESTEQ_I n next_label, -- PUSH_G name_for_n, -- JMP l_exit] -- -- ----------------------------------------------------------------------------- -- -- pushAtom -- -- Push an atom onto the stack, returning suitable code & number of -- -- stack words used. -- -- -- -- The env p must map each variable to the highest- numbered stack -- -- slot for it. For example, if the stack has depth 4 and we -- -- tagged-ly push (v :: Int#) on it, the value will be in stack[4], -- -- the tag in stack[5], the stack will have depth 6, and p must map v -- -- to 5 and not to 4. Stack locations are numbered from zero, so a -- -- depth 6 stack has valid words 0 .. 5. -- pushAtom :: Word -> BCEnv -> AnnExpr' Id VarSet -> BcM (BCInstrList, Word16) -- pushAtom d p e -- | Just e' <- bcView e -- = pushAtom d p e' -- pushAtom _ _ (AnnCoercion {}) -- Coercions are zero-width things, -- = return (nilOL, 0) -- treated just like a variable V -- pushAtom d p (AnnVar v) -- | UnaryRep rep_ty <- repType (idType v) -- , V <- typeArgRep rep_ty -- = return (nilOL, 0) -- | isFCallId v -- = pprPanic "pushAtom: shouldn't get an FCallId here" (ppr v) -- | Just primop <- isPrimOpId_maybe v -- = return (unitOL (PUSH_PRIMOP primop), 1) -- | Just d_v <- lookupBCEnv_maybe v p -- v is a local variable -- = do dflags <- getDynFlags -- let sz :: Word16 -- sz = fromIntegral (idSizeW dflags v) -- l = trunc16 $ d - d_v + fromIntegral sz - 2 -- return (toOL (genericReplicate sz (PUSH_L l)), sz) -- -- d - d_v the number of words between the TOS -- -- and the 1st slot of the object -- -- -- -- d - d_v - 1 the offset from the TOS of the 1st slot -- -- -- -- d - d_v - 1 + sz - 1 the offset from the TOS of the last slot -- -- of the object. -- -- -- -- Having found the last slot, we proceed to copy the right number of -- -- slots on to the top of the stack. -- | otherwise -- v must be a global variable -- = do dflags <- getDynFlags -- let sz :: Word16 -- sz = fromIntegral (idSizeW dflags v) -- MASSERT(sz == 1) -- return (unitOL (PUSH_G (getName v)), sz) -- pushAtom _ _ (AnnLit lit) = do -- dflags <- getDynFlags -- let code rep -- = let size_host_words = fromIntegral (argRepSizeW dflags rep) -- in return (unitOL (PUSH_UBX (Left lit) size_host_words), -- size_host_words) -- case lit of -- MachLabel _ _ _ -> code N -- MachWord _ -> code N -- MachInt _ -> code N -- MachWord64 _ -> code L -- MachInt64 _ -> code L -- MachFloat _ -> code F -- MachDouble _ -> code D -- MachChar _ -> code N -- MachNullAddr -> code N -- MachStr s -> pushStr s -- -- No LitInteger's should be left by the time this is called. -- -- CorePrep should have converted them all to a real core -- -- representation. -- LitInteger {} -> panic "pushAtom: LitInteger" -- where -- pushStr s -- = let getMallocvilleAddr -- = -- -- we could grab the Ptr from the ForeignPtr, -- -- but then we have no way to control its lifetime. -- -- In reality it'll probably stay alive long enoungh -- -- by virtue of the global FastString table, but -- -- to be on the safe side we copy the string into -- -- a malloc'd area of memory. -- do let n = BS.length s -- ptr <- ioToBc (mallocBytes (n+1)) -- recordMallocBc ptr -- ioToBc ( -- BS.unsafeUseAsCString s $ \p -> do -- memcpy ptr p (fromIntegral n) -- pokeByteOff ptr n (fromIntegral (ord '\0') :: Word8) -- return ptr -- ) -- in do -- addr <- getMallocvilleAddr -- -- Get the addr on the stack, untaggedly -- return (unitOL (PUSH_UBX (Right addr) 1), 1) -- pushAtom _ _ expr -- = pprPanic "ByteCodeGen.pushAtom" -- (pprCoreExpr (deAnnotate (undefined, expr))) -- foreign import ccall unsafe "memcpy" -- memcpy :: Ptr a -> Ptr b -> CSize -> IO () -- -- ----------------------------------------------------------------------------- -- -- Given a bunch of alts code and their discrs, do the donkey work -- -- of making a multiway branch using a switch tree. -- -- What a load of hassle! -- mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt -- -- a hint; generates better code -- -- Nothing is always safe -- -> [(Discr, BCInstrList)] -- -> BcM BCInstrList -- mkMultiBranch maybe_ncons raw_ways = do -- lbl_default <- getLabelBc -- let -- mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList -- mkTree [] _range_lo _range_hi = return (unitOL (JMP lbl_default)) -- -- shouldn't happen? -- mkTree [val] range_lo range_hi -- | range_lo == range_hi -- = return (snd val) -- | null defaults -- Note [CASEFAIL] -- = do lbl <- getLabelBc -- return (testEQ (fst val) lbl -- `consOL` (snd val -- `appOL` (LABEL lbl `consOL` unitOL CASEFAIL))) -- | otherwise -- = return (testEQ (fst val) lbl_default `consOL` snd val) -- -- Note [CASEFAIL] It may be that this case has no default -- -- branch, but the alternatives are not exhaustive - this -- -- happens for GADT cases for example, where the types -- -- prove that certain branches are impossible. We could -- -- just assume that the other cases won't occur, but if -- -- this assumption was wrong (because of a bug in GHC) -- -- then the result would be a segfault. So instead we -- -- emit an explicit test and a CASEFAIL instruction that -- -- causes the interpreter to barf() if it is ever -- -- executed. -- mkTree vals range_lo range_hi -- = let n = length vals `div` 2 -- vals_lo = take n vals -- vals_hi = drop n vals -- v_mid = fst (head vals_hi) -- in do -- label_geq <- getLabelBc -- code_lo <- mkTree vals_lo range_lo (dec v_mid) -- code_hi <- mkTree vals_hi v_mid range_hi -- return (testLT v_mid label_geq -- `consOL` (code_lo -- `appOL` unitOL (LABEL label_geq) -- `appOL` code_hi)) -- the_default -- = case defaults of -- [] -> nilOL -- [(_, def)] -> LABEL lbl_default `consOL` def -- _ -> panic "mkMultiBranch/the_default" -- instrs <- mkTree notd_ways init_lo init_hi -- return (instrs `appOL` the_default) -- where -- (defaults, not_defaults) = partition (isNoDiscr.fst) raw_ways -- notd_ways = sortBy (comparing fst) not_defaults -- testLT (DiscrI i) fail_label = TESTLT_I i fail_label -- testLT (DiscrW i) fail_label = TESTLT_W i fail_label -- testLT (DiscrF i) fail_label = TESTLT_F i fail_label -- testLT (DiscrD i) fail_label = TESTLT_D i fail_label -- testLT (DiscrP i) fail_label = TESTLT_P i fail_label -- testLT NoDiscr _ = panic "mkMultiBranch NoDiscr" -- testEQ (DiscrI i) fail_label = TESTEQ_I i fail_label -- testEQ (DiscrW i) fail_label = TESTEQ_W i fail_label -- testEQ (DiscrF i) fail_label = TESTEQ_F i fail_label -- testEQ (DiscrD i) fail_label = TESTEQ_D i fail_label -- testEQ (DiscrP i) fail_label = TESTEQ_P i fail_label -- testEQ NoDiscr _ = panic "mkMultiBranch NoDiscr" -- -- None of these will be needed if there are no non-default alts -- (init_lo, init_hi) -- | null notd_ways -- = panic "mkMultiBranch: awesome foursome" -- | otherwise -- = case fst (head notd_ways) of -- DiscrI _ -> ( DiscrI minBound, DiscrI maxBound ) -- DiscrW _ -> ( DiscrW minBound, DiscrW maxBound ) -- DiscrF _ -> ( DiscrF minF, DiscrF maxF ) -- DiscrD _ -> ( DiscrD minD, DiscrD maxD ) -- DiscrP _ -> ( DiscrP algMinBound, DiscrP algMaxBound ) -- NoDiscr -> panic "mkMultiBranch NoDiscr" -- (algMinBound, algMaxBound) -- = case maybe_ncons of -- -- XXX What happens when n == 0? -- Just n -> (0, fromIntegral n - 1) -- Nothing -> (minBound, maxBound) -- isNoDiscr NoDiscr = True -- isNoDiscr _ = False -- dec (DiscrI i) = DiscrI (i-1) -- dec (DiscrW w) = DiscrW (w-1) -- dec (DiscrP i) = DiscrP (i-1) -- dec other = other -- not really right, but if you -- -- do cases on floating values, you'll get what you deserve -- -- same snotty comment applies to the following -- minF, maxF :: Float -- minD, maxD :: Double -- minF = -1.0e37 -- maxF = 1.0e37 -- minD = -1.0e308 -- maxD = 1.0e308 -- -- ----------------------------------------------------------------------------- -- -- Supporting junk for the compilation schemes -- -- Describes case alts -- data Discr -- = DiscrI Int -- | DiscrW Word -- | DiscrF Float -- | DiscrD Double -- | DiscrP Word16 -- | NoDiscr -- deriving (Eq, Ord) -- instance Outputable Discr where -- ppr (DiscrI i) = int i -- ppr (DiscrW w) = text (show w) -- ppr (DiscrF f) = text (show f) -- ppr (DiscrD d) = text (show d) -- ppr (DiscrP i) = ppr i -- ppr NoDiscr = text "DEF" -- lookupBCEnv_maybe :: Id -> BCEnv -> Maybe Word -- lookupBCEnv_maybe = Map.lookup -- idSizeW :: DynFlags -> Id -> Int -- idSizeW dflags = argRepSizeW dflags . bcIdArgRep -- bcIdArgRep :: Id -> ArgRep -- bcIdArgRep = toArgRep . bcIdPrimRep -- bcIdPrimRep :: Id -> PrimRep -- bcIdPrimRep = typePrimRep . bcIdUnaryType -- isFollowableArg :: ArgRep -> Bool -- isFollowableArg P = True -- isFollowableArg _ = False -- isVoidArg :: ArgRep -> Bool -- isVoidArg V = True -- isVoidArg _ = False -- bcIdUnaryType :: Id -> UnaryType -- bcIdUnaryType x = case repType (idType x) of -- UnaryRep rep_ty -> rep_ty -- UbxTupleRep [rep_ty] -> rep_ty -- UbxTupleRep [rep_ty1, rep_ty2] -- | VoidRep <- typePrimRep rep_ty1 -> rep_ty2 -- | VoidRep <- typePrimRep rep_ty2 -> rep_ty1 -- _ -> pprPanic "bcIdUnaryType" (ppr x $$ ppr (idType x)) -- -- See bug #1257 -- unboxedTupleException :: a -- unboxedTupleException -- = throwGhcException -- (ProgramError -- ("Error: bytecode compiler can't handle unboxed tuples.\n"++ -- " Possibly due to foreign import/export decls in source.\n"++ -- " Workaround: use -fobject-code, or compile this module to .o separately.")) -- mkSLIDE :: Word16 -> Word -> OrdList BCInstr -- mkSLIDE n d -- -- if the amount to slide doesn't fit in a word, -- -- generate multiple slide instructions -- | d > fromIntegral limit -- = SLIDE n limit `consOL` mkSLIDE n (d - fromIntegral limit) -- | d == 0 -- = nilOL -- | otherwise -- = if d == 0 then nilOL else unitOL (SLIDE n $ fromIntegral d) -- where -- limit :: Word16 -- limit = maxBound -- splitApp :: AnnExpr' Var ann -> (AnnExpr' Var ann, [AnnExpr' Var ann]) -- -- The arguments are returned in *right-to-left* order -- splitApp e | Just e' <- bcView e = splitApp e' -- splitApp (AnnApp (_,f) (_,a)) = case splitApp f of -- (f', as) -> (f', a:as) -- splitApp e = (e, []) -- bcView :: AnnExpr' Var ann -> Maybe (AnnExpr' Var ann) -- -- The "bytecode view" of a term discards -- -- a) type abstractions -- -- b) type applications -- -- c) casts -- -- d) ticks (but not breakpoints) -- -- Type lambdas *can* occur in random expressions, -- -- whereas value lambdas cannot; that is why they are nuked here -- bcView (AnnCast (_,e) _) = Just e -- bcView (AnnLam v (_,e)) | isTyVar v = Just e -- bcView (AnnApp (_,e) (_, AnnType _)) = Just e -- bcView (AnnTick Breakpoint{} _) = Nothing -- bcView (AnnTick _other_tick (_,e)) = Just e -- bcView _ = Nothing -- isVAtom :: AnnExpr' Var ann -> Bool -- isVAtom e | Just e' <- bcView e = isVAtom e' -- isVAtom (AnnVar v) = isVoidArg (bcIdArgRep v) -- isVAtom (AnnCoercion {}) = True -- isVAtom _ = False -- atomPrimRep :: AnnExpr' Id ann -> PrimRep -- atomPrimRep e | Just e' <- bcView e = atomPrimRep e' -- atomPrimRep (AnnVar v) = bcIdPrimRep v -- atomPrimRep (AnnLit l) = typePrimRep (literalType l) -- atomPrimRep (AnnCoercion {}) = VoidRep -- atomPrimRep other = pprPanic "atomPrimRep" (ppr (deAnnotate (undefined,other))) -- atomRep :: AnnExpr' Id ann -> ArgRep -- atomRep e = toArgRep (atomPrimRep e) -- isPtrAtom :: AnnExpr' Id ann -> Bool -- isPtrAtom e = isFollowableArg (atomRep e) -- -- Let szsw be the sizes in words of some items pushed onto the stack, -- -- which has initial depth d'. Return the values which the stack environment -- -- should map these items to. -- mkStackOffsets :: Word -> [Word] -> [Word] -- mkStackOffsets original_depth szsw -- = map (subtract 1) (tail (scanl (+) original_depth szsw)) -- typeArgRep :: Type -> ArgRep -- typeArgRep = toArgRep . typePrimRep -- -- ----------------------------------------------------------------------------- -- -- The bytecode generator's monad -- type BcPtr = Either ItblPtr (Ptr ()) -- data BcM_State -- = BcM_State -- { bcm_dflags :: DynFlags -- , uniqSupply :: UniqSupply -- for generating fresh variable names -- , thisModule :: Module -- current module (for breakpoints) -- , nextlabel :: Word16 -- for generating local labels -- , malloced :: [BcPtr] -- thunks malloced for current BCO -- -- Should be free()d when it is GCd -- , breakArray :: BreakArray -- array of breakpoint flags -- } -- newtype BcM r = BcM (BcM_State -> IO (BcM_State, r)) -- ioToBc :: IO a -> BcM a -- ioToBc io = BcM $ \st -> do -- x <- io -- return (st, x) -- runBc :: DynFlags -> UniqSupply -> Module -> ModBreaks -> BcM r -- -> IO (BcM_State, r) -- runBc dflags us this_mod modBreaks (BcM m) -- = m (BcM_State dflags us this_mod 0 [] breakArray) -- where -- breakArray = modBreaks_flags modBreaks -- thenBc :: BcM a -> (a -> BcM b) -> BcM b -- thenBc (BcM expr) cont = BcM $ \st0 -> do -- (st1, q) <- expr st0 -- let BcM k = cont q -- (st2, r) <- k st1 -- return (st2, r) -- thenBc_ :: BcM a -> BcM b -> BcM b -- thenBc_ (BcM expr) (BcM cont) = BcM $ \st0 -> do -- (st1, _) <- expr st0 -- (st2, r) <- cont st1 -- return (st2, r) -- returnBc :: a -> BcM a -- returnBc result = BcM $ \st -> (return (st, result)) -- instance Functor BcM where -- fmap = liftM -- instance Applicative BcM where -- pure = return -- (<*>) = ap -- instance Monad BcM where -- (>>=) = thenBc -- (>>) = thenBc_ -- return = returnBc -- instance HasDynFlags BcM where -- getDynFlags = BcM $ \st -> return (st, bcm_dflags st) -- emitBc :: ([BcPtr] -> ProtoBCO Name) -> BcM (ProtoBCO Name) -- emitBc bco -- = BcM $ \st -> return (st{malloced=[]}, bco (malloced st)) -- recordMallocBc :: Ptr a -> BcM () -- recordMallocBc a -- = BcM $ \st -> return (st{malloced = Right (castPtr a) : malloced st}, ()) -- recordItblMallocBc :: ItblPtr -> BcM () -- recordItblMallocBc a -- = BcM $ \st -> return (st{malloced = Left a : malloced st}, ()) -- getLabelBc :: BcM Word16 -- getLabelBc -- = BcM $ \st -> do let nl = nextlabel st -- when (nl == maxBound) $ -- panic "getLabelBc: Ran out of labels" -- return (st{nextlabel = nl + 1}, nl) -- getLabelsBc :: Word16 -> BcM [Word16] -- getLabelsBc n -- = BcM $ \st -> let ctr = nextlabel st -- in return (st{nextlabel = ctr+n}, [ctr .. ctr+n-1]) -- getBreakArray :: BcM BreakArray -- getBreakArray = BcM $ \st -> return (st, breakArray st) -- newUnique :: BcM Unique -- newUnique = BcM $ -- \st -> case takeUniqFromSupply (uniqSupply st) of -- (uniq, us) -> let newState = st { uniqSupply = us } -- in return (newState, uniq) -- getCurrentModule :: BcM Module -- getCurrentModule = BcM $ \st -> return (st, thisModule st) -- newId :: Type -> BcM Id -- newId ty = do -- uniq <- newUnique -- return $ mkSysLocal tickFS uniq ty -- tickFS :: FastString -- tickFS = fsLit "ticked"
alexander-at-github/eta
compiler/ETA/Interactive/ByteCodeGen.hs
bsd-3-clause
70,081
0
5
22,512
1,710
1,605
105
51
1
{-# language CPP #-} -- No documentation found for Chapter "AccessFlags2" module Vulkan.Core13.Enums.AccessFlags2 ( pattern ACCESS_2_NONE_KHR , pattern ACCESS_2_INDIRECT_COMMAND_READ_BIT_KHR , pattern ACCESS_2_INDEX_READ_BIT_KHR , pattern ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT_KHR , pattern ACCESS_2_UNIFORM_READ_BIT_KHR , pattern ACCESS_2_INPUT_ATTACHMENT_READ_BIT_KHR , pattern ACCESS_2_SHADER_READ_BIT_KHR , pattern ACCESS_2_SHADER_WRITE_BIT_KHR , pattern ACCESS_2_COLOR_ATTACHMENT_READ_BIT_KHR , pattern ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT_KHR , pattern ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT_KHR , pattern ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT_KHR , pattern ACCESS_2_TRANSFER_READ_BIT_KHR , pattern ACCESS_2_TRANSFER_WRITE_BIT_KHR , pattern ACCESS_2_HOST_READ_BIT_KHR , pattern ACCESS_2_HOST_WRITE_BIT_KHR , pattern ACCESS_2_MEMORY_READ_BIT_KHR , pattern ACCESS_2_MEMORY_WRITE_BIT_KHR , pattern ACCESS_2_SHADER_SAMPLED_READ_BIT_KHR , pattern ACCESS_2_SHADER_STORAGE_READ_BIT_KHR , pattern ACCESS_2_SHADER_STORAGE_WRITE_BIT_KHR , AccessFlags2 , AccessFlagBits2( ACCESS_2_NONE , ACCESS_2_INDIRECT_COMMAND_READ_BIT , ACCESS_2_INDEX_READ_BIT , ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT , ACCESS_2_UNIFORM_READ_BIT , ACCESS_2_INPUT_ATTACHMENT_READ_BIT , ACCESS_2_SHADER_READ_BIT , ACCESS_2_SHADER_WRITE_BIT , ACCESS_2_COLOR_ATTACHMENT_READ_BIT , ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT , ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT , ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT , ACCESS_2_TRANSFER_READ_BIT , ACCESS_2_TRANSFER_WRITE_BIT , ACCESS_2_HOST_READ_BIT , ACCESS_2_HOST_WRITE_BIT , ACCESS_2_MEMORY_READ_BIT , ACCESS_2_MEMORY_WRITE_BIT , ACCESS_2_SHADER_SAMPLED_READ_BIT , ACCESS_2_SHADER_STORAGE_READ_BIT , ACCESS_2_SHADER_STORAGE_WRITE_BIT , ACCESS_2_INVOCATION_MASK_READ_BIT_HUAWEI , ACCESS_2_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT , ACCESS_2_FRAGMENT_DENSITY_MAP_READ_BIT_EXT , ACCESS_2_ACCELERATION_STRUCTURE_WRITE_BIT_KHR , ACCESS_2_ACCELERATION_STRUCTURE_READ_BIT_KHR , ACCESS_2_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR , ACCESS_2_COMMAND_PREPROCESS_WRITE_BIT_NV , ACCESS_2_COMMAND_PREPROCESS_READ_BIT_NV , ACCESS_2_CONDITIONAL_RENDERING_READ_BIT_EXT , ACCESS_2_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT , ACCESS_2_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT , ACCESS_2_TRANSFORM_FEEDBACK_WRITE_BIT_EXT , .. ) ) where import Vulkan.Internal.Utils (enumReadPrec) import Vulkan.Internal.Utils (enumShowsPrec) import GHC.Show (showString) import Numeric (showHex) import Vulkan.Zero (Zero) import Data.Bits (Bits) import Data.Bits (FiniteBits) import Foreign.Storable (Storable) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Vulkan.Core10.FundamentalTypes (Flags64) -- No documentation found for TopLevel "VK_ACCESS_2_NONE_KHR" pattern ACCESS_2_NONE_KHR = ACCESS_2_NONE -- No documentation found for TopLevel "VK_ACCESS_2_INDIRECT_COMMAND_READ_BIT_KHR" pattern ACCESS_2_INDIRECT_COMMAND_READ_BIT_KHR = ACCESS_2_INDIRECT_COMMAND_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_INDEX_READ_BIT_KHR" pattern ACCESS_2_INDEX_READ_BIT_KHR = ACCESS_2_INDEX_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT_KHR" pattern ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT_KHR = ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_UNIFORM_READ_BIT_KHR" pattern ACCESS_2_UNIFORM_READ_BIT_KHR = ACCESS_2_UNIFORM_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_INPUT_ATTACHMENT_READ_BIT_KHR" pattern ACCESS_2_INPUT_ATTACHMENT_READ_BIT_KHR = ACCESS_2_INPUT_ATTACHMENT_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_SHADER_READ_BIT_KHR" pattern ACCESS_2_SHADER_READ_BIT_KHR = ACCESS_2_SHADER_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_SHADER_WRITE_BIT_KHR" pattern ACCESS_2_SHADER_WRITE_BIT_KHR = ACCESS_2_SHADER_WRITE_BIT -- No documentation found for TopLevel "VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT_KHR" pattern ACCESS_2_COLOR_ATTACHMENT_READ_BIT_KHR = ACCESS_2_COLOR_ATTACHMENT_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT_KHR" pattern ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT_KHR = ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT -- No documentation found for TopLevel "VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT_KHR" pattern ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT_KHR = ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT_KHR" pattern ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT_KHR = ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT -- No documentation found for TopLevel "VK_ACCESS_2_TRANSFER_READ_BIT_KHR" pattern ACCESS_2_TRANSFER_READ_BIT_KHR = ACCESS_2_TRANSFER_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_TRANSFER_WRITE_BIT_KHR" pattern ACCESS_2_TRANSFER_WRITE_BIT_KHR = ACCESS_2_TRANSFER_WRITE_BIT -- No documentation found for TopLevel "VK_ACCESS_2_HOST_READ_BIT_KHR" pattern ACCESS_2_HOST_READ_BIT_KHR = ACCESS_2_HOST_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_HOST_WRITE_BIT_KHR" pattern ACCESS_2_HOST_WRITE_BIT_KHR = ACCESS_2_HOST_WRITE_BIT -- No documentation found for TopLevel "VK_ACCESS_2_MEMORY_READ_BIT_KHR" pattern ACCESS_2_MEMORY_READ_BIT_KHR = ACCESS_2_MEMORY_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_MEMORY_WRITE_BIT_KHR" pattern ACCESS_2_MEMORY_WRITE_BIT_KHR = ACCESS_2_MEMORY_WRITE_BIT -- No documentation found for TopLevel "VK_ACCESS_2_SHADER_SAMPLED_READ_BIT_KHR" pattern ACCESS_2_SHADER_SAMPLED_READ_BIT_KHR = ACCESS_2_SHADER_SAMPLED_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_SHADER_STORAGE_READ_BIT_KHR" pattern ACCESS_2_SHADER_STORAGE_READ_BIT_KHR = ACCESS_2_SHADER_STORAGE_READ_BIT -- No documentation found for TopLevel "VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT_KHR" pattern ACCESS_2_SHADER_STORAGE_WRITE_BIT_KHR = ACCESS_2_SHADER_STORAGE_WRITE_BIT type AccessFlags2 = AccessFlagBits2 -- | VkAccessFlagBits2 - Access flags for VkAccessFlags2 -- -- = Description -- -- Note -- -- In situations where an application wishes to select all access types for -- a given set of pipeline stages, 'ACCESS_2_MEMORY_READ_BIT' or -- 'ACCESS_2_MEMORY_WRITE_BIT' can be used. This is particularly useful -- when specifying stages that only have a single access type. -- -- Note -- -- The 'AccessFlags2' bitmask goes beyond the 31 individual bit flags -- allowable within a C99 enum, which is how -- 'Vulkan.Core10.Enums.AccessFlagBits.AccessFlagBits' is defined. The -- first 31 values are common to both, and are interchangeable. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_synchronization2 VK_KHR_synchronization2>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_3 VK_VERSION_1_3> newtype AccessFlagBits2 = AccessFlagBits2 Flags64 deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) -- | 'ACCESS_2_NONE' specifies no accesses. pattern ACCESS_2_NONE = AccessFlagBits2 0x0000000000000000 -- | 'ACCESS_2_INDIRECT_COMMAND_READ_BIT' specifies read access to command -- data read from indirect buffers as part of an indirect build, trace, -- drawing or dispatch command. Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_DRAW_INDIRECT_BIT' -- pipeline stage. pattern ACCESS_2_INDIRECT_COMMAND_READ_BIT = AccessFlagBits2 0x0000000000000001 -- | 'ACCESS_2_INDEX_READ_BIT' specifies read access to an index buffer as -- part of an indexed drawing command, bound by -- 'Vulkan.Core10.CommandBufferBuilding.cmdBindIndexBuffer'. Such access -- occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_INDEX_INPUT_BIT' -- pipeline stage. pattern ACCESS_2_INDEX_READ_BIT = AccessFlagBits2 0x0000000000000002 -- | 'ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT' specifies read access to a vertex -- buffer as part of a drawing command, bound by -- 'Vulkan.Core10.CommandBufferBuilding.cmdBindVertexBuffers'. Such access -- occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT' -- pipeline stage. pattern ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT = AccessFlagBits2 0x0000000000000004 -- | 'ACCESS_2_UNIFORM_READ_BIT' specifies read access to a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#descriptorsets-uniformbuffer uniform buffer> -- in any shader pipeline stage. pattern ACCESS_2_UNIFORM_READ_BIT = AccessFlagBits2 0x0000000000000008 -- | 'ACCESS_2_INPUT_ATTACHMENT_READ_BIT' specifies read access to an -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass input attachment> -- within a render pass during subpass shading or fragment shading. Such -- access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_SUBPASS_SHADING_BIT_HUAWEI' -- or -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT' -- pipeline stage. pattern ACCESS_2_INPUT_ATTACHMENT_READ_BIT = AccessFlagBits2 0x0000000000000010 -- | 'ACCESS_2_SHADER_READ_BIT' specifies read access to a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#shader-binding-table shader binding table> -- in any shader pipeline. In addition, it is equivalent to the logical OR -- of: -- -- - 'ACCESS_2_UNIFORM_READ_BIT' -- -- - 'ACCESS_2_SHADER_SAMPLED_READ_BIT' -- -- - 'ACCESS_2_SHADER_STORAGE_READ_BIT' pattern ACCESS_2_SHADER_READ_BIT = AccessFlagBits2 0x0000000000000020 -- | 'ACCESS_2_SHADER_WRITE_BIT' is equivalent to -- 'ACCESS_2_SHADER_STORAGE_WRITE_BIT'. pattern ACCESS_2_SHADER_WRITE_BIT = AccessFlagBits2 0x0000000000000040 -- | 'ACCESS_2_COLOR_ATTACHMENT_READ_BIT' specifies read access to a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass color attachment>, -- such as via -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#framebuffer-blending blending>, -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#framebuffer-logicop logic operations>, -- or via certain -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass-load-store-ops subpass load operations>. -- It does not include -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#framebuffer-blend-advanced advanced blend operations>. -- Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT' -- pipeline stage. pattern ACCESS_2_COLOR_ATTACHMENT_READ_BIT = AccessFlagBits2 0x0000000000000080 -- | 'ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT' specifies write access to a -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#renderpass color, resolve, or depth\/stencil resolve attachment> -- during a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass render pass> -- or via certain -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass-load-store-ops subpass load and store operations>. -- Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT' -- pipeline stage. pattern ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT = AccessFlagBits2 0x0000000000000100 -- | 'ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT' specifies read access to a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass depth\/stencil attachment>, -- via -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#fragops-ds-state depth or stencil operations> -- or via certain -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass-load-store-ops subpass load operations>. -- Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT' -- or -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT' -- pipeline stages. pattern ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT = AccessFlagBits2 0x0000000000000200 -- | 'ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT' specifies write access to -- a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass depth\/stencil attachment>, -- via -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#fragops-ds-state depth or stencil operations> -- or via certain -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass-load-store-ops subpass load and store operations>. -- Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT' -- or -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT' -- pipeline stages. pattern ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT = AccessFlagBits2 0x0000000000000400 -- | 'ACCESS_2_TRANSFER_READ_BIT' specifies read access to an image or buffer -- in a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#copies copy> -- operation. Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_COPY_BIT', -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_BLIT_BIT', or -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_RESOLVE_BIT' -- pipeline stages. pattern ACCESS_2_TRANSFER_READ_BIT = AccessFlagBits2 0x0000000000000800 -- | 'ACCESS_2_TRANSFER_WRITE_BIT' specifies write access to an image or -- buffer in a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#clears clear> -- or -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#copies copy> -- operation. Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_COPY_BIT', -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_BLIT_BIT', -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_CLEAR_BIT', or -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_RESOLVE_BIT' -- pipeline stages. pattern ACCESS_2_TRANSFER_WRITE_BIT = AccessFlagBits2 0x0000000000001000 -- | 'ACCESS_2_HOST_READ_BIT' specifies read access by a host operation. -- Accesses of this type are not performed through a resource, but directly -- on memory. Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_HOST_BIT' -- pipeline stage. pattern ACCESS_2_HOST_READ_BIT = AccessFlagBits2 0x0000000000002000 -- | 'ACCESS_2_HOST_WRITE_BIT' specifies write access by a host operation. -- Accesses of this type are not performed through a resource, but directly -- on memory. Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_HOST_BIT' -- pipeline stage. pattern ACCESS_2_HOST_WRITE_BIT = AccessFlagBits2 0x0000000000004000 -- | 'ACCESS_2_MEMORY_READ_BIT' specifies all read accesses. It is always -- valid in any access mask, and is treated as equivalent to setting all -- @READ@ access flags that are valid where it is used. pattern ACCESS_2_MEMORY_READ_BIT = AccessFlagBits2 0x0000000000008000 -- | 'ACCESS_2_MEMORY_WRITE_BIT' specifies all write accesses. It is always -- valid in any access mask, and is treated as equivalent to setting all -- @WRITE@ access flags that are valid where it is used. pattern ACCESS_2_MEMORY_WRITE_BIT = AccessFlagBits2 0x0000000000010000 -- | 'ACCESS_2_SHADER_SAMPLED_READ_BIT' specifies read access to a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#descriptorsets-uniformtexelbuffer uniform texel buffer> -- or -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#descriptorsets-sampledimage sampled image> -- in any shader pipeline stage. pattern ACCESS_2_SHADER_SAMPLED_READ_BIT = AccessFlagBits2 0x0000000100000000 -- | 'ACCESS_2_SHADER_STORAGE_READ_BIT' specifies read access to a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#descriptorsets-storagebuffer storage buffer>, -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#descriptorsets-physical-storage-buffer physical storage buffer>, -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#descriptorsets-storagetexelbuffer storage texel buffer>, -- or -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#descriptorsets-storageimage storage image> -- in any shader pipeline stage. pattern ACCESS_2_SHADER_STORAGE_READ_BIT = AccessFlagBits2 0x0000000200000000 -- | 'ACCESS_2_SHADER_STORAGE_WRITE_BIT' specifies write access to a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#descriptorsets-storagebuffer storage buffer>, -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#descriptorsets-physical-storage-buffer physical storage buffer>, -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#descriptorsets-storagetexelbuffer storage texel buffer>, -- or -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#descriptorsets-storageimage storage image> -- in any shader pipeline stage. pattern ACCESS_2_SHADER_STORAGE_WRITE_BIT = AccessFlagBits2 0x0000000400000000 -- | 'ACCESS_2_INVOCATION_MASK_READ_BIT_HUAWEI' specifies read access to a -- invocation mask image in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_INVOCATION_MASK_BIT_HUAWEI' -- pipeline stage. pattern ACCESS_2_INVOCATION_MASK_READ_BIT_HUAWEI = AccessFlagBits2 0x0000008000000000 -- | 'ACCESS_2_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT' specifies read -- access to -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass color attachments>, -- including -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#framebuffer-blend-advanced advanced blend operations>. -- Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT' -- pipeline stage. pattern ACCESS_2_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT = AccessFlagBits2 0x0000000000080000 -- | 'ACCESS_2_FRAGMENT_DENSITY_MAP_READ_BIT_EXT' specifies read access to a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass-fragmentdensitymapattachment fragment density map attachment> -- during dynamic -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#fragmentdensitymapops fragment density map operations>. -- Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_FRAGMENT_DENSITY_PROCESS_BIT_EXT' -- pipeline stage. pattern ACCESS_2_FRAGMENT_DENSITY_MAP_READ_BIT_EXT = AccessFlagBits2 0x0000000001000000 -- | 'ACCESS_2_ACCELERATION_STRUCTURE_WRITE_BIT_KHR' specifies write access -- to an acceleration structure or -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#acceleration-structure-scratch acceleration structure scratch buffer> -- as part of a build or copy command. Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_ACCELERATION_STRUCTURE_BUILD_BIT_KHR' -- pipeline stage. pattern ACCESS_2_ACCELERATION_STRUCTURE_WRITE_BIT_KHR = AccessFlagBits2 0x0000000000400000 -- | 'ACCESS_2_ACCELERATION_STRUCTURE_READ_BIT_KHR' specifies read access to -- an acceleration structure as part of a trace, build, or copy command, or -- to an -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#acceleration-structure-scratch acceleration structure scratch buffer> -- as part of a build command. Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_RAY_TRACING_SHADER_BIT_KHR' -- pipeline stage or -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_ACCELERATION_STRUCTURE_BUILD_BIT_KHR' -- pipeline stage. pattern ACCESS_2_ACCELERATION_STRUCTURE_READ_BIT_KHR = AccessFlagBits2 0x0000000000200000 -- | 'ACCESS_2_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR' specifies read -- access to a fragment shading rate attachment during rasterization. Such -- access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR' -- pipeline stage. pattern ACCESS_2_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR = AccessFlagBits2 0x0000000000800000 -- | 'ACCESS_2_COMMAND_PREPROCESS_WRITE_BIT_NV' specifies writes to the -- target command buffer preprocess outputs. Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_COMMAND_PREPROCESS_BIT_NV' -- pipeline stage. pattern ACCESS_2_COMMAND_PREPROCESS_WRITE_BIT_NV = AccessFlagBits2 0x0000000000040000 -- | 'ACCESS_2_COMMAND_PREPROCESS_READ_BIT_NV' specifies reads from buffer -- inputs to -- 'Vulkan.Extensions.VK_NV_device_generated_commands.cmdPreprocessGeneratedCommandsNV'. -- Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_COMMAND_PREPROCESS_BIT_NV' -- pipeline stage. pattern ACCESS_2_COMMAND_PREPROCESS_READ_BIT_NV = AccessFlagBits2 0x0000000000020000 -- | 'ACCESS_2_CONDITIONAL_RENDERING_READ_BIT_EXT' specifies read access to a -- predicate as part of conditional rendering. Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_CONDITIONAL_RENDERING_BIT_EXT' -- pipeline stage. pattern ACCESS_2_CONDITIONAL_RENDERING_READ_BIT_EXT = AccessFlagBits2 0x0000000000100000 -- | 'ACCESS_2_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT' specifies write -- access to a transform feedback counter buffer which is written when -- 'Vulkan.Extensions.VK_EXT_transform_feedback.cmdEndTransformFeedbackEXT' -- executes. Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_TRANSFORM_FEEDBACK_BIT_EXT' -- pipeline stage. pattern ACCESS_2_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT = AccessFlagBits2 0x0000000008000000 -- | 'ACCESS_2_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT' specifies read access -- to a transform feedback counter buffer which is read when -- 'Vulkan.Extensions.VK_EXT_transform_feedback.cmdBeginTransformFeedbackEXT' -- executes. Such access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_TRANSFORM_FEEDBACK_BIT_EXT' -- pipeline stage. pattern ACCESS_2_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT = AccessFlagBits2 0x0000000004000000 -- | 'ACCESS_2_TRANSFORM_FEEDBACK_WRITE_BIT_EXT' specifies write access to a -- transform feedback buffer made when transform feedback is active. Such -- access occurs in the -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_TRANSFORM_FEEDBACK_BIT_EXT' -- pipeline stage. pattern ACCESS_2_TRANSFORM_FEEDBACK_WRITE_BIT_EXT = AccessFlagBits2 0x0000000002000000 conNameAccessFlagBits2 :: String conNameAccessFlagBits2 = "AccessFlagBits2" enumPrefixAccessFlagBits2 :: String enumPrefixAccessFlagBits2 = "ACCESS_2_" showTableAccessFlagBits2 :: [(AccessFlagBits2, String)] showTableAccessFlagBits2 = [ (ACCESS_2_NONE , "NONE") , (ACCESS_2_INDIRECT_COMMAND_READ_BIT , "INDIRECT_COMMAND_READ_BIT") , (ACCESS_2_INDEX_READ_BIT , "INDEX_READ_BIT") , (ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT , "VERTEX_ATTRIBUTE_READ_BIT") , (ACCESS_2_UNIFORM_READ_BIT , "UNIFORM_READ_BIT") , (ACCESS_2_INPUT_ATTACHMENT_READ_BIT , "INPUT_ATTACHMENT_READ_BIT") , (ACCESS_2_SHADER_READ_BIT , "SHADER_READ_BIT") , (ACCESS_2_SHADER_WRITE_BIT , "SHADER_WRITE_BIT") , (ACCESS_2_COLOR_ATTACHMENT_READ_BIT , "COLOR_ATTACHMENT_READ_BIT") , (ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT , "COLOR_ATTACHMENT_WRITE_BIT") , (ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT , "DEPTH_STENCIL_ATTACHMENT_READ_BIT") , (ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, "DEPTH_STENCIL_ATTACHMENT_WRITE_BIT") , (ACCESS_2_TRANSFER_READ_BIT , "TRANSFER_READ_BIT") , (ACCESS_2_TRANSFER_WRITE_BIT , "TRANSFER_WRITE_BIT") , (ACCESS_2_HOST_READ_BIT , "HOST_READ_BIT") , (ACCESS_2_HOST_WRITE_BIT , "HOST_WRITE_BIT") , (ACCESS_2_MEMORY_READ_BIT , "MEMORY_READ_BIT") , (ACCESS_2_MEMORY_WRITE_BIT , "MEMORY_WRITE_BIT") , (ACCESS_2_SHADER_SAMPLED_READ_BIT , "SHADER_SAMPLED_READ_BIT") , (ACCESS_2_SHADER_STORAGE_READ_BIT , "SHADER_STORAGE_READ_BIT") , (ACCESS_2_SHADER_STORAGE_WRITE_BIT , "SHADER_STORAGE_WRITE_BIT") , (ACCESS_2_INVOCATION_MASK_READ_BIT_HUAWEI , "INVOCATION_MASK_READ_BIT_HUAWEI") , (ACCESS_2_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT, "COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT") , (ACCESS_2_FRAGMENT_DENSITY_MAP_READ_BIT_EXT , "FRAGMENT_DENSITY_MAP_READ_BIT_EXT") , (ACCESS_2_ACCELERATION_STRUCTURE_WRITE_BIT_KHR, "ACCELERATION_STRUCTURE_WRITE_BIT_KHR") , (ACCESS_2_ACCELERATION_STRUCTURE_READ_BIT_KHR, "ACCELERATION_STRUCTURE_READ_BIT_KHR") , (ACCESS_2_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR, "FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR") , (ACCESS_2_COMMAND_PREPROCESS_WRITE_BIT_NV , "COMMAND_PREPROCESS_WRITE_BIT_NV") , (ACCESS_2_COMMAND_PREPROCESS_READ_BIT_NV , "COMMAND_PREPROCESS_READ_BIT_NV") , (ACCESS_2_CONDITIONAL_RENDERING_READ_BIT_EXT, "CONDITIONAL_RENDERING_READ_BIT_EXT") , (ACCESS_2_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT, "TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT") , (ACCESS_2_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT, "TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT") , (ACCESS_2_TRANSFORM_FEEDBACK_WRITE_BIT_EXT , "TRANSFORM_FEEDBACK_WRITE_BIT_EXT") ] instance Show AccessFlagBits2 where showsPrec = enumShowsPrec enumPrefixAccessFlagBits2 showTableAccessFlagBits2 conNameAccessFlagBits2 (\(AccessFlagBits2 x) -> x) (\x -> showString "0x" . showHex x) instance Read AccessFlagBits2 where readPrec = enumReadPrec enumPrefixAccessFlagBits2 showTableAccessFlagBits2 conNameAccessFlagBits2 AccessFlagBits2
expipiplus1/vulkan
src/Vulkan/Core13/Enums/AccessFlags2.hs
bsd-3-clause
29,511
1
10
5,699
1,553
1,006
547
-1
-1
module Main.Opts where import System.Console.GetOpt import ACO (Config(..)) import SA (Config(..)) import BB (Config(..)) import Problems.TSP as TSP (Config(..), DistConf(..)) data Flag = FTwoOpt | FVersion | FHelp | FGen Int | FAnts Int | FCoords | FVerb | FPlot FilePath | FFin Double | FOpts | FEst Double | FREuc deriving (Eq) options :: [OptDescr Flag] options = [ Option ['t'] ["two-opt"] (NoArg FTwoOpt) "use 2-opt" , Option ['v','?'] ["version"] (NoArg FVersion) "show version number" , Option ['h'] ["help"] (NoArg FHelp) "display this usage info" , Option ['g'] ["generations"] (ReqArg (FGen . read) "N") "number of ACO generations" , Option ['a'] ["ants"] (ReqArg (FAnts . read) "N") "number of ants in one generation" , Option [] ["coords"] (NoArg FCoords) "coordinates file format for TSP" , Option [] ["verb"] (NoArg FVerb) "verbose" , Option ['p'] ["plot"] (ReqArg FPlot "FILE") "plot score" , Option [] ["fin"] (ReqArg (FFin . read) "D") "final temperature for SA" , Option [] ["est"] (ReqArg (FEst . read) "D") "initial estimate for BB" , Option [] ["reuc"] (NoArg FREuc) "round Euclidean distance to nearest integer" , Option [] ["list-options"] (NoArg FOpts) "list options" ] getOpts :: [String] -> IO ([Flag], [String]) getOpts argv = case getOpt Permute options argv of (o, n, []) -> return (o,n) (_, _, errs) -> ioError (userError (concat errs ++ usageInfo header options)) listOpts :: [OptDescr Flag] -> IO () listOpts = mapM_ (\(Option _ [o] _ _) -> putStrLn $ "--" ++ o) header :: String header = "Usage: discrete-opt <tsp|vrp> <aco|sa|nn> FILE [OPTION...]" modConfigTSP :: TSP.Config -> Flag -> TSP.Config modConfigTSP conf FREuc = conf {distanceC = Euc2DRounded} modConfigTSP conf _ = conf modConfigACO :: ACO.Config -> Flag -> ACO.Config modConfigACO conf (FGen g) = conf {paramNGen = g} modConfigACO conf (FAnts a) = conf {paramAGen = a} modConfigACO conf FTwoOpt = conf {paramUse2Opt = True} modConfigACO conf _ = conf modConfigSA :: SA.Config -> Flag -> SA.Config modConfigSA conf (FFin t) = conf {finalTemp = t} modConfigSA conf _ = conf modConfigBB :: BB.Config -> Flag -> BB.Config modConfigBB conf (FEst e) = conf {initEst = Just e} modConfigBB conf _ = conf fPlot :: [Flag] -> Maybe FilePath fPlot (FPlot f:_) = Just f fPlot (_:fs) = fPlot fs fPlot [] = Nothing
tomasmcz/discrete-opt
src-main/Main/Opts.hs
bsd-3-clause
2,347
0
13
425
954
523
431
48
2
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} module Opaleye.Internal.Unpackspec where import qualified Opaleye.Internal.PackMap as PM import qualified Opaleye.Column as C import Control.Applicative (Applicative, pure, (<*>)) import Data.Profunctor (Profunctor, dimap) import Data.Profunctor.Product (ProductProfunctor, empty, (***!)) import qualified Data.Profunctor.Product as PP import qualified Data.Profunctor.Product.Default as D import qualified Database.HaskellDB.PrimQuery as PQ newtype Unpackspec columns columns' = Unpackspec (PM.PackMap PQ.PrimExpr PQ.PrimExpr columns columns') unpackspecColumn :: Unpackspec (C.Column a) (C.Column a) unpackspecColumn = Unpackspec (PM.PackMap (\f (C.Column pe) -> fmap C.Column (f pe))) runUnpackspec :: Applicative f => Unpackspec columns b -> (PQ.PrimExpr -> f PQ.PrimExpr) -> (columns -> f b) runUnpackspec (Unpackspec f) = PM.packmap f instance D.Default Unpackspec (C.Column a) (C.Column a) where def = unpackspecColumn -- { -- Boilerplate instance definitions. Theoretically, these are derivable. instance Functor (Unpackspec a) where fmap f (Unpackspec g) = Unpackspec (fmap f g) instance Applicative (Unpackspec a) where pure = Unpackspec . pure Unpackspec f <*> Unpackspec x = Unpackspec (f <*> x) instance Profunctor Unpackspec where dimap f g (Unpackspec q) = Unpackspec (dimap f g q) instance ProductProfunctor Unpackspec where empty = PP.defaultEmpty (***!) = PP.defaultProfunctorProduct --}
k0001/haskell-opaleye
Opaleye/Internal/Unpackspec.hs
bsd-3-clause
1,596
0
12
314
464
258
206
32
1
{-# LANGUAGE DataKinds #-} module LDrive.LED where import Ivory.Language import Ivory.Tower import Ivory.HW.Module import Ivory.BSP.STM32.Peripheral.GPIOF4 import LDrive.Utils data LEDPolarity = ActiveHigh | ActiveLow data LED = LED GPIOPin LEDPolarity ledSetup :: LED -> Ivory eff () ledSetup led@(LED pin _polarity) = do pinEnable pin pinSetOutputType pin gpio_outputtype_pushpull pinSetSpeed pin gpio_speed_2mhz pinSetPUPD pin gpio_pupd_none ledOff led ledOn :: LED -> Ivory eff () ledOn (LED pin ActiveHigh) = pinHigh pin ledOn (LED pin ActiveLow) = pinLow pin ledOff :: LED -> Ivory eff () ledOff (LED pin _) = pinHiZ pin -- | LED Controller: Given a set of leds and a control channel of booleans, -- setup the pin hardware, and turn the leds on when the control channel is -- true. ledController :: [LED] -> ChanOutput ('Stored IBool) -> Monitor e () ledController leds rxer = do -- Bookkeeping: this task uses Ivory.HW.Module.hw_moduledef monitorModuleDef $ hw_moduledef -- Setup hardware before running any event handlers handler systemInit "hardwareinit" $ callback $ const $ mapM_ ledSetup leds -- Run a callback on each message posted to the channel handler rxer "newoutput" $ callback $ \outref -> do out <- deref outref -- Turn pins on or off according to event value ifte_ out (mapM_ ledOn leds) (mapM_ ledOff leds) -- | Blink task: Given a period and a channel source, output an alternating -- stream of true / false on each period. blinker :: Time a => a -> Tower e (ChanOutput ('Stored IBool)) blinker t = do p_chan <- period t (cin, cout) <- channel monitor "blinker" $ do handler p_chan "per" $ do e <- emitter cin 1 callback $ \timeref -> do time <- deref timeref -- Emit boolean value which will alternate each period. emitV e (time .% (2*p) <? p) return cout where p = toITime t blink :: Time a => a -> [LED] -> Tower p () blink per pins = do onoff <- blinker per -- monitor "setup" $ do -- handler systemInit "init" $ do -- callback $ const $ do -- mapM_ ledSetup pins monitor "led" $ ledController pins onoff
sorki/odrive
src/LDrive/LED.hs
bsd-3-clause
2,177
0
22
493
593
292
301
47
1
-- ----------------------------------------------------------------------------- -- Copyright 2002, Simon Marlow. -- Copyright 2009, Henning Thielemann. -- 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 copyright holder(s) nor the names of -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- ----------------------------------------------------------------------------- module Network.MoHWS.Configuration.Parser ( T, lift, run, field, set, addToList, stringLiteral, bool, int, ) where import qualified Network.MoHWS.Configuration.Accessor as ConfigA import qualified Network.MoHWS.Configuration as Config import Network.MoHWS.ParserUtility (countBetween, ) import Control.Monad (liftM2, ) import Network.MoHWS.Utility (readM, ) import Text.ParserCombinators.Parsec (GenParser, ParseError, parseFromFile, (<|>), choice, many, option, try, char, digit, eof, ) import Text.ParserCombinators.Parsec.Language (LanguageDef, emptyDef, commentLine, nestedComments, reservedOpNames, reservedNames, caseSensitive, ) import qualified Text.ParserCombinators.Parsec.Token as Token import qualified Data.Set as Set import qualified Data.Accessor.Basic as Accessor type T st ext = GenParser Char st (Builder ext) type Builder ext = Config.T ext -> Config.T ext {- lift :: Accessor.T fullExt partExt -> GenParser Char st (partExt -> partExt) -> T st fullExt lift act = fmap (Accessor.modify Config.extensionAcc . Accessor.modify act) -} lift :: Accessor.T fullExt partExt -> T st partExt -> T st fullExt lift act = fmap (\build c -> fmap (flip (Accessor.set act) (Config.extension c)) $ build $ fmap (Accessor.get act) c) field :: String -> T st ext -> T st ext field keyword parser = Token.reserved p keyword >> parser p :: Token.TokenParser st p = Token.makeTokenParser tokenDef stringLiteral :: GenParser Char st String stringLiteral = Token.stringLiteral p bool :: GenParser Char st Bool bool = ( Token.reserved p "On" >> return True ) <|> ( Token.reserved p "Off" >> return False ) int :: GenParser Char st Int int = fmap fromInteger $ Token.integer p tokenDef :: LanguageDef st tokenDef = emptyDef { commentLine = "#", nestedComments = False, reservedOpNames = [], reservedNames = [], caseSensitive = False } run :: T () ext -> String -> IO (Either ParseError (Builder ext)) run parseExt fname = parseFromFile (configParser parseExt) fname configParser :: T st ext -> T st ext configParser parseExt = do Token.whiteSpace p cs <- many $ parseExt <|> configLine eof return (fixConfig . foldr (.) id cs) fixConfig :: Builder ext fixConfig conf = let f xs = if length xs > 1 then init xs else xs in Accessor.modify ConfigA.listen f conf configLine :: T st ext configLine = choice $ (field "user" p_user) : (field "group" p_group) : (field "timeout" p_timeout) : (field "keepalivetimeout" p_keepAliveTimeout) : (field "maxclients" p_maxClients) : (field "listen" p_listen) : (field "serveradmin" p_serverAdmin) : (field "servername" p_serverName) : (field "serveralias" p_serverAlias) : (field "usecanonicalname" p_useCanonicalName) : (field "documentroot" p_documentRoot) : (field "accessfilename" p_accessFileName) : (field "followsymboliclinks" p_followSymbolicLinks) : (field "chunksize" p_chunkSize) : (field "typesconfig" p_typesConfig) : (field "defaulttype" p_defaultType) : (field "hostnamelookups" p_hostnameLookups) : (field "errorlog" p_errorLog) : (field "loglevel" p_logLevel) : (field "customlog" p_customLog) : (field "listen" p_listen) : (field "addlanguage" p_addLanguage) : (field "languagepriority" p_languagePriority) : [] set :: Accessor.T r a -> GenParser Char st a -> GenParser Char st (r -> r) set acc = fmap (Accessor.set acc) addToList :: Accessor.T r [a] -> GenParser Char st a -> GenParser Char st (r -> r) addToList acc = fmap (Accessor.modify acc . (:)) p_user :: T st ext p_user = set ConfigA.user $ stringLiteral p_group :: T st ext p_group = set ConfigA.group $ stringLiteral p_timeout :: T st ext p_timeout = set ConfigA.requestTimeout $ int p_keepAliveTimeout :: T st ext p_keepAliveTimeout = set ConfigA.keepAliveTimeout $ int p_maxClients :: T st ext p_maxClients = set ConfigA.maxClients $ int p_serverAdmin :: T st ext p_serverAdmin = set ConfigA.serverAdmin $ stringLiteral p_serverName :: T st ext p_serverName = set ConfigA.serverName $ stringLiteral p_serverAlias :: T st ext p_serverAlias = fmap (Accessor.modify ConfigA.serverAlias . Set.insert) $ stringLiteral p_useCanonicalName :: T st ext p_useCanonicalName = set ConfigA.useCanonicalName $ bool p_documentRoot :: T st ext p_documentRoot = set ConfigA.documentRoot $ stringLiteral p_accessFileName :: T st ext p_accessFileName = set ConfigA.accessFileName $ stringLiteral p_followSymbolicLinks :: T st ext p_followSymbolicLinks = set ConfigA.followSymbolicLinks $ bool p_chunkSize :: T st ext p_chunkSize = set ConfigA.chunkSize $ int p_typesConfig :: T st ext p_typesConfig = set ConfigA.typesConfig $ stringLiteral p_defaultType :: T st ext p_defaultType = set ConfigA.defaultType $ stringLiteral p_hostnameLookups :: T st ext p_hostnameLookups = set ConfigA.hostnameLookups $ bool p_errorLog :: T st ext p_errorLog = set ConfigA.errorLogFile $ stringLiteral p_logLevel :: T st ext p_logLevel = set ConfigA.logLevel $ Token.identifier p >>= readM p_customLog :: T st ext p_customLog = addToList ConfigA.customLogs $ liftM2 (,) stringLiteral stringLiteral p_listen :: T st ext p_listen = let p_addr = option Nothing $ try $ do addr <- p_ip_addr _ <- char ':' return $ Just addr p_ip_addr = fmap concat $ sequence $ p_dec_byte : replicate 3 p_dot_dec_byte p_dec_byte = countBetween 1 3 digit p_dot_dec_byte = liftM2 (:) (char '.') p_dec_byte in addToList ConfigA.listen $ liftM2 (,) p_addr (fmap fromInteger $ Token.integer p) p_addLanguage :: T st ext p_addLanguage = addToList ConfigA.addLanguage $ liftM2 (,) stringLiteral stringLiteral p_languagePriority :: T st ext p_languagePriority = set ConfigA.languagePriority $ many stringLiteral
xpika/mohws
src/Network/MoHWS/Configuration/Parser.hs
bsd-3-clause
7,996
0
30
1,730
1,910
1,005
905
152
2
module Main where import Haste import Haste.HPlay.View hiding (head) import Binary.Application import Control.Monad.IO.Class import Prelude hiding (div, id) import Binary.Util main :: IO (Maybe ()) main = do addCss "./bootstrap.min.css" addCss "./bootstrap-theme.min.css" embedCss myCss addJs "./jquery-1.11.2.min.js" addJs "./bootstrap.min.js" embedJs myJs runBody $ at "main-content" Insert $ timeout 1000 (runApplication initialState) addCss :: String -> IO () addCss s = addHeader $ link ! atr "rel" "stylesheet" ! href s embedCss :: String -> IO () embedCss s = addHeader $ styleBlock s addJs :: String -> IO () addJs s = addHeader $ script noHtml ! src s embedJs :: String -> IO () embedJs s = addHeader $ script s myCss :: String myCss = ".vertical-align {\n" ++ " display: flex;\n" ++ " flex-direction: row;\n" ++ "}\n" ++ ".vertical-align > [class^=\"col-\"],\n" ++ ".vertical-align > [class*=\" col-\"] {\n" ++ " display: flex;\n" ++ " align-items: center;\n" ++ " justify-content: center; \n" ++ "}" myJs :: String myJs = "var mouse = {x: 0, y: 0};\n" ++ "document.addEventListener('mousemove', function(e){\n" ++ "mouse.x = e.clientX || e.pageX;\n" ++ "mouse.y = e.clientY || e.pageY\n" ++ "}, false);"
Teaspot-Studio/bmstu-binary-genetics-haste
Main.hs
bsd-3-clause
1,355
0
13
323
340
170
170
43
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_HADDOCK hide #-} -- | -- Module : Data.Array.Accelerate.Pretty -- Copyright : [2008..2014] Manuel M T Chakravarty, Gabriele Keller -- [2008..2009] Sean Lee -- [2009..2014] Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <chak@cse.unsw.edu.au> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- module Data.Array.Accelerate.Pretty ( -- * Pretty printing functions module Data.Array.Accelerate.Pretty.Print -- * Instances of Show ) where -- standard libraries import Text.PrettyPrint -- friends import Data.Array.Accelerate.AST import Data.Array.Accelerate.Trafo.Base import Data.Array.Accelerate.Pretty.Print -- |Show instances -- --------------- wide :: Style wide = style { lineLength = 150 } -- Explicitly enumerate Show instances for the Accelerate array AST types. If we -- instead use a generic instance of the form: -- -- instance Kit acc => Show (acc aenv a) where -- -- This matches any type of kind (* -> * -> *), which can cause problems -- interacting with other packages. See Issue #108. -- instance Show (OpenAcc aenv a) where show c = renderStyle wide $ prettyAcc 0 noParens c instance Show (DelayedOpenAcc aenv a) where show c = renderStyle wide $ prettyAcc 0 noParens c -- These parameterised instances are fine because there is a concrete kind -- instance Kit acc => Show (PreOpenAfun acc aenv f) where show f = renderStyle wide $ prettyPreAfun prettyAcc 0 f instance Kit acc => Show (PreOpenFun acc env aenv f) where show f = renderStyle wide $ prettyPreFun prettyAcc 0 f instance Kit acc => Show (PreOpenExp acc env aenv t) where show e = renderStyle wide $ prettyPreExp prettyAcc 0 0 noParens e
kumasento/accelerate
Data/Array/Accelerate/Pretty.hs
bsd-3-clause
1,987
0
7
384
324
185
139
25
1
{-| Instance status data collector. -} {- Copyright (C) 2013 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.DataCollectors.InstStatus ( main , options , arguments , dcName , dcVersion , dcFormatVersion , dcCategory , dcKind , dcReport ) where import Control.Exception.Base import Data.List import Data.Maybe import qualified Data.Map as Map import Network.BSD (getHostName) import qualified Text.JSON as J import Ganeti.BasicTypes as BT import Ganeti.Confd.ClientFunctions import Ganeti.Common import Ganeti.DataCollectors.CLI import Ganeti.DataCollectors.InstStatusTypes import Ganeti.DataCollectors.Types import Ganeti.Hypervisor.Xen import Ganeti.Hypervisor.Xen.Types import Ganeti.Logging import Ganeti.Objects import Ganeti.Path import Ganeti.Types import Ganeti.Utils -- | The name of this data collector. dcName :: String dcName = "inst-status-xen" -- | The version of this data collector. dcVersion :: DCVersion dcVersion = DCVerBuiltin -- | The version number for the data format of this data collector. dcFormatVersion :: Int dcFormatVersion = 1 -- | The category of this data collector. dcCategory :: Maybe DCCategory dcCategory = Just DCInstance -- | The kind of this data collector. dcKind :: DCKind dcKind = DCKStatus -- | The report of this data collector. dcReport :: IO DCReport dcReport = buildInstStatusReport Nothing Nothing -- * Command line options options :: IO [OptType] options = return [ oConfdAddr , oConfdPort ] -- | The list of arguments supported by the program. arguments :: [ArgCompletion] arguments = [] -- | Try to get the reason trail for an instance. In case it is not possible, -- log the failure and return an empty list instead. getReasonTrail :: String -> IO ReasonTrail getReasonTrail instanceName = do fileName <- getInstReasonFilename instanceName content <- try $ readFile fileName case content of Left e -> do logWarning $ "Unable to open the reason trail for instance " ++ instanceName ++ " expected at " ++ fileName ++ ": " ++ show (e :: IOException) return [] Right trailString -> case J.decode trailString of J.Ok t -> return t J.Error msg -> do logWarning $ "Unable to parse the reason trail: " ++ msg return [] -- | Determine the value of the status field for the report of one instance computeStatusField :: AdminState -> ActualState -> DCStatus computeStatusField AdminDown actualState = if actualState `notElem` [ActualShutdown, ActualDying] then DCStatus DCSCBad "The instance is not stopped as it should be" else DCStatus DCSCOk "" computeStatusField AdminUp ActualHung = DCStatus DCSCUnknown "Instance marked as running, but it appears to be hung" computeStatusField AdminUp actualState = if actualState `notElem` [ActualRunning, ActualBlocked] then DCStatus DCSCBad "The instance is not running as it should be" else DCStatus DCSCOk "" computeStatusField AdminOffline _ = -- FIXME: The "offline" status seems not to be used anywhere in the source -- code, but it is defined, so we have to consider it anyway here. DCStatus DCSCUnknown "The instance is marked as offline" -- Builds the status of an instance using runtime information about the Xen -- Domains, their uptime information and the static information provided by -- the ConfD server. buildStatus :: Map.Map String Domain -> Map.Map Int UptimeInfo -> Instance -> IO InstStatus buildStatus domains uptimes inst = do let name = instName inst currDomain = Map.lookup name domains idNum = fmap domId currDomain currUInfo = idNum >>= (`Map.lookup` uptimes) uptime = fmap uInfoUptime currUInfo adminState = instAdminState inst actualState = if adminState == AdminDown && isNothing currDomain then ActualShutdown else case currDomain of (Just dom@(Domain _ _ _ _ (Just isHung))) -> if isHung then ActualHung else domState dom _ -> ActualUnknown status = computeStatusField adminState actualState trail <- getReasonTrail name return $ InstStatus name (instUuid inst) adminState actualState uptime (instMtime inst) trail status -- | Compute the status code and message, given the current DRBD data -- The final state will have the code corresponding to the worst code of -- all the devices, and the error message given from the concatenation of the -- non-empty error messages. computeGlobalStatus :: [InstStatus] -> DCStatus computeGlobalStatus instStatusList = let dcstatuses = map iStatStatus instStatusList statuses = map (\s -> (dcStatusCode s, dcStatusMessage s)) dcstatuses (code, strList) = foldr mergeStatuses (DCSCOk, [""]) statuses in DCStatus code $ intercalate "\n" strList -- | Build the report of this data collector, containing all the information -- about the status of the instances. buildInstStatusReport :: Maybe String -> Maybe Int -> IO DCReport buildInstStatusReport srvAddr srvPort = do node <- getHostName answer <- getInstances node srvAddr srvPort inst <- exitIfBad "Can't get instance info from ConfD" answer d <- getInferredDomInfo reportData <- case d of BT.Ok domains -> do uptimes <- getUptimeInfo let primaryInst = fst inst iStatus <- mapM (buildStatus domains uptimes) primaryInst let globalStatus = computeGlobalStatus iStatus return $ ReportData iStatus globalStatus BT.Bad m -> return . ReportData [] . DCStatus DCSCBad $ "Unable to receive the list of instances: " ++ m let jsonReport = J.showJSON reportData buildReport dcName dcVersion dcFormatVersion dcCategory dcKind jsonReport -- | Main function. main :: Options -> [String] -> IO () main opts _ = do report <- buildInstStatusReport (optConfdAddr opts) (optConfdPort opts) putStrLn $ J.encode report
vladimir-ipatov/ganeti
src/Ganeti/DataCollectors/InstStatus.hs
gpl-2.0
6,637
0
20
1,408
1,226
640
586
135
4
{- | Module : ./CspCASLProver/IsabelleUtils.hs Description : Utilities for CspCASLProver related to Isabelle Copyright : (c) Liam O'Reilly and Markus Roggenbach, Swansea University 2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : csliam@swansea.ac.uk Stability : provisional Portability : portable Utilities for CspCASLProver related to Isabelle. The functions here typically manipulate Isabelle signatures. -} module CspCASLProver.IsabelleUtils ( addConst , addDef , addInstanceOf , addLemmasCollection , addPrimRec , addTheoremWithProof , updateDomainTab , writeIsaTheory ) where import Common.AS_Annotation (makeNamed, Named, SenAttr (..)) import Common.ProofUtils (prepareSenNames) import Comorphisms.CFOL2IsabelleHOL (IsaTheory) -- import CspCASLProver.Consts import qualified Data.Map as Map import Isabelle.IsaParse (parseTheory) import Isabelle.IsaPrint (getAxioms, printIsaTheory) import Isabelle.IsaSign (DomainEntry, IsaProof (..), mkCond, mkSen , Sentence (..), Sign (..), Sort , Term (..), Typ (..)) import Isabelle.IsaConsts (mkVName) import Isabelle.Translate (transString) import Logic.Prover (Theory (..), toNamedList) import Text.ParserCombinators.Parsec (parse) -- | Add a single constant to the signature of an Isabelle theory addConst :: String -> Typ -> IsaTheory -> IsaTheory addConst cName cType isaTh = let isaTh_sign = fst isaTh isaTh_sen = snd isaTh isaTh_sign_ConstTab = constTab isaTh_sign isaTh_sign_ConstTabUpdated = Map.insert (mkVName cName) cType isaTh_sign_ConstTab isaTh_sign_updated = isaTh_sign { constTab = isaTh_sign_ConstTabUpdated } in (isaTh_sign_updated, isaTh_sen) -- | Function to add a def command to an Isabelle theory addDef :: String -> Term -> Term -> IsaTheory -> IsaTheory addDef name lhs rhs isaTh = let isaTh_sign = fst isaTh isaTh_sen = snd isaTh sen = ConstDef (IsaEq lhs rhs) namedSen = makeNamed name sen in (isaTh_sign, isaTh_sen ++ [namedSen]) {- | Function to add an instance of command to an Isabelle theory. The sort parameters here are basically strings. -} addInstanceOf :: String -> [Sort] -> Sort -> [(String, Term)] -> IsaProof -> IsaTheory -> IsaTheory addInstanceOf name args res defs prf isaTh = let isaTh_sign = fst isaTh isaTh_sen = snd isaTh sen = Instance name args res defs prf namedSen = makeNamed name sen in (isaTh_sign, isaTh_sen ++ [namedSen]) {- | Add a lemmas sentence (definition) that allow us to group large collections of lemmas in to a single lemma. This cuts down on the repreated addition of lemmas in the proofs. -} addLemmasCollection :: String -> [String] -> IsaTheory -> IsaTheory addLemmasCollection lemmaname lemmas isaTh = if null lemmas then isaTh else let isaTh_sign = fst isaTh isaTh_sen = snd isaTh -- Make a named lemmas sentence namedSen = (makeNamed lemmaname (Lemmas lemmaname lemmas)) {isAxiom = False} in (isaTh_sign, isaTh_sen ++ [namedSen]) {- | Add a constant with a primrec defintion to the sentences of an Isabelle theory. Parameters: constant name, type, primrec defintions and isabelle theory to be added to. -} addPrimRec :: String -> Typ -> [Term] -> IsaTheory -> IsaTheory addPrimRec cName cType terms isaTh = let isaTh_sign = fst isaTh isaTh_sen = snd isaTh primRecDef = RecDef { keyword = Nothing, constName = mkVName cName, constType = Just cType, primRecSenTerms = terms} namedPrimRecDef = (makeNamed "BUG_what_does_this_word_do?" primRecDef) { isAxiom = False, isDef = True} in (isaTh_sign, isaTh_sen ++ [namedPrimRecDef]) -- | Add a theorem with proof to an Isabelle theory addTheoremWithProof :: String -> [Term] -> Term -> IsaProof -> IsaTheory -> IsaTheory addTheoremWithProof name conds concl proof' isaTh = let isaTh_sign = fst isaTh isaTh_sen = snd isaTh sen = if null conds then ((mkSen concl) {thmProof = Just proof'}) else ((mkCond conds concl) {thmProof = Just proof'}) namedSen = (makeNamed name sen) {isAxiom = False} in (isaTh_sign, isaTh_sen ++ [namedSen]) {- | Prepare a theory for writing it out to a file. This function is based off the function Isabelle.IsaProve.prepareTheory. The difference being that this function does not mark axioms nor theorms as to be added to the simplifier in Isabelle. -} prepareTheory :: Theory Sign Sentence () -> (Sign, [Named Sentence], [Named Sentence], Map.Map String String) prepareTheory (Theory sig nSens) = let oSens = toNamedList nSens nSens' = prepareSenNames transString oSens (disAxs, disGoals) = getAxioms nSens' in (sig, disAxs, disGoals, Map.fromList $ zip (map senAttr nSens') $ map senAttr oSens) -- | Add a DomainEntry to the domain tab of an Isabelle signature. updateDomainTab :: DomainEntry -> IsaTheory -> IsaTheory updateDomainTab domEnt (isaSign, isaSens) = let oldDomTab = domainTab isaSign isaSignUpdated = isaSign {domainTab = oldDomTab ++ [[domEnt]]} in (isaSignUpdated, isaSens) {- | Write out an Isabelle Theory. The theory should just run through in Isabelle without any user interactions. This is based heavily off Isabelle.IsaProve.isaProve -} writeIsaTheory :: String -> Theory Sign Sentence () -> IO () writeIsaTheory thName th = do let (sig, axs, ths, _) = prepareTheory th -- thms = map senAttr ths thBaseName = reverse . takeWhile (/= '/') $ reverse thName {- useaxs = filter (\ s -> sentence s /= mkSen true && (isDef s || isSuffixOf "def" (senAttr s))) axs defaultProof = Just $ IsaProof (if null useaxs then [] else [Using $ map senAttr useaxs]) By Auto -} thy = shows (printIsaTheory thBaseName sig $ axs ++ ths) "\n" thyFile = thBaseName ++ ".thy" -- Check if the Isabelle theory is a valid Isabelle theory case parse parseTheory thyFile thy of Right _ -> do {- prepareThyFiles (ho, bo) thyFile thy removeDepFiles thBaseName thms isabelle <- getEnvDef "HETS_ISABELLE" "Isabelle" callSystem $ isabelle ++ " " ++ thyFile ok <- checkFinalThyFile (ho, bo) thyFile if ok then getAllProofDeps m thBaseName thms else return [] -} writeFile thyFile thy return () {- The Isabelle theory is not a valid theory (according to Hets) as it cannot be parsed. -} Left err -> do print err putStrLn $ "Sorry, a generated theory cannot be parsed, see: " ++ thyFile writeFile thyFile thy putStrLn "Aborting Isabelle proof attempt" return ()
spechub/Hets
CspCASLProver/IsabelleUtils.hs
gpl-2.0
6,948
0
14
1,731
1,359
740
619
107
2
{-| Module : CompileUtils License : GPL Maintainer : helium@cs.uu.nl Stability : experimental Portability : portable -} module Helium.Main.CompileUtils ( module Helium.Main.CompileUtils , Option(..) , splitFilePath, combinePathAndFile , when, unless , exitWith, ExitCode(..), exitSuccess, getArgs , module Helium.ModuleSystem.ImportEnvironment , Module(..) ) where import Helium.Main.Args(Option(..)) import Helium.StaticAnalysis.Messages.Messages(HasMessage) import Helium.StaticAnalysis.Messages.HeliumMessages(sortAndShowMessages,sortMessages) import Control.Monad import Helium.Utils.Utils(splitFilePath, combinePathAndFile) import System.Exit import System.Environment(getArgs) import Helium.Utils.Logger import Helium.ModuleSystem.ImportEnvironment import Helium.Syntax.UHA_Syntax(Module(..)) import Data.Maybe import Lvm.Path(searchPathMaybe) import System.FilePath (joinPath) import System.Process(system) type Phase err a = IO (Either [err] a) type CompileOptions = ([Option], String, [String]) (===>) :: Phase err1 a -> (a -> Phase err2 b) -> Phase (Either err1 err2) b p ===> f = p >>= either (return . Left . map Left) (f >=> return . either (Left . map Right) Right) doPhaseWithExit :: HasMessage err => Int -> ([err] -> String) -> CompileOptions -> Phase err a -> IO a doPhaseWithExit nrOfMsgs code (options, fullName, doneModules) phase = do result <- phase case result of Left errs -> do sendLog (code errs) fullName doneModules options showErrorsAndExit errs nrOfMsgs Right a -> return a sendLog :: String -> String -> [String] -> [Option] -> IO () sendLog code fullName modules = logger code (Just (modules,fullName)) enterNewPhase :: String -> [Option] -> IO () enterNewPhase phase options = when (Verbose `elem` options) $ putStrLn (phase ++ "...") showErrorsAndExit :: HasMessage a => [a] -> Int -> IO b showErrorsAndExit errors maximumNumber = do let someErrors = take maximumNumber (sortMessages errors) showMessages someErrors when (number > maximumNumber) $ putStrLn "(...)\n" putStrLn ("Compilation failed with " ++ show number ++ " error" ++ (if number == 1 then "" else "s")) exitWith (ExitFailure 1) where number = length errors showMessages :: HasMessage a => [a] -> IO () showMessages = putStr . sortAndShowMessages makeCoreLib :: String -> String -> IO () makeCoreLib basepath name = do let bps = [basepath] maybeFullName <- searchPathMaybe bps ".lvm" name case maybeFullName of Just _ -> return () Nothing -> do maybeCoreName <- searchPathMaybe bps ".core" name case maybeCoreName of Just _ -> sys ("coreasm " ++ joinPath [basepath, name]) Nothing -> do putStr ( "Cannot find " ++ name ++ ".core in \n" ++ basepath) exitWith (ExitFailure 1) sys :: String -> IO () sys s = do -- putStrLn ("System:" ++ s) _ <- system s return () checkExistence :: [String] -> String -> IO () checkExistence path name = do maybeLocation <- resolve path name when (isNothing maybeLocation) $ do putStr ( "Cannot find " ++ name ++ ".hs (or .lvm) in search path:\n" ++ unlines (map ("\t" ++) path) ++ "Use the -P option to add paths to the search path.\n" ) exitWith (ExitFailure 1) resolve :: [String] -> String -> IO (Maybe String) resolve path name = do maybeFullName <- searchPathMaybe path ".hs" name case maybeFullName of Just fullName -> return (Just fullName) Nothing -> searchPathMaybe path ".lvm" name
roberth/uu-helium
src/Helium/Main/CompileUtils.hs
gpl-3.0
4,118
0
21
1,277
1,184
614
570
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.ElastiCache.PurchaseReservedCacheNodesOffering -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- The /PurchaseReservedCacheNodesOffering/ action allows you to purchase a -- reserved cache node offering. -- -- /See:/ <http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_PurchaseReservedCacheNodesOffering.html AWS API Reference> for PurchaseReservedCacheNodesOffering. module Network.AWS.ElastiCache.PurchaseReservedCacheNodesOffering ( -- * Creating a Request purchaseReservedCacheNodesOffering , PurchaseReservedCacheNodesOffering -- * Request Lenses , prcnoCacheNodeCount , prcnoReservedCacheNodeId , prcnoReservedCacheNodesOfferingId -- * Destructuring the Response , purchaseReservedCacheNodesOfferingResponse , PurchaseReservedCacheNodesOfferingResponse -- * Response Lenses , prcnorsReservedCacheNode , prcnorsResponseStatus ) where import Network.AWS.ElastiCache.Types import Network.AWS.ElastiCache.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Represents the input of a /PurchaseReservedCacheNodesOffering/ action. -- -- /See:/ 'purchaseReservedCacheNodesOffering' smart constructor. data PurchaseReservedCacheNodesOffering = PurchaseReservedCacheNodesOffering' { _prcnoCacheNodeCount :: !(Maybe Int) , _prcnoReservedCacheNodeId :: !(Maybe Text) , _prcnoReservedCacheNodesOfferingId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PurchaseReservedCacheNodesOffering' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'prcnoCacheNodeCount' -- -- * 'prcnoReservedCacheNodeId' -- -- * 'prcnoReservedCacheNodesOfferingId' purchaseReservedCacheNodesOffering :: Text -- ^ 'prcnoReservedCacheNodesOfferingId' -> PurchaseReservedCacheNodesOffering purchaseReservedCacheNodesOffering pReservedCacheNodesOfferingId_ = PurchaseReservedCacheNodesOffering' { _prcnoCacheNodeCount = Nothing , _prcnoReservedCacheNodeId = Nothing , _prcnoReservedCacheNodesOfferingId = pReservedCacheNodesOfferingId_ } -- | The number of cache node instances to reserve. -- -- Default: '1' prcnoCacheNodeCount :: Lens' PurchaseReservedCacheNodesOffering (Maybe Int) prcnoCacheNodeCount = lens _prcnoCacheNodeCount (\ s a -> s{_prcnoCacheNodeCount = a}); -- | A customer-specified identifier to track this reservation. -- -- Example: myreservationID prcnoReservedCacheNodeId :: Lens' PurchaseReservedCacheNodesOffering (Maybe Text) prcnoReservedCacheNodeId = lens _prcnoReservedCacheNodeId (\ s a -> s{_prcnoReservedCacheNodeId = a}); -- | The ID of the reserved cache node offering to purchase. -- -- Example: 438012d3-4052-4cc7-b2e3-8d3372e0e706 prcnoReservedCacheNodesOfferingId :: Lens' PurchaseReservedCacheNodesOffering Text prcnoReservedCacheNodesOfferingId = lens _prcnoReservedCacheNodesOfferingId (\ s a -> s{_prcnoReservedCacheNodesOfferingId = a}); instance AWSRequest PurchaseReservedCacheNodesOffering where type Rs PurchaseReservedCacheNodesOffering = PurchaseReservedCacheNodesOfferingResponse request = postQuery elastiCache response = receiveXMLWrapper "PurchaseReservedCacheNodesOfferingResult" (\ s h x -> PurchaseReservedCacheNodesOfferingResponse' <$> (x .@? "ReservedCacheNode") <*> (pure (fromEnum s))) instance ToHeaders PurchaseReservedCacheNodesOffering where toHeaders = const mempty instance ToPath PurchaseReservedCacheNodesOffering where toPath = const "/" instance ToQuery PurchaseReservedCacheNodesOffering where toQuery PurchaseReservedCacheNodesOffering'{..} = mconcat ["Action" =: ("PurchaseReservedCacheNodesOffering" :: ByteString), "Version" =: ("2015-02-02" :: ByteString), "CacheNodeCount" =: _prcnoCacheNodeCount, "ReservedCacheNodeId" =: _prcnoReservedCacheNodeId, "ReservedCacheNodesOfferingId" =: _prcnoReservedCacheNodesOfferingId] -- | /See:/ 'purchaseReservedCacheNodesOfferingResponse' smart constructor. data PurchaseReservedCacheNodesOfferingResponse = PurchaseReservedCacheNodesOfferingResponse' { _prcnorsReservedCacheNode :: !(Maybe ReservedCacheNode) , _prcnorsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PurchaseReservedCacheNodesOfferingResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'prcnorsReservedCacheNode' -- -- * 'prcnorsResponseStatus' purchaseReservedCacheNodesOfferingResponse :: Int -- ^ 'prcnorsResponseStatus' -> PurchaseReservedCacheNodesOfferingResponse purchaseReservedCacheNodesOfferingResponse pResponseStatus_ = PurchaseReservedCacheNodesOfferingResponse' { _prcnorsReservedCacheNode = Nothing , _prcnorsResponseStatus = pResponseStatus_ } -- | Undocumented member. prcnorsReservedCacheNode :: Lens' PurchaseReservedCacheNodesOfferingResponse (Maybe ReservedCacheNode) prcnorsReservedCacheNode = lens _prcnorsReservedCacheNode (\ s a -> s{_prcnorsReservedCacheNode = a}); -- | The response status code. prcnorsResponseStatus :: Lens' PurchaseReservedCacheNodesOfferingResponse Int prcnorsResponseStatus = lens _prcnorsResponseStatus (\ s a -> s{_prcnorsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-elasticache/gen/Network/AWS/ElastiCache/PurchaseReservedCacheNodesOffering.hs
mpl-2.0
6,288
0
13
1,103
712
427
285
93
1
module Control.Monad.M where import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Either import Control.Monad.Trans.Reader import Data.String.Util import Pipes import System.Exit type M r = ReaderT Env (EitherT String IO) r data Env = Env { indention :: Int, verbosity :: Bool } newEnv :: Bool -> Env newEnv = Env 0 env :: M Env env = ask warning :: String -> M () warning str = do i <- indention <$> env liftIO $ do putStr $ indenting i ("warning: " ++ str) putStr "\n" indent :: Int -> Env -> Env indent amount (Env i v) = Env (i + amount) v indentM :: Int -> M r -> M r indentM amount = local (indent amount) msg :: (MonadIO m) => String -> ReaderT Env m () msg str = do e <- ask when (verbosity e) . liftIO . putStr . indenting (indention e) $ str err :: String -> M r err = lift . left fromE :: (Unquoted b) => Either b a -> M a fromE (Left er) = err . toString $ er fromE (Right val) = return val runM :: Env -> M () -> IO () runM env' comp = do result <- runEitherT (runReaderT comp env') case result of Left e -> do liftIO . putStrLn $ "fatal error:\n" ++ e exitFailure Right () -> exitSuccess type ConsumerM i r = Consumer i (ReaderT Env (EitherT String IO)) r type ProducerM i r = Producer i (ReaderT Env (EitherT String IO)) r type PipeM a b r = Pipe a b (ReaderT Env (EitherT String IO)) r
jfeltz/dash-haskell
src/Control/Monad/M.hs
lgpl-3.0
1,413
0
14
351
621
320
301
45
2
main = do let value = True if value then putStrLn "Got true" else putStrLn "Got else" let value = False if value then putStrLn "Got true" else putStrLn "Got else" let result = 3 if result == 1 then putStrLn "Got true" else if result == 2 then putStrLn "Got else" else putStrLn "Got if else"
Bigsby/HelloLanguages
src/hs/ifelse.hs
apache-2.0
392
0
9
158
103
49
54
15
5
module Propellor.Property.HostingProvider.DigitalOcean ( distroKernel ) where import Propellor import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.File as File import qualified Propellor.Property.Reboot as Reboot import Data.List -- | Digital Ocean does not provide any way to boot -- the kernel provided by the distribution, except using kexec. -- Without this, some old, and perhaps insecure kernel will be used. -- -- This property causes the distro kernel to be loaded on reboot, using kexec. -- -- If the power is cycled, the non-distro kernel still boots up. -- So, this property also checks if the running kernel is present in /boot, -- and if not, reboots immediately into a distro kernel. distroKernel :: Property NoInfo distroKernel = propertyList "digital ocean distro kernel hack" [ Apt.installed ["grub-pc", "kexec-tools", "file"] , "/etc/default/kexec" `File.containsLines` [ "LOAD_KEXEC=true" , "USE_GRUB_CONFIG=true" ] `describe` "kexec configured" , check (not <$> runningInstalledKernel) Reboot.now `describe` "running installed kernel" ] runningInstalledKernel :: IO Bool runningInstalledKernel = do kernelver <- takeWhile (/= '\n') <$> readProcess "uname" ["-r"] when (null kernelver) $ error "failed to read uname -r" kernelimages <- concat <$> mapM kernelsIn ["/", "/boot/"] when (null kernelimages) $ error "failed to find any installed kernel images" findVersion kernelver <$> readProcess "file" ("-L" : kernelimages) -- | File output looks something like this, we want to unambiguously -- match the running kernel version: -- Linux kernel x86 boot executable bzImage, version 3.16-3-amd64 (debian-kernel@lists.debian.org) #1 SMP Debian 3.1, RO-rootFS, swap_dev 0x2, Normal VGA findVersion :: String -> String -> Bool findVersion ver s = (" version " ++ ver ++ " ") `isInfixOf` s kernelsIn :: FilePath -> IO [FilePath] kernelsIn d = filter ("vmlinu" `isInfixOf`) <$> dirContents d
sjfloat/propellor
src/Propellor/Property/HostingProvider/DigitalOcean.hs
bsd-2-clause
1,969
18
10
309
359
203
156
30
1
{-| Contains all the data structures and functions for composing and rendering graphics. -} module FRP.Helm.Graphics ( -- * Types Element(..), FontWeight(..), FontStyle(..), Text(..), Form(..), FormStyle(..), FillStyle(..), LineCap(..), LineJoin(..), LineStyle(..), Path, Shape(..), -- * Elements image, fittedImage, croppedImage, collage, centeredCollage, fixedCollage, -- * Styles & Forms defaultLine, solid, dashed, dotted, filled, textured, gradient, outlined, traced, sprite, toForm, blank, -- * Grouping group, groupTransform, -- * Transforming rotate, scale, move, moveX, moveY, -- * Paths path, segment, -- * Shapes polygon, rect, square, oval, circle, ngon ) where import FRP.Helm.Color (Color, black, Gradient) import Graphics.Rendering.Cairo.Matrix (Matrix) {-| A data structure describing the weight of a piece of font. -} data FontWeight = LightWeight | NormalWeight | BoldWeight deriving (Show, Eq, Ord, Enum, Read) {-| A data structure describing the style of of a piece of font. -} data FontStyle = NormalStyle | ObliqueStyle | ItalicStyle deriving (Show, Eq, Ord, Enum, Read) {-| A data structure describing a piece of formatted text. -} data Text = Text { textUTF8 :: String, textColor :: Color, textTypeface :: String, textHeight :: Double, textWeight :: FontWeight, textStyle :: FontStyle } deriving (Show, Eq) {-| A data structure describing something that can be rendered to the screen. Elements are the most important structure in Helm. Games essentially feed the engine a stream of elements which are then rendered directly to the screen. The usual way to render art in a Helm game is to call off to the 'collage' function, which essentially renders a collection of forms together. -} data Element = CollageElement Int Int (Maybe (Double, Double)) [Form] | ImageElement (Int, Int) Int Int FilePath Bool | TextElement Text deriving (Show, Eq) {-| Create an element from an image with a given width, height and image file path. If the image dimensions are not the same as given, then it will stretch/shrink to fit. Only PNG files are supported currently. -} image :: Int -> Int -> FilePath -> Element image w h src = ImageElement (0, 0) w h src True {-| Create an element from an image with a given width, height and image file path. If the image dimensions are not the same as given, then it will only use the relevant pixels (i.e. cut out the given dimensions instead of scaling). If the given dimensions are bigger than the actual image, than irrelevant pixels are ignored. -} fittedImage :: Int -> Int -> FilePath -> Element fittedImage w h src = ImageElement (0, 0) w h src False {-| Create an element from an image by cropping it with a certain position, width, height and image file path. This can be used to divide a single image up into smaller ones. -} croppedImage :: (Int, Int) -> Int -> Int -> FilePath -> Element croppedImage pos w h src = ImageElement pos w h src False {-| A data structure describing a form. A form is essentially a notion of a transformed graphic, whether it be an element or shape. See 'FormStyle' for an insight into what sort of graphics can be wrapped in a form. -} data Form = Form { formTheta :: Double, formScale :: Double, formX :: Double, formY :: Double, formStyle :: FormStyle } deriving (Show, Eq) {-| A data structure describing how a shape or path looks when filled. -} data FillStyle = Solid Color | Texture String | Gradient Gradient deriving (Show, Eq, Ord, Read) {-| A data structure describing the shape of the ends of a line. -} data LineCap = FlatCap | RoundCap | PaddedCap deriving (Show, Eq, Enum, Ord, Read) {-| A data structure describing the shape of the join of a line, i.e. where separate line segments join. The 'Sharp' variant takes an argument to limit the length of the join. -} data LineJoin = SmoothJoin | SharpJoin Double | ClippedJoin deriving (Show, Eq, Ord, Read) {-| A data structure describing how a shape or path looks when stroked. -} data LineStyle = LineStyle { lineColor :: Color, lineWidth :: Double, lineCap :: LineCap, lineJoin :: LineJoin, lineDashing :: [Double], lineDashOffset :: Double } deriving (Show, Eq) {-| Creates the default line style. By default, the line is black with a width of 1, flat caps and regular sharp joints. -} defaultLine :: LineStyle defaultLine = LineStyle { lineColor = black, lineWidth = 1, lineCap = FlatCap, lineJoin = SharpJoin 10, lineDashing = [], lineDashOffset = 0 } {-| Create a solid line style with a color. -} solid :: Color -> LineStyle solid color = defaultLine { lineColor = color } {-| Create a dashed line style with a color. -} dashed :: Color -> LineStyle dashed color = defaultLine { lineColor = color, lineDashing = [8, 4] } {-| Create a dotted line style with a color. -} dotted :: Color -> LineStyle dotted color = defaultLine { lineColor = color, lineDashing = [3, 3] } {-| A data structure describing a few ways that graphics that can be wrapped in a form and hence transformed. -} data FormStyle = PathForm LineStyle Path | ShapeForm (Either LineStyle FillStyle) Shape | ElementForm Element | GroupForm (Maybe Matrix) [Form] deriving (Show, Eq) {-| Utility function for creating a form. -} form :: FormStyle -> Form form style = Form { formTheta = 0, formScale = 1, formX = 0, formY = 0, formStyle = style } {-| Utility function for creating a filled form from a fill style and shape. -} fill :: FillStyle -> Shape -> Form fill style shape = form (ShapeForm (Right style) shape) {-| Creates a form from a shape by filling it with a specific color. -} filled :: Color -> Shape -> Form filled color = fill (Solid color) {-| Creates a form from a shape with a tiled texture and image file path. -} textured :: String -> Shape -> Form textured src = fill (Texture src) {-| Creates a form from a shape filled with a gradient. -} gradient :: Gradient -> Shape -> Form gradient grad = fill (Gradient grad) {-| Creates a form from a shape by outlining it with a specific line style. -} outlined :: LineStyle -> Shape -> Form outlined style shape = form (ShapeForm (Left style) shape) {-| Creates a form from a path by tracing it with a specific line style. -} traced :: LineStyle -> Path -> Form traced style p = form (PathForm style p) {-| Creates a form from a image file path with additional position, width and height arguments. Allows you to splice smaller parts from a single image. -} sprite :: Int -> Int -> (Int, Int) -> FilePath -> Form sprite w h pos src = form (ElementForm (ImageElement pos w h src False)) {-| Creates a form from an element. -} toForm :: Element -> Form toForm element = form (ElementForm element) {-| Creates a empty form, useful for having forms rendered only at some state. -} blank :: Form blank = group [] {-| Groups a collection of forms into a single one. -} group :: [Form] -> Form group forms = form (GroupForm Nothing forms) {-| Groups a collection of forms into a single one, also applying a matrix transformation. -} groupTransform :: Matrix -> [Form] -> Form groupTransform matrix forms = form (GroupForm (Just matrix) forms) {-| Rotates a form by an amount (in radians). -} rotate :: Double -> Form -> Form rotate t f = f { formTheta = t + formTheta f } {-| Scales a form by an amount, e.g. scaling by /2.0/ will double the size. -} scale :: Double -> Form -> Form scale n f = f { formScale = n * formScale f } {-| Moves a form relative to its current position. -} move :: (Double, Double) -> Form -> Form move (rx, ry) f = f { formX = rx + formX f, formY = ry + formY f } {-| Moves a form's x-coordinate relative to its current position. -} moveX :: Double -> Form -> Form moveX x = move (x, 0) {-| Moves a form's y-coordinate relative to its current position. -} moveY :: Double -> Form -> Form moveY y = move (0, y) {-| Create an element from a collection of forms, with width and height arguments. All forms are centered and clipped within the supplied dimensions. It is generally used to directly render a collection of forms. > collage 800 600 [move (100, 100) $ filled red $ square 100, > move (100, 100) $ outlined (solid white) $ circle 50] -} collage :: Int -> Int -> [Form] -> Element collage w h = CollageElement w h Nothing {-| Like 'collage', but it centers the forms within the supplied dimensions. -} centeredCollage :: Int -> Int -> [Form] -> Element centeredCollage w h = CollageElement w h (Just (realToFrac w / 2, realToFrac h / 2)) {-| Like 'centeredCollage', but it centers the forms around a specific point. -} fixedCollage :: Int -> Int -> (Double, Double) -> [Form] -> Element fixedCollage w h (x, y) = CollageElement w h (Just (realToFrac w / 2 - x, realToFrac h / 2 - y)) {-| A data type made up a collection of points that form a path when joined. -} type Path = [(Double, Double)] {-| Creates a path for a collection of points. -} path :: [(Double, Double)] -> Path path points = points {-| Creates a path from a line segment, i.e. a start and end point. -} segment :: (Double, Double) -> (Double, Double) -> Path segment p1 p2 = [p1, p2] {-| A data structure describing a some sort of graphically representable object, such as a polygon formed from a list of points or a rectangle. -} data Shape = PolygonShape Path | RectangleShape (Double, Double) | ArcShape (Double, Double) Double Double Double (Double, Double) deriving (Show, Eq, Ord, Read) {-| Creates a shape from a path (a list of points). -} polygon :: Path -> Shape polygon = PolygonShape {-| Creates a rectangular shape with a width and height. -} rect :: Double -> Double -> Shape rect w h = RectangleShape (w, h) {-| Creates a square shape with a side length. -} square :: Double -> Shape square n = rect n n {-| Creates an oval shape with a width and height. -} oval :: Double -> Double -> Shape oval w h = ArcShape (0, 0) 0 (2 * pi) 1 (w / 2, h / 2) {-| Creates a circle shape with a radius. -} circle :: Double -> Shape circle r = ArcShape (0, 0) 0 (2 * pi) r (1, 1) {-| Creates a generic n-sided polygon (e.g. octagon, pentagon, etc) with an amount of sides and radius. -} ngon :: Int -> Double -> Shape ngon n r = PolygonShape (map (\i -> (r * cos (t * i), r * sin (t * i))) [0 .. fromIntegral (n - 1)]) where m = fromIntegral n t = 2 * pi / m
didmar/helm
src/FRP/Helm/Graphics.hs
mit
10,649
0
14
2,356
2,293
1,312
981
169
1
module Yst.Sqlite3 (readSqlite3) where import Database.HDBC import Database.HDBC.Sqlite3 import Data.Maybe import Yst.Types readSqlite3 :: FilePath -> String -> IO Node readSqlite3 filename query = do conn <- connectSqlite3 filename stmt <- prepare conn query execute stmt [] records <- sFetchAllRows' stmt fieldNames <- getColumnNames stmt disconnect conn return $ NList $ map (NMap . (zip fieldNames) . (map (fieldToNode . fromMaybe ""))) records fieldToNode :: String -> Node fieldToNode s = case parseAsDate s of Nothing -> NString s Just d -> NDate d
2ion/yst
Yst/Sqlite3.hs
gpl-2.0
646
0
15
174
210
101
109
21
2
module Main where import CV.Image import CV.Thresholding main = do Just x <- loadImage "smallLena.jpg" saveImage "thresholding.png" $ montage (3,2) 5 $ [x ,unsafeImageTo32F $ nibbly 1.2 0.01 x ,unsafeImageTo32F $ otsu 64 x ,unsafeImageTo32F $ kittler 0.1 x ,unsafeImageTo32F $ bernsen (9,9) 0.2 x ]
aleator/CV
examples/thresholding.hs
bsd-3-clause
357
0
11
104
118
61
57
11
1
module T5441a where import Unsafe.Coerce (unsafeCoerce) import GHC.Base (Any) listmap :: (a -> b) -> [a] -> [b] listmap f [] = [] listmap f (x : xs) = f x : listmap f xs data Nat = Z | S Nat {-# NOINLINE inject #-} inject :: Nat -> Nat -> Nat inject m i = i {-# NOINLINE look #-} look :: Nat -> String -> Char look Z _ = '0' showDigit :: Nat -> () -> Nat -> Char showDigit base prf d = look (inject base d) "" toDigits :: Nat -> Nat -> [Nat] toDigits Z Z = [Z] coe1 :: (Nat -> String) -> Any coe1 = unsafeCoerce coe2 :: Any -> (Nat -> String) coe2 = unsafeCoerce showInBase :: Nat -> Any showInBase base = coe1 (\n -> listmap (showDigit base ()) (toDigits base n)) showNat :: Nat -> String showNat = coe2 (showInBase Z)
ezyang/ghc
testsuite/tests/simplCore/should_run/T5441a.hs
bsd-3-clause
771
0
11
204
342
184
158
28
1
module Main where import Base import Extends -- Previously GHC was giving this false positive: -- -- T10890_1.hs:4:1: Warning: -- The import of ‘Extends’ is redundant -- except perhaps to import instances from ‘Extends’ -- To import instances alone, use: import Extends() data Bar = Bar instance AClass Bar where has = Bar instance BClass Bar where has = Bar main :: IO () main = return ()
ezyang/ghc
testsuite/tests/warnings/should_compile/T10890/T10890_1.hs
bsd-3-clause
430
0
6
100
69
41
28
10
1
{-# LANGUAGE OverloadedStrings #-} module Language where import Data.Aeson.Types newtype Language = Language String defaultLanguage :: Language defaultLanguage = Language "en" ppLang :: Language -> String ppLang (Language l) = l instance ToJSON Language where toJSON = toJSON . ppLang instance FromJSON Language where parseJSON s = Language <$> parseJSON s
entropia/tip-toi-reveng
src/Language.hs
mit
373
0
7
67
95
52
43
12
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module ConcurrentWatched ( forkIO , allThreads , module Control.Concurrent ) where import Control.Concurrent hiding (forkIO) import qualified Control.Concurrent as Concurrent (forkIO) import Control.Monad import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as ByteString (putStrLn) import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Text as Text (pack) import GHC.Generics import System.IO.Unsafe data ThreadState = ThreadRunning | ThreadStopped deriving(Generic) instance ToJSON ThreadState where toJSON ThreadRunning = String "running" toJSON ThreadStopped = String "stopped" threadStatesJSON :: IO () threadStatesJSON = do threads <- readMVar allThreads states <- forM (Map.toList threads) $ \(tid, threadFinished) -> do mf <- tryReadMVar threadFinished case mf of Nothing -> return (tid, ThreadRunning) Just _ -> return (tid, ThreadStopped) ByteString.putStrLn (encode $ object (map (\(k, v) -> Text.pack (show k) .= v) states)) {-# NOINLINE allThreads #-} allThreads :: MVar (Map ThreadId (MVar ())) allThreads = unsafePerformIO $ newMVar Map.empty forkIO :: IO () -> IO ThreadId forkIO acao = do finished <- newEmptyMVar tid <- Concurrent.forkIO $ do acao putMVar finished () modifyMVar_ allThreads $ \threads -> return (Map.insert tid finished threads) return tid
haskellbr/meetups
01-2016/concorrencia-em-haskell/ghci-threads-mvars/ConcurrentWatched.hs
mit
1,661
0
18
471
454
242
212
45
2
---------------------------------------------------------------- -- -- | aartifact -- http://www.aartifact.org/ -- -- @src\/Set.hs@ -- -- Set representation and common operations. -- ---------------------------------------------------------------- -- module Set where import Data.List ---------------------------------------------------------------- -- | Sets are represented as lists; because this is a standard -- practice, this module exposes this fact, and exists solely -- to provide concise synonyms for common operations. type Set a = [a] add :: Eq a => a -> Set a -> Set a add x set = if x `elem` set then set else x:set subset :: Eq a => Set a -> Set a -> Bool subset s1 s2 = and $ map (\x -> elem x s2) s1 eql :: Eq a => Set a -> Set a -> Bool eql s1 s2 = (s1 `subset` s2) && (s2 `subset` s1) set :: Eq a => [a] -> Set a set = nub (\/) :: Eq a => Set a -> Set a -> Set a (\/) = Data.List.union (/\) :: Eq a => Set a -> Set a -> Set a (/\) = Data.List.intersect diff :: Eq a => Set a -> Set a -> Set a diff = (\\) (><) :: (Eq a, Eq b) => Set a -> Set b -> Set (a,b) (><) s s' = [(x,y) | x<-s, y<-s'] rgt :: (a -> a -> Bool) -> Set (a,b) -> a -> Set b rgt eq r x = [y | (x',y) <- r, x' `eq` x] lft :: (b -> b -> Bool) -> Set (a,b) -> b -> Set a lft eq r y = [x | (x,y') <- r, y' `eq` y] --eof
aartifact/aartifact-verifier
src/Set.hs
mit
1,324
0
9
296
590
323
267
23
2
fibo :: Integer-> Integer fibo n |n==0 =0 |n==1 =1 |n>0 =fibo (n-1)+fibo (n-2) |otherwise =error " undefined negative error " main=print(fibo 10)
manuchandel/Academics
Principles-Of-Programming-Languages/fibo.hs
mit
151
0
9
28
104
49
55
7
1